Add `rustik-tui-*` crates

61f97153e99f63b07f42756d3204cf1798ab506f
Alexis Sellier committed ago 1 parent 7cc45381
.cargo/config.toml added +2 -0
1 +
[alias]
2 +
coverage = "llvm-cov --all-targets --summary-only --fail-under-lines 80"
.gitignore added +2 -0
1 +
/target/
2 +
/tmp/
Cargo.lock added +60 -0
1 +
# This file is automatically @generated by Cargo.
2 +
# It is not intended for manual editing.
3 +
version = 4
4 +
5 +
[[package]]
6 +
name = "libc"
7 +
version = "0.2.186"
8 +
source = "registry+https://github.com/rust-lang/crates.io-index"
9 +
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
10 +
11 +
[[package]]
12 +
name = "numtoa"
13 +
version = "0.2.4"
14 +
source = "registry+https://github.com/rust-lang/crates.io-index"
15 +
checksum = "6aa2c4e539b869820a2b82e1aef6ff40aa85e65decdd5185e83fb4b1249cd00f"
16 +
17 +
[[package]]
18 +
name = "rustik"
19 +
version = "0.1.0"
20 +
dependencies = [
21 +
 "rustik-tui",
22 +
]
23 +
24 +
[[package]]
25 +
name = "rustik-tui"
26 +
version = "0.1.0"
27 +
dependencies = [
28 +
 "rustik-tui-core",
29 +
 "rustik-tui-termion",
30 +
 "rustik-tui-widgets",
31 +
]
32 +
33 +
[[package]]
34 +
name = "rustik-tui-core"
35 +
version = "0.1.0"
36 +
37 +
[[package]]
38 +
name = "rustik-tui-termion"
39 +
version = "0.1.0"
40 +
dependencies = [
41 +
 "rustik-tui-core",
42 +
 "termion",
43 +
]
44 +
45 +
[[package]]
46 +
name = "rustik-tui-widgets"
47 +
version = "0.1.0"
48 +
dependencies = [
49 +
 "rustik-tui-core",
50 +
]
51 +
52 +
[[package]]
53 +
name = "termion"
54 +
version = "4.0.6"
55 +
source = "registry+https://github.com/rust-lang/crates.io-index"
56 +
checksum = "f44138a9ae08f0f502f24104d82517ef4da7330c35acd638f1f29d3cd5475ecb"
57 +
dependencies = [
58 +
 "libc",
59 +
 "numtoa",
60 +
]
Cargo.toml added +52 -0
1 +
[workspace]
2 +
members = [
3 +
  "crates/tui",
4 +
  "crates/tui-core",
5 +
  "crates/tui-termion",
6 +
  "crates/tui-widgets"
7 +
]
8 +
resolver = "3"
9 +
10 +
[package]
11 +
name = "rustik"
12 +
description = "Rust development kit for minimal, high performance tools."
13 +
version.workspace = true
14 +
edition.workspace = true
15 +
homepage = "https://crates.io/crates/rustik"
16 +
documentation = "https://docs.rs/rustik"
17 +
license.workspace = true
18 +
19 +
[features]
20 +
default = []
21 +
widgets = ["rustik-tui/widgets"]
22 +
all = ["widgets"]
23 +
24 +
[dependencies]
25 +
rustik-tui = { workspace = true }
26 +
27 +
[lints]
28 +
workspace = true
29 +
30 +
[workspace.package]
31 +
version = "0.1.0"
32 +
edition = "2024"
33 +
license = "MIT"
34 +
35 +
[workspace.dependencies]
36 +
termion = "4"
37 +
rustik-tui = { path = "crates/tui", version = "0.1.0" }
38 +
rustik-tui-core = { path = "crates/tui-core", version = "0.1.0" }
39 +
rustik-tui-widgets = { path = "crates/tui-widgets", version = "0.1.0" }
40 +
rustik-tui-termion = { path = "crates/tui-termion", version = "0.1.0" }
41 +
42 +
[workspace.lints.clippy]
43 +
inline_always = "allow"
44 +
must_use_candidate = "allow"
45 +
needless_pass_by_value = "allow"
46 +
return_self_not_must_use = "allow"
47 +
too_many_lines = "allow"
48 +
trivially_copy_pass_by_ref = "allow"
49 +
unused_self = "allow"
50 +
unwrap_used = "warn"
51 +
expect_used = "warn"
52 +
panic = "warn"
LICENSE added +21 -0
1 +
MIT License
2 +
3 +
Copyright (c) 2026 Alexis Sellier
4 +
5 +
Permission is hereby granted, free of charge, to any person obtaining a copy
6 +
of this software and associated documentation files (the "Software"), to deal
7 +
in the Software without restriction, including without limitation the rights
8 +
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 +
copies of the Software, and to permit persons to whom the Software is
10 +
furnished to do so, subject to the following conditions:
11 +
12 +
The above copyright notice and this permission notice shall be included in all
13 +
copies or substantial portions of the Software.
14 +
15 +
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 +
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 +
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 +
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 +
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 +
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 +
SOFTWARE.
README.md added +16 -0
1 +
# rustik
2 +
3 +
Rustik is a Rust development kit for minimal, high performance tools.
4 +
5 +
`rustik` is a thin umbrella crate for the Rustik workspace.
6 +
7 +
## Installation
8 +
9 +
```toml
10 +
[dependencies]
11 +
rustik = "0.1.0"
12 +
```
13 +
14 +
## License
15 +
16 +
MIT. See [LICENSE](LICENSE).
crates/tui-core/Cargo.toml added +11 -0
1 +
[package]
2 +
name = "rustik-tui-core"
3 +
version.workspace = true
4 +
edition.workspace = true
5 +
description = "Rustik is a rust development kit for minimal, high performance tools. Core primitives for the rustik-tui crate."
6 +
homepage = "https://crates.io/crates/rustik-tui-core"
7 +
documentation = "https://docs.rs/rustik-tui-core"
8 +
license.workspace = true
9 +
10 +
[lints]
11 +
workspace = true
crates/tui-core/README.md added +25 -0
1 +
# rustik-tui-core
2 +
3 +
*Rustik is a Rust development kit for minimal, high performance tools.*
4 +
5 +
Terminal-independent primitives for immediate-mode terminal UI.
6 +
7 +
`rustik-tui-core` provides the shared data model and rendering types used by the
8 +
workspace:
9 +
10 +
* Styled buffers and cells
11 +
* Labels and text
12 +
* Layout and constraints
13 +
* Widget sizing and render traits
14 +
* App/runtime and backend traits
15 +
16 +
No extra runtime dependencies.
17 +
18 +
```toml
19 +
[dependencies]
20 +
rustik-tui-core = "0.1.0"
21 +
```
22 +
23 +
## License
24 +
25 +
MIT. See [LICENSE](../../LICENSE).
crates/tui-core/src/aligned.rs added +84 -0
1 +
//! Widget wrapper for horizontal alignment.
2 +
//!
3 +
//! `Aligned` lets a child render left, centered, or right inside a wider
4 +
//! rectangle without changing the child widget itself. It is useful for small
5 +
//! layout adjustments at the edge of a composed view.
6 +
7 +
use super::{Buffer, Constraint, Rect, Size, Widget};
8 +
9 +
/// Horizontal alignment for a widget inside an allocated width.
10 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
11 +
pub enum Align {
12 +
    /// Keep content at the left edge.
13 +
    Left,
14 +
    /// Keep content at the right edge.
15 +
    Right,
16 +
}
17 +
18 +
/// Widget wrapper that aligns its child within the parent width.
19 +
#[derive(Debug)]
20 +
pub struct Aligned<T> {
21 +
    /// Wrapped widget.
22 +
    child: T,
23 +
    /// Horizontal alignment mode.
24 +
    align: Align,
25 +
}
26 +
27 +
impl<T> Aligned<T> {
28 +
    /// Creates an aligned wrapper around a child widget.
29 +
    pub fn new(child: T, align: Align) -> Self {
30 +
        Self { child, align }
31 +
    }
32 +
}
33 +
34 +
impl<T: Widget> Widget for Aligned<T> {
35 +
    fn size(&self, parent: Constraint) -> Size {
36 +
        let child = self.child.size(parent);
37 +
        let cols = if parent.max.cols == usize::MAX {
38 +
            child.cols
39 +
        } else {
40 +
            parent.max.cols.max(child.cols)
41 +
        };
42 +
        Size::new(cols, child.rows).constrain(parent)
43 +
    }
44 +
45 +
    fn render(&self, area: Rect, buf: &mut Buffer) {
46 +
        let child = self.child.size(Constraint::max(area.size()));
47 +
        let cols = child.cols.min(area.cols);
48 +
        let x = match self.align {
49 +
            Align::Left => area.x,
50 +
            Align::Right => area.x + area.cols.saturating_sub(cols),
51 +
        }
52 +
        .min(area.right());
53 +
54 +
        self.child
55 +
            .render(Rect::new(x, area.y, cols, area.rows), buf);
56 +
    }
57 +
}
58 +
59 +
#[cfg(test)]
60 +
mod tests {
61 +
    use super::*;
62 +
    use crate::Line;
63 +
64 +
    #[test]
65 +
    fn left_alignment_pads_to_parent_width() {
66 +
        let aligned = Aligned::new(Line::new("cat"), Align::Left);
67 +
68 +
        assert_eq!(aligned.display(Constraint::tight(6)), "cat   \n");
69 +
    }
70 +
71 +
    #[test]
72 +
    fn right_alignment_pads_before_content() {
73 +
        let aligned = Aligned::new(Line::new("cat"), Align::Right);
74 +
75 +
        assert_eq!(aligned.display(Constraint::tight(6)), "   cat\n");
76 +
    }
77 +
78 +
    #[test]
79 +
    fn alignment_truncates_content_to_allocated_width() {
80 +
        let aligned = Aligned::new(Line::new("abcdef"), Align::Left);
81 +
82 +
        assert_eq!(aligned.display(Constraint::tight(4)), "abc…\n");
83 +
    }
84 +
}
crates/tui-core/src/ansi.rs added +21 -0
1 +
//! ANSI color, style, and painted-display support.
2 +
//!
3 +
//! The rest of the crate stores style as data and only turns it into escape
4 +
//! sequences at explicit formatting boundaries. This module is derived from
5 +
//! the `yansi` crate.
6 +
//! Copyright (c) 2017 Sergio Benitez
7 +
//!
8 +
/// ANSI color type.
9 +
mod color;
10 +
/// Styled display wrapper.
11 +
mod paint;
12 +
/// ANSI style properties.
13 +
mod style;
14 +
15 +
pub use color::Color;
16 +
pub use paint::Filled;
17 +
pub use paint::Paint;
18 +
pub use paint::PaintMode;
19 +
pub use paint::Painted;
20 +
pub use paint::paint;
21 +
pub use style::Style;
crates/tui-core/src/ansi/color.rs added +104 -0
1 +
//! ANSI color code formatting.
2 +
//!
3 +
//! `Color` captures unset, indexed, fixed-palette, and RGB colors and knows how
4 +
//! to write the corresponding ANSI foreground/background parameters. Higher
5 +
//! layers store colors in styles and leave escape generation here.
6 +
7 +
use std::fmt;
8 +
9 +
use super::{Paint, Style};
10 +
11 +
/// An enum representing an ANSI color code.
12 +
#[derive(Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash, Copy, Clone)]
13 +
pub enum Color {
14 +
    /// No color has been set. Nothing is changed when applied.
15 +
    #[default]
16 +
    Unset,
17 +
    /// Black #0 (foreground code `30`, background code `40`).
18 +
    Black,
19 +
    /// Red: #1 (foreground code `31`, background code `41`).
20 +
    Red,
21 +
    /// Green: #2 (foreground code `32`, background code `42`).
22 +
    Green,
23 +
    /// Yellow: #3 (foreground code `33`, background code `43`).
24 +
    Yellow,
25 +
    /// Blue: #4 (foreground code `34`, background code `44`).
26 +
    Blue,
27 +
    /// Magenta: #5 (foreground code `35`, background code `45`).
28 +
    Magenta,
29 +
    /// Cyan: #6 (foreground code `36`, background code `46`).
30 +
    Cyan,
31 +
    /// White: #7 (foreground code `37`, background code `47`).
32 +
    White,
33 +
    /// A color number from 0 to 255, for use in 256-color terminals.
34 +
    Fixed(u8),
35 +
    /// A 24-bit RGB color, as specified by ISO-8613-3.
36 +
    RGB(u8, u8, u8),
37 +
}
38 +
39 +
impl Color {
40 +
    /// Constructs a new `Paint` structure that encapsulates `item` with the
41 +
    /// foreground color set to the color `self`.
42 +
    #[inline]
43 +
    pub fn paint<T>(self, item: T) -> Paint<T> {
44 +
        Paint::new(item).fg(self)
45 +
    }
46 +
47 +
    /// Constructs a new `Style` structure with the foreground color set to the
48 +
    /// color `self`.
49 +
    #[inline]
50 +
    pub const fn style(self) -> Style {
51 +
        Style::new(self)
52 +
    }
53 +
54 +
    pub(crate) fn ansi_fmt(&self, f: &mut dyn fmt::Write) -> fmt::Result {
55 +
        match *self {
56 +
            Color::Unset => Ok(()),
57 +
            Color::Black => write!(f, "0"),
58 +
            Color::Red => write!(f, "1"),
59 +
            Color::Green => write!(f, "2"),
60 +
            Color::Yellow => write!(f, "3"),
61 +
            Color::Blue => write!(f, "4"),
62 +
            Color::Magenta => write!(f, "5"),
63 +
            Color::Cyan => write!(f, "6"),
64 +
            Color::White => write!(f, "7"),
65 +
            Color::Fixed(num) => write!(f, "8;5;{num}"),
66 +
            Color::RGB(r, g, b) => write!(f, "8;2;{r};{g};{b}"),
67 +
        }
68 +
    }
69 +
}
70 +
71 +
#[cfg(test)]
72 +
#[allow(clippy::unwrap_used)]
73 +
mod tests {
74 +
    use super::*;
75 +
76 +
    fn ansi(color: Color) -> String {
77 +
        let mut out = String::new();
78 +
        color.ansi_fmt(&mut out).unwrap();
79 +
        out
80 +
    }
81 +
82 +
    #[test]
83 +
    fn unset_color_writes_no_ansi_code() {
84 +
        assert_eq!(ansi(Color::Unset), "");
85 +
    }
86 +
87 +
    #[test]
88 +
    fn basic_colors_write_ansi_indexes() {
89 +
        assert_eq!(ansi(Color::Black), "0");
90 +
        assert_eq!(ansi(Color::Red), "1");
91 +
        assert_eq!(ansi(Color::Green), "2");
92 +
        assert_eq!(ansi(Color::Yellow), "3");
93 +
        assert_eq!(ansi(Color::Blue), "4");
94 +
        assert_eq!(ansi(Color::Magenta), "5");
95 +
        assert_eq!(ansi(Color::Cyan), "6");
96 +
        assert_eq!(ansi(Color::White), "7");
97 +
    }
98 +
99 +
    #[test]
100 +
    fn extended_colors_write_ansi_parameters() {
101 +
        assert_eq!(ansi(Color::Fixed(236)), "8;5;236");
102 +
        assert_eq!(ansi(Color::RGB(1, 2, 3)), "8;2;1;2;3");
103 +
    }
104 +
}
crates/tui-core/src/ansi/paint.rs added +409 -0
1 +
//! Styled display wrappers.
2 +
//!
3 +
//! `Paint` pairs an arbitrary display value with a [`Style`](crate::Style).
4 +
//! Its display adapters can render either plain text or ANSI-styled text,
5 +
//! letting the same value be measured, buffered, or printed with explicit
6 +
//! formatting mode.
7 +
8 +
use std::fmt;
9 +
10 +
use super::color::Color;
11 +
use super::style::{Property, Style};
12 +
13 +
/// Paint formatting mode.
14 +
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
15 +
pub enum PaintMode {
16 +
    /// Write plain text with no ANSI escapes.
17 +
    #[default]
18 +
    Plain,
19 +
    /// Write ANSI escapes for the stored style.
20 +
    Styled,
21 +
}
22 +
23 +
/// A paint object paired with an explicit formatting mode.
24 +
#[derive(Debug, Clone, Copy)]
25 +
pub struct Painted<'a, T> {
26 +
    paint: &'a Paint<T>,
27 +
    mode: PaintMode,
28 +
}
29 +
30 +
/// A structure encapsulating an item and styling.
31 +
#[derive(Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash, Copy, Clone)]
32 +
pub struct Paint<T> {
33 +
    /// Wrapped display item.
34 +
    pub item: T,
35 +
    /// Style applied when the item is displayed.
36 +
    pub style: Style,
37 +
}
38 +
39 +
impl<T: AsRef<str>> Paint<T> {
40 +
    /// Return plain content.
41 +
    pub fn content(&self) -> &str {
42 +
        self.item.as_ref()
43 +
    }
44 +
}
45 +
46 +
impl<T> From<T> for Paint<T> {
47 +
    fn from(value: T) -> Self {
48 +
        Self::new(value)
49 +
    }
50 +
}
51 +
52 +
impl From<&str> for Paint<String> {
53 +
    fn from(item: &str) -> Self {
54 +
        Self::new(item.to_string())
55 +
    }
56 +
}
57 +
58 +
impl From<Paint<&str>> for Paint<String> {
59 +
    fn from(paint: Paint<&str>) -> Self {
60 +
        Self {
61 +
            item: paint.item.to_owned(),
62 +
            style: paint.style,
63 +
        }
64 +
    }
65 +
}
66 +
67 +
impl From<Paint<String>> for String {
68 +
    fn from(value: Paint<String>) -> Self {
69 +
        value.item
70 +
    }
71 +
}
72 +
73 +
impl<T> Paint<T> {
74 +
    /// Constructs a new `Paint` structure encapsulating `item` with no set
75 +
    /// styling.
76 +
    #[inline]
77 +
    pub const fn new(item: T) -> Paint<T> {
78 +
        Paint {
79 +
            item,
80 +
            style: Style {
81 +
                foreground: Color::Unset,
82 +
                background: Color::Unset,
83 +
                properties: Property::new(),
84 +
                wrap: false,
85 +
            },
86 +
        }
87 +
    }
88 +
89 +
    /// Constructs a new _wrapping_ `Paint` structure encapsulating `item` with
90 +
    /// default styling.
91 +
    ///
92 +
    /// A wrapping `Paint` converts all color resets written out by the internal
93 +
    /// value to the styling of itself. This allows for seamless color wrapping
94 +
    /// of other colored text.
95 +
    ///
96 +
    /// # Performance
97 +
    ///
98 +
    /// In order to wrap an internal value, the internal value must first be
99 +
    /// written out to a local buffer and examined. As a result, displaying a
100 +
    /// wrapped value is likely to result in a heap allocation and copy.
101 +
    #[inline]
102 +
    pub const fn wrapping(item: T) -> Paint<T> {
103 +
        Paint::new(item).wrap()
104 +
    }
105 +
106 +
    /// Constructs a new `Paint` structure encapsulating `item` with the
107 +
    /// foreground color set to the RGB color `r`, `g`, `b`.
108 +
    #[inline]
109 +
    pub const fn rgb(r: u8, g: u8, b: u8, item: T) -> Paint<T> {
110 +
        Paint::new(item).fg(Color::RGB(r, g, b))
111 +
    }
112 +
113 +
    /// Constructs a new `Paint` structure encapsulating `item` with the
114 +
    /// foreground color set to the fixed 8-bit color `color`.
115 +
    #[inline]
116 +
    pub const fn fixed(color: u8, item: T) -> Paint<T> {
117 +
        Paint::new(item).fg(Color::Fixed(color))
118 +
    }
119 +
120 +
    /// Constructs red foreground text.
121 +
    pub const fn red(item: T) -> Paint<T> {
122 +
        Paint::new(item).fg(Color::Red)
123 +
    }
124 +
125 +
    /// Constructs black foreground text.
126 +
    pub const fn black(item: T) -> Paint<T> {
127 +
        Paint::new(item).fg(Color::Black)
128 +
    }
129 +
130 +
    /// Constructs yellow foreground text.
131 +
    pub const fn yellow(item: T) -> Paint<T> {
132 +
        Paint::new(item).fg(Color::Yellow)
133 +
    }
134 +
135 +
    /// Constructs green foreground text.
136 +
    pub const fn green(item: T) -> Paint<T> {
137 +
        Paint::new(item).fg(Color::Green)
138 +
    }
139 +
140 +
    /// Constructs cyan foreground text.
141 +
    pub const fn cyan(item: T) -> Paint<T> {
142 +
        Paint::new(item).fg(Color::Cyan)
143 +
    }
144 +
145 +
    /// Constructs blue foreground text.
146 +
    pub const fn blue(item: T) -> Paint<T> {
147 +
        Paint::new(item).fg(Color::Blue)
148 +
    }
149 +
150 +
    /// Constructs magenta foreground text.
151 +
    pub const fn magenta(item: T) -> Paint<T> {
152 +
        Paint::new(item).fg(Color::Magenta)
153 +
    }
154 +
155 +
    /// Constructs white foreground text.
156 +
    pub const fn white(item: T) -> Paint<T> {
157 +
        Paint::new(item).fg(Color::White)
158 +
    }
159 +
160 +
    /// Retrieves the style currently set on `self`.
161 +
    #[inline]
162 +
    pub const fn style(&self) -> Style {
163 +
        self.style
164 +
    }
165 +
166 +
    /// Retrieves a borrow to the inner item.
167 +
    #[inline]
168 +
    pub const fn inner(&self) -> &T {
169 +
        &self.item
170 +
    }
171 +
172 +
    /// Sets the style of `self` to `style`.
173 +
    #[inline]
174 +
    pub fn with_style(mut self, style: Style) -> Paint<T> {
175 +
        self.style = style;
176 +
        self
177 +
    }
178 +
179 +
    /// Makes `self` a _wrapping_ `Paint`.
180 +
    ///
181 +
    /// A wrapping `Paint` converts all color resets written out by the internal
182 +
    /// value to the styling of itself. This allows for seamless color wrapping
183 +
    /// of other colored text.
184 +
    ///
185 +
    /// # Performance
186 +
    ///
187 +
    /// In order to wrap an internal value, the internal value must first be
188 +
    /// written out to a local buffer and examined. As a result, displaying a
189 +
    /// wrapped value is likely to result in a heap allocation and copy.
190 +
    #[inline]
191 +
    pub const fn wrap(mut self) -> Paint<T> {
192 +
        self.style.wrap = true;
193 +
        self
194 +
    }
195 +
196 +
    /// Sets the foreground to `color`.
197 +
    #[inline]
198 +
    pub const fn fg(mut self, color: Color) -> Paint<T> {
199 +
        self.style.foreground = color;
200 +
        self
201 +
    }
202 +
203 +
    /// Sets the background to `color`.
204 +
    #[inline]
205 +
    pub const fn bg(mut self, color: Color) -> Paint<T> {
206 +
        self.style.background = color;
207 +
        self
208 +
    }
209 +
210 +
    /// Adds bold styling.
211 +
    pub fn bold(mut self) -> Self {
212 +
        self.style.properties.set(Property::BOLD);
213 +
        self
214 +
    }
215 +
216 +
    /// Adds dim styling.
217 +
    pub fn dim(mut self) -> Self {
218 +
        self.style.properties.set(Property::DIM);
219 +
        self
220 +
    }
221 +
222 +
    /// Adds italic styling.
223 +
    pub fn italic(mut self) -> Self {
224 +
        self.style.properties.set(Property::ITALIC);
225 +
        self
226 +
    }
227 +
228 +
    /// Adds underline styling.
229 +
    pub fn underline(mut self) -> Self {
230 +
        self.style.properties.set(Property::UNDERLINE);
231 +
        self
232 +
    }
233 +
234 +
    /// Adds inverse-video styling.
235 +
    pub fn invert(mut self) -> Self {
236 +
        self.style.properties.set(Property::INVERT);
237 +
        self
238 +
    }
239 +
240 +
    /// Adds strikethrough styling.
241 +
    pub fn strikethrough(mut self) -> Self {
242 +
        self.style.properties.set(Property::STRIKETHROUGH);
243 +
        self
244 +
    }
245 +
246 +
    /// Adds blink styling.
247 +
    pub fn blink(mut self) -> Self {
248 +
        self.style.properties.set(Property::BLINK);
249 +
        self
250 +
    }
251 +
252 +
    /// Adds hidden styling.
253 +
    pub fn hidden(mut self) -> Self {
254 +
        self.style.properties.set(Property::HIDDEN);
255 +
        self
256 +
    }
257 +
258 +
    /// Return a display adapter using `mode`.
259 +
    pub const fn rendered(&self, mode: PaintMode) -> Painted<'_, T> {
260 +
        Painted { paint: self, mode }
261 +
    }
262 +
263 +
    /// Return a display adapter that writes styled text.
264 +
    pub const fn styled(&self) -> Painted<'_, T> {
265 +
        self.rendered(PaintMode::Styled)
266 +
    }
267 +
268 +
    /// Return a display adapter that writes plain text.
269 +
    pub const fn plain(&self) -> Painted<'_, T> {
270 +
        self.rendered(PaintMode::Plain)
271 +
    }
272 +
}
273 +
274 +
impl<T: fmt::Display> fmt::Display for Paint<T> {
275 +
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
276 +
        fmt::Display::fmt(&self.item, f)
277 +
    }
278 +
}
279 +
280 +
impl<T: fmt::Display> fmt::Display for Painted<'_, T> {
281 +
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
282 +
        match self.mode {
283 +
            PaintMode::Plain => fmt::Display::fmt(&self.paint.item, f),
284 +
            PaintMode::Styled => self.paint.fmt_ansi(f),
285 +
        }
286 +
    }
287 +
}
288 +
289 +
impl<T: fmt::Display> Paint<T> {
290 +
    /// Write the item with ANSI styling.
291 +
    pub fn fmt_ansi(&self, f: &mut dyn fmt::Write) -> fmt::Result {
292 +
        if self.style.wrap {
293 +
            let mut prefix = String::new();
294 +
            prefix.push_str("\x1B[0m");
295 +
            self.style.fmt_prefix(&mut prefix)?;
296 +
            self.style.fmt_prefix(f)?;
297 +
298 +
            let item = format!("{}", &self.item).replace("\x1B[0m", &prefix);
299 +
            write!(f, "{item}")?;
300 +
            self.style.fmt_suffix(f)
301 +
        } else {
302 +
            self.style.fmt_prefix(f)?;
303 +
            write!(f, "{}", &self.item)?;
304 +
            self.style.fmt_suffix(f)
305 +
        }
306 +
    }
307 +
}
308 +
309 +
impl Paint<()> {
310 +
    /// Check 24-bit RGB color support.
311 +
    pub fn truecolor() -> bool {
312 +
        std::env::var("COLORTERM").is_ok_and(|term| term.eq_ignore_ascii_case("truecolor"))
313 +
    }
314 +
}
315 +
316 +
/// An object filled with a background color.
317 +
#[derive(Debug, Clone)]
318 +
pub struct Filled<T> {
319 +
    /// Wrapped display item.
320 +
    pub item: T,
321 +
    /// Background fill color.
322 +
    pub color: Color,
323 +
}
324 +
325 +
impl<T: fmt::Display> fmt::Display for Filled<T> {
326 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
327 +
        write!(f, "{}", Paint::wrapping(&self.item).bg(self.color))
328 +
    }
329 +
}
330 +
331 +
/// Shorthand for [`Paint::new`].
332 +
pub fn paint<T>(item: T) -> Paint<T> {
333 +
    Paint::new(item)
334 +
}
335 +
336 +
#[cfg(test)]
337 +
mod tests {
338 +
    use super::*;
339 +
340 +
    #[test]
341 +
    fn paint_constructors_set_expected_colors() {
342 +
        assert_eq!(Paint::red("x").style().fg_color(), Color::Red);
343 +
        assert_eq!(Paint::black("x").style().fg_color(), Color::Black);
344 +
        assert_eq!(Paint::yellow("x").style().fg_color(), Color::Yellow);
345 +
        assert_eq!(Paint::green("x").style().fg_color(), Color::Green);
346 +
        assert_eq!(Paint::cyan("x").style().fg_color(), Color::Cyan);
347 +
        assert_eq!(Paint::blue("x").style().fg_color(), Color::Blue);
348 +
        assert_eq!(Paint::magenta("x").style().fg_color(), Color::Magenta);
349 +
        assert_eq!(Paint::white("x").style().fg_color(), Color::White);
350 +
        assert_eq!(Paint::fixed(42, "x").style().fg_color(), Color::Fixed(42));
351 +
        assert_eq!(
352 +
            Paint::rgb(1, 2, 3, "x").style().fg_color(),
353 +
            Color::RGB(1, 2, 3)
354 +
        );
355 +
    }
356 +
357 +
    #[test]
358 +
    fn paint_records_background_and_wrapping() {
359 +
        let paint = Paint::wrapping("x").bg(Color::Blue);
360 +
361 +
        assert_eq!(paint.style().bg_color(), Color::Blue);
362 +
        assert!(paint.style().is_wrapping());
363 +
    }
364 +
365 +
    #[test]
366 +
    fn paint_from_conversions_preserve_content_and_style() {
367 +
        let borrowed = Paint::red("content");
368 +
        let owned = Paint::<String>::from(borrowed);
369 +
370 +
        assert_eq!(owned.content(), "content");
371 +
        assert_eq!(owned.style().fg_color(), Color::Red);
372 +
        assert_eq!(String::from(owned), "content");
373 +
        assert_eq!(Paint::<String>::from("other").content(), "other");
374 +
    }
375 +
376 +
    #[test]
377 +
    fn display_is_plain_and_styled_adapter_is_explicit() {
378 +
        let paint = Paint::red("content");
379 +
380 +
        assert_eq!(paint.to_string(), "content");
381 +
        assert_eq!(paint.plain().to_string(), "content");
382 +
        assert_eq!(paint.styled().to_string(), "\x1B[31mcontent\x1B[0m");
383 +
        assert_eq!(
384 +
            paint.rendered(PaintMode::Styled).to_string(),
385 +
            "\x1B[31mcontent\x1B[0m"
386 +
        );
387 +
    }
388 +
389 +
    #[test]
390 +
    fn styled_adapter_reapplies_wrapping_style_after_reset() {
391 +
        let paint = Paint::wrapping("a\x1B[0mb").fg(Color::Red);
392 +
393 +
        assert_eq!(
394 +
            paint.styled().to_string(),
395 +
            "\x1B[31ma\x1B[0m\x1B[31mb\x1B[0m"
396 +
        );
397 +
    }
398 +
399 +
    #[test]
400 +
    fn filled_records_item_and_background_color() {
401 +
        let filled = Filled {
402 +
            item: "x",
403 +
            color: Color::Red,
404 +
        };
405 +
406 +
        assert_eq!(filled.item, "x");
407 +
        assert_eq!(filled.color, Color::Red);
408 +
    }
409 +
}
crates/tui-core/src/ansi/style.rs added +352 -0
1 +
//! ANSI style properties.
2 +
//!
3 +
//! `Style` records foreground/background colors and text attributes such as
4 +
//! bold or italic. It is a value type shared by cells, labels, borders, and
5 +
//! painted display wrappers.
6 +
7 +
use std::fmt::{self, Display};
8 +
use std::hash::{Hash, Hasher};
9 +
use std::ops::BitOr;
10 +
11 +
use super::{Color, Paint};
12 +
13 +
/// Bitset of ANSI text style properties.
14 +
#[derive(Default, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Copy, Clone)]
15 +
pub struct Property(u8);
16 +
17 +
impl Property {
18 +
    /// Bold text property.
19 +
    pub const BOLD: Self = Property(1 << 0);
20 +
    /// Dim text property.
21 +
    pub const DIM: Self = Property(1 << 1);
22 +
    /// Italic text property.
23 +
    pub const ITALIC: Self = Property(1 << 2);
24 +
    /// Underlined text property.
25 +
    pub const UNDERLINE: Self = Property(1 << 3);
26 +
    /// Blinking text property.
27 +
    pub const BLINK: Self = Property(1 << 4);
28 +
    /// Inverse-video text property.
29 +
    pub const INVERT: Self = Property(1 << 5);
30 +
    /// Hidden text property.
31 +
    pub const HIDDEN: Self = Property(1 << 6);
32 +
    /// Strikethrough text property.
33 +
    pub const STRIKETHROUGH: Self = Property(1 << 7);
34 +
35 +
    /// Returns an empty property set.
36 +
    pub const fn new() -> Self {
37 +
        Property(0)
38 +
    }
39 +
40 +
    /// Returns whether all bits in `other` are set.
41 +
    pub const fn contains(self, other: Property) -> bool {
42 +
        (other.0 & self.0) == other.0
43 +
    }
44 +
45 +
    /// Adds all bits from `other`.
46 +
    #[inline(always)]
47 +
    pub fn set(&mut self, other: Property) {
48 +
        self.0 |= other.0;
49 +
    }
50 +
51 +
    /// Iterates over enabled ANSI property indexes.
52 +
    #[inline(always)]
53 +
    pub fn iter(self) -> Iter {
54 +
        Iter {
55 +
            index: 0,
56 +
            properties: self,
57 +
        }
58 +
    }
59 +
}
60 +
61 +
impl BitOr for Property {
62 +
    type Output = Self;
63 +
64 +
    #[inline(always)]
65 +
    fn bitor(self, rhs: Self) -> Self {
66 +
        Property(self.0 | rhs.0)
67 +
    }
68 +
}
69 +
70 +
/// Iterator over enabled ANSI property indexes.
71 +
pub struct Iter {
72 +
    /// Next bit index to inspect.
73 +
    index: u8,
74 +
    /// Properties being iterated.
75 +
    properties: Property,
76 +
}
77 +
78 +
impl Iterator for Iter {
79 +
    type Item = usize;
80 +
81 +
    fn next(&mut self) -> Option<Self::Item> {
82 +
        while self.index < 8 {
83 +
            let index = self.index;
84 +
            self.index += 1;
85 +
86 +
            if self.properties.contains(Property(1 << index)) {
87 +
                return Some(index as usize);
88 +
            }
89 +
        }
90 +
        None
91 +
    }
92 +
}
93 +
94 +
/// Represents a set of styling options.
95 +
#[repr(C, packed)]
96 +
#[derive(Default, Debug, Eq, Ord, PartialOrd, Copy, Clone)]
97 +
pub struct Style {
98 +
    pub(crate) foreground: Color,
99 +
    pub(crate) background: Color,
100 +
    pub(crate) properties: Property,
101 +
    pub(crate) wrap: bool,
102 +
}
103 +
104 +
impl PartialEq for Style {
105 +
    fn eq(&self, other: &Style) -> bool {
106 +
        self.foreground == other.foreground
107 +
            && self.background == other.background
108 +
            && self.properties == other.properties
109 +
    }
110 +
}
111 +
112 +
impl Hash for Style {
113 +
    fn hash<H: Hasher>(&self, state: &mut H) {
114 +
        self.foreground.hash(state);
115 +
        self.background.hash(state);
116 +
        self.properties.hash(state);
117 +
    }
118 +
}
119 +
120 +
impl Style {
121 +
    /// Default style with the foreground set to `color` and no other set
122 +
    /// properties.
123 +
    pub const fn new(color: Color) -> Style {
124 +
        Self {
125 +
            foreground: color,
126 +
            background: Color::Unset,
127 +
            properties: Property::new(),
128 +
            wrap: false,
129 +
        }
130 +
    }
131 +
132 +
    /// Sets the foreground to `color`.
133 +
    pub const fn fg(mut self, color: Color) -> Style {
134 +
        self.foreground = color;
135 +
        self
136 +
    }
137 +
138 +
    /// Sets the background to `color`.
139 +
    pub const fn bg(mut self, color: Color) -> Style {
140 +
        self.background = color;
141 +
        self
142 +
    }
143 +
144 +
    /// Merge styles with other. This is an additive process, so colors will only
145 +
    /// be changed if they aren't set on the receiver object.
146 +
    pub fn merge(mut self, other: Style) -> Style {
147 +
        if self.foreground == Color::Unset {
148 +
            self.foreground = other.foreground;
149 +
        }
150 +
        if self.background == Color::Unset {
151 +
            self.background = other.background;
152 +
        }
153 +
        self.properties.set(other.properties);
154 +
        self
155 +
    }
156 +
157 +
    /// Sets `self` to be wrapping.
158 +
    ///
159 +
    /// A wrapping `Style` converts all color resets written out by the internal
160 +
    /// value to the styling of itself. This allows for seamless color wrapping
161 +
    /// of other colored text.
162 +
    pub const fn wrap(mut self) -> Style {
163 +
        self.wrap = true;
164 +
        self
165 +
    }
166 +
167 +
    /// Adds bold styling.
168 +
    pub fn bold(mut self) -> Self {
169 +
        self.properties.set(Property::BOLD);
170 +
        self
171 +
    }
172 +
173 +
    /// Adds dim styling.
174 +
    pub fn dim(mut self) -> Self {
175 +
        self.properties.set(Property::DIM);
176 +
        self
177 +
    }
178 +
179 +
    /// Adds italic styling.
180 +
    pub fn italic(mut self) -> Self {
181 +
        self.properties.set(Property::ITALIC);
182 +
        self
183 +
    }
184 +
185 +
    /// Adds underline styling.
186 +
    pub fn underline(mut self) -> Self {
187 +
        self.properties.set(Property::UNDERLINE);
188 +
        self
189 +
    }
190 +
191 +
    /// Adds inverse-video styling.
192 +
    pub fn invert(mut self) -> Self {
193 +
        self.properties.set(Property::INVERT);
194 +
        self
195 +
    }
196 +
197 +
    /// Adds strikethrough styling.
198 +
    pub fn strikethrough(mut self) -> Self {
199 +
        self.properties.set(Property::STRIKETHROUGH);
200 +
        self
201 +
    }
202 +
203 +
    /// Constructs a new `Paint` structure that encapsulates `item` with the
204 +
    /// style set to `self`.
205 +
    pub fn paint<T>(self, item: T) -> Paint<T> {
206 +
        Paint::new(item).with_style(self)
207 +
    }
208 +
209 +
    /// Returns the foreground color of `self`.
210 +
    pub const fn fg_color(&self) -> Color {
211 +
        self.foreground
212 +
    }
213 +
214 +
    /// Returns the foreground color of `self`.
215 +
    pub const fn bg_color(&self) -> Color {
216 +
        self.background
217 +
    }
218 +
219 +
    /// Returns `true` if `self` is wrapping.
220 +
    pub const fn is_wrapping(&self) -> bool {
221 +
        self.wrap
222 +
    }
223 +
224 +
    /// Returns whether the style has no visible properties.
225 +
    #[inline(always)]
226 +
    fn is_plain(&self) -> bool {
227 +
        self == &Style::default()
228 +
    }
229 +
230 +
    /// Writes the ANSI code prefix for the currently set styles.
231 +
    ///
232 +
    /// This method is intended to be used inside of [`fmt::Display`] and
233 +
    /// [`fmt::Debug`] implementations for custom or specialized use-cases. Most
234 +
    /// users should use [`Paint`] for all painting needs.
235 +
    ///
236 +
    /// This method writes the ANSI code prefix for non-plain styles. Most
237 +
    /// callers should use [`Paint::styled`] instead.
238 +
    pub fn fmt_prefix(&self, f: &mut dyn fmt::Write) -> fmt::Result {
239 +
        // A user may just want a code-free string when no styles are applied.
240 +
        if self.is_plain() {
241 +
            return Ok(());
242 +
        }
243 +
        let mut splice = false;
244 +
        write!(f, "\x1B[")?;
245 +
246 +
        for i in self.properties.iter() {
247 +
            let k = if i >= 5 { i + 2 } else { i + 1 };
248 +
            write_spliced(&mut splice, f, k)?;
249 +
        }
250 +
        if self.background != Color::Unset {
251 +
            write_spliced(&mut splice, f, "4")?;
252 +
            self.background.ansi_fmt(f)?;
253 +
        }
254 +
        if self.foreground != Color::Unset {
255 +
            write_spliced(&mut splice, f, "3")?;
256 +
            self.foreground.ansi_fmt(f)?;
257 +
        }
258 +
        // All the codes end with an `m`.
259 +
        write!(f, "m")
260 +
    }
261 +
262 +
    /// Writes the ANSI code suffix for the currently set styles.
263 +
    ///
264 +
    /// This method is intended to be used inside of [`fmt::Display`] and
265 +
    /// [`fmt::Debug`] implementations for custom or specialized use-cases. Most
266 +
    /// users should use [`Paint`] for all painting needs.
267 +
    ///
268 +
    /// This method writes the ANSI code suffix for non-plain styles. Most
269 +
    /// callers should use [`Paint::styled`] instead.
270 +
    pub fn fmt_suffix(&self, f: &mut dyn fmt::Write) -> fmt::Result {
271 +
        if self.is_plain() {
272 +
            return Ok(());
273 +
        }
274 +
        write!(f, "\x1B[0m")
275 +
    }
276 +
}
277 +
278 +
/// Writes an ANSI parameter, inserting a separator after the first one.
279 +
#[inline]
280 +
fn write_spliced<T: Display>(c: &mut bool, f: &mut dyn fmt::Write, t: T) -> fmt::Result {
281 +
    if *c {
282 +
        write!(f, ";{t}")
283 +
    } else {
284 +
        *c = true;
285 +
        write!(f, "{t}")
286 +
    }
287 +
}
288 +
289 +
#[cfg(test)]
290 +
#[allow(clippy::unwrap_used)]
291 +
mod tests {
292 +
    use super::*;
293 +
294 +
    fn prefix(style: Style) -> String {
295 +
        let mut out = String::new();
296 +
        style.fmt_prefix(&mut out).unwrap();
297 +
        out
298 +
    }
299 +
300 +
    fn suffix(style: Style) -> String {
301 +
        let mut out = String::new();
302 +
        style.fmt_suffix(&mut out).unwrap();
303 +
        out
304 +
    }
305 +
306 +
    #[test]
307 +
    fn property_iteration_yields_enabled_indexes() {
308 +
        let properties = Property::BOLD | Property::UNDERLINE | Property::STRIKETHROUGH;
309 +
310 +
        assert_eq!(properties.iter().collect::<Vec<_>>(), vec![0, 3, 7]);
311 +
    }
312 +
313 +
    #[test]
314 +
    fn style_merge_keeps_receiver_colors_and_adds_properties() {
315 +
        let style = Style::new(Color::Red)
316 +
            .bg(Color::Blue)
317 +
            .bold()
318 +
            .merge(Style::new(Color::Green).bg(Color::Yellow).underline());
319 +
320 +
        assert_eq!(style.fg_color(), Color::Red);
321 +
        assert_eq!(style.bg_color(), Color::Blue);
322 +
        assert!(style.properties.contains(Property::BOLD));
323 +
        assert!(style.properties.contains(Property::UNDERLINE));
324 +
    }
325 +
326 +
    #[test]
327 +
    fn plain_style_writes_no_ansi_codes() {
328 +
        let style = Style::default();
329 +
330 +
        assert_eq!(prefix(style), "");
331 +
        assert_eq!(suffix(style), "");
332 +
    }
333 +
334 +
    #[test]
335 +
    fn style_prefix_splices_properties_background_and_foreground() {
336 +
        let style = Style::new(Color::Fixed(42))
337 +
            .bg(Color::RGB(1, 2, 3))
338 +
            .bold()
339 +
            .italic()
340 +
            .underline()
341 +
            .invert()
342 +
            .strikethrough();
343 +
344 +
        assert_eq!(prefix(style), "\x1B[1;3;4;7;9;48;2;1;2;3;38;5;42m");
345 +
        assert_eq!(suffix(style), "\x1B[0m");
346 +
    }
347 +
348 +
    #[test]
349 +
    fn wrapping_flag_is_recorded() {
350 +
        assert!(Style::new(Color::Red).wrap().is_wrapping());
351 +
    }
352 +
}
crates/tui-core/src/app.rs added +152 -0
1 +
//! Application update loop contracts.
2 +
//!
3 +
//! Apps own their state and describe how typed input events change that state.
4 +
//! The runner in this module is intentionally small: it routes events into an
5 +
//! [`App`], renders when requested, and leaves terminal I/O to the backend
6 +
//! layer.
7 +
8 +
use crate::backend::Backend;
9 +
use crate::event::Event;
10 +
use crate::{Frame, Terminal};
11 +
12 +
/// Application-owned state machine.
13 +
pub trait App {
14 +
    /// User-defined event payload.
15 +
    type Event;
16 +
17 +
    /// Updates application state from an event.
18 +
    fn update(&mut self, event: Event<Self::Event>) -> Control;
19 +
20 +
    /// Renders application state.
21 +
    fn render(&self, frame: &mut Frame<'_>);
22 +
}
23 +
24 +
/// Control returned by [`App::update`].
25 +
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
26 +
pub enum Control {
27 +
    /// Continue without forcing a redraw.
28 +
    Continue,
29 +
    /// Continue and redraw.
30 +
    Redraw,
31 +
    /// Continue and wait for another event.
32 +
    Wait,
33 +
    /// Exit the runner.
34 +
    Quit,
35 +
}
36 +
37 +
/// Drives an app with synthetic events.
38 +
pub fn drive<A, B, I>(
39 +
    app: &mut A,
40 +
    terminal: &mut Terminal<B>,
41 +
    events: I,
42 +
) -> Result<Control, B::Error>
43 +
where
44 +
    A: App,
45 +
    B: Backend,
46 +
    I: IntoIterator<Item = Event<A::Event>>,
47 +
{
48 +
    terminal.draw(|frame| app.render(frame))?;
49 +
50 +
    for event in events {
51 +
        match app.update(event) {
52 +
            Control::Continue | Control::Wait => {}
53 +
            Control::Redraw => terminal.draw(|frame| app.render(frame))?,
54 +
            Control::Quit => return Ok(Control::Quit),
55 +
        }
56 +
    }
57 +
    Ok(Control::Continue)
58 +
}
59 +
60 +
#[cfg(test)]
61 +
mod tests {
62 +
    use super::*;
63 +
    use crate::{Key, Label, Paint, Size, TestBackend};
64 +
65 +
    #[derive(Default)]
66 +
    struct Counter {
67 +
        value: usize,
68 +
    }
69 +
70 +
    impl App for Counter {
71 +
        type Event = ();
72 +
73 +
        fn update(&mut self, event: Event<Self::Event>) -> Control {
74 +
            match event {
75 +
                Event::Key(Key::Char('+')) => {
76 +
                    self.value += 1;
77 +
                    Control::Redraw
78 +
                }
79 +
                Event::Key(Key::Esc) => Control::Quit,
80 +
                _ => Control::Continue,
81 +
            }
82 +
        }
83 +
84 +
        fn render(&self, frame: &mut Frame<'_>) {
85 +
            frame.render_widget(Label::from(Paint::new(self.value)), frame.area);
86 +
        }
87 +
    }
88 +
89 +
    #[test]
90 +
    fn drive_updates_and_renders_app_state() {
91 +
        let backend = TestBackend::new(Size::new(3, 1));
92 +
        let mut terminal = Terminal::new(backend).unwrap();
93 +
        let mut app = Counter::default();
94 +
95 +
        let control = drive(
96 +
            &mut app,
97 +
            &mut terminal,
98 +
            [Event::Key(Key::Char('+')), Event::Key(Key::Esc)],
99 +
        )
100 +
        .unwrap();
101 +
102 +
        assert_eq!(control, Control::Quit);
103 +
        assert_eq!(terminal.backend().lines(), vec!["1  "]);
104 +
    }
105 +
106 +
    #[test]
107 +
    fn drive_can_deliver_synthetic_events_without_redraw() {
108 +
        #[derive(Default)]
109 +
        struct Recorder {
110 +
            events: Vec<&'static str>,
111 +
        }
112 +
113 +
        impl App for Recorder {
114 +
            type Event = &'static str;
115 +
116 +
            fn update(&mut self, event: Event<Self::Event>) -> Control {
117 +
                match event {
118 +
                    Event::Tick => self.events.push("tick"),
119 +
                    Event::Resize(_) => self.events.push("resize"),
120 +
                    Event::Paste(_) => self.events.push("paste"),
121 +
                    Event::User(value) => self.events.push(value),
122 +
                    _ => {}
123 +
                }
124 +
                Control::Wait
125 +
            }
126 +
127 +
            fn render(&self, frame: &mut Frame<'_>) {
128 +
                frame.render_widget(Label::new("r"), frame.area);
129 +
            }
130 +
        }
131 +
132 +
        let backend = TestBackend::new(Size::new(2, 1));
133 +
        let mut terminal = Terminal::new(backend).unwrap();
134 +
        let mut app = Recorder::default();
135 +
136 +
        let control = drive(
137 +
            &mut app,
138 +
            &mut terminal,
139 +
            [
140 +
                Event::Tick,
141 +
                Event::Resize(Size::new(5, 5)),
142 +
                Event::Paste(String::from("text")),
143 +
                Event::User("user"),
144 +
            ],
145 +
        )
146 +
        .unwrap();
147 +
148 +
        assert_eq!(control, Control::Continue);
149 +
        assert_eq!(app.events, vec!["tick", "resize", "paste", "user"]);
150 +
        assert_eq!(terminal.backend().lines(), vec!["r "]);
151 +
    }
152 +
}
crates/tui-core/src/backend.rs added +147 -0
1 +
//! Backend boundary for terminal output.
2 +
//!
3 +
//! Backends receive dirty [`Cell`](crate::Cell) runs, cursor updates, and clear
4 +
//! operations from [`Terminal`](crate::Terminal). The core crate keeps this
5 +
//! trait independent from any concrete terminal library so rendering can be
6 +
//! tested deterministically.
7 +
8 +
use std::convert::Infallible;
9 +
10 +
use crate::Size;
11 +
use crate::buffer::{Buffer, DirtyRun};
12 +
use crate::layout::{Point, Rect};
13 +
14 +
/// Terminal drawing backend.
15 +
pub trait Backend {
16 +
    /// Backend error type.
17 +
    type Error;
18 +
19 +
    /// Returns the current terminal size.
20 +
    fn size(&mut self) -> Result<Size, Self::Error>;
21 +
    /// Draws dirty cell runs.
22 +
    fn draw(&mut self, runs: &[DirtyRun<'_>]) -> Result<(), Self::Error>;
23 +
    /// Clears the visible screen.
24 +
    fn clear(&mut self) -> Result<(), Self::Error>;
25 +
    /// Flushes buffered output.
26 +
    fn flush(&mut self) -> Result<(), Self::Error>;
27 +
28 +
    /// Moves the cursor.
29 +
    fn set_cursor_position(&mut self, _: Point) -> Result<(), Self::Error> {
30 +
        Ok(())
31 +
    }
32 +
    /// Shows or hides the cursor.
33 +
    fn set_cursor_visible(&mut self, _: bool) -> Result<(), Self::Error> {
34 +
        Ok(())
35 +
    }
36 +
}
37 +
38 +
/// In-memory backend for tests.
39 +
#[derive(Debug, Clone)]
40 +
pub struct TestBackend {
41 +
    buffer: Buffer,
42 +
    cursor: Option<Point>,
43 +
}
44 +
45 +
impl TestBackend {
46 +
    /// Creates a backend with a fixed size.
47 +
    pub fn new(size: Size) -> Self {
48 +
        Self {
49 +
            buffer: Buffer::empty(Rect::from_size(size)),
50 +
            cursor: None,
51 +
        }
52 +
    }
53 +
54 +
    /// Resizes the backend.
55 +
    pub fn resize(&mut self, size: Size) {
56 +
        self.buffer.resize(Rect::from_size(size));
57 +
    }
58 +
59 +
    /// Returns the captured buffer.
60 +
    pub const fn buffer(&self) -> &Buffer {
61 +
        &self.buffer
62 +
    }
63 +
64 +
    /// Returns the captured cursor position.
65 +
    pub const fn cursor(&self) -> Option<Point> {
66 +
        self.cursor
67 +
    }
68 +
69 +
    /// Returns plain screen lines.
70 +
    pub fn lines(&self) -> Vec<String> {
71 +
        self.buffer.lines()
72 +
    }
73 +
}
74 +
75 +
impl Backend for TestBackend {
76 +
    type Error = Infallible;
77 +
78 +
    fn size(&mut self) -> Result<Size, Self::Error> {
79 +
        Ok(self.buffer.size())
80 +
    }
81 +
82 +
    fn draw(&mut self, runs: &[DirtyRun<'_>]) -> Result<(), Self::Error> {
83 +
        for run in runs {
84 +
            for (dx, cell) in run.cells.iter().enumerate() {
85 +
                self.buffer.set(run.x + dx, run.y, cell.clone());
86 +
            }
87 +
        }
88 +
        Ok(())
89 +
    }
90 +
91 +
    fn clear(&mut self) -> Result<(), Self::Error> {
92 +
        self.buffer
93 +
            .fill(self.buffer.area(), crate::buffer::Cell::blank());
94 +
        Ok(())
95 +
    }
96 +
97 +
    fn flush(&mut self) -> Result<(), Self::Error> {
98 +
        Ok(())
99 +
    }
100 +
101 +
    fn set_cursor_position(&mut self, point: Point) -> Result<(), Self::Error> {
102 +
        self.cursor = Some(point);
103 +
        Ok(())
104 +
    }
105 +
}
106 +
107 +
#[cfg(test)]
108 +
#[allow(clippy::unwrap_used)]
109 +
mod tests {
110 +
    use super::*;
111 +
    use crate::Style;
112 +
    use crate::terminal::Terminal;
113 +
114 +
    #[test]
115 +
    fn test_backend_captures_dirty_runs() {
116 +
        let backend = TestBackend::new(Size::new(6, 1));
117 +
        let mut terminal = Terminal::new(backend).unwrap();
118 +
119 +
        terminal
120 +
            .draw(|frame| frame.buffer.set_str(1, 0, "abc", Style::default()))
121 +
            .unwrap();
122 +
123 +
        assert_eq!(terminal.backend().lines(), vec![" abc  "]);
124 +
    }
125 +
126 +
    #[test]
127 +
    fn test_backend_supports_resize_clear_and_cursor_capture() {
128 +
        let mut backend = TestBackend::new(Size::new(3, 1));
129 +
130 +
        backend
131 +
            .draw(&[DirtyRun {
132 +
                x: 0,
133 +
                y: 0,
134 +
                cells: &[crate::buffer::Cell::new("x", Style::default())],
135 +
            }])
136 +
            .unwrap();
137 +
        backend.set_cursor_position(Point::new(2, 0)).unwrap();
138 +
        assert_eq!(backend.lines(), vec!["x  "]);
139 +
        assert_eq!(backend.cursor(), Some(Point::new(2, 0)));
140 +
141 +
        backend.clear().unwrap();
142 +
        assert_eq!(backend.lines(), vec!["   "]);
143 +
144 +
        backend.resize(Size::new(2, 2));
145 +
        assert_eq!(backend.lines(), vec!["  ", "  "]);
146 +
    }
147 +
}
crates/tui-core/src/border.rs added +221 -0
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: &'static str,
15 +
    /// Top-right corner.
16 +
    pub top_right: &'static str,
17 +
    /// Bottom-left corner.
18 +
    pub bottom_left: &'static str,
19 +
    /// Bottom-right corner.
20 +
    pub bottom_right: &'static str,
21 +
    /// Vertical edge.
22 +
    pub vertical: &'static str,
23 +
    /// Horizontal edge.
24 +
    pub horizontal: &'static str,
25 +
    /// Left divider junction.
26 +
    pub divider_left: &'static str,
27 +
    /// Right divider junction.
28 +
    pub divider_right: &'static str,
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 +
    style: Style,
55 +
    chars: BorderChars,
56 +
}
57 +
58 +
impl Border {
59 +
    /// Creates a rounded border from a foreground color.
60 +
    pub const fn new(color: Color) -> Self {
61 +
        Self::with_style(Style::new(color))
62 +
    }
63 +
64 +
    /// Creates a rounded border from a style.
65 +
    pub const fn with_style(style: Style) -> Self {
66 +
        Self {
67 +
            style,
68 +
            chars: BorderChars::ROUNDED,
69 +
        }
70 +
    }
71 +
72 +
    /// Returns the border style.
73 +
    pub const fn style(self) -> Style {
74 +
        self.style
75 +
    }
76 +
77 +
    /// Returns the border glyphs.
78 +
    pub const fn chars(self) -> BorderChars {
79 +
        self.chars
80 +
    }
81 +
82 +
    /// Returns a top border line with `cols` inner columns.
83 +
    pub fn top(self, cols: usize) -> Line {
84 +
        self.horizontal(
85 +
            self.chars.top_left,
86 +
            self.chars.horizontal,
87 +
            self.chars.top_right,
88 +
            cols,
89 +
        )
90 +
    }
91 +
92 +
    /// Returns a divider line with `cols` inner columns.
93 +
    pub fn divider(self, cols: usize, sigil: &str) -> Line {
94 +
        self.horizontal(
95 +
            self.chars.divider_left,
96 +
            sigil,
97 +
            self.chars.divider_right,
98 +
            cols,
99 +
        )
100 +
    }
101 +
102 +
    /// Returns a bottom border line with `cols` inner columns.
103 +
    pub fn bottom(self, cols: usize) -> Line {
104 +
        self.horizontal(
105 +
            self.chars.bottom_left,
106 +
            self.chars.horizontal,
107 +
            self.chars.bottom_right,
108 +
            cols,
109 +
        )
110 +
    }
111 +
112 +
    /// Returns a left border segment with padding.
113 +
    pub fn left(self, padding: usize) -> Paint<String> {
114 +
        self.paint(format!("{}{}", self.chars.vertical, " ".repeat(padding)))
115 +
    }
116 +
117 +
    /// Returns a right border segment with padding.
118 +
    pub fn right(self, padding: usize) -> Paint<String> {
119 +
        self.paint(format!("{}{}", " ".repeat(padding), self.chars.vertical))
120 +
    }
121 +
122 +
    /// Draws the border into a buffer.
123 +
    pub fn draw(self, area: Rect, buf: &mut Buffer) {
124 +
        if area.is_empty() {
125 +
            return;
126 +
        }
127 +
        if area.cols == 1 && area.rows == 1 {
128 +
            self.set(buf, area.x, area.y, self.chars.top_left);
129 +
            return;
130 +
        }
131 +
        if area.rows == 1 {
132 +
            let right = area.right().saturating_sub(1);
133 +
            self.set(buf, area.x, area.y, self.chars.top_left);
134 +
            for x in area.x + 1..right {
135 +
                self.set(buf, x, area.y, self.chars.horizontal);
136 +
            }
137 +
            self.set(buf, right, area.y, self.chars.top_right);
138 +
            return;
139 +
        }
140 +
        if area.cols == 1 {
141 +
            let bottom = area.bottom().saturating_sub(1);
142 +
            self.set(buf, area.x, area.y, self.chars.top_left);
143 +
            for y in area.y + 1..bottom {
144 +
                self.set(buf, area.x, y, self.chars.vertical);
145 +
            }
146 +
            self.set(buf, area.x, bottom, self.chars.bottom_left);
147 +
            return;
148 +
        }
149 +
150 +
        let right = area.right().saturating_sub(1);
151 +
        let bottom = area.bottom().saturating_sub(1);
152 +
153 +
        self.set(buf, area.x, area.y, self.chars.top_left);
154 +
        self.set(buf, right, area.y, self.chars.top_right);
155 +
        self.set(buf, area.x, bottom, self.chars.bottom_left);
156 +
        self.set(buf, right, bottom, self.chars.bottom_right);
157 +
158 +
        for x in area.x + 1..right {
159 +
            self.set(buf, x, area.y, self.chars.horizontal);
160 +
            self.set(buf, x, bottom, self.chars.horizontal);
161 +
        }
162 +
        for y in area.y + 1..bottom {
163 +
            self.set(buf, area.x, y, self.chars.vertical);
164 +
            self.set(buf, right, y, self.chars.vertical);
165 +
        }
166 +
    }
167 +
168 +
    fn horizontal(self, left: &str, fill: &str, right: &str, cols: usize) -> Line {
169 +
        Line::default()
170 +
            .item(self.paint(left))
171 +
            .item(self.paint(fill.repeat(cols)))
172 +
            .item(self.paint(right))
173 +
    }
174 +
175 +
    fn paint<T>(self, item: T) -> Paint<T> {
176 +
        Paint::new(item).with_style(self.style)
177 +
    }
178 +
179 +
    fn set(self, buf: &mut Buffer, x: usize, y: usize, glyph: &str) {
180 +
        buf.set_glyph(x, y, glyph, self.style);
181 +
    }
182 +
}
183 +
184 +
#[cfg(test)]
185 +
mod tests {
186 +
    use super::*;
187 +
188 +
    #[test]
189 +
    fn border_lines_use_shared_glyphs_and_style() {
190 +
        let border = Border::new(Color::Red);
191 +
        let line = border.top(3);
192 +
193 +
        assert_eq!(line.to_string(), "╭───╮");
194 +
        assert!(
195 +
            line.labels()
196 +
                .iter()
197 +
                .all(|label| { label.paint().style().fg_color() == Color::Red })
198 +
        );
199 +
        assert_eq!(border.divider(2, "┄").to_string(), "├┄┄┤");
200 +
        assert_eq!(border.bottom(1).to_string(), "╰─╯");
201 +
    }
202 +
203 +
    #[test]
204 +
    fn border_draws_degenerate_and_rectangular_buffers() {
205 +
        let border = Border::new(Color::Unset);
206 +
        let mut one = Buffer::empty(Rect::new(0, 0, 1, 1));
207 +
        let mut row = Buffer::empty(Rect::new(0, 0, 4, 1));
208 +
        let mut column = Buffer::empty(Rect::new(0, 0, 1, 3));
209 +
        let mut rect = Buffer::empty(Rect::new(0, 0, 4, 3));
210 +
211 +
        border.draw(one.area(), &mut one);
212 +
        border.draw(row.area(), &mut row);
213 +
        border.draw(column.area(), &mut column);
214 +
        border.draw(rect.area(), &mut rect);
215 +
216 +
        assert_eq!(one.lines(), vec!["╭"]);
217 +
        assert_eq!(row.lines(), vec!["╭──╮"]);
218 +
        assert_eq!(column.lines(), vec!["╭", "│", "╰"]);
219 +
        assert_eq!(rect.lines(), vec!["╭──╮", "│  │", "╰──╯"]);
220 +
    }
221 +
}
crates/tui-core/src/buffer.rs added +599 -0
1 +
//! Styled terminal cell buffer.
2 +
//!
3 +
//! `Buffer` is the render artifact for the core crate: widgets write styled
4 +
//! [`Cell`] values into it, and the terminal flushes only the cells that changed
5 +
//! since the previous frame. It also handles wide glyph continuation cells so
6 +
//! higher-level widgets can write glyphs without manual cleanup.
7 +
8 +
use std::borrow::Cow;
9 +
use std::{slice, str};
10 +
11 +
use crate::cell::{Text as _, char_width};
12 +
use crate::layout::{Point, Rect};
13 +
use crate::{Label, Line, Paint, Size, Style};
14 +
15 +
/// A styled terminal cell.
16 +
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
17 +
pub struct Cell {
18 +
    /// Cell glyph.
19 +
    glyph: CellGlyph,
20 +
    /// Cell style.
21 +
    style: Style,
22 +
}
23 +
24 +
/// Renderable cell glyph.
25 +
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
26 +
enum CellGlyph {
27 +
    /// A blank terminal cell.
28 +
    #[default]
29 +
    Blank,
30 +
    /// A single ASCII terminal glyph.
31 +
    Ascii(u8),
32 +
    /// A single non-ASCII terminal glyph.
33 +
    Unicode(char),
34 +
    /// A heap-backed multi-scalar terminal glyph.
35 +
    Grapheme(String),
36 +
    /// Continuation cell occupied by a wide leading glyph.
37 +
    Continuation,
38 +
}
39 +
40 +
impl Cell {
41 +
    /// Creates a cell from a glyph and style.
42 +
    pub fn new(glyph: impl AsRef<str>, style: Style) -> Self {
43 +
        Self {
44 +
            glyph: normalize_glyph(glyph.as_ref()),
45 +
            style,
46 +
        }
47 +
    }
48 +
49 +
    /// Creates a blank cell.
50 +
    pub fn blank() -> Self {
51 +
        Self::default()
52 +
    }
53 +
54 +
    /// Returns the cell glyph.
55 +
    pub fn glyph(&self) -> Cow<'_, str> {
56 +
        match &self.glyph {
57 +
            CellGlyph::Blank => Cow::Borrowed(" "),
58 +
            CellGlyph::Ascii(glyph) => {
59 +
                Cow::Borrowed(str::from_utf8(slice::from_ref(glyph)).unwrap_or(" "))
60 +
            }
61 +
            CellGlyph::Unicode(glyph) => Cow::Owned(glyph.to_string()),
62 +
            CellGlyph::Grapheme(glyph) => Cow::Borrowed(glyph),
63 +
            CellGlyph::Continuation => Cow::Borrowed(""),
64 +
        }
65 +
    }
66 +
67 +
    /// Returns the cell style.
68 +
    pub const fn style(&self) -> Style {
69 +
        self.style
70 +
    }
71 +
72 +
    /// Returns whether this cell is a wide-glyph continuation.
73 +
    pub fn is_continuation(&self) -> bool {
74 +
        matches!(self.glyph, CellGlyph::Continuation)
75 +
    }
76 +
77 +
    /// Returns this cell as styled display text.
78 +
    pub fn paint(&self) -> Paint<Cow<'_, str>> {
79 +
        Paint::new(self.glyph()).with_style(self.style)
80 +
    }
81 +
82 +
    /// Returns this cell with a different style.
83 +
    pub fn with_style(mut self, style: Style) -> Self {
84 +
        self.style = style;
85 +
        self
86 +
    }
87 +
88 +
    /// Creates a continuation cell.
89 +
    fn continuation(style: Style) -> Self {
90 +
        Self {
91 +
            glyph: CellGlyph::Continuation,
92 +
            style,
93 +
        }
94 +
    }
95 +
96 +
    /// Creates a cell from one character.
97 +
    fn from_char(ch: char, style: Style) -> Self {
98 +
        Self {
99 +
            glyph: normalize_char(ch),
100 +
            style,
101 +
        }
102 +
    }
103 +
104 +
    /// Returns the terminal width of this cell's leading glyph.
105 +
    fn width(&self) -> usize {
106 +
        match &self.glyph {
107 +
            CellGlyph::Blank | CellGlyph::Ascii(_) => 1,
108 +
            CellGlyph::Unicode(glyph) => char_width(*glyph),
109 +
            CellGlyph::Grapheme(glyph) => glyph.width(),
110 +
            CellGlyph::Continuation => 0,
111 +
        }
112 +
    }
113 +
}
114 +
115 +
/// A contiguous run of dirty cells.
116 +
#[derive(Debug, Clone, Copy)]
117 +
pub struct DirtyRun<'a> {
118 +
    /// Start column.
119 +
    pub x: usize,
120 +
    /// Row.
121 +
    pub y: usize,
122 +
    /// Dirty cells.
123 +
    pub cells: &'a [Cell],
124 +
}
125 +
126 +
/// A rectangular styled cell buffer.
127 +
#[derive(Clone, Debug, PartialEq, Eq)]
128 +
pub struct Buffer {
129 +
    area: Rect,
130 +
    cells: Vec<Cell>,
131 +
    dirty: Vec<bool>,
132 +
}
133 +
134 +
impl Buffer {
135 +
    /// Creates an empty buffer for an area.
136 +
    pub fn empty(area: Rect) -> Self {
137 +
        let len = area.cols.saturating_mul(area.rows);
138 +
        Self {
139 +
            area,
140 +
            cells: vec![Cell::blank(); len],
141 +
            dirty: vec![true; len],
142 +
        }
143 +
    }
144 +
145 +
    /// Returns the covered area.
146 +
    pub const fn area(&self) -> Rect {
147 +
        self.area
148 +
    }
149 +
150 +
    /// Returns the buffer size.
151 +
    pub const fn size(&self) -> Size {
152 +
        self.area.size()
153 +
    }
154 +
155 +
    /// Returns whether the buffer has no cells.
156 +
    pub fn is_empty(&self) -> bool {
157 +
        self.cells.is_empty()
158 +
    }
159 +
160 +
    /// Resizes the buffer and marks all cells dirty.
161 +
    pub fn resize(&mut self, area: Rect) {
162 +
        if self.area == area {
163 +
            return;
164 +
        }
165 +
        *self = Self::empty(area);
166 +
    }
167 +
168 +
    /// Clears the buffer to blank cells.
169 +
    pub fn clear(&mut self) {
170 +
        for (cell, dirty) in self.cells.iter_mut().zip(&mut self.dirty) {
171 +
            if *cell != Cell::blank() {
172 +
                *cell = Cell::blank();
173 +
                *dirty = true;
174 +
            }
175 +
        }
176 +
    }
177 +
178 +
    /// Marks all cells clean.
179 +
    pub fn reset_dirty(&mut self) {
180 +
        self.dirty.fill(false);
181 +
    }
182 +
183 +
    /// Returns a cell by absolute position.
184 +
    pub fn get(&self, x: usize, y: usize) -> Option<&Cell> {
185 +
        self.index(x, y).map(|index| &self.cells[index])
186 +
    }
187 +
188 +
    /// Sets a cell by absolute position.
189 +
    pub fn set(&mut self, x: usize, y: usize, cell: Cell) {
190 +
        if cell.is_continuation() {
191 +
            self.set_exact(x, y, cell);
192 +
            return;
193 +
        }
194 +
        let width = cell.width().max(1);
195 +
        self.clear_glyph_at(x, y);
196 +
197 +
        if width > self.area.right().saturating_sub(x) {
198 +
            return;
199 +
        }
200 +
        let style = cell.style();
201 +
        self.set_exact(x, y, cell);
202 +
203 +
        for dx in 1..width {
204 +
            self.set_exact(x + dx, y, Cell::continuation(style));
205 +
        }
206 +
    }
207 +
208 +
    /// Sets a cell without adjusting neighboring wide cells.
209 +
    fn set_exact(&mut self, x: usize, y: usize, cell: Cell) {
210 +
        let Some(index) = self.index(x, y) else {
211 +
            return;
212 +
        };
213 +
        if self.cells[index] != cell {
214 +
            self.cells[index] = cell;
215 +
            self.dirty[index] = true;
216 +
        }
217 +
    }
218 +
219 +
    /// Sets one styled glyph by absolute position.
220 +
    pub fn set_glyph(&mut self, x: usize, y: usize, glyph: impl AsRef<str>, style: Style) {
221 +
        self.set(x, y, Cell::new(glyph, style));
222 +
    }
223 +
224 +
    /// Writes styled text by absolute position.
225 +
    pub fn set_str(&mut self, x: usize, y: usize, text: &str, style: Style) {
226 +
        let mut cursor = x;
227 +
        for ch in text.chars() {
228 +
            if cursor >= self.area.right() {
229 +
                break;
230 +
            }
231 +
            let width = char_width(ch);
232 +
            if width == 0 {
233 +
                continue;
234 +
            }
235 +
            if width > self.area.right().saturating_sub(cursor) {
236 +
                break;
237 +
            }
238 +
            self.set(cursor, y, Cell::from_char(ch, style));
239 +
            cursor += width;
240 +
        }
241 +
    }
242 +
243 +
    /// Writes a label by absolute position.
244 +
    pub fn set_label(&mut self, x: usize, y: usize, label: &Label) {
245 +
        self.set_str(x, y, label.content(), label.paint().style());
246 +
    }
247 +
248 +
    /// Writes a styled line by absolute position.
249 +
    pub fn set_line(&mut self, x: usize, y: usize, line: &Line) {
250 +
        let mut cursor = x;
251 +
        for label in line.labels() {
252 +
            self.set_label(cursor, y, label);
253 +
            cursor += label.content().width();
254 +
            if cursor >= self.area.right() {
255 +
                break;
256 +
            }
257 +
        }
258 +
    }
259 +
260 +
    /// Fills an area with a cell.
261 +
    pub fn fill(&mut self, area: Rect, cell: Cell) {
262 +
        let area = self.area.intersection(area);
263 +
        for y in area.y..area.bottom() {
264 +
            let mut x = area.x;
265 +
            while x < area.right() {
266 +
                let width = cell.width().max(1);
267 +
                if width > area.right().saturating_sub(x) {
268 +
                    break;
269 +
                }
270 +
                self.set(x, y, cell.clone());
271 +
                x += width;
272 +
            }
273 +
        }
274 +
    }
275 +
276 +
    /// Returns dirty runs based on explicit dirty marks.
277 +
    pub fn dirty_runs(&self) -> Vec<DirtyRun<'_>> {
278 +
        self.runs(|index, _| self.dirty[index])
279 +
    }
280 +
281 +
    /// Returns dirty runs by diffing against `previous`.
282 +
    pub fn diff(&self, previous: &Self) -> Vec<DirtyRun<'_>> {
283 +
        if self.area != previous.area {
284 +
            return self.runs(|_, _| true);
285 +
        }
286 +
        self.runs(|index, cell| previous.cells[index] != *cell)
287 +
    }
288 +
289 +
    /// Returns plain rendered lines.
290 +
    pub fn lines(&self) -> Vec<String> {
291 +
        (0..self.area.rows).map(|row| self.line(row)).collect()
292 +
    }
293 +
294 +
    /// Returns one plain rendered line by local row index.
295 +
    pub fn line(&self, row: usize) -> String {
296 +
        if row >= self.area.rows {
297 +
            return String::new();
298 +
        }
299 +
        let start = row * self.area.cols;
300 +
        let end = start + self.area.cols;
301 +
302 +
        self.cells[start..end]
303 +
            .iter()
304 +
            .map(|cell| cell.glyph())
305 +
            .collect::<String>()
306 +
    }
307 +
308 +
    /// Computes dirty runs using a cell predicate.
309 +
    fn runs(&self, mut dirty: impl FnMut(usize, &Cell) -> bool) -> Vec<DirtyRun<'_>> {
310 +
        let mut runs = Vec::new();
311 +
312 +
        for row in 0..self.area.rows {
313 +
            let start = row * self.area.cols;
314 +
            let end = start + self.area.cols;
315 +
            let mut index = start;
316 +
317 +
            while index < end {
318 +
                while index < end && !dirty(index, &self.cells[index]) {
319 +
                    index += 1;
320 +
                }
321 +
                if index == end {
322 +
                    break;
323 +
                }
324 +
                let run_start = index;
325 +
                while index < end && dirty(index, &self.cells[index]) {
326 +
                    index += 1;
327 +
                }
328 +
                runs.push(DirtyRun {
329 +
                    x: self.area.x + run_start - start,
330 +
                    y: self.area.y + row,
331 +
                    cells: &self.cells[run_start..index],
332 +
                });
333 +
            }
334 +
        }
335 +
        runs
336 +
    }
337 +
338 +
    /// Returns an index for an absolute position.
339 +
    fn index(&self, x: usize, y: usize) -> Option<usize> {
340 +
        if !self.area.contains(Point::new(x, y)) {
341 +
            return None;
342 +
        }
343 +
        let local_x = x - self.area.x;
344 +
        let local_y = y - self.area.y;
345 +
346 +
        Some(local_y * self.area.cols + local_x)
347 +
    }
348 +
349 +
    /// Clears the leading glyph that covers a position.
350 +
    fn clear_glyph_at(&mut self, x: usize, y: usize) {
351 +
        if self.index(x, y).is_none() {
352 +
            return;
353 +
        }
354 +
        let mut lead = x;
355 +
356 +
        while lead > self.area.x {
357 +
            let Some(cell) = self.get(lead, y) else {
358 +
                break;
359 +
            };
360 +
            if !cell.is_continuation() {
361 +
                break;
362 +
            }
363 +
            lead -= 1;
364 +
        }
365 +
        let width = self.get(lead, y).map_or(1, |cell| cell.width().max(1));
366 +
367 +
        for dx in 0..width {
368 +
            self.set_exact(lead + dx, y, Cell::blank());
369 +
        }
370 +
    }
371 +
}
372 +
373 +
/// Normalizes arbitrary input into one terminal glyph.
374 +
fn normalize_glyph(input: &str) -> CellGlyph {
375 +
    let mut chars = input.chars();
376 +
    let Some(first) = chars.next() else {
377 +
        return CellGlyph::Blank;
378 +
    };
379 +
    if first.is_control() {
380 +
        return CellGlyph::Blank;
381 +
    }
382 +
    if first.is_ascii() {
383 +
        return ascii_glyph(first);
384 +
    }
385 +
    if !matches!(chars.clone().next(), Some('\u{fe0f}' | '\u{fe0e}')) {
386 +
        return normalize_char(first);
387 +
    }
388 +
    let mut glyph = String::from(first);
389 +
390 +
    if let Some(second @ ('\u{fe0f}' | '\u{fe0e}')) = chars.next() {
391 +
        glyph.push(second);
392 +
393 +
        for ch in chars {
394 +
            if !matches!(ch, '\u{fe0f}' | '\u{fe0e}') {
395 +
                break;
396 +
            }
397 +
            glyph.push(ch);
398 +
        }
399 +
    }
400 +
    if glyph.width() == 0 {
401 +
        CellGlyph::Blank
402 +
    } else {
403 +
        CellGlyph::Grapheme(glyph)
404 +
    }
405 +
}
406 +
407 +
/// Normalizes one character into one terminal glyph.
408 +
fn normalize_char(ch: char) -> CellGlyph {
409 +
    if ch.is_control() || char_width(ch) == 0 {
410 +
        CellGlyph::Blank
411 +
    } else if ch.is_ascii() {
412 +
        ascii_glyph(ch)
413 +
    } else {
414 +
        CellGlyph::Unicode(ch)
415 +
    }
416 +
}
417 +
418 +
/// Normalizes one non-control ASCII character.
419 +
fn ascii_glyph(ch: char) -> CellGlyph {
420 +
    if ch == ' ' {
421 +
        CellGlyph::Blank
422 +
    } else {
423 +
        CellGlyph::Ascii(ch as u8)
424 +
    }
425 +
}
426 +
427 +
#[cfg(test)]
428 +
#[allow(clippy::unwrap_used)]
429 +
mod tests {
430 +
    use super::*;
431 +
432 +
    #[test]
433 +
    fn cell_normalizes_to_one_terminal_glyph() {
434 +
        let style = Style::new(crate::Color::Red);
435 +
436 +
        let cell = Cell::new("ab", style);
437 +
        let control = Cell::new("\n", style);
438 +
439 +
        assert_eq!(cell.glyph(), "a");
440 +
        assert_eq!(cell.style(), style);
441 +
        assert_eq!(control.glyph(), " ");
442 +
        assert!(!cell.is_continuation());
443 +
    }
444 +
445 +
    #[test]
446 +
    fn cell_uses_inline_storage_for_blank_and_ascii_glyphs() {
447 +
        let style = Style::new(crate::Color::Blue);
448 +
449 +
        assert!(matches!(Cell::blank().glyph, CellGlyph::Blank));
450 +
        assert!(matches!(Cell::new(" ", style).glyph, CellGlyph::Blank));
451 +
        assert!(matches!(
452 +
            Cell::new("x", style).glyph,
453 +
            CellGlyph::Ascii(b'x')
454 +
        ));
455 +
        assert!(matches!(
456 +
            Cell::new("╭", style).glyph,
457 +
            CellGlyph::Unicode('╭')
458 +
        ));
459 +
        assert!(matches!(
460 +
            Cell::new("❤️", style).glyph,
461 +
            CellGlyph::Grapheme(glyph) if glyph == "❤️"
462 +
        ));
463 +
        assert!(matches!(
464 +
            Cell::new("λ", style).glyph,
465 +
            CellGlyph::Unicode('λ')
466 +
        ));
467 +
    }
468 +
469 +
    #[test]
470 +
    fn buffer_writes_plain_and_styled_text() {
471 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 8, 2));
472 +
473 +
        buffer.set_str(1, 0, "hi", Style::default());
474 +
        buffer.set_line(0, 1, &Line::new("ok"));
475 +
476 +
        assert_eq!(buffer.lines(), vec![" hi     ", "ok      "]);
477 +
    }
478 +
479 +
    #[test]
480 +
    fn new_buffer_starts_dirty_and_reset_clears_dirty_marks() {
481 +
        let mut buffer = Buffer::empty(Rect::new(2, 3, 4, 2));
482 +
        let runs = buffer.dirty_runs();
483 +
484 +
        assert_eq!(runs.len(), 2);
485 +
        assert_eq!(runs[0].x, 2);
486 +
        assert_eq!(runs[0].y, 3);
487 +
        assert_eq!(runs[0].cells.len(), 4);
488 +
489 +
        buffer.reset_dirty();
490 +
491 +
        assert!(buffer.dirty_runs().is_empty());
492 +
    }
493 +
494 +
    #[test]
495 +
    fn buffer_tracks_dirty_runs() {
496 +
        let mut previous = Buffer::empty(Rect::new(0, 0, 6, 1));
497 +
        previous.reset_dirty();
498 +
        let mut next = previous.clone();
499 +
500 +
        next.set_str(1, 0, "abc", Style::default());
501 +
502 +
        let runs = next.diff(&previous);
503 +
        assert_eq!(runs.len(), 1);
504 +
        assert_eq!(runs[0].x, 1);
505 +
        assert_eq!(runs[0].cells.len(), 3);
506 +
    }
507 +
508 +
    #[test]
509 +
    fn setting_same_cell_after_reset_does_not_mark_dirty() {
510 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 3, 1));
511 +
512 +
        buffer.reset_dirty();
513 +
        buffer.set(0, 0, Cell::blank());
514 +
515 +
        assert!(buffer.dirty_runs().is_empty());
516 +
    }
517 +
518 +
    #[test]
519 +
    fn fill_clips_to_buffer_area_and_out_of_bounds_writes_are_ignored() {
520 +
        let mut buffer = Buffer::empty(Rect::new(1, 1, 4, 2));
521 +
522 +
        buffer.reset_dirty();
523 +
        buffer.fill(
524 +
            Rect::new(3, 0, 4, 4),
525 +
            Cell::new("x", Style::new(crate::Color::Blue)),
526 +
        );
527 +
        buffer.set(0, 0, Cell::new("z", Style::default()));
528 +
529 +
        assert_eq!(buffer.lines(), vec!["  xx", "  xx"]);
530 +
        assert_eq!(buffer.dirty_runs().len(), 2);
531 +
    }
532 +
533 +
    #[test]
534 +
    fn resize_reallocates_cells_and_marks_new_area_dirty() {
535 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 2, 1));
536 +
537 +
        buffer.reset_dirty();
538 +
        buffer.resize(Rect::new(0, 0, 3, 2));
539 +
540 +
        assert_eq!(buffer.size(), Size::new(3, 2));
541 +
        assert_eq!(buffer.lines(), vec!["   ", "   "]);
542 +
        assert_eq!(buffer.dirty_runs().len(), 2);
543 +
    }
544 +
545 +
    #[test]
546 +
    fn wide_glyphs_occupy_continuation_cells_without_extra_text() {
547 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 4, 1));
548 +
549 +
        buffer.reset_dirty();
550 +
        buffer.set_str(0, 0, "🍍a", Style::default());
551 +
552 +
        assert_eq!(buffer.line(0), "🍍a ");
553 +
        assert_eq!(buffer.get(0, 0).unwrap().glyph(), "🍍");
554 +
        assert!(buffer.get(1, 0).unwrap().is_continuation());
555 +
        assert_eq!(buffer.get(2, 0).unwrap().glyph(), "a");
556 +
        assert_eq!(buffer.dirty_runs()[0].cells.len(), 3);
557 +
    }
558 +
559 +
    #[test]
560 +
    fn overwriting_inside_wide_glyph_clears_the_leading_cell() {
561 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 4, 1));
562 +
563 +
        buffer.set_str(0, 0, "🍍x", Style::default());
564 +
        buffer.reset_dirty();
565 +
        buffer.set_str(1, 0, "a", Style::default());
566 +
567 +
        assert_eq!(buffer.line(0), " ax ");
568 +
        assert_eq!(buffer.get(0, 0).unwrap().glyph(), " ");
569 +
        assert_eq!(buffer.get(1, 0).unwrap().glyph(), "a");
570 +
        assert!(!buffer.get(1, 0).unwrap().is_continuation());
571 +
    }
572 +
573 +
    #[test]
574 +
    fn wide_glyph_that_cannot_fit_is_not_written() {
575 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 3, 1));
576 +
577 +
        buffer.set_str(2, 0, "🍍", Style::default());
578 +
579 +
        assert_eq!(buffer.line(0), "   ");
580 +
    }
581 +
582 +
    #[test]
583 +
    fn wide_fill_tiles_by_visual_width() {
584 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 1));
585 +
586 +
        buffer.fill(buffer.area(), Cell::new("🍍", Style::default()));
587 +
588 +
        assert_eq!(buffer.line(0), "🍍🍍 ");
589 +
        assert!(buffer.get(1, 0).unwrap().is_continuation());
590 +
        assert!(buffer.get(3, 0).unwrap().is_continuation());
591 +
    }
592 +
593 +
    #[test]
594 +
    fn line_returns_empty_string_for_out_of_bounds_rows() {
595 +
        let buffer = Buffer::empty(Rect::new(0, 0, 2, 1));
596 +
597 +
        assert_eq!(buffer.line(99), "");
598 +
    }
599 +
}
crates/tui-core/src/cell.rs added +274 -0
1 +
//! Text measurement and padding support.
2 +
//!
3 +
//! This module defines the [`Text`] trait used by labels, lines, and painted
4 +
//! values to measure terminal display width, truncate content, and pad rows.
5 +
//! Cell storage itself lives in [`buffer`](crate::buffer); this module is about
6 +
//! text-like values that occupy terminal columns.
7 +
8 +
use std::fmt;
9 +
10 +
use super::{Color, Filled, Line, Paint};
11 +
12 +
/// Default background color for text-like values.
13 +
pub const DEFAULT_BACKGROUND: Color = Color::Unset;
14 +
15 +
/// Text that can be displayed on the terminal, measured, truncated and padded.
16 +
pub trait Text: fmt::Display {
17 +
    /// Type after truncation.
18 +
    type Truncated: Text;
19 +
    /// Type after padding.
20 +
    type Padded: Text;
21 +
22 +
    /// Cell display width in number of terminal columns.
23 +
    fn width(&self) -> usize;
24 +
    /// Background color of cell.
25 +
    fn background(&self) -> Color {
26 +
        DEFAULT_BACKGROUND
27 +
    }
28 +
29 +
    /// Truncate cell if longer than given width. Shows the delimiter if truncated.
30 +
    #[must_use]
31 +
    fn truncate(&self, width: usize, delim: &str) -> Self::Truncated;
32 +
    /// Pad the cell so that it is the given width, while keeping the content left-aligned.
33 +
    #[must_use]
34 +
    fn pad(&self, width: usize) -> Self::Padded;
35 +
}
36 +
37 +
impl Text for Paint<String> {
38 +
    type Truncated = Self;
39 +
    type Padded = Self;
40 +
41 +
    fn width(&self) -> usize {
42 +
        Text::width(self.content())
43 +
    }
44 +
45 +
    fn background(&self) -> Color {
46 +
        self.style.background
47 +
    }
48 +
49 +
    fn truncate(&self, width: usize, delim: &str) -> Self {
50 +
        Self {
51 +
            item: self.item.truncate(width, delim),
52 +
            style: self.style,
53 +
        }
54 +
    }
55 +
56 +
    fn pad(&self, width: usize) -> Self {
57 +
        Self {
58 +
            item: self.item.pad(width),
59 +
            style: self.style,
60 +
        }
61 +
    }
62 +
}
63 +
64 +
impl Text for Line {
65 +
    type Truncated = Line;
66 +
    type Padded = Line;
67 +
68 +
    fn width(&self) -> usize {
69 +
        Line::width(self)
70 +
    }
71 +
72 +
    fn pad(&self, width: usize) -> Self::Padded {
73 +
        let mut line = self.clone();
74 +
        Line::pad(&mut line, width);
75 +
        line
76 +
    }
77 +
78 +
    fn truncate(&self, width: usize, delim: &str) -> Self::Truncated {
79 +
        let mut line = self.clone();
80 +
        Line::truncate(&mut line, width, delim);
81 +
        line
82 +
    }
83 +
}
84 +
85 +
impl Text for Paint<&str> {
86 +
    type Truncated = Paint<String>;
87 +
    type Padded = Paint<String>;
88 +
89 +
    fn width(&self) -> usize {
90 +
        Text::width(self.item)
91 +
    }
92 +
93 +
    fn background(&self) -> Color {
94 +
        self.style.background
95 +
    }
96 +
97 +
    fn truncate(&self, width: usize, delim: &str) -> Paint<String> {
98 +
        Paint {
99 +
            item: self.item.truncate(width, delim),
100 +
            style: self.style,
101 +
        }
102 +
    }
103 +
104 +
    fn pad(&self, width: usize) -> Paint<String> {
105 +
        Paint {
106 +
            item: self.item.pad(width),
107 +
            style: self.style,
108 +
        }
109 +
    }
110 +
}
111 +
112 +
impl Text for String {
113 +
    type Truncated = Self;
114 +
    type Padded = Self;
115 +
116 +
    fn width(&self) -> usize {
117 +
        Text::width(self.as_str())
118 +
    }
119 +
120 +
    fn truncate(&self, width: usize, delim: &str) -> Self {
121 +
        self.as_str().truncate(width, delim)
122 +
    }
123 +
124 +
    fn pad(&self, width: usize) -> Self {
125 +
        self.as_str().pad(width)
126 +
    }
127 +
}
128 +
129 +
impl Text for str {
130 +
    type Truncated = String;
131 +
    type Padded = String;
132 +
133 +
    fn width(&self) -> usize {
134 +
        if self.is_ascii() {
135 +
            self.len()
136 +
        } else {
137 +
            self.chars().map(char_width).sum()
138 +
        }
139 +
    }
140 +
141 +
    fn truncate(&self, width: usize, delim: &str) -> String {
142 +
        if width >= Text::width(self) {
143 +
            return self.to_owned();
144 +
        }
145 +
        let d = Text::width(delim);
146 +
147 +
        if width < d {
148 +
            return String::new();
149 +
        }
150 +
        let mut cols = 0;
151 +
        let mut boundary = 0;
152 +
153 +
        for (index, ch) in self.char_indices() {
154 +
            let c = char_width(ch);
155 +
            if cols + c + d > width {
156 +
                break;
157 +
            }
158 +
            cols += c;
159 +
            boundary = index + ch.len_utf8();
160 +
        }
161 +
162 +
        if self[boundary..].trim().is_empty() {
163 +
            self[..boundary].to_owned()
164 +
        } else {
165 +
            format!("{}{delim}", &self[..boundary])
166 +
        }
167 +
    }
168 +
169 +
    fn pad(&self, max: usize) -> String {
170 +
        let width = Text::width(self);
171 +
172 +
        if width < max {
173 +
            format!("{self}{}", " ".repeat(max - width))
174 +
        } else {
175 +
            self.to_owned()
176 +
        }
177 +
    }
178 +
}
179 +
180 +
impl<T: Text + ?Sized> Text for &T {
181 +
    type Truncated = T::Truncated;
182 +
    type Padded = T::Padded;
183 +
184 +
    fn width(&self) -> usize {
185 +
        T::width(self)
186 +
    }
187 +
188 +
    fn truncate(&self, width: usize, delim: &str) -> Self::Truncated {
189 +
        T::truncate(self, width, delim)
190 +
    }
191 +
192 +
    fn pad(&self, width: usize) -> Self::Padded {
193 +
        T::pad(self, width)
194 +
    }
195 +
}
196 +
197 +
impl<T: Text + fmt::Display> Text for Filled<T> {
198 +
    type Truncated = T::Truncated;
199 +
    type Padded = T::Padded;
200 +
201 +
    fn width(&self) -> usize {
202 +
        T::width(&self.item)
203 +
    }
204 +
205 +
    fn background(&self) -> Color {
206 +
        self.color
207 +
    }
208 +
209 +
    fn truncate(&self, width: usize, delim: &str) -> Self::Truncated {
210 +
        T::truncate(&self.item, width, delim)
211 +
    }
212 +
213 +
    fn pad(&self, width: usize) -> Self::Padded {
214 +
        T::pad(&self.item, width)
215 +
    }
216 +
}
217 +
218 +
/// Returns display width for one character.
219 +
pub(crate) fn char_width(ch: char) -> usize {
220 +
    if ch == '\u{fe0f}' || ch == '\u{fe0e}' || ch.is_control() {
221 +
        0
222 +
    // TODO: Move these glyphs somewhere and make them configurable, or include the
223 +
    // full set of unicode glyphs.
224 +
    } else if matches!(ch, '✓' | '✔' | '🗩') {
225 +
        1
226 +
    } else if matches!(
227 +
        ch as u32,
228 +
        0x1100..=0x115f
229 +
            | 0x2329..=0x232a
230 +
            | 0x2600..=0x27bf
231 +
            | 0x2e80..=0xa4cf
232 +
            | 0xac00..=0xd7a3
233 +
            | 0xf900..=0xfaff
234 +
            | 0xfe10..=0xfe19
235 +
            | 0xfe30..=0xfe6f
236 +
            | 0xff00..=0xff60
237 +
            | 0xffe0..=0xffe6
238 +
            | 0x1f000..=0x1faff
239 +
            | 0x20000..=0x3fffd
240 +
    ) {
241 +
        2
242 +
    } else {
243 +
        1
244 +
    }
245 +
}
246 +
247 +
#[cfg(test)]
248 +
mod tests {
249 +
    use super::Text as _;
250 +
251 +
    #[test]
252 +
    fn test_width() {
253 +
        assert_eq!("abc".width(), 3);
254 +
        assert_eq!("✓".width(), 1);
255 +
        assert_eq!("✔".width(), 1);
256 +
        assert_eq!("🗩".width(), 1);
257 +
        assert_eq!("2 ✔ · 4 hunks left".width(), 18);
258 +
        assert_eq!("❤️".width(), 2);
259 +
        assert_eq!("🪵".width(), 2);
260 +
    }
261 +
262 +
    #[test]
263 +
    fn test_truncate() {
264 +
        assert_eq!("🍍".truncate(1, "…"), String::from("…"));
265 +
        assert_eq!("🍍".truncate(1, ""), String::new());
266 +
        assert_eq!("🍍🍍".truncate(2, "…"), String::from("…"));
267 +
        assert_eq!("hello".truncate(3, "…"), String::from("he…"));
268 +
        assert_eq!("🍍🍍".truncate(3, "…"), String::from("🍍…"));
269 +
        assert_eq!("🍍".truncate(1, "🍎"), String::new());
270 +
        assert_eq!("🍍".truncate(2, "🍎"), String::from("🍍"));
271 +
        assert_eq!("🍍🍍".truncate(3, "🍎"), String::from("🍎"));
272 +
        assert_eq!("🍍🍍🍍".truncate(4, "🍎"), String::from("🍍🍎"));
273 +
    }
274 +
}
crates/tui-core/src/colors.rs added +115 -0
1 +
//! Shared color palette for terminal UI rendering.
2 +
//!
3 +
//! The constants here provide a small semantic palette for chrome, selection,
4 +
//! and text emphasis. Both RGB and fixed-color variants are grouped here so
5 +
//! widgets can use named colors without scattering terminal palette numbers.
6 +
7 +
use super::ansi::Color;
8 +
9 +
/// The faintest color; useful for borders and such.
10 +
pub const FAINT: Color = fixed::FAINT;
11 +
12 +
/// RGB (24-bit) colors supported by modern terminals.
13 +
pub mod rgb {
14 +
    use super::Color;
15 +
16 +
    /// Background color for removed or failing content.
17 +
    pub const NEGATIVE: Color = Color::RGB(60, 10, 20);
18 +
    /// Background color for added or successful content.
19 +
    pub const POSITIVE: Color = Color::RGB(10, 60, 20);
20 +
    /// Darker negative background color.
21 +
    pub const NEGATIVE_DARK: Color = Color::RGB(30, 10, 20);
22 +
    /// Darker positive background color.
23 +
    pub const POSITIVE_DARK: Color = Color::RGB(10, 30, 20);
24 +
    /// Lighter negative foreground color.
25 +
    pub const NEGATIVE_LIGHT: Color = Color::RGB(170, 80, 120);
26 +
    /// Lighter positive foreground color.
27 +
    pub const POSITIVE_LIGHT: Color = Color::RGB(80, 170, 120);
28 +
    /// Dim neutral foreground color.
29 +
    pub const DIM: Color = Color::RGB(100, 100, 100);
30 +
    /// Faint neutral foreground color.
31 +
    pub const FAINT: Color = Color::RGB(20, 20, 20);
32 +
33 +
    /// Default syntax theme purple.
34 +
    pub const PURPLE: Color = Color::RGB(0xd2, 0xa8, 0xff);
35 +
    /// Default syntax theme red.
36 +
    pub const RED: Color = Color::RGB(0xff, 0x7b, 0x72);
37 +
    /// Default syntax theme green.
38 +
    pub const GREEN: Color = Color::RGB(0x7e, 0xd7, 0x87);
39 +
    /// Default syntax theme teal.
40 +
    pub const TEAL: Color = Color::RGB(0xa5, 0xd6, 0xff);
41 +
    /// Default syntax theme orange.
42 +
    pub const ORANGE: Color = Color::RGB(0xff, 0xa6, 0x57);
43 +
    /// Default syntax theme blue.
44 +
    pub const BLUE: Color = Color::RGB(0x79, 0xc0, 0xff);
45 +
    /// Default syntax theme grey.
46 +
    pub const GREY: Color = Color::RGB(0x8b, 0x94, 0x9e);
47 +
    /// Default syntax theme light grey.
48 +
    pub const GREY_LIGHT: Color = Color::RGB(0xc9, 0xd1, 0xd9);
49 +
50 +
    /// Get a color using the color name.
51 +
    pub fn theme(name: &'static str) -> Option<Color> {
52 +
        match name {
53 +
            "negative" => Some(NEGATIVE),
54 +
            "negative.dark" => Some(NEGATIVE_DARK),
55 +
            "negative.light" => Some(NEGATIVE_LIGHT),
56 +
            "positive" => Some(POSITIVE),
57 +
            "positive.dark" => Some(POSITIVE_DARK),
58 +
            "positive.light" => Some(POSITIVE_LIGHT),
59 +
            "dim" => Some(DIM),
60 +
            "faint" => Some(FAINT),
61 +
            "purple" => Some(PURPLE),
62 +
            "red" => Some(RED),
63 +
            "green" => Some(GREEN),
64 +
            "teal" => Some(TEAL),
65 +
            "orange" => Some(ORANGE),
66 +
            "blue" => Some(BLUE),
67 +
            "grey" => Some(GREY),
68 +
            "grey.light" => Some(GREY_LIGHT),
69 +
70 +
            _ => None,
71 +
        }
72 +
    }
73 +
}
74 +
75 +
/// "Fixed" ANSI colors, supported by most terminals.
76 +
pub mod fixed {
77 +
    use super::Color;
78 +
79 +
    /// The faintest color; useful for borders and such.
80 +
    pub const FAINT: Color = Color::Fixed(236);
81 +
    /// Slightly brighter than faint.
82 +
    pub const DIM: Color = Color::Fixed(239);
83 +
84 +
    /// Get a color using the color name.
85 +
    pub fn theme(name: &'static str) -> Option<Color> {
86 +
        match name {
87 +
            "negative" | "red" => Some(Color::Red),
88 +
            "positive" | "green" => Some(Color::Green),
89 +
            "blue" => Some(Color::Blue),
90 +
            "teal" => Some(Color::Cyan),
91 +
            "purple" => Some(Color::Magenta),
92 +
            _ => None,
93 +
        }
94 +
    }
95 +
}
96 +
97 +
#[cfg(test)]
98 +
mod tests {
99 +
    use super::*;
100 +
101 +
    #[test]
102 +
    fn rgb_theme_resolves_named_palette_colors() {
103 +
        assert_eq!(rgb::theme("negative"), Some(rgb::NEGATIVE));
104 +
        assert_eq!(rgb::theme("positive"), Some(rgb::POSITIVE));
105 +
        assert_eq!(rgb::theme("unknown"), None);
106 +
    }
107 +
108 +
    #[test]
109 +
    fn fixed_theme_resolves_common_color_names() {
110 +
        assert_eq!(fixed::theme("red"), Some(Color::Red));
111 +
        assert_eq!(fixed::theme("green"), Some(Color::Green));
112 +
        assert_eq!(fixed::theme("blue"), Some(Color::Blue));
113 +
        assert_eq!(fixed::theme("unknown"), None);
114 +
    }
115 +
}
crates/tui-core/src/event.rs added +113 -0
1 +
//! Typed terminal events.
2 +
//!
3 +
//! Events are the input vocabulary consumed by [`App`](crate::App): key
4 +
//! presses, mouse input, resizes, and caller-defined custom events. Concrete
5 +
//! backends translate their native event streams into these values.
6 +
7 +
use crate::Size;
8 +
use crate::layout::Point;
9 +
10 +
/// Input or application event.
11 +
#[derive(Debug, Clone, PartialEq, Eq)]
12 +
pub enum Event<User = ()> {
13 +
    /// Key input.
14 +
    Key(Key),
15 +
    /// Mouse input.
16 +
    Mouse(Mouse),
17 +
    /// Terminal resize.
18 +
    Resize(Size),
19 +
    /// Bracketed paste or pasted text.
20 +
    Paste(String),
21 +
    /// Timer tick.
22 +
    Tick,
23 +
    /// User-defined event.
24 +
    User(User),
25 +
    /// Unsupported terminal input.
26 +
    Unsupported,
27 +
}
28 +
29 +
/// Keyboard input.
30 +
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
31 +
pub enum Key {
32 +
    /// Printable character.
33 +
    Char(char),
34 +
    /// Control character.
35 +
    Ctrl(char),
36 +
    /// Alt-modified character.
37 +
    Alt(char),
38 +
    /// Escape.
39 +
    Esc,
40 +
    /// Enter.
41 +
    Enter,
42 +
    /// Tab.
43 +
    Tab,
44 +
    /// Back-tab.
45 +
    BackTab,
46 +
    /// Backspace.
47 +
    Backspace,
48 +
    /// Delete.
49 +
    Delete,
50 +
    /// Insert.
51 +
    Insert,
52 +
    /// Left arrow.
53 +
    Left,
54 +
    /// Right arrow.
55 +
    Right,
56 +
    /// Up arrow.
57 +
    Up,
58 +
    /// Down arrow.
59 +
    Down,
60 +
    /// Home.
61 +
    Home,
62 +
    /// End.
63 +
    End,
64 +
    /// Page up.
65 +
    PageUp,
66 +
    /// Page down.
67 +
    PageDown,
68 +
    /// Function key.
69 +
    F(u8),
70 +
    /// Null key.
71 +
    Null,
72 +
    /// Unknown key.
73 +
    Unknown,
74 +
}
75 +
76 +
/// Mouse input.
77 +
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
78 +
pub enum Mouse {
79 +
    /// Button press.
80 +
    Press {
81 +
        /// Pressed button.
82 +
        button: MouseButton,
83 +
        /// Position.
84 +
        at: Point,
85 +
    },
86 +
    /// Button release.
87 +
    Release {
88 +
        /// Position.
89 +
        at: Point,
90 +
    },
91 +
    /// Mouse drag or hold.
92 +
    Hold {
93 +
        /// Position.
94 +
        at: Point,
95 +
    },
96 +
}
97 +
98 +
/// Mouse button.
99 +
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
100 +
pub enum MouseButton {
101 +
    /// Left button.
102 +
    Left,
103 +
    /// Right button.
104 +
    Right,
105 +
    /// Middle button.
106 +
    Middle,
107 +
    /// Wheel up.
108 +
    WheelUp,
109 +
    /// Wheel down.
110 +
    WheelDown,
111 +
    /// Unknown button.
112 +
    Unknown,
113 +
}
crates/tui-core/src/frame.rs added +41 -0
1 +
//! Render-time frame passed to applications.
2 +
//!
3 +
//! A frame exposes the current drawing area and mutable buffer for one render
4 +
//! pass. Applications render widgets into this frame; terminal diffing and
5 +
//! backend flushing happen after the frame is complete.
6 +
7 +
use crate::Widget;
8 +
use crate::buffer::Buffer;
9 +
use crate::layout::{Point, Rect};
10 +
11 +
/// Frame passed to application render methods.
12 +
#[derive(Debug)]
13 +
pub struct Frame<'a> {
14 +
    /// Area available for this frame.
15 +
    pub area: Rect,
16 +
    /// Buffer receiving rendered cells.
17 +
    pub buffer: &'a mut Buffer,
18 +
    /// Requested cursor position after rendering.
19 +
    pub cursor: Option<Point>,
20 +
}
21 +
22 +
impl<'a> Frame<'a> {
23 +
    /// Creates a frame over a buffer.
24 +
    pub fn new(area: Rect, buffer: &'a mut Buffer) -> Self {
25 +
        Self {
26 +
            area,
27 +
            buffer,
28 +
            cursor: None,
29 +
        }
30 +
    }
31 +
32 +
    /// Renders a widget into an area.
33 +
    pub fn render_widget<W: Widget>(&mut self, widget: W, area: Rect) {
34 +
        widget.render(area, self.buffer);
35 +
    }
36 +
37 +
    /// Sets the terminal cursor.
38 +
    pub fn set_cursor_position(&mut self, point: Point) {
39 +
        self.cursor = Some(point);
40 +
    }
41 +
}
crates/tui-core/src/hstack.rs added +213 -0
1 +
//! Horizontal widget layout container.
2 +
//!
3 +
//! `HStack` packs child widgets from left to right at their natural widths.
4 +
//! Spacer slots absorb leftover columns, making it a small primitive for
5 +
//! toolbar, header, and status-line composition.
6 +
7 +
use super::{Buffer, Constraint, Rect, Size, Widget};
8 +
9 +
/// One slot in an [`HStack`]: a fixed-width widget or a flexible spacer.
10 +
#[derive(Default, Debug)]
11 +
enum Slot<'a> {
12 +
    /// Widget rendered at its natural width.
13 +
    Widget(Box<dyn Widget + 'a>),
14 +
    /// Flexible spacer that absorbs leftover horizontal space.
15 +
    #[default]
16 +
    Spacer,
17 +
}
18 +
19 +
/// Horizontal stack of [`Widget`] objects.
20 +
///
21 +
/// Each widget child is laid out at its natural width. Spacer slots
22 +
/// absorb the leftover horizontal space allowed by the parent constraint,
23 +
/// allowing space-between layouts without manual padding arithmetic.
24 +
#[derive(Default, Debug)]
25 +
pub struct HStack<'a> {
26 +
    /// Slots in left-to-right rendering order.
27 +
    slots: Vec<Slot<'a>>,
28 +
}
29 +
30 +
impl<'a> HStack<'a> {
31 +
    /// Add a widget child to the stack.
32 +
    pub fn child(mut self, child: impl Widget + 'a) -> Self {
33 +
        self.push(child);
34 +
        self
35 +
    }
36 +
37 +
    /// Append a widget child to the stack in place.
38 +
    pub fn push(&mut self, child: impl Widget + 'a) {
39 +
        self.slots.push(Slot::Widget(Box::new(child)));
40 +
    }
41 +
42 +
    /// Add a flexible spacer that grows to fill leftover horizontal space.
43 +
    pub fn spacer(mut self) -> Self {
44 +
        self.slots.push(Slot::Spacer);
45 +
        self
46 +
    }
47 +
}
48 +
49 +
impl Widget for HStack<'_> {
50 +
    fn size(&self, parent: Constraint) -> Size {
51 +
        let widths = allocate_widths(&self.slots, parent);
52 +
        let total = widths.iter().copied().fold(0usize, usize::saturating_add);
53 +
        let height = self
54 +
            .slots
55 +
            .iter()
56 +
            .zip(&widths)
57 +
            .map(|(slot, &cols)| match slot {
58 +
                Slot::Widget(e) => e.rows(Constraint::tight(cols.max(1))),
59 +
                Slot::Spacer => 0,
60 +
            })
61 +
            .max()
62 +
            .unwrap_or(0);
63 +
64 +
        Size::new(total, height)
65 +
    }
66 +
67 +
    fn render(&self, area: Rect, buf: &mut Buffer) {
68 +
        let widths = allocate_widths(&self.slots, Constraint::max(area.size()));
69 +
        let mut x = area.x;
70 +
71 +
        for (slot, width) in self.slots.iter().zip(widths) {
72 +
            if x >= area.right() {
73 +
                break;
74 +
            }
75 +
            let width = width.min(area.right() - x);
76 +
            if let Slot::Widget(widget) = slot {
77 +
                widget.render(Rect::new(x, area.y, width, area.rows), buf);
78 +
            }
79 +
            x += width;
80 +
        }
81 +
    }
82 +
}
83 +
84 +
/// Allocates a column width to every slot, distributing leftover into spacers.
85 +
fn allocate_widths(slots: &[Slot<'_>], parent: Constraint) -> Vec<usize> {
86 +
    let max_cols = parent.max.cols;
87 +
    let mut widths = Vec::with_capacity(slots.len());
88 +
    let mut natural_total = 0usize;
89 +
    let mut spacer_count = 0usize;
90 +
91 +
    for slot in slots {
92 +
        match slot {
93 +
            Slot::Widget(e) => {
94 +
                let w = e.columns(Constraint::UNBOUNDED);
95 +
                widths.push(w);
96 +
                natural_total = natural_total.saturating_add(w);
97 +
            }
98 +
            Slot::Spacer => {
99 +
                widths.push(0);
100 +
                spacer_count += 1;
101 +
            }
102 +
        }
103 +
    }
104 +
105 +
    if spacer_count == 0 {
106 +
        return widths;
107 +
    }
108 +
    let remaining = if max_cols == usize::MAX {
109 +
        spacer_count
110 +
    } else {
111 +
        max_cols.saturating_sub(natural_total).max(spacer_count)
112 +
    };
113 +
    let per = remaining / spacer_count;
114 +
    let extra = remaining % spacer_count;
115 +
    let mut k = 0;
116 +
    for (i, slot) in slots.iter().enumerate() {
117 +
        if matches!(slot, Slot::Spacer) {
118 +
            widths[i] = per + usize::from(k < extra);
119 +
            k += 1;
120 +
        }
121 +
    }
122 +
    widths
123 +
}
124 +
125 +
#[cfg(test)]
126 +
mod tests {
127 +
    use super::*;
128 +
    use crate::Line;
129 +
130 +
    #[derive(Debug)]
131 +
    struct Expanding;
132 +
133 +
    impl Widget for Expanding {
134 +
        fn size(&self, parent: Constraint) -> Size {
135 +
            parent.max
136 +
        }
137 +
138 +
        fn render(&self, _area: Rect, _buf: &mut Buffer) {}
139 +
    }
140 +
141 +
    #[test]
142 +
    fn empty_stack_uses_no_space() {
143 +
        let stack = HStack::default();
144 +
145 +
        assert_eq!(stack.size(Constraint::tight(8)), Size::new(0, 0));
146 +
        assert!(stack.display(Constraint::tight(8)).is_empty());
147 +
    }
148 +
149 +
    #[test]
150 +
    fn natural_widths_sum_for_widget_children() {
151 +
        let stack = HStack::default()
152 +
            .child(Line::new("abcdef"))
153 +
            .child(Line::new("ghij"));
154 +
155 +
        assert_eq!(stack.size(Constraint::tight(80)), Size::new(10, 1));
156 +
        assert_eq!(
157 +
            stack.display(Constraint::tight(80)),
158 +
            "abcdefghij\n",
159 +
            "widgets pack at their natural widths"
160 +
        );
161 +
    }
162 +
163 +
    #[test]
164 +
    fn unbounded_expanding_children_do_not_overflow_natural_width() {
165 +
        let stack = HStack::default().child(Expanding).child(Expanding);
166 +
167 +
        assert_eq!(
168 +
            stack.size(Constraint::UNBOUNDED),
169 +
            Size::new(usize::MAX, usize::MAX)
170 +
        );
171 +
    }
172 +
173 +
    #[test]
174 +
    fn spacer_absorbs_leftover_horizontal_space() {
175 +
        let stack = HStack::default()
176 +
            .child(Line::new("L"))
177 +
            .spacer()
178 +
            .child(Line::new("R"));
179 +
180 +
        assert_eq!(stack.display(Constraint::tight(6)), "L    R\n");
181 +
    }
182 +
183 +
    #[test]
184 +
    fn multiple_spacers_split_remainder_evenly() {
185 +
        let stack = HStack::default()
186 +
            .child(Line::new("a"))
187 +
            .spacer()
188 +
            .child(Line::new("b"))
189 +
            .spacer()
190 +
            .child(Line::new("c"));
191 +
192 +
        assert_eq!(stack.display(Constraint::tight(7)), "a  b  c\n");
193 +
    }
194 +
195 +
    #[test]
196 +
    fn spacer_falls_back_to_one_column_when_unbounded() {
197 +
        let stack = HStack::default()
198 +
            .child(Line::new("L"))
199 +
            .spacer()
200 +
            .child(Line::new("R"));
201 +
202 +
        assert_eq!(stack.display(Constraint::UNBOUNDED), "L R\n");
203 +
    }
204 +
205 +
    #[test]
206 +
    fn column_rows_pad_to_column_width_when_neighbors_have_more_lines() {
207 +
        let stack = HStack::default()
208 +
            .child(vec![Line::new("aa"), Line::new("bb")])
209 +
            .child(Line::new("cc"));
210 +
211 +
        assert_eq!(stack.display(Constraint::tight(10)), "aacc\nbb  \n");
212 +
    }
213 +
}
crates/tui-core/src/label.rs added +146 -0
1 +
//! Single styled text segment.
2 +
//!
3 +
//! `Label` is the smallest styled text unit used by [`Line`](crate::Line) and
4 +
//! text widgets. It combines string content with paint/style metadata while
5 +
//! still supporting width-aware truncation and padding.
6 +
7 +
use std::fmt;
8 +
9 +
use super::{Color, Constraint, Filled, Line, Paint, Size, Style, Widget, cell::Text};
10 +
11 +
/// A styled string that does not contain any `'\n'` and implements [`Widget`] and [`Text`].
12 +
#[derive(Clone, Default, Debug)]
13 +
pub struct Label(Paint<String>);
14 +
15 +
impl Label {
16 +
    /// Creates a new label.
17 +
    pub fn new(s: &str) -> Self {
18 +
        Self(Paint::new(clean(s.to_owned())))
19 +
    }
20 +
21 +
    /// Creates a blank label.
22 +
    pub fn blank() -> Self {
23 +
        Self(Paint::default())
24 +
    }
25 +
26 +
    /// Returns whether this label is empty.
27 +
    pub fn is_blank(&self) -> bool {
28 +
        self.content().is_empty()
29 +
    }
30 +
31 +
    /// Returns unstyled content.
32 +
    pub fn content(&self) -> &str {
33 +
        self.0.content()
34 +
    }
35 +
36 +
    /// Creates a single-space label.
37 +
    pub fn space() -> Self {
38 +
        Self(Paint::new(" ".to_owned()))
39 +
    }
40 +
41 +
    /// Boxes the label.
42 +
    pub fn boxed(self) -> Box<dyn Widget> {
43 +
        Box::new(self)
44 +
    }
45 +
46 +
    /// Color the label's foreground.
47 +
    pub fn fg(self, color: Color) -> Self {
48 +
        Self(self.0.fg(color))
49 +
    }
50 +
51 +
    /// Color the label's background.
52 +
    pub fn bg(self, color: Color) -> Self {
53 +
        Self(self.0.bg(color))
54 +
    }
55 +
56 +
    /// Styles the label.
57 +
    pub fn style(self, style: Style) -> Self {
58 +
        Self(self.0.with_style(style))
59 +
    }
60 +
61 +
    /// Returns the inner paint object.
62 +
    pub fn paint(&self) -> &Paint<String> {
63 +
        &self.0
64 +
    }
65 +
66 +
    /// Returns this label with a fill background.
67 +
    pub fn filled(self, color: Color) -> Filled<Self> {
68 +
        Filled { item: self, color }
69 +
    }
70 +
71 +
    /// Wraps this label into a line.
72 +
    pub fn to_line(self) -> Line {
73 +
        Line::from(self)
74 +
    }
75 +
}
76 +
77 +
impl Widget for Label {
78 +
    fn size(&self, _parent: Constraint) -> Size {
79 +
        Size::new(self.0.width(), 1)
80 +
    }
81 +
82 +
    fn render(&self, area: crate::Rect, buf: &mut crate::Buffer) {
83 +
        Line::renders([Line::new(self.clone())], area, buf);
84 +
    }
85 +
}
86 +
87 +
impl fmt::Display for Label {
88 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89 +
        fmt::Display::fmt(&self.0, f)
90 +
    }
91 +
}
92 +
93 +
impl Text for Label {
94 +
    type Padded = Self;
95 +
    type Truncated = Self;
96 +
97 +
    fn background(&self) -> Color {
98 +
        self.paint().style.background
99 +
    }
100 +
101 +
    fn pad(&self, width: usize) -> Self::Padded {
102 +
        Self(self.0.pad(width))
103 +
    }
104 +
105 +
    fn truncate(&self, width: usize, delim: &str) -> Self::Truncated {
106 +
        Self(self.0.truncate(width, delim))
107 +
    }
108 +
109 +
    fn width(&self) -> usize {
110 +
        Text::width(&self.0)
111 +
    }
112 +
}
113 +
114 +
impl<D: fmt::Display> From<Paint<D>> for Label {
115 +
    fn from(paint: Paint<D>) -> Self {
116 +
        Self(Paint {
117 +
            item: clean(format!("{}", paint.item)),
118 +
            style: paint.style,
119 +
        })
120 +
    }
121 +
}
122 +
123 +
impl From<String> for Label {
124 +
    fn from(value: String) -> Self {
125 +
        Self(Paint::new(clean(value)))
126 +
    }
127 +
}
128 +
129 +
impl From<&str> for Label {
130 +
    fn from(value: &str) -> Self {
131 +
        Self::new(value)
132 +
    }
133 +
}
134 +
135 +
/// Creates a new label from a [`Paint`] object.
136 +
pub fn label(s: impl Into<Paint<String>>) -> Label {
137 +
    Label::from(s.into())
138 +
}
139 +
140 +
/// Removes unsupported label line breaks.
141 +
fn clean(mut input: String) -> String {
142 +
    if input.contains(['\n', '\r']) {
143 +
        input.retain(|c| c != '\n' && c != '\r');
144 +
    }
145 +
    input
146 +
}
crates/tui-core/src/layout.rs added +374 -0
1 +
//! Terminal geometry and splitting primitives.
2 +
//!
3 +
//! This module defines points, sizes, rectangles, layout constraints, and the
4 +
//! fixed/min/fill length model used by containers. It is deliberately numeric
5 +
//! and widget-agnostic so layout helpers can be tested without rendering.
6 +
7 +
use std::array;
8 +
use std::marker::PhantomData;
9 +
10 +
use crate::Size;
11 +
12 +
pub mod coord {
13 +
    //! Coordinate system markers.
14 +
15 +
    /// Terminal screen coordinates.
16 +
    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
17 +
    pub struct Screen;
18 +
19 +
    /// Widget-local coordinates.
20 +
    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
21 +
    pub struct Local;
22 +
}
23 +
24 +
/// A point in a coordinate system.
25 +
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
26 +
pub struct Point<U = coord::Screen> {
27 +
    /// Column coordinate.
28 +
    pub x: usize,
29 +
    /// Row coordinate.
30 +
    pub y: usize,
31 +
    /// Dimensional unit.
32 +
    unit: PhantomData<fn() -> U>,
33 +
}
34 +
35 +
impl<U> Clone for Point<U> {
36 +
    fn clone(&self) -> Self {
37 +
        *self
38 +
    }
39 +
}
40 +
41 +
impl<U> Copy for Point<U> {}
42 +
43 +
impl<U> Point<U> {
44 +
    /// Creates a point.
45 +
    pub const fn new(x: usize, y: usize) -> Self {
46 +
        Self {
47 +
            x,
48 +
            y,
49 +
            unit: PhantomData,
50 +
        }
51 +
    }
52 +
}
53 +
54 +
/// A rectangular terminal region.
55 +
#[derive(Debug, PartialEq, Eq, Hash)]
56 +
pub struct Rect<U = coord::Screen> {
57 +
    /// Left column.
58 +
    pub x: usize,
59 +
    /// Top row.
60 +
    pub y: usize,
61 +
    /// Width in terminal cells.
62 +
    pub cols: usize,
63 +
    /// Height in terminal cells.
64 +
    pub rows: usize,
65 +
    /// Dimensional unit.
66 +
    unit: PhantomData<fn() -> U>,
67 +
}
68 +
69 +
impl<U> Clone for Rect<U> {
70 +
    fn clone(&self) -> Self {
71 +
        *self
72 +
    }
73 +
}
74 +
75 +
impl<U> Copy for Rect<U> {}
76 +
77 +
impl<U> Default for Rect<U> {
78 +
    fn default() -> Self {
79 +
        Self::ZERO
80 +
    }
81 +
}
82 +
83 +
impl<U> Rect<U> {
84 +
    /// Empty rectangle at the origin.
85 +
    pub const ZERO: Self = Self::new(0, 0, 0, 0);
86 +
87 +
    /// Creates a rectangle.
88 +
    pub const fn new(x: usize, y: usize, cols: usize, rows: usize) -> Self {
89 +
        Self {
90 +
            x,
91 +
            y,
92 +
            cols,
93 +
            rows,
94 +
            unit: PhantomData,
95 +
        }
96 +
    }
97 +
98 +
    /// Creates a rectangle at the origin.
99 +
    pub const fn from_size(size: Size) -> Self {
100 +
        Self::new(0, 0, size.cols, size.rows)
101 +
    }
102 +
103 +
    /// Returns the rectangle size.
104 +
    pub const fn size(self) -> Size {
105 +
        Size::new(self.cols, self.rows)
106 +
    }
107 +
108 +
    /// Returns the right edge.
109 +
    pub const fn right(self) -> usize {
110 +
        self.x + self.cols
111 +
    }
112 +
113 +
    /// Returns the bottom edge.
114 +
    pub const fn bottom(self) -> usize {
115 +
        self.y + self.rows
116 +
    }
117 +
118 +
    /// Returns whether this rectangle is empty.
119 +
    pub const fn is_empty(self) -> bool {
120 +
        self.cols == 0 || self.rows == 0
121 +
    }
122 +
123 +
    /// Returns whether the point is inside this rectangle.
124 +
    pub const fn contains(self, point: Point<U>) -> bool {
125 +
        point.x >= self.x && point.x < self.right() && point.y >= self.y && point.y < self.bottom()
126 +
    }
127 +
128 +
    /// Returns this rectangle inset by `margin` cells.
129 +
    pub const fn inner(self, margin: usize) -> Self {
130 +
        let inset = margin * 2;
131 +
        if self.cols <= inset || self.rows <= inset {
132 +
            Self::new(self.x + margin, self.y + margin, 0, 0)
133 +
        } else {
134 +
            Self::new(
135 +
                self.x + margin,
136 +
                self.y + margin,
137 +
                self.cols - inset,
138 +
                self.rows - inset,
139 +
            )
140 +
        }
141 +
    }
142 +
143 +
    /// Returns the intersection of two rectangles.
144 +
    pub fn intersection(self, other: Self) -> Self {
145 +
        let x = self.x.max(other.x);
146 +
        let y = self.y.max(other.y);
147 +
        let right = self.right().min(other.right());
148 +
        let bottom = self.bottom().min(other.bottom());
149 +
150 +
        Self::new(x, y, right.saturating_sub(x), bottom.saturating_sub(y))
151 +
    }
152 +
}
153 +
154 +
/// Layout direction.
155 +
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
156 +
pub enum Direction {
157 +
    /// Split left-to-right.
158 +
    Horizontal,
159 +
    /// Split top-to-bottom.
160 +
    Vertical,
161 +
}
162 +
163 +
/// Length allocated by a split layout.
164 +
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
165 +
pub enum Length {
166 +
    /// A fixed number of terminal cells.
167 +
    Fixed(usize),
168 +
    /// A minimum number of cells plus a share of remaining space.
169 +
    Min(usize),
170 +
    /// Weighted share of remaining space.
171 +
    Fill(u16),
172 +
}
173 +
174 +
/// Deterministic split layout.
175 +
#[derive(Debug, Clone, PartialEq, Eq)]
176 +
pub struct Layout {
177 +
    /// Split direction.
178 +
    direction: Direction,
179 +
    /// Child lengths.
180 +
    lengths: Vec<Length>,
181 +
}
182 +
183 +
impl Layout {
184 +
    /// Creates a layout with a direction.
185 +
    pub fn new(direction: Direction) -> Self {
186 +
        Self {
187 +
            direction,
188 +
            lengths: Vec::new(),
189 +
        }
190 +
    }
191 +
192 +
    /// Adds a child length.
193 +
    pub fn child(mut self, length: Length) -> Self {
194 +
        self.lengths.push(length);
195 +
        self
196 +
    }
197 +
198 +
    /// Splits an area into child rectangles.
199 +
    pub fn split<U>(&self, area: Rect<U>) -> Vec<Rect<U>> {
200 +
        split(area, self.direction, &self.lengths)
201 +
    }
202 +
203 +
    /// Splits an area into a fixed-size array of child rectangles.
204 +
    pub fn areas<U, const N: usize>(&self, area: Rect<U>) -> [Rect<U>; N] {
205 +
        areas(area, self.direction, self.lengths.as_slice())
206 +
    }
207 +
}
208 +
209 +
/// Splits an area into rectangles.
210 +
pub fn split<U>(area: Rect<U>, direction: Direction, lengths: &[Length]) -> Vec<Rect<U>> {
211 +
    if lengths.is_empty() {
212 +
        return Vec::new();
213 +
    }
214 +
215 +
    let total = match direction {
216 +
        Direction::Horizontal => area.cols,
217 +
        Direction::Vertical => area.rows,
218 +
    };
219 +
    let widths = allocate(total, lengths);
220 +
    let mut cursor = match direction {
221 +
        Direction::Horizontal => area.x,
222 +
        Direction::Vertical => area.y,
223 +
    };
224 +
225 +
    widths
226 +
        .into_iter()
227 +
        .map(|amount| {
228 +
            let rect = match direction {
229 +
                Direction::Horizontal => Rect::new(cursor, area.y, amount, area.rows),
230 +
                Direction::Vertical => Rect::new(area.x, cursor, area.cols, amount),
231 +
            };
232 +
            cursor += amount;
233 +
            rect
234 +
        })
235 +
        .collect()
236 +
}
237 +
238 +
/// Splits an area into a fixed-size array of rectangles.
239 +
pub fn areas<U, const N: usize>(
240 +
    area: Rect<U>,
241 +
    direction: Direction,
242 +
    lengths: &[Length],
243 +
) -> [Rect<U>; N] {
244 +
    let chunks = split(area, direction, lengths);
245 +
246 +
    array::from_fn(|index| chunks.get(index).copied().unwrap_or(Rect::ZERO))
247 +
}
248 +
249 +
/// Allocates a one-dimensional split.
250 +
fn allocate(total: usize, lengths: &[Length]) -> Vec<usize> {
251 +
    let base = lengths
252 +
        .iter()
253 +
        .map(|length| match *length {
254 +
            Length::Fixed(n) | Length::Min(n) => n,
255 +
            Length::Fill(_) => 0,
256 +
        })
257 +
        .sum::<usize>();
258 +
    let fill = lengths
259 +
        .iter()
260 +
        .map(|length| match *length {
261 +
            Length::Fill(weight) => weight.max(1) as usize,
262 +
            _ => 0,
263 +
        })
264 +
        .sum::<usize>();
265 +
    let remaining = total.saturating_sub(base);
266 +
    let mut used = 0usize;
267 +
268 +
    lengths
269 +
        .iter()
270 +
        .enumerate()
271 +
        .map(|(i, length)| {
272 +
            let mut amount = match *length {
273 +
                Length::Fixed(n) | Length::Min(n) => n,
274 +
                Length::Fill(weight) if fill > 0 => remaining * weight.max(1) as usize / fill,
275 +
                Length::Fill(_) => 0,
276 +
            };
277 +
            if i == lengths.len() - 1 {
278 +
                amount = total.saturating_sub(used);
279 +
            }
280 +
            amount = amount.min(total.saturating_sub(used));
281 +
            used += amount;
282 +
            amount
283 +
        })
284 +
        .collect()
285 +
}
286 +
287 +
#[cfg(test)]
288 +
mod tests {
289 +
    use super::*;
290 +
291 +
    #[test]
292 +
    fn rect_inner_insets_edges() {
293 +
        let rect: Rect = Rect::new(2, 3, 10, 8);
294 +
295 +
        assert_eq!(rect.inner(1), Rect::new(3, 4, 8, 6));
296 +
        assert!(rect.contains(Point::new(2, 3)));
297 +
        assert!(!rect.contains(Point::new(12, 3)));
298 +
    }
299 +
300 +
    #[test]
301 +
    fn horizontal_split_distributes_fill() {
302 +
        let area: Rect = Rect::new(0, 0, 10, 3);
303 +
        let layout = Layout::new(Direction::Horizontal)
304 +
            .child(Length::Fixed(2))
305 +
            .child(Length::Fill(1))
306 +
            .child(Length::Fill(1));
307 +
308 +
        assert_eq!(
309 +
            layout.split(area),
310 +
            vec![
311 +
                Rect::new(0, 0, 2, 3),
312 +
                Rect::new(2, 0, 4, 3),
313 +
                Rect::new(6, 0, 4, 3),
314 +
            ]
315 +
        );
316 +
    }
317 +
318 +
    #[test]
319 +
    fn vertical_split_uses_minimums_and_weighted_fill() {
320 +
        let area: Rect = Rect::new(1, 2, 5, 10);
321 +
        let layout = Layout::new(Direction::Vertical)
322 +
            .child(Length::Min(2))
323 +
            .child(Length::Fill(1))
324 +
            .child(Length::Fill(2));
325 +
326 +
        assert_eq!(
327 +
            layout.split(area),
328 +
            vec![
329 +
                Rect::new(1, 2, 5, 2),
330 +
                Rect::new(1, 4, 5, 2),
331 +
                Rect::new(1, 6, 5, 6),
332 +
            ]
333 +
        );
334 +
    }
335 +
336 +
    #[test]
337 +
    fn split_clamps_when_fixed_lengths_exceed_available_space() {
338 +
        let area: Rect = Rect::new(0, 0, 3, 1);
339 +
        let layout = Layout::new(Direction::Horizontal)
340 +
            .child(Length::Fixed(2))
341 +
            .child(Length::Fixed(2))
342 +
            .child(Length::Fill(1));
343 +
344 +
        assert_eq!(
345 +
            layout.split(area),
346 +
            vec![
347 +
                Rect::new(0, 0, 2, 1),
348 +
                Rect::new(2, 0, 1, 1),
349 +
                Rect::new(3, 0, 0, 1),
350 +
            ]
351 +
        );
352 +
    }
353 +
354 +
    #[test]
355 +
    fn empty_split_returns_no_rectangles() {
356 +
        let area: Rect = Rect::new(0, 0, 3, 1);
357 +
358 +
        assert!(split(area, Direction::Horizontal, &[]).is_empty());
359 +
    }
360 +
361 +
    #[test]
362 +
    fn areas_returns_fixed_array_and_zero_fills_missing_chunks() {
363 +
        let area: Rect = Rect::new(0, 0, 5, 1);
364 +
        let [left, right, missing] = areas(
365 +
            area,
366 +
            Direction::Horizontal,
367 +
            &[Length::Fixed(2), Length::Fill(1)],
368 +
        );
369 +
370 +
        assert_eq!(left, Rect::new(0, 0, 2, 1));
371 +
        assert_eq!(right, Rect::new(2, 0, 3, 1));
372 +
        assert_eq!(missing, Rect::ZERO);
373 +
    }
374 +
}
crates/tui-core/src/lib.rs added +77 -0
1 +
//! Core primitives for the `rustik_tui` facade crate.
2 +
//!
3 +
//! The core keeps terminal I/O at the edge: applications own their state,
4 +
//! render into a reusable [`Buffer`], and flush through a narrow backend.
5 +
//! Widgets are plain values that measure themselves with [`Constraint`] and
6 +
//! write styled [`Cell`] values into the frame buffer.
7 +
//!
8 +
//! Styled text moves through three layers:
9 +
//!
10 +
//! - [`Paint<T>`](Paint) attaches a [`Style`] to any display value.
11 +
//! - [`Label`] is one cleaned, single-line styled text run used by [`Line`].
12 +
//! - [`Cell`] is the final buffer unit: one terminal glyph plus its style.
13 +
//!
14 +
#![deny(unsafe_code)]
15 +
#![warn(missing_docs)]
16 +
#![warn(clippy::unwrap_used)]
17 +
18 +
/// Widget alignment wrappers.
19 +
pub mod aligned;
20 +
/// ANSI color and style primitives.
21 +
pub mod ansi;
22 +
/// Application update and render traits.
23 +
pub mod app;
24 +
/// Terminal backends.
25 +
pub mod backend;
26 +
/// Shared border drawing primitives.
27 +
pub mod border;
28 +
/// Cell buffer and dirty-run diffing.
29 +
pub mod buffer;
30 +
/// Table cell sizing and padding support.
31 +
pub mod cell;
32 +
/// Shared terminal color palette.
33 +
pub mod colors;
34 +
/// Typed terminal events.
35 +
pub mod event;
36 +
/// Frame passed into application render calls.
37 +
pub mod frame;
38 +
/// Horizontal layout container.
39 +
pub mod hstack;
40 +
/// Text label widget.
41 +
pub mod label;
42 +
/// Strongly typed terminal layout primitives.
43 +
pub mod layout;
44 +
/// Core line and sizing primitives.
45 +
pub mod primitive;
46 +
/// Column-aligned table widget.
47 +
pub mod table;
48 +
/// Double-buffered terminal renderer.
49 +
pub mod terminal;
50 +
/// Styled text constructors.
51 +
pub mod text;
52 +
/// Wrapped text area widget.
53 +
pub mod textarea;
54 +
/// Vertical layout container.
55 +
pub mod vstack;
56 +
/// Immediate-mode widgets.
57 +
pub mod widget;
58 +
59 +
pub use aligned::{Align, Aligned};
60 +
pub use ansi::Color;
61 +
pub use ansi::{Filled, Paint, PaintMode, Painted, Style, paint};
62 +
pub use app::{App, Control, drive};
63 +
pub use backend::{Backend, TestBackend};
64 +
pub use border::{Border, BorderChars};
65 +
pub use buffer::{Buffer, Cell};
66 +
pub use cell::Text;
67 +
pub use event::{Event, Key, Mouse, MouseButton};
68 +
pub use frame::Frame;
69 +
pub use hstack::HStack;
70 +
pub use label::{Label, label};
71 +
pub use layout::{Direction, Length, Point, Rect};
72 +
pub use primitive::{Constraint, Line, Size, StyledLine};
73 +
pub use table::{Table, TableOptions};
74 +
pub use terminal::Terminal;
75 +
pub use textarea::{TextArea, textarea};
76 +
pub use vstack::{VStack, VStackOptions};
77 +
pub use widget::{Block, Clear, Fill, Widget};
crates/tui-core/src/primitive.rs added +473 -0
1 +
//! Core text-line and sizing primitives.
2 +
//!
3 +
//! `Constraint`, `Size`, and `Line` are the shared building blocks most widgets
4 +
//! depend on. This module keeps text-line composition and basic widget sizing
5 +
//! close together because width-aware rendering needs both.
6 +
7 +
use std::fmt;
8 +
use std::vec;
9 +
10 +
use super::cell::Text;
11 +
use crate::widget::Widget;
12 +
13 +
use super::{Buffer, Color, Filled, Label, Rect, Style};
14 +
15 +
/// Rendering constraint.
16 +
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
17 +
pub struct Constraint {
18 +
    /// Minimum space the widget can take.
19 +
    pub min: Size,
20 +
    /// Maximum space the widget can take.
21 +
    pub max: Size,
22 +
}
23 +
24 +
impl Default for Constraint {
25 +
    fn default() -> Self {
26 +
        Self::UNBOUNDED
27 +
    }
28 +
}
29 +
30 +
impl Constraint {
31 +
    /// Can satisfy any size of object.
32 +
    pub const UNBOUNDED: Self = Self {
33 +
        min: Size::MIN,
34 +
        max: Size::MAX,
35 +
    };
36 +
37 +
    /// Creates a new constraint.
38 +
    pub fn new(min: Size, max: Size) -> Self {
39 +
        assert!(min.cols <= max.cols && min.rows <= max.rows);
40 +
41 +
        Self { min, max }
42 +
    }
43 +
44 +
    /// A constraint with only a maximum size.
45 +
    pub fn max(max: Size) -> Self {
46 +
        Self {
47 +
            min: Size::MIN,
48 +
            max,
49 +
        }
50 +
    }
51 +
52 +
    /// A constraint that can only be satisfied by a single column size.
53 +
    /// The rows are unconstrained.
54 +
    pub fn tight(cols: usize) -> Self {
55 +
        Self {
56 +
            min: Size::new(cols, 1),
57 +
            max: Size::new(cols, usize::MAX),
58 +
        }
59 +
    }
60 +
61 +
    /// Returns a finite size that satisfies this constraint.
62 +
    pub fn bounded_size(self) -> Size {
63 +
        Size::new(
64 +
            bounded(self.min.cols, self.max.cols),
65 +
            bounded(self.min.rows, self.max.rows),
66 +
        )
67 +
        .constrain(self)
68 +
    }
69 +
}
70 +
71 +
/// Chooses a finite bound from a minimum and maximum constraint.
72 +
fn bounded(min: usize, max: usize) -> usize {
73 +
    if max == usize::MAX { min } else { max }
74 +
}
75 +
76 +
/// A line of text that has styling and can be displayed.
77 +
#[derive(Clone, Default, Debug)]
78 +
pub struct Line {
79 +
    items: Vec<Label>,
80 +
}
81 +
82 +
/// A line display adapter that writes styled text.
83 +
pub struct StyledLine<'a> {
84 +
    line: &'a Line,
85 +
}
86 +
87 +
impl Line {
88 +
    /// Creates a new line.
89 +
    pub fn new(item: impl Into<Label>) -> Self {
90 +
        Self {
91 +
            items: vec![item.into()],
92 +
        }
93 +
    }
94 +
95 +
    /// Creates a blank line.
96 +
    pub fn blank() -> Self {
97 +
        Self::default()
98 +
    }
99 +
100 +
    /// Returns a styled line by styling all its labels.
101 +
    pub fn style(self, style: Style) -> Line {
102 +
        Self {
103 +
            items: self
104 +
                .items
105 +
                .into_iter()
106 +
                .map(|l| {
107 +
                    let style = l.paint().style().merge(style);
108 +
                    l.style(style)
109 +
                })
110 +
                .collect(),
111 +
        }
112 +
    }
113 +
114 +
    /// Returns a line with a single space between the given labels.
115 +
    // TODO: Use [`Iterator::intersperse`] when MSRV is updated.
116 +
    pub fn spaced(items: impl IntoIterator<Item = Label>) -> Self {
117 +
        let items = items.into_iter();
118 +
        let mut line = Self {
119 +
            items: Vec::with_capacity(items.size_hint().1.unwrap_or_default().saturating_mul(2)),
120 +
        };
121 +
122 +
        // Don't create spaces around empty labels.
123 +
        for item in items.filter(|i| !i.is_blank()) {
124 +
            line.push(item);
125 +
            line.push(Label::space());
126 +
        }
127 +
        line.items.pop();
128 +
        line
129 +
    }
130 +
131 +
    /// Adds an item to this line.
132 +
    pub fn item(mut self, item: impl Into<Label>) -> Self {
133 +
        self.push(item);
134 +
        self
135 +
    }
136 +
137 +
    /// Adds multiple items to this line.
138 +
    pub fn extend(mut self, items: impl IntoIterator<Item = Label>) -> Self {
139 +
        self.items.extend(items);
140 +
        self
141 +
    }
142 +
143 +
    /// Adds an item to this line.
144 +
    pub fn push(&mut self, item: impl Into<Label>) {
145 +
        self.items.push(item.into());
146 +
    }
147 +
148 +
    /// Pad this line to occupy the given width.
149 +
    pub fn pad(&mut self, width: usize) {
150 +
        let w = self.width();
151 +
152 +
        if width > w {
153 +
            let pad = width - w;
154 +
            let bg = self.items.last().map_or(Color::Unset, Label::background);
155 +
            self.items.push(Label::new(" ".repeat(pad).as_str()).bg(bg));
156 +
        }
157 +
    }
158 +
159 +
    /// Returns this line padded to occupy the given width.
160 +
    pub fn padded(mut self, width: usize) -> Self {
161 +
        Line::pad(&mut self, width);
162 +
        self
163 +
    }
164 +
165 +
    /// Truncate this line to the given width.
166 +
    pub fn truncate(&mut self, width: usize, delim: &str) {
167 +
        while self.width() > width {
168 +
            let total = self.width();
169 +
170 +
            if total - self.items.last().map_or(0, Text::width) > width {
171 +
                self.items.pop();
172 +
            } else if let Some(item) = self.items.last_mut() {
173 +
                *item = item.truncate(width - (total - Text::width(item)), delim);
174 +
            }
175 +
        }
176 +
    }
177 +
178 +
    /// Returns this line truncated to the given width.
179 +
    pub fn truncated(mut self, width: usize, delim: &str) -> Self {
180 +
        Line::truncate(&mut self, width, delim);
181 +
        self
182 +
    }
183 +
184 +
    /// Returns this line with one leading space and padding to the given width.
185 +
    pub fn inset(self, width: usize) -> Self {
186 +
        if width <= 2 {
187 +
            return self;
188 +
        }
189 +
190 +
        Line::new(" ").extend(self).padded(width)
191 +
    }
192 +
193 +
    /// Returns the actual column width of this line.
194 +
    pub fn width(&self) -> usize {
195 +
        self.items.iter().map(Text::width).sum()
196 +
    }
197 +
198 +
    /// Returns the labels that make up this line.
199 +
    pub fn labels(&self) -> &[Label] {
200 +
        &self.items
201 +
    }
202 +
203 +
    /// Returns a display adapter that writes styled text.
204 +
    pub const fn styled(&self) -> StyledLine<'_> {
205 +
        StyledLine { line: self }
206 +
    }
207 +
208 +
    /// Creates a line that contains a single space.
209 +
    pub fn space(mut self) -> Self {
210 +
        self.items.push(Label::space());
211 +
        self
212 +
    }
213 +
214 +
    /// Boxes this line as a [`Widget`].
215 +
    pub fn boxed(self) -> Box<dyn Widget> {
216 +
        Box::new(self)
217 +
    }
218 +
219 +
    /// Returns a filled line.
220 +
    pub fn filled(self, color: Color) -> Filled<Self> {
221 +
        Filled { item: self, color }
222 +
    }
223 +
224 +
    /// Renders line rows into a buffer area.
225 +
    pub fn renders(lines: impl IntoIterator<Item = Line>, area: Rect, buf: &mut Buffer) {
226 +
        for (row, mut line) in lines.into_iter().enumerate() {
227 +
            if row >= area.rows {
228 +
                break;
229 +
            }
230 +
            if line.width() > area.cols {
231 +
                Line::truncate(&mut line, area.cols, "…");
232 +
            }
233 +
            buf.set_line(area.x, area.y + row, &line);
234 +
        }
235 +
    }
236 +
}
237 +
238 +
impl IntoIterator for Line {
239 +
    type Item = Label;
240 +
    type IntoIter = vec::IntoIter<Label>;
241 +
242 +
    fn into_iter(self) -> Self::IntoIter {
243 +
        self.items.into_iter()
244 +
    }
245 +
}
246 +
247 +
impl<T: Into<Label>> From<T> for Line {
248 +
    fn from(value: T) -> Self {
249 +
        Self::new(value)
250 +
    }
251 +
}
252 +
253 +
impl From<Vec<Label>> for Line {
254 +
    fn from(items: Vec<Label>) -> Self {
255 +
        Self { items }
256 +
    }
257 +
}
258 +
259 +
impl Widget for Line {
260 +
    fn size(&self, _parent: Constraint) -> Size {
261 +
        Size::new(self.width(), 1)
262 +
    }
263 +
264 +
    fn render(&self, area: crate::Rect, buf: &mut crate::Buffer) {
265 +
        Line::renders([self.clone()], area, buf);
266 +
    }
267 +
}
268 +
269 +
impl Widget for Vec<Line> {
270 +
    fn size(&self, _parent: Constraint) -> Size {
271 +
        let width = self.iter().map(Line::width).max().unwrap_or_default();
272 +
        let height = self.len();
273 +
274 +
        Size::new(width, height)
275 +
    }
276 +
277 +
    fn render(&self, area: crate::Rect, buf: &mut crate::Buffer) {
278 +
        Line::renders(self.clone(), area, buf);
279 +
    }
280 +
}
281 +
282 +
impl fmt::Display for Line {
283 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
284 +
        for item in &self.items {
285 +
            write!(f, "{item}")?;
286 +
        }
287 +
        Ok(())
288 +
    }
289 +
}
290 +
291 +
impl fmt::Display for StyledLine<'_> {
292 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293 +
        for item in &self.line.items {
294 +
            write!(f, "{}", item.paint().styled())?;
295 +
        }
296 +
        Ok(())
297 +
    }
298 +
}
299 +
300 +
/// Size of terminal content, in columns and rows.
301 +
#[derive(Clone, Debug, Default, Copy, PartialEq, Eq)]
302 +
pub struct Size {
303 +
    /// Columns occupied.
304 +
    pub cols: usize,
305 +
    /// Rows occupied.
306 +
    pub rows: usize,
307 +
}
308 +
309 +
impl Size {
310 +
    /// Minimum size.
311 +
    pub const MIN: Self = Self {
312 +
        cols: usize::MIN,
313 +
        rows: usize::MIN,
314 +
    };
315 +
    /// Maximum size.
316 +
    pub const MAX: Self = Self {
317 +
        cols: usize::MAX,
318 +
        rows: usize::MAX,
319 +
    };
320 +
321 +
    /// Creates a new [`Size`].
322 +
    pub const fn new(cols: usize, rows: usize) -> Self {
323 +
        Self { cols, rows }
324 +
    }
325 +
326 +
    /// Constrain size.
327 +
    pub fn constrain(self, c: Constraint) -> Self {
328 +
        Self {
329 +
            cols: self.cols.clamp(c.min.cols, c.max.cols),
330 +
            rows: self.rows.clamp(c.min.rows, c.max.rows),
331 +
        }
332 +
    }
333 +
}
334 +
335 +
#[cfg(test)]
336 +
#[allow(clippy::unwrap_used)]
337 +
mod tests {
338 +
    use super::*;
339 +
340 +
    #[test]
341 +
    fn test_truncate() {
342 +
        let line = Line::default().item("banana").item("peach").item("apple");
343 +
344 +
        let mut actual = line.clone();
345 +
        Line::truncate(&mut actual, 9, "…");
346 +
        assert_eq!(actual.to_string(), "bananape…");
347 +
348 +
        let mut actual = line.clone();
349 +
        Line::truncate(&mut actual, 7, "…");
350 +
        assert_eq!(actual.to_string(), "banana…");
351 +
352 +
        let mut actual = line.clone();
353 +
        Line::truncate(&mut actual, 1, "…");
354 +
        assert_eq!(actual.to_string(), "…");
355 +
356 +
        let mut actual = line;
357 +
        Line::truncate(&mut actual, 0, "…");
358 +
        assert_eq!(actual.to_string(), "");
359 +
    }
360 +
361 +
    #[test]
362 +
    fn test_width() {
363 +
        // Nb. This might not display correctly in some editors or terminals.
364 +
        let line = Line::new("Radicle Heartwood Protocol & Stack ❤️🪵");
365 +
        assert_eq!(line.width(), 39, "{line}");
366 +
        let line = Line::new("❤\u{fe0f}");
367 +
        assert_eq!(line.width(), 2, "{line}");
368 +
        let line = Line::new("❤️");
369 +
        assert_eq!(line.width(), 2, "{line}");
370 +
    }
371 +
372 +
    #[test]
373 +
    fn test_spaced() {
374 +
        let line = Line::spaced(["banana", "peach", "apple"].into_iter().map(Label::new));
375 +
376 +
        let iterated: Vec<_> = line.into_iter().collect();
377 +
        assert_eq!(
378 +
            iterated
379 +
                .into_iter()
380 +
                .map(|l| l.to_string())
381 +
                .collect::<Vec<_>>(),
382 +
            ["banana", " ", "peach", " ", "apple"]
383 +
        );
384 +
    }
385 +
386 +
    #[test]
387 +
    fn spaced_ignores_blank_labels() {
388 +
        let line = Line::spaced([Label::new("banana"), Label::blank(), Label::new("apple")]);
389 +
390 +
        assert_eq!(line.to_string(), "banana apple");
391 +
    }
392 +
393 +
    #[test]
394 +
    fn line_styled_adapter_formats_label_styles_explicitly() {
395 +
        let line = Line::new(Label::new("x").fg(Color::Red)).item(Label::new("y").fg(Color::Blue));
396 +
397 +
        assert_eq!(line.to_string(), "xy");
398 +
        assert_eq!(
399 +
            line.styled().to_string(),
400 +
            "\x1B[31mx\x1B[0m\x1B[34my\x1B[0m"
401 +
        );
402 +
        assert_eq!(
403 +
            Widget::display_styled(&line, Constraint::UNBOUNDED),
404 +
            "\x1B[31mx\x1B[0m\x1B[34my\x1B[0m\n"
405 +
        );
406 +
    }
407 +
408 +
    #[test]
409 +
    fn line_pad_uses_last_label_background() {
410 +
        let mut line = Line::new(Label::new("x").bg(Color::Red));
411 +
412 +
        Line::pad(&mut line, 3);
413 +
414 +
        let labels = line.into_iter().collect::<Vec<_>>();
415 +
        assert_eq!(labels.len(), 2);
416 +
        assert_eq!(labels[1].content(), "  ");
417 +
        assert_eq!(labels[1].background(), Color::Red);
418 +
    }
419 +
420 +
    #[test]
421 +
    fn line_value_helpers_pad_truncate_and_inset() {
422 +
        assert_eq!(Line::new("x").padded(3).to_string(), "x  ");
423 +
        assert_eq!(Line::new("abcdef").truncated(4, "…").to_string(), "abc…");
424 +
        assert_eq!(Line::new("x").inset(4).to_string(), " x  ");
425 +
    }
426 +
427 +
    #[test]
428 +
    fn line_boxed_dispatches_widget_methods() {
429 +
        let line = Line::new("boxed");
430 +
        let boxed = line.boxed();
431 +
432 +
        assert_eq!(boxed.size(Constraint::UNBOUNDED), Size::new(5, 1));
433 +
        assert_eq!(boxed.display(Constraint::UNBOUNDED), "boxed\n");
434 +
    }
435 +
436 +
    #[test]
437 +
    fn widget_reference_dispatches_widget_methods() {
438 +
        let line = Line::new("ref");
439 +
        let reference = &line;
440 +
441 +
        assert_eq!(reference.size(Constraint::UNBOUNDED), Size::new(3, 1));
442 +
        assert_eq!(reference.display(Constraint::UNBOUNDED), "ref\n");
443 +
    }
444 +
445 +
    #[test]
446 +
    fn vec_line_widget_size_uses_widest_line_and_line_count() {
447 +
        let lines = vec![Line::new("short"), Line::new("longer")];
448 +
449 +
        assert_eq!(lines.size(Constraint::UNBOUNDED), Size::new(6, 2));
450 +
        assert_eq!(lines.display(Constraint::UNBOUNDED), "short \nlonger\n");
451 +
    }
452 +
453 +
    #[test]
454 +
    fn size_and_constraint_helpers_clamp_dimensions() {
455 +
        let constraint = Constraint::new(Size::new(2, 3), Size::new(5, 7));
456 +
457 +
        assert_eq!(Size::new(1, 9).constrain(constraint), Size::new(2, 7));
458 +
        assert_eq!(
459 +
            Constraint::max(Size::new(4, 8)),
460 +
            Constraint {
461 +
                min: Size::MIN,
462 +
                max: Size::new(4, 8),
463 +
            }
464 +
        );
465 +
        assert_eq!(
466 +
            Constraint::tight(6),
467 +
            Constraint {
468 +
                min: Size::new(6, 1),
469 +
                max: Size::new(6, usize::MAX),
470 +
            }
471 +
        );
472 +
    }
473 +
}
crates/tui-core/src/table.rs added +602 -0
1 +
//! Column-aligned table widget.
2 +
//!
3 +
//! `Table` tracks per-column widths as rows are pushed, then renders rows as
4 +
//! styled [`Line`](crate::Line) values or directly as a widget. It is intended
5 +
//! for compact operational views where stable alignment matters more than
6 +
//! complex cell layout.
7 +
//!
8 +
//! Example:
9 +
//! ```
10 +
//! use rustik_tui_core::{Constraint, Table, TableOptions, Widget};
11 +
//!
12 +
//! let mut t = Table::new(TableOptions::default());
13 +
//! t.push(["pest", "biological control"]);
14 +
//! t.push(["aphid", "lacewing"]);
15 +
//! t.push(["spider mite", "ladybug"]);
16 +
//!
17 +
//! let out = t
18 +
//!     .display(Constraint::UNBOUNDED)
19 +
//!     .lines()
20 +
//!     .map(str::trim_end)
21 +
//!     .collect::<Vec<_>>()
22 +
//!     .join("\n")
23 +
//!     + "\n";
24 +
//! assert_eq!(
25 +
//!     out,
26 +
//!     "pest        biological control\naphid       lacewing\nspider mite ladybug\n",
27 +
//! );
28 +
//! # Ok::<(), Box<dyn std::error::Error>>(())
29 +
//! ```
30 +
//! Output:
31 +
//! ``` plain
32 +
//! pest        biological control
33 +
//! aphid       lacewing
34 +
//! spider mite ladybug
35 +
//! ```
36 +
use std::fmt;
37 +
38 +
use super::cell::Text;
39 +
use super::{Border, Constraint, Line, Size, Style, Widget, colors};
40 +
41 +
/// Rendering options for a table.
42 +
#[derive(Debug)]
43 +
pub struct TableOptions {
44 +
    /// Whether the table should be allowed to overflow.
45 +
    pub overflow: bool,
46 +
    /// Horizontal spacing between table cells.
47 +
    pub spacing: usize,
48 +
    /// Table border.
49 +
    pub border: Option<Border>,
50 +
}
51 +
52 +
impl Default for TableOptions {
53 +
    fn default() -> Self {
54 +
        Self {
55 +
            overflow: false,
56 +
            spacing: 1,
57 +
            border: None,
58 +
        }
59 +
    }
60 +
}
61 +
62 +
impl TableOptions {
63 +
    /// Returns default options with a faint border enabled.
64 +
    pub fn bordered() -> Self {
65 +
        Self {
66 +
            border: Some(Border::new(colors::FAINT)),
67 +
            spacing: 3,
68 +
            ..Self::default()
69 +
        }
70 +
    }
71 +
}
72 +
73 +
/// Internal row representation for table rendering.
74 +
#[derive(Debug)]
75 +
enum Row<const W: usize, T> {
76 +
    /// Header row.
77 +
    Header([T; W]),
78 +
    /// Data row.
79 +
    Data([T; W]),
80 +
    /// Horizontal divider row.
81 +
    Divider {
82 +
        /// Horizontal line sigil used for this divider.
83 +
        sigil: &'static str,
84 +
    },
85 +
}
86 +
87 +
/// Fixed-width table with `W` columns.
88 +
#[derive(Debug)]
89 +
pub struct Table<const W: usize, T> {
90 +
    /// Rows in insertion order.
91 +
    rows: Vec<Row<W, T>>,
92 +
    /// Maximum content width for each column.
93 +
    widths: [usize; W],
94 +
    /// Rendering options.
95 +
    opts: TableOptions,
96 +
}
97 +
98 +
impl<const W: usize, T> Default for Table<W, T> {
99 +
    fn default() -> Self {
100 +
        Self {
101 +
            rows: Vec::new(),
102 +
            widths: [0; W],
103 +
            opts: TableOptions::default(),
104 +
        }
105 +
    }
106 +
}
107 +
108 +
impl<const W: usize, T: Text> FromIterator<[T; W]> for Table<W, T> {
109 +
    fn from_iter<I: IntoIterator<Item = [T; W]>>(iter: I) -> Self {
110 +
        let mut table = Self::default();
111 +
        table.extend(iter);
112 +
        table
113 +
    }
114 +
}
115 +
116 +
impl<const W: usize, T: Text + fmt::Debug + Send + Sync> Widget for Table<W, T>
117 +
where
118 +
    T::Padded: Into<Line>,
119 +
{
120 +
    fn size(&self, parent: Constraint) -> Size {
121 +
        Table::size(self, parent)
122 +
    }
123 +
124 +
    fn render(&self, area: crate::Rect, buf: &mut crate::Buffer) {
125 +
        let size = area.size();
126 +
        Line::renders(self.lines(Constraint::new(size, size)), area, buf);
127 +
    }
128 +
}
129 +
130 +
impl<const W: usize, T: Text> Table<W, T>
131 +
where
132 +
    T::Padded: Into<Line>,
133 +
{
134 +
    /// Returns the table as styled render lines under a parent constraint.
135 +
    pub fn lines(&self, parent: Constraint) -> Vec<Line> {
136 +
        let mut lines = Vec::new();
137 +
138 +
        // Don't print empty tables.
139 +
        if self.is_empty() {
140 +
            return lines;
141 +
        }
142 +
143 +
        let border = self.opts.border;
144 +
        let inner = self.inner(parent);
145 +
        let cols = inner.cols;
146 +
        let max_rows = parent.max.rows;
147 +
148 +
        if let Some(border) = border {
149 +
            lines.push(border.top(cols));
150 +
        }
151 +
152 +
        for row in &self.rows {
153 +
            if lines.len() == max_rows {
154 +
                break;
155 +
            }
156 +
            let mut line = Line::default();
157 +
158 +
            match row {
159 +
                Row::Header(cells) | Row::Data(cells) => {
160 +
                    if let Some(border) = border {
161 +
                        line.push(border.left(1));
162 +
                    }
163 +
                    for (i, cell) in cells.iter().enumerate() {
164 +
                        let pad = if i == cells.len() - 1 {
165 +
                            0
166 +
                        } else {
167 +
                            self.widths[i] + self.opts.spacing
168 +
                        };
169 +
                        line = line.extend(
170 +
                            cell.pad(pad)
171 +
                                .into()
172 +
                                .style(Style::default().bg(cell.background())),
173 +
                        );
174 +
                    }
175 +
                    Line::pad(&mut line, cols);
176 +
                    Line::truncate(&mut line, cols, "…");
177 +
178 +
                    if let Some(border) = border {
179 +
                        line.push(border.right(1));
180 +
                    }
181 +
                    lines.push(line);
182 +
                }
183 +
                Row::Divider { sigil } => {
184 +
                    if let Some(border) = border {
185 +
                        lines.push(border.divider(cols, sigil));
186 +
                    } else {
187 +
                        lines.push(Line::default());
188 +
                    }
189 +
                }
190 +
            }
191 +
        }
192 +
        if let Some(border) = border
193 +
            && lines.len() < max_rows
194 +
        {
195 +
            lines.push(border.bottom(cols));
196 +
        }
197 +
        lines
198 +
    }
199 +
}
200 +
201 +
impl<const W: usize, T: Text> Table<W, T> {
202 +
    /// Creates an empty table with explicit options.
203 +
    pub fn new(opts: TableOptions) -> Self {
204 +
        Self {
205 +
            rows: Vec::new(),
206 +
            widths: [0; W],
207 +
            opts,
208 +
        }
209 +
    }
210 +
211 +
    /// Returns the table with replacement options.
212 +
    pub fn with_opts(mut self, opts: TableOptions) -> Self {
213 +
        self.opts = opts;
214 +
        self
215 +
    }
216 +
217 +
    /// Returns the rendered table size under a parent constraint.
218 +
    pub fn size(&self, parent: Constraint) -> Size {
219 +
        if self.is_empty() {
220 +
            return Size::MIN;
221 +
        }
222 +
        self.outer(parent)
223 +
    }
224 +
225 +
    /// Adds a divider row.
226 +
    pub fn divider(&mut self) {
227 +
        self.divider_with_sigil("─");
228 +
    }
229 +
230 +
    /// Adds a divider row with an explicit line sigil.
231 +
    pub fn divider_with_sigil(&mut self, sigil: &'static str) {
232 +
        self.rows.push(Row::Divider { sigil });
233 +
    }
234 +
235 +
    /// Adds a data row.
236 +
    pub fn push(&mut self, row: [T; W]) {
237 +
        for (i, cell) in row.iter().enumerate() {
238 +
            self.widths[i] = self.widths[i].max(cell.width());
239 +
        }
240 +
        self.rows.push(Row::Data(row));
241 +
    }
242 +
243 +
    /// Adds a header row.
244 +
    pub fn header(&mut self, row: [T; W]) {
245 +
        for (i, cell) in row.iter().enumerate() {
246 +
            self.widths[i] = self.widths[i].max(cell.width());
247 +
        }
248 +
        self.rows.push(Row::Header(row));
249 +
    }
250 +
251 +
    /// Returns whether the table contains no data rows.
252 +
    pub fn is_empty(&self) -> bool {
253 +
        !self.rows.iter().any(|r| matches!(r, Row::Data(..)))
254 +
    }
255 +
256 +
    /// Returns the table size inside any border.
257 +
    fn inner(&self, c: Constraint) -> Size {
258 +
        let mut outer = self.outer(c);
259 +
260 +
        if self.opts.border.is_some() {
261 +
            outer.cols = outer.cols.saturating_sub(2);
262 +
            outer.rows = outer.rows.saturating_sub(2);
263 +
        }
264 +
        outer
265 +
    }
266 +
267 +
    /// Returns the table size including any border.
268 +
    fn outer(&self, c: Constraint) -> Size {
269 +
        let mut cols = self.widths.iter().sum::<usize>() + (W - 1) * self.opts.spacing;
270 +
        let mut rows = self.rows.len();
271 +
        let padding = 2;
272 +
273 +
        // Account for outer borders.
274 +
        if self.opts.border.is_some() {
275 +
            cols += 2 + padding;
276 +
            rows += 2;
277 +
        }
278 +
        Size::new(cols, rows).constrain(c)
279 +
    }
280 +
}
281 +
282 +
impl<const W: usize, T: Text> Extend<[T; W]> for Table<W, T> {
283 +
    fn extend<I>(&mut self, iter: I)
284 +
    where
285 +
        I: IntoIterator<Item = [T; W]>,
286 +
    {
287 +
        for row in iter {
288 +
            self.push(row);
289 +
        }
290 +
    }
291 +
}
292 +
293 +
#[cfg(test)]
294 +
mod tests {
295 +
    use crate::Color;
296 +
297 +
    use crate::Widget;
298 +
299 +
    use super::*;
300 +
301 +
    #[test]
302 +
    fn test_table() {
303 +
        let mut t = Table::new(TableOptions::default());
304 +
305 +
        t.push(["pineapple", "rosemary"]);
306 +
        t.push(["apples", "pears"]);
307 +
308 +
        #[rustfmt::skip]
309 +
        assert_eq!(
310 +
            t.display(Constraint::UNBOUNDED),
311 +
            [
312 +
                "pineapple rosemary\n",
313 +
                "apples    pears   \n"
314 +
            ].join("")
315 +
        );
316 +
    }
317 +
318 +
    #[test]
319 +
    fn test_table_border() {
320 +
        let mut t = Table::new(TableOptions {
321 +
            border: Some(Border::new(Color::Unset)),
322 +
            spacing: 3,
323 +
            ..TableOptions::default()
324 +
        });
325 +
326 +
        t.push(["Country", "Population", "Code"]);
327 +
        t.divider();
328 +
        t.push(["France", "60M", "FR"]);
329 +
        t.push(["Switzerland", "7M", "CH"]);
330 +
        t.push(["Germany", "80M", "DE"]);
331 +
332 +
        let inner = t.inner(Constraint::UNBOUNDED);
333 +
        assert_eq!(inner.cols, 33);
334 +
        assert_eq!(inner.rows, 5);
335 +
336 +
        let outer = t.outer(Constraint::UNBOUNDED);
337 +
        assert_eq!(outer.cols, 35);
338 +
        assert_eq!(outer.rows, 7);
339 +
340 +
        assert_eq!(
341 +
            t.display(Constraint::UNBOUNDED),
342 +
            r"
343 +
╭─────────────────────────────────╮
344 +
│ Country       Population   Code │
345 +
├─────────────────────────────────┤
346 +
│ France        60M          FR   │
347 +
│ Switzerland   7M           CH   │
348 +
│ Germany       80M          DE   │
349 +
╰─────────────────────────────────╯
350 +
"
351 +
            .trim_start()
352 +
        );
353 +
    }
354 +
355 +
    #[test]
356 +
    fn test_table_border_truncated() {
357 +
        let mut t = Table::new(TableOptions {
358 +
            border: Some(Border::new(Color::Unset)),
359 +
            spacing: 3,
360 +
            ..TableOptions::default()
361 +
        });
362 +
363 +
        t.push(["Code", "Name"]);
364 +
        t.divider();
365 +
        t.push(["FR", "France"]);
366 +
        t.push(["CH", "Switzerland"]);
367 +
        t.push(["DE", "Germany"]);
368 +
369 +
        let constrain = Constraint::max(Size {
370 +
            cols: 19,
371 +
            rows: usize::MAX,
372 +
        });
373 +
        let outer = t.outer(constrain);
374 +
        assert_eq!(outer.cols, 19);
375 +
        assert_eq!(outer.rows, 7);
376 +
377 +
        let inner = t.inner(constrain);
378 +
        assert_eq!(inner.cols, 17);
379 +
        assert_eq!(inner.rows, 5);
380 +
381 +
        assert_eq!(
382 +
            t.display(constrain),
383 +
            r"
384 +
╭─────────────────╮
385 +
│ Code   Name     │
386 +
├─────────────────┤
387 +
│ FR     France   │
388 +
│ CH     Switzer… │
389 +
│ DE     Germany  │
390 +
╰─────────────────╯
391 +
"
392 +
            .trim_start()
393 +
        );
394 +
    }
395 +
396 +
    #[test]
397 +
    fn test_table_border_maximized() {
398 +
        let mut t = Table::new(TableOptions {
399 +
            border: Some(Border::new(Color::Unset)),
400 +
            spacing: 3,
401 +
            ..TableOptions::default()
402 +
        });
403 +
404 +
        t.push(["Code", "Name"]);
405 +
        t.divider();
406 +
        t.push(["FR", "France"]);
407 +
        t.push(["CH", "Switzerland"]);
408 +
        t.push(["DE", "Germany"]);
409 +
410 +
        let constrain = Constraint::new(
411 +
            Size { cols: 26, rows: 0 },
412 +
            Size {
413 +
                cols: 26,
414 +
                rows: usize::MAX,
415 +
            },
416 +
        );
417 +
        let outer = t.outer(constrain);
418 +
        assert_eq!(outer.cols, 26);
419 +
        assert_eq!(outer.rows, 7);
420 +
421 +
        let inner = t.inner(constrain);
422 +
        assert_eq!(inner.cols, 24);
423 +
        assert_eq!(inner.rows, 5);
424 +
425 +
        assert_eq!(
426 +
            t.display(constrain),
427 +
            r"
428 +
╭────────────────────────╮
429 +
│ Code   Name            │
430 +
├────────────────────────┤
431 +
│ FR     France          │
432 +
│ CH     Switzerland     │
433 +
│ DE     Germany         │
434 +
╰────────────────────────╯
435 +
"
436 +
            .trim_start()
437 +
        );
438 +
    }
439 +
440 +
    #[test]
441 +
    fn test_table_truncate() {
442 +
        let mut t = Table::default();
443 +
        let constrain = Constraint::new(
444 +
            Size::MIN,
445 +
            Size {
446 +
                cols: 16,
447 +
                rows: usize::MAX,
448 +
            },
449 +
        );
450 +
451 +
        t.push(["pineapple", "rosemary"]);
452 +
        t.push(["apples", "pears"]);
453 +
454 +
        #[rustfmt::skip]
455 +
        assert_eq!(
456 +
            t.display(constrain),
457 +
            [
458 +
                "pineapple rosem…\n",
459 +
                "apples    pears \n"
460 +
            ].join("")
461 +
        );
462 +
    }
463 +
464 +
    #[test]
465 +
    fn test_table_unicode() {
466 +
        let mut t = Table::new(TableOptions::default());
467 +
468 +
        t.push(["🍍pineapple", "__rosemary", "__sage"]);
469 +
        t.push(["__pears", "🍎apples", "🍌bananas"]);
470 +
471 +
        #[rustfmt::skip]
472 +
        assert_eq!(
473 +
            t.display(Constraint::UNBOUNDED),
474 +
            [
475 +
                "🍍pineapple __rosemary __sage   \n",
476 +
                "__pears     🍎apples   🍌bananas\n"
477 +
            ].join("")
478 +
        );
479 +
    }
480 +
481 +
    #[test]
482 +
    fn test_table_unicode_truncate() {
483 +
        let mut t = Table::new(TableOptions {
484 +
            ..TableOptions::default()
485 +
        });
486 +
        let constrain = Constraint::max(Size {
487 +
            cols: 16,
488 +
            rows: usize::MAX,
489 +
        });
490 +
        t.push(["🍍pineapple", "__rosemary"]);
491 +
        t.push(["__pears", "🍎apples"]);
492 +
493 +
        #[rustfmt::skip]
494 +
        assert_eq!(
495 +
            t.display(constrain),
496 +
            [
497 +
                "🍍pineapple __r…\n",
498 +
                "__pears     🍎a…\n"
499 +
            ].join("")
500 +
        );
501 +
    }
502 +
503 +
    #[test]
504 +
    fn empty_table_renders_no_lines_even_with_divider_or_header() {
505 +
        let mut t = Table::new(TableOptions::bordered());
506 +
507 +
        t.header(["Name", "Value"]);
508 +
        t.divider();
509 +
510 +
        assert!(t.is_empty());
511 +
        assert_eq!(t.display(Constraint::UNBOUNDED), "");
512 +
    }
513 +
514 +
    #[test]
515 +
    fn header_rows_render_once_data_exists() {
516 +
        let mut t = Table::new(TableOptions::default());
517 +
518 +
        t.header(["Name", "Value"]);
519 +
        t.divider();
520 +
        t.push(["status", "ready"]);
521 +
522 +
        assert!(!t.is_empty());
523 +
        assert_eq!(
524 +
            t.display(Constraint::UNBOUNDED),
525 +
            "Name   Value\n            \nstatus ready\n"
526 +
        );
527 +
    }
528 +
529 +
    #[test]
530 +
    fn from_iterator_tracks_column_widths() {
531 +
        let t = [["a", "beta"], ["alpha", "b"]]
532 +
            .into_iter()
533 +
            .collect::<Table<2, _>>();
534 +
535 +
        assert_eq!(t.display(Constraint::UNBOUNDED), "a     beta\nalpha b   \n");
536 +
    }
537 +
538 +
    #[test]
539 +
    fn extend_appends_data_rows_and_updates_widths() {
540 +
        let mut t = Table::default();
541 +
542 +
        t.push(["a", "b"]);
543 +
        t.extend([["long", "value"]]);
544 +
545 +
        assert_eq!(t.display(Constraint::UNBOUNDED), "a    b    \nlong value\n");
546 +
    }
547 +
548 +
    #[test]
549 +
    fn with_opts_replaces_rendering_options() {
550 +
        let mut t = Table::default().with_opts(TableOptions {
551 +
            border: Some(Border::new(Color::Unset)),
552 +
            spacing: 3,
553 +
            ..TableOptions::default()
554 +
        });
555 +
556 +
        t.push(["A", "B"]);
557 +
558 +
        assert_eq!(
559 +
            t.display(Constraint::UNBOUNDED),
560 +
            r"
561 +
╭───────╮
562 +
│ A   B │
563 +
╰───────╯
564 +
"
565 +
            .trim_start()
566 +
        );
567 +
    }
568 +
569 +
    #[test]
570 +
    fn border_options_use_faint_border_and_wide_spacing() {
571 +
        let opts = TableOptions::bordered();
572 +
573 +
        assert_eq!(opts.border, Some(Border::new(colors::FAINT)));
574 +
        assert_eq!(opts.spacing, 3);
575 +
        assert!(!opts.overflow);
576 +
    }
577 +
578 +
    #[test]
579 +
    fn divider_sigil_options_replace_horizontal_lines() {
580 +
        let mut t = Table::new(TableOptions {
581 +
            border: Some(Border::new(Color::Unset)),
582 +
            spacing: 3,
583 +
            ..TableOptions::default()
584 +
        });
585 +
586 +
        t.push(["Code", "Name"]);
587 +
        t.divider_with_sigil("─");
588 +
        t.push(["FR", "France"]);
589 +
590 +
        assert_eq!(
591 +
            t.display(Constraint::UNBOUNDED),
592 +
            r"
593 +
╭───────────────╮
594 +
│ Code   Name   │
595 +
├───────────────┤
596 +
│ FR     France │
597 +
╰───────────────╯
598 +
"
599 +
            .trim_start()
600 +
        );
601 +
    }
602 +
}
crates/tui-core/src/terminal.rs added +180 -0
1 +
//! Double-buffered terminal renderer.
2 +
//!
3 +
//! `Terminal` owns the previous and current buffers for a backend, asks apps to
4 +
//! draw into a frame, computes dirty cell runs, and flushes those runs through
5 +
//! the backend. This keeps redraw policy centralized instead of spread through
6 +
//! widgets.
7 +
8 +
use crate::Buffer;
9 +
use crate::backend::Backend;
10 +
use crate::frame::Frame;
11 +
use crate::layout::{Point, Rect};
12 +
13 +
/// Double-buffered terminal.
14 +
#[derive(Debug)]
15 +
pub struct Terminal<B> {
16 +
    backend: B,
17 +
    previous: Buffer,
18 +
    current: Buffer,
19 +
}
20 +
21 +
impl<B: Backend> Terminal<B> {
22 +
    /// Creates a terminal around a backend.
23 +
    pub fn new(mut backend: B) -> Result<Self, B::Error> {
24 +
        let area = Rect::from_size(backend.size()?);
25 +
26 +
        Ok(Self {
27 +
            backend,
28 +
            previous: Buffer::empty(area),
29 +
            current: Buffer::empty(area),
30 +
        })
31 +
    }
32 +
33 +
    /// Returns the visible area.
34 +
    pub const fn area(&self) -> Rect {
35 +
        self.current.area()
36 +
    }
37 +
38 +
    /// Returns the backend.
39 +
    pub const fn backend(&self) -> &B {
40 +
        &self.backend
41 +
    }
42 +
43 +
    /// Returns the backend mutably.
44 +
    pub fn backend_mut(&mut self) -> &mut B {
45 +
        &mut self.backend
46 +
    }
47 +
48 +
    /// Clears the terminal and both buffers.
49 +
    pub fn clear(&mut self) -> Result<(), B::Error> {
50 +
        self.backend.clear()?;
51 +
        self.previous.clear();
52 +
        self.current.clear();
53 +
54 +
        Ok(())
55 +
    }
56 +
57 +
    /// Shows or hides the terminal cursor.
58 +
    pub fn set_cursor_visible(&mut self, visible: bool) -> Result<(), B::Error> {
59 +
        self.backend.set_cursor_visible(visible)
60 +
    }
61 +
62 +
    /// Draws one frame and flushes the diff.
63 +
    pub fn draw(&mut self, render: impl FnOnce(&mut Frame<'_>)) -> Result<(), B::Error> {
64 +
        self.resize()?;
65 +
        self.current.clear();
66 +
67 +
        let cursor = {
68 +
            let mut frame = Frame::new(self.current.area(), &mut self.current);
69 +
            render(&mut frame);
70 +
            frame.cursor
71 +
        };
72 +
73 +
        {
74 +
            let runs = self.current.diff(&self.previous);
75 +
            self.backend.draw(&runs)?;
76 +
        }
77 +
        if let Some(point) = cursor {
78 +
            self.backend.set_cursor_position(point)?;
79 +
        }
80 +
        self.backend.flush()?;
81 +
        self.previous.clone_from(&self.current);
82 +
        self.previous.reset_dirty();
83 +
        self.current.reset_dirty();
84 +
85 +
        Ok(())
86 +
    }
87 +
88 +
    /// Sets the terminal cursor immediately.
89 +
    pub fn set_cursor_position(&mut self, point: Point) -> Result<(), B::Error> {
90 +
        self.backend.set_cursor_position(point)
91 +
    }
92 +
93 +
    /// Resizes buffers if the backend size changed.
94 +
    fn resize(&mut self) -> Result<(), B::Error> {
95 +
        let area = Rect::from_size(self.backend.size()?);
96 +
        if area != self.current.area() {
97 +
            self.previous.resize(area);
98 +
            self.current.resize(area);
99 +
            self.backend.clear()?;
100 +
        }
101 +
        Ok(())
102 +
    }
103 +
}
104 +
105 +
#[cfg(test)]
106 +
mod tests {
107 +
    use super::*;
108 +
    use crate::{Label, Size, Style, TestBackend};
109 +
110 +
    #[test]
111 +
    fn terminal_draws_widget_frames() {
112 +
        let backend = TestBackend::new(Size::new(6, 1));
113 +
        let mut terminal = Terminal::new(backend).unwrap();
114 +
115 +
        terminal
116 +
            .draw(|frame| frame.render_widget(Label::new("hello"), frame.area))
117 +
            .unwrap();
118 +
119 +
        assert_eq!(terminal.backend().lines(), vec!["hello "]);
120 +
    }
121 +
122 +
    #[test]
123 +
    fn terminal_clears_previous_frame_content_before_diffing() {
124 +
        let backend = TestBackend::new(Size::new(6, 1));
125 +
        let mut terminal = Terminal::new(backend).unwrap();
126 +
127 +
        terminal
128 +
            .draw(|frame| frame.buffer.set_str(0, 0, "abcdef", Style::default()))
129 +
            .unwrap();
130 +
        terminal
131 +
            .draw(|frame| frame.buffer.set_str(0, 0, "x", Style::default()))
132 +
            .unwrap();
133 +
134 +
        assert_eq!(terminal.backend().lines(), vec!["x     "]);
135 +
    }
136 +
137 +
    #[test]
138 +
    fn terminal_resizes_when_backend_size_changes() {
139 +
        let backend = TestBackend::new(Size::new(4, 1));
140 +
        let mut terminal = Terminal::new(backend).unwrap();
141 +
142 +
        terminal.backend_mut().resize(Size::new(2, 2));
143 +
        terminal
144 +
            .draw(|frame| frame.buffer.set_str(0, 1, "y", Style::default()))
145 +
            .unwrap();
146 +
147 +
        assert_eq!(terminal.area(), Rect::new(0, 0, 2, 2));
148 +
        assert_eq!(terminal.backend().lines(), vec!["  ", "y "]);
149 +
    }
150 +
151 +
    #[test]
152 +
    fn terminal_forwards_frame_and_direct_cursor_requests() {
153 +
        let backend = TestBackend::new(Size::new(3, 1));
154 +
        let mut terminal = Terminal::new(backend).unwrap();
155 +
156 +
        terminal
157 +
            .draw(|frame| {
158 +
                assert_eq!(frame.area.size(), Size::new(3, 1));
159 +
                frame.set_cursor_position(Point::new(2, 0));
160 +
            })
161 +
            .unwrap();
162 +
        assert_eq!(terminal.backend().cursor(), Some(Point::new(2, 0)));
163 +
164 +
        terminal.set_cursor_position(Point::new(1, 0)).unwrap();
165 +
        assert_eq!(terminal.backend().cursor(), Some(Point::new(1, 0)));
166 +
    }
167 +
168 +
    #[test]
169 +
    fn terminal_clear_clears_backend_and_buffers() {
170 +
        let backend = TestBackend::new(Size::new(4, 1));
171 +
        let mut terminal = Terminal::new(backend).unwrap();
172 +
173 +
        terminal
174 +
            .draw(|frame| frame.buffer.set_str(0, 0, "data", Style::default()))
175 +
            .unwrap();
176 +
        terminal.clear().unwrap();
177 +
178 +
        assert_eq!(terminal.backend().lines(), vec!["    "]);
179 +
    }
180 +
}
crates/tui-core/src/text.rs added +102 -0
1 +
//! Convenience constructors for consistently styled terminal text.
2 +
//!
3 +
//! These helpers create common painted text fragments such as dim, bold,
4 +
//! emphasized, or badge-like labels. They keep small style choices consistent
5 +
//! across examples and widgets without adding a larger theme system.
6 +
7 +
use std::fmt;
8 +
9 +
use super::{Color, Paint, Style, colors};
10 +
11 +
/// Default foreground color for faint neutral text.
12 +
pub const FAINT_COLOR: Color = colors::fixed::FAINT;
13 +
14 +
/// Returns unstyled text.
15 +
pub fn default<D: fmt::Display>(msg: D) -> Paint<D> {
16 +
    Paint::new(msg)
17 +
}
18 +
19 +
/// Returns wrapping text that preserves outer styling across resets.
20 +
pub fn wrap<D: fmt::Display>(msg: D) -> Paint<D> {
21 +
    Paint::wrapping(msg)
22 +
}
23 +
24 +
/// Returns text styled as negative or failing.
25 +
pub fn negative<D: fmt::Display>(msg: D) -> Paint<D> {
26 +
    Paint::red(msg)
27 +
}
28 +
29 +
/// Returns text styled as positive or successful.
30 +
pub fn positive<D: fmt::Display>(msg: D) -> Paint<D> {
31 +
    Paint::green(msg)
32 +
}
33 +
34 +
/// Returns faint neutral text.
35 +
pub fn faint<D: fmt::Display>(msg: D) -> Paint<D> {
36 +
    Paint::new(msg).fg(FAINT_COLOR)
37 +
}
38 +
39 +
/// Returns emphasized highlighted text.
40 +
pub fn highlight<D: fmt::Debug + fmt::Display>(input: D) -> Paint<D> {
41 +
    Paint::green(input).bold()
42 +
}
43 +
44 +
/// Returns bold text.
45 +
pub fn bold<D: fmt::Display>(input: D) -> Paint<D> {
46 +
    Paint::new(input).bold()
47 +
}
48 +
49 +
/// Returns dim text.
50 +
pub fn dim<D: fmt::Display>(input: D) -> Paint<D> {
51 +
    Paint::new(input).dim()
52 +
}
53 +
54 +
/// Returns dim italic text.
55 +
pub fn italic<D: fmt::Display>(input: D) -> Paint<D> {
56 +
    Paint::new(input).italic().dim()
57 +
}
58 +
59 +
/// Returns text styled as an inverted badge.
60 +
pub fn badge(text: impl fmt::Display, color: Color) -> Paint<String> {
61 +
    Paint::new(format!(" {text} ")).with_style(Style::new(color).invert())
62 +
}
63 +
64 +
#[cfg(test)]
65 +
#[allow(clippy::unwrap_used)]
66 +
mod tests {
67 +
    use super::*;
68 +
    use crate::Color;
69 +
70 +
    fn prefix<D: std::fmt::Display>(paint: Paint<D>) -> String {
71 +
        let mut out = String::new();
72 +
        paint.style().fmt_prefix(&mut out).unwrap();
73 +
        out
74 +
    }
75 +
76 +
    #[test]
77 +
    fn text_constructors_apply_expected_foreground_colors() {
78 +
        assert_eq!(default("x").style().fg_color(), Color::Unset);
79 +
        assert_eq!(wrap("x").style().fg_color(), Color::Unset);
80 +
        assert!(wrap("x").style().is_wrapping());
81 +
        assert_eq!(negative("x").style().fg_color(), Color::Red);
82 +
        assert_eq!(positive("x").style().fg_color(), Color::Green);
83 +
        assert_eq!(faint("x").style().fg_color(), Color::Fixed(236));
84 +
    }
85 +
86 +
    #[test]
87 +
    fn emphasis_constructors_set_style_properties() {
88 +
        assert_eq!(prefix(highlight("x")), "\x1B[1;32m");
89 +
        assert_eq!(prefix(bold("x")), "\x1B[1m");
90 +
        assert_eq!(prefix(dim("x")), "\x1B[2m");
91 +
        assert_eq!(prefix(italic("x")), "\x1B[2;3m");
92 +
    }
93 +
94 +
    #[test]
95 +
    fn badge_returns_inverted_paint() {
96 +
        let badge = badge("new", Color::Magenta);
97 +
98 +
        assert_eq!(badge.content(), " new ");
99 +
        assert_eq!(badge.style().fg_color(), Color::Magenta);
100 +
        assert_eq!(badge.styled().to_string(), "\x1B[7;35m new \x1B[0m");
101 +
    }
102 +
}
crates/tui-core/src/textarea.rs added +217 -0
1 +
//! Wrapped multi-line text widget.
2 +
//!
3 +
//! `TextArea` stores plain text plus body style and exposes wrapped lines for a
4 +
//! target width. It is useful both as a widget and as a line producer for
5 +
//! scrollable previews.
6 +
7 +
use super::{Constraint, Line, Paint, Size, Widget, cell::Text};
8 +
9 +
/// Default text wrap width.
10 +
pub const DEFAULT_WRAP: usize = 80;
11 +
/// Soft tab replacement for '\t'.
12 +
pub const SOFT_TAB: &str = "  ";
13 +
14 +
/// Text area.
15 +
///
16 +
/// A block of text that can contain multiple lines.
17 +
#[derive(Debug)]
18 +
pub struct TextArea {
19 +
    body: Paint<String>,
20 +
    wrap: usize,
21 +
}
22 +
23 +
impl TextArea {
24 +
    /// Creates a new text area.
25 +
    pub fn new(body: impl Into<Paint<String>>) -> Self {
26 +
        Self {
27 +
            body: body.into(),
28 +
            wrap: DEFAULT_WRAP,
29 +
        }
30 +
    }
31 +
32 +
    /// Sets the wrap width.
33 +
    pub fn wrap(mut self, cols: usize) -> Self {
34 +
        self.wrap = cols;
35 +
        self
36 +
    }
37 +
38 +
    /// Returns the lines of text in this text area.
39 +
    pub fn lines(&self) -> impl Iterator<Item = String> + use<> {
40 +
        let mut lines: Vec<String> = Vec::new();
41 +
        let mut fenced = false;
42 +
43 +
        for line in self
44 +
            .body
45 +
            .content()
46 +
            .lines()
47 +
            // Replace tabs as their visual width cannot be calculated.
48 +
            .map(|l| l.replace('\t', SOFT_TAB))
49 +
        {
50 +
            // Fenced code block support.
51 +
            if line.starts_with("```") {
52 +
                fenced = !fenced;
53 +
            }
54 +
            // Code blocks are not wrapped, they are truncated.
55 +
            if fenced || line.starts_with('\t') || line.starts_with(' ') {
56 +
                lines.push(line.truncate(self.wrap, "…"));
57 +
                continue;
58 +
            }
59 +
            let mut current = String::new();
60 +
61 +
            for word in line.split_whitespace() {
62 +
                if current.width() + word.width() > self.wrap {
63 +
                    lines.push(current.trim_end().to_owned());
64 +
                    word.clone_into(&mut current);
65 +
                } else {
66 +
                    current.push_str(word);
67 +
                }
68 +
                current.push(' ');
69 +
            }
70 +
            lines.push(current.trim_end().to_owned());
71 +
        }
72 +
        lines.into_iter()
73 +
    }
74 +
75 +
    /// Boxes the text area.
76 +
    pub fn boxed(self) -> Box<dyn Widget> {
77 +
        Box::new(self)
78 +
    }
79 +
}
80 +
81 +
impl Widget for TextArea {
82 +
    fn size(&self, _parent: Constraint) -> Size {
83 +
        let cols = self.lines().map(|l| l.width()).max().unwrap_or(0);
84 +
        let rows = self.lines().count();
85 +
86 +
        Size::new(cols, rows)
87 +
    }
88 +
89 +
    fn render(&self, area: crate::Rect, buf: &mut crate::Buffer) {
90 +
        Line::renders(
91 +
            self.lines()
92 +
                .map(|l| Line::new(Paint::new(l).with_style(self.body.style))),
93 +
            area,
94 +
            buf,
95 +
        );
96 +
    }
97 +
}
98 +
99 +
/// Creates a new text area.
100 +
pub fn textarea(content: impl Into<Paint<String>>) -> TextArea {
101 +
    TextArea::new(content)
102 +
}
103 +
104 +
#[cfg(test)]
105 +
mod tests {
106 +
    use super::*;
107 +
108 +
    #[test]
109 +
    fn test_wrapping() {
110 +
        let t = TextArea::new(
111 +
            "Radicle enables users to run their own nodes, \
112 +
            ensuring censorship-resistant code collaboration \
113 +
            and fostering a resilient network without reliance \
114 +
            on third-parties.",
115 +
        )
116 +
        .wrap(50);
117 +
        let wrapped = t.lines().collect::<Vec<_>>();
118 +
119 +
        assert_eq!(
120 +
            wrapped,
121 +
            vec![
122 +
                "Radicle enables users to run their own nodes,".to_owned(),
123 +
                "ensuring censorship-resistant code collaboration".to_owned(),
124 +
                "and fostering a resilient network without reliance".to_owned(),
125 +
                "on third-parties.".to_owned(),
126 +
            ]
127 +
        );
128 +
    }
129 +
130 +
    #[test]
131 +
    fn test_wrapping_paragraphs() {
132 +
        let t = TextArea::new(
133 +
            "Radicle enables users to run their own nodes, \
134 +
            ensuring censorship-resistant code collaboration \
135 +
            and fostering a resilient network without reliance \
136 +
            on third-parties.\n\n\
137 +
            All social artifacts are stored in git, and signed \
138 +
            using public-key cryptography. Radicle verifies \
139 +
            the authenticity and authorship of all data \
140 +
            automatically.",
141 +
        )
142 +
        .wrap(50);
143 +
        let wrapped = t.lines().collect::<Vec<_>>();
144 +
145 +
        assert_eq!(
146 +
            wrapped,
147 +
            vec![
148 +
                "Radicle enables users to run their own nodes,".to_owned(),
149 +
                "ensuring censorship-resistant code collaboration".to_owned(),
150 +
                "and fostering a resilient network without reliance".to_owned(),
151 +
                "on third-parties.".to_owned(),
152 +
                String::new(),
153 +
                "All social artifacts are stored in git, and signed".to_owned(),
154 +
                "using public-key cryptography. Radicle verifies".to_owned(),
155 +
                "the authenticity and authorship of all data".to_owned(),
156 +
                "automatically.".to_owned(),
157 +
            ]
158 +
        );
159 +
    }
160 +
161 +
    #[test]
162 +
    fn test_wrapping_code_block() {
163 +
        let t = TextArea::new(
164 +
            "\
165 +
Here's an example:
166 +
167 +
  $ git push rad://z3gqcJUoA1n9HaHKufZs5FCSGazv5/z6MksFqXN3Yhqk8pTJdUGLwATkRfQvwZXPqR2qMEhbS9wzpT
168 +
  $ rad sync
169 +
170 +
Run the above and wait for your project to sync.\
171 +
        ",
172 +
        )
173 +
        .wrap(50);
174 +
        let wrapped = t.lines().collect::<Vec<_>>();
175 +
176 +
        assert_eq!(
177 +
            wrapped,
178 +
            vec![
179 +
                "Here's an example:".to_owned(),
180 +
                String::new(),
181 +
                "  $ git push rad://z3gqcJUoA1n9HaHKufZs5FCSGazv5/…".to_owned(),
182 +
                "  $ rad sync".to_owned(),
183 +
                String::new(),
184 +
                "Run the above and wait for your project to sync.".to_owned()
185 +
            ]
186 +
        );
187 +
    }
188 +
189 +
    #[test]
190 +
    fn test_wrapping_fenced_block() {
191 +
        let t = TextArea::new(
192 +
            "\
193 +
Here's an example:
194 +
```
195 +
$ git push rad://z3gqcJUoA1n9HaHKufZs5FCSGazv5/z6MksFqXN3Yhqk8pTJdUGLwATkRfQvwZXPqR2qMEhbS9wzpT
196 +
$ rad sync
197 +
```
198 +
Run the above and wait for your project to sync.\
199 +
        ",
200 +
        )
201 +
        .wrap(40);
202 +
        let wrapped = t.lines().collect::<Vec<_>>();
203 +
204 +
        assert_eq!(
205 +
            wrapped,
206 +
            vec![
207 +
                "Here's an example:".to_owned(),
208 +
                "```".to_owned(),
209 +
                "$ git push rad://z3gqcJUoA1n9HaHKufZs5F…".to_owned(),
210 +
                "$ rad sync".to_owned(),
211 +
                "```".to_owned(),
212 +
                "Run the above and wait for your project".to_owned(),
213 +
                "to sync.".to_owned()
214 +
            ]
215 +
        );
216 +
    }
217 +
}
crates/tui-core/src/vstack.rs added +562 -0
1 +
//! Vertical widget layout container.
2 +
//!
3 +
//! `VStack` lays child widgets from top to bottom with optional border,
4 +
//! horizontal padding, dividers, and fill rows. It is the main primitive for
5 +
//! stacking small widgets into panels while preserving each child's own render
6 +
//! logic.
7 +
8 +
use super::colors;
9 +
use super::{Border, Buffer, Cell, Constraint, Label, Length, Rect, Size, Style, Widget};
10 +
11 +
/// Default horizontal padding inside a stack border.
12 +
pub const DEFAULT_PADDING: usize = 1;
13 +
/// Default divider glyph.
14 +
pub const DEFAULT_DIVIDER_GLYPH: &str = "─";
15 +
/// Default divider style.
16 +
pub const DEFAULT_DIVIDER_STYLE: Style = Style::new(super::Color::Unset);
17 +
18 +
/// Options for [`VStack`].
19 +
#[derive(Debug)]
20 +
pub struct VStackOptions {
21 +
    /// Optional outer border color.
22 +
    border: Option<Border>,
23 +
    /// Horizontal padding inside the outer border.
24 +
    padding: usize,
25 +
}
26 +
27 +
impl Default for VStackOptions {
28 +
    fn default() -> Self {
29 +
        Self {
30 +
            border: None,
31 +
            padding: DEFAULT_PADDING,
32 +
        }
33 +
    }
34 +
}
35 +
36 +
/// A vertical stack row.
37 +
#[derive(Debug)]
38 +
enum Row<'a> {
39 +
    Widget {
40 +
        /// Widget rendered in this row.
41 +
        widget: Box<dyn Widget + 'a>,
42 +
        /// Optional row height policy.
43 +
        height: Option<Length>,
44 +
    },
45 +
    Divider {
46 +
        /// Cell repeated across the divider row.
47 +
        cell: Cell,
48 +
    },
49 +
}
50 +
51 +
impl Default for Row<'_> {
52 +
    /// Create the default divider row.
53 +
    fn default() -> Self {
54 +
        Self::Divider {
55 +
            cell: Cell::new(DEFAULT_DIVIDER_GLYPH, DEFAULT_DIVIDER_STYLE),
56 +
        }
57 +
    }
58 +
}
59 +
60 +
impl Row<'_> {
61 +
    /// Return the row's natural width under the given parent constraint.
62 +
    fn width(&self, c: Constraint) -> usize {
63 +
        match self {
64 +
            Self::Widget { widget, .. } => widget.columns(c),
65 +
            Self::Divider { .. } => c.min.cols,
66 +
        }
67 +
    }
68 +
69 +
    /// Return the row's natural height before leftover space is distributed.
70 +
    fn natural_height(&self, c: Constraint) -> usize {
71 +
        match self {
72 +
            Self::Widget { widget, height } => match height {
73 +
                Some(Length::Fixed(rows) | Length::Min(rows)) => *rows,
74 +
                Some(Length::Fill(_)) => 0,
75 +
                None => widget.rows(c),
76 +
            },
77 +
            Self::Divider { .. } => 1,
78 +
        }
79 +
    }
80 +
81 +
    /// Return the height policy used when allocating render rows.
82 +
    fn layout_height(&self, c: Constraint) -> Length {
83 +
        match self {
84 +
            Self::Widget { widget, height } => {
85 +
                height.unwrap_or_else(|| Length::Fixed(widget.rows(c)))
86 +
            }
87 +
            Self::Divider { .. } => Length::Fixed(1),
88 +
        }
89 +
    }
90 +
}
91 +
92 +
/// Vertical stack of [`Widget`] objects.
93 +
#[derive(Default, Debug)]
94 +
pub struct VStack<'a> {
95 +
    rows: Vec<Row<'a>>,
96 +
    opts: VStackOptions,
97 +
}
98 +
99 +
impl<'a> VStack<'a> {
100 +
    /// Add a widget to the stack and return the stack.
101 +
    pub fn child(mut self, child: impl Widget + 'a) -> Self {
102 +
        self.push(child);
103 +
        self
104 +
    }
105 +
106 +
    /// Add a widget with an explicit row height policy.
107 +
    pub fn child_with_height(mut self, child: impl Widget + 'a, height: Length) -> Self {
108 +
        self.push_with_height(child, height);
109 +
        self
110 +
    }
111 +
112 +
    /// Add a widget that fills remaining vertical space.
113 +
    pub fn fill(self, child: impl Widget + 'a) -> Self {
114 +
        self.child_with_height(child, Length::Fill(1))
115 +
    }
116 +
117 +
    /// Add a blank line to the stack.
118 +
    pub fn blank(self) -> Self {
119 +
        self.child(Label::blank())
120 +
    }
121 +
122 +
    /// Add a horizontal divider.
123 +
    pub fn divider(mut self) -> Self {
124 +
        self.rows.push(Row::default());
125 +
        self
126 +
    }
127 +
128 +
    /// Check if this stack is empty.
129 +
    pub fn is_empty(&self) -> bool {
130 +
        self.rows.is_empty()
131 +
    }
132 +
133 +
    /// Add multiple widgets to the stack.
134 +
    pub fn children<I>(mut self, children: I) -> Self
135 +
    where
136 +
        I: IntoIterator<Item = Box<dyn Widget + 'a>>,
137 +
    {
138 +
        self.rows
139 +
            .extend(children.into_iter().map(|widget| Row::Widget {
140 +
                widget,
141 +
                height: None,
142 +
            }));
143 +
        self
144 +
    }
145 +
146 +
    /// Merge with another `VStack`.
147 +
    pub fn merge(mut self, other: Self) -> Self {
148 +
        self.rows.extend(other.rows);
149 +
        self
150 +
    }
151 +
152 +
    /// Set or unset the outer border.
153 +
    pub fn border(mut self, border: Option<Border>) -> Self {
154 +
        self.opts.border = border;
155 +
        self
156 +
    }
157 +
158 +
    /// Set horizontal padding.
159 +
    pub fn padding(mut self, cols: usize) -> Self {
160 +
        self.opts.padding = cols;
161 +
        self
162 +
    }
163 +
164 +
    /// Add a horizontal divider with an explicit cell.
165 +
    pub fn divider_cell(mut self, cell: Cell) -> Self {
166 +
        self.rows.push(Row::Divider { cell });
167 +
        self
168 +
    }
169 +
170 +
    /// Add a widget to the stack.
171 +
    pub fn push(&mut self, child: impl Widget + 'a) {
172 +
        self.rows.push(Row::Widget {
173 +
            widget: Box::new(child),
174 +
            height: None,
175 +
        });
176 +
    }
177 +
178 +
    /// Add a widget to the stack with an explicit row height policy.
179 +
    pub fn push_with_height(&mut self, child: impl Widget + 'a, height: Length) {
180 +
        self.rows.push(Row::Widget {
181 +
            widget: Box::new(child),
182 +
            height: Some(height),
183 +
        });
184 +
    }
185 +
186 +
    /// Box this widget.
187 +
    pub fn boxed(self) -> Box<dyn Widget + 'a> {
188 +
        Box::new(self)
189 +
    }
190 +
191 +
    /// Inner size.
192 +
    #[cfg(test)]
193 +
    fn inner(&self, c: Constraint) -> Size {
194 +
        let mut outer = self.outer(c);
195 +
196 +
        if self.opts.border.is_some() {
197 +
            outer.cols = outer.cols.saturating_sub(2);
198 +
            outer.rows = outer.rows.saturating_sub(2);
199 +
        }
200 +
        outer
201 +
    }
202 +
203 +
    /// Outer size (includes borders).
204 +
    fn outer(&self, c: Constraint) -> Size {
205 +
        let padding = self.opts.padding * 2;
206 +
        let mut cols = self
207 +
            .rows
208 +
            .iter()
209 +
            .map(|r| r.width(c))
210 +
            .max()
211 +
            .unwrap_or(0)
212 +
            .saturating_add(padding);
213 +
        let mut rows = self
214 +
            .rows
215 +
            .iter()
216 +
            .map(|r| r.natural_height(c))
217 +
            .fold(0usize, usize::saturating_add);
218 +
219 +
        // Account for outer borders.
220 +
        if self.opts.border.is_some() {
221 +
            cols = cols.saturating_add(2);
222 +
            rows = rows.saturating_add(2);
223 +
        }
224 +
        Size::new(cols, rows).constrain(c)
225 +
    }
226 +
}
227 +
228 +
impl Widget for VStack<'_> {
229 +
    fn size(&self, parent: Constraint) -> Size {
230 +
        self.outer(parent)
231 +
    }
232 +
233 +
    fn render(&self, area: Rect, buf: &mut Buffer) {
234 +
        let padding = self.opts.padding;
235 +
        let content = if self.opts.border.is_some() {
236 +
            area.inner(1)
237 +
        } else {
238 +
            area
239 +
        };
240 +
        let child_cols = content.cols.saturating_sub(padding * 2);
241 +
        let child_constraint = Constraint::tight(child_cols);
242 +
        let child_x = content.x + padding.min(content.cols);
243 +
        let heights = allocate_heights(
244 +
            content.rows,
245 +
            &self
246 +
                .rows
247 +
                .iter()
248 +
                .map(|row| row.layout_height(child_constraint))
249 +
                .collect::<Vec<_>>(),
250 +
        );
251 +
        let mut y = content.y;
252 +
253 +
        if let Some(border) = self.opts.border {
254 +
            border.draw(area, buf);
255 +
        }
256 +
        for (row, rows) in self.rows.iter().zip(heights) {
257 +
            match row {
258 +
                Row::Widget { widget, .. } => {
259 +
                    if rows > 0 && y < content.bottom() {
260 +
                        let area = Rect::new(child_x, y, child_cols, rows);
261 +
                        widget.render(area, buf);
262 +
                    }
263 +
                    y += rows;
264 +
                }
265 +
                Row::Divider { cell } => {
266 +
                    let row_y = y;
267 +
                    y += rows;
268 +
                    if rows == 0 || row_y >= area.bottom() {
269 +
                        continue;
270 +
                    }
271 +
                    if let Some(border) = self.opts.border {
272 +
                        let chars = border.chars();
273 +
                        buf.set_glyph(area.x, row_y, chars.divider_left, border.style());
274 +
                        buf.fill(Rect::new(content.x, row_y, content.cols, 1), cell.clone());
275 +
                        if area.cols > 1 {
276 +
                            buf.set_glyph(
277 +
                                area.right().saturating_sub(1),
278 +
                                row_y,
279 +
                                chars.divider_right,
280 +
                                border.style(),
281 +
                            );
282 +
                        }
283 +
                    } else {
284 +
                        buf.fill(Rect::new(content.x, row_y, content.cols, 1), cell.clone());
285 +
                    }
286 +
                }
287 +
            }
288 +
        }
289 +
    }
290 +
}
291 +
292 +
/// Allocates row heights without growing fixed rows when no fill row exists.
293 +
fn allocate_heights(total: usize, lengths: &[Length]) -> Vec<usize> {
294 +
    let base = lengths
295 +
        .iter()
296 +
        .map(|length| match *length {
297 +
            Length::Fixed(rows) | Length::Min(rows) => rows,
298 +
            Length::Fill(_) => 0,
299 +
        })
300 +
        .sum::<usize>();
301 +
    let fill = lengths
302 +
        .iter()
303 +
        .map(|length| match *length {
304 +
            Length::Fill(weight) => weight.max(1) as usize,
305 +
            _ => 0,
306 +
        })
307 +
        .sum::<usize>();
308 +
    let remaining = total.saturating_sub(base);
309 +
    let mut used = 0usize;
310 +
    let mut remaining_fill = fill;
311 +
    let mut used_fill = 0usize;
312 +
313 +
    lengths
314 +
        .iter()
315 +
        .map(|length| {
316 +
            let rows = match *length {
317 +
                Length::Fixed(rows) | Length::Min(rows) => rows,
318 +
                Length::Fill(weight) if fill > 0 => {
319 +
                    let weight = weight.max(1) as usize;
320 +
                    let rows = if remaining_fill == weight {
321 +
                        remaining.saturating_sub(used_fill)
322 +
                    } else {
323 +
                        remaining * weight / fill
324 +
                    };
325 +
                    remaining_fill = remaining_fill.saturating_sub(weight);
326 +
                    used_fill += rows;
327 +
                    rows
328 +
                }
329 +
                Length::Fill(_) => 0,
330 +
            }
331 +
            .min(total.saturating_sub(used));
332 +
            used += rows;
333 +
            rows
334 +
        })
335 +
        .collect()
336 +
}
337 +
338 +
/// Simple bordered vstack.
339 +
pub fn bordered<'a>(child: impl Widget + 'a) -> VStack<'a> {
340 +
    VStack::default()
341 +
        .border(Some(Border::new(colors::FAINT)))
342 +
        .child(child)
343 +
}
344 +
345 +
#[cfg(test)]
346 +
mod tests {
347 +
    use super::*;
348 +
    use crate::{Color, Line};
349 +
350 +
    #[derive(Debug)]
351 +
    struct Expanding;
352 +
353 +
    impl Widget for Expanding {
354 +
        fn size(&self, parent: Constraint) -> Size {
355 +
            parent.max
356 +
        }
357 +
358 +
        fn render(&self, _area: Rect, _buf: &mut Buffer) {}
359 +
    }
360 +
361 +
    #[test]
362 +
    fn test_vstack() {
363 +
        let mut v = VStack::default()
364 +
            .border(Some(Border::new(Color::Unset)))
365 +
            .padding(1);
366 +
367 +
        v.push(Line::new("banana"));
368 +
        v.push(Line::new("apple"));
369 +
        v.push(Line::new("abricot"));
370 +
371 +
        let constraint = Constraint::default();
372 +
        let outer = v.outer(constraint);
373 +
        assert_eq!(outer.cols, 11);
374 +
        assert_eq!(outer.rows, 5);
375 +
376 +
        let inner = v.inner(constraint);
377 +
        assert_eq!(inner.cols, 9);
378 +
        assert_eq!(inner.rows, 3);
379 +
380 +
        assert_eq!(
381 +
            v.display(constraint),
382 +
            r"
383 +
╭─────────╮
384 +
│ banana  │
385 +
│ apple   │
386 +
│ abricot │
387 +
╰─────────╯
388 +
"
389 +
            .trim_start()
390 +
        );
391 +
    }
392 +
393 +
    #[test]
394 +
    fn test_vstack_maximize() {
395 +
        let mut v = VStack::default()
396 +
            .border(Some(Border::new(Color::Unset)))
397 +
            .padding(1);
398 +
399 +
        v.push(Line::new("banana"));
400 +
        v.push(Line::new("apple"));
401 +
        v.push(Line::new("abricot"));
402 +
403 +
        let constraint = Constraint {
404 +
            min: Size::new(14, 0),
405 +
            max: Size::new(14, usize::MAX),
406 +
        };
407 +
        let outer = v.outer(constraint);
408 +
        assert_eq!(outer.cols, 14);
409 +
        assert_eq!(outer.rows, 5);
410 +
411 +
        let inner = v.inner(constraint);
412 +
        assert_eq!(inner.cols, 12);
413 +
        assert_eq!(inner.rows, 3);
414 +
415 +
        assert_eq!(
416 +
            v.display(constraint),
417 +
            r"
418 +
╭────────────╮
419 +
│ banana     │
420 +
│ apple      │
421 +
│ abricot    │
422 +
╰────────────╯
423 +
"
424 +
            .trim_start()
425 +
        );
426 +
    }
427 +
428 +
    #[test]
429 +
    fn empty_vstack_has_padding_width_and_no_rows() {
430 +
        let v = VStack::default();
431 +
432 +
        assert!(v.is_empty());
433 +
        assert_eq!(v.size(Constraint::UNBOUNDED), Size::new(2, 0));
434 +
        assert_eq!(v.display(Constraint::UNBOUNDED), "");
435 +
    }
436 +
437 +
    #[test]
438 +
    fn unbordered_vstack_renders_widgets_and_plain_divider() {
439 +
        let v = VStack::default()
440 +
            .padding(0)
441 +
            .child(Line::new("top"))
442 +
            .divider()
443 +
            .child(Line::new("bottom"));
444 +
445 +
        assert!(!v.is_empty());
446 +
        assert_eq!(v.size(Constraint::UNBOUNDED), Size::new(6, 3));
447 +
        assert_eq!(v.display(Constraint::UNBOUNDED), "top   \n──────\nbottom\n");
448 +
    }
449 +
450 +
    #[test]
451 +
    fn bordered_divider_keeps_border_and_fill_styles_separate() {
452 +
        let v = VStack::default()
453 +
            .border(Some(Border::new(Color::Blue)))
454 +
            .padding(0)
455 +
            .child(Line::new("top"))
456 +
            .divider_cell(Cell::new("┄", Style::new(Color::Red)))
457 +
            .child(Line::new("bottom"));
458 +
        let mut buffer = Buffer::empty(Rect::from_size(v.size(Constraint::UNBOUNDED)));
459 +
460 +
        v.render(buffer.area(), &mut buffer);
461 +
462 +
        assert_eq!(
463 +
            buffer.lines(),
464 +
            vec!["╭──────╮", "│top   │", "├┄┄┄┄┄┄┤", "│bottom│", "╰──────╯"]
465 +
        );
466 +
        assert_eq!(
467 +
            buffer.get(0, 2).map(|cell| cell.style().fg_color()),
468 +
            Some(Color::Blue)
469 +
        );
470 +
        assert_eq!(
471 +
            buffer.get(1, 2).map(|cell| cell.style().fg_color()),
472 +
            Some(Color::Red)
473 +
        );
474 +
        assert_eq!(
475 +
            buffer.get(7, 2).map(|cell| cell.style().fg_color()),
476 +
            Some(Color::Blue)
477 +
        );
478 +
    }
479 +
480 +
    #[test]
481 +
    fn blank_adds_empty_widget_row() {
482 +
        let v = VStack::default()
483 +
            .padding(0)
484 +
            .child(Line::new("top"))
485 +
            .blank()
486 +
            .child(Line::new("bottom"));
487 +
488 +
        assert_eq!(v.display(Constraint::UNBOUNDED), "top   \n      \nbottom\n");
489 +
    }
490 +
491 +
    #[test]
492 +
    fn children_appends_boxed_widgets() {
493 +
        let children = vec![Line::new("one").boxed(), Line::new("two").boxed()];
494 +
        let v = VStack::default().padding(0).children(children);
495 +
496 +
        assert_eq!(v.display(Constraint::UNBOUNDED), "one\ntwo\n");
497 +
    }
498 +
499 +
    #[test]
500 +
    fn fill_child_absorbs_remaining_height() {
501 +
        let stack = VStack::default()
502 +
            .padding(0)
503 +
            .child(Line::new("top"))
504 +
            .fill(crate::Fill::new(".", crate::Style::default()));
505 +
        let constraint = Constraint::new(Size::new(5, 4), Size::new(5, 4));
506 +
507 +
        assert_eq!(stack.display(constraint), "top  \n.....\n.....\n.....\n");
508 +
    }
509 +
510 +
    #[test]
511 +
    fn unbounded_expanding_child_does_not_overflow_natural_width() {
512 +
        let stack = VStack::default()
513 +
            .border(Some(Border::new(Color::Unset)))
514 +
            .fill(Expanding);
515 +
516 +
        assert_eq!(stack.size(Constraint::UNBOUNDED), Size::new(usize::MAX, 2));
517 +
    }
518 +
519 +
    #[test]
520 +
    fn merge_preserves_row_order() {
521 +
        let left = VStack::default().padding(0).child(Line::new("left"));
522 +
        let right = VStack::default().padding(0).child(Line::new("right"));
523 +
524 +
        assert_eq!(
525 +
            left.merge(right).display(Constraint::UNBOUNDED),
526 +
            "left \nright\n"
527 +
        );
528 +
    }
529 +
530 +
    #[test]
531 +
    fn boxed_vstack_dispatches_widget_methods() {
532 +
        let boxed = VStack::default()
533 +
            .padding(0)
534 +
            .child(Line::new("boxed"))
535 +
            .boxed();
536 +
537 +
        assert_eq!(boxed.size(Constraint::UNBOUNDED), Size::new(5, 1));
538 +
        assert_eq!(boxed.display(Constraint::UNBOUNDED), "boxed\n");
539 +
    }
540 +
541 +
    #[test]
542 +
    fn bordered_helper_wraps_child_with_faint_border() {
543 +
        let v = bordered(Line::new("x")).padding(0);
544 +
        let mut buffer = Buffer::empty(Rect::from_size(v.size(Constraint::UNBOUNDED)));
545 +
546 +
        v.render(buffer.area(), &mut buffer);
547 +
548 +
        assert_eq!(buffer.lines(), vec!["╭─╮", "│x│", "╰─╯"]);
549 +
        assert_eq!(
550 +
            buffer.get(0, 0).map(|cell| cell.style().fg_color()),
551 +
            Some(colors::FAINT)
552 +
        );
553 +
        assert_eq!(
554 +
            buffer.get(0, 1).map(|cell| cell.style().fg_color()),
555 +
            Some(colors::FAINT)
556 +
        );
557 +
        assert_eq!(
558 +
            buffer.get(2, 2).map(|cell| cell.style().fg_color()),
559 +
            Some(colors::FAINT)
560 +
        );
561 +
    }
562 +
}
crates/tui-core/src/widget.rs added +299 -0
1 +
//! Core widget trait and generic widget wrappers.
2 +
//!
3 +
//! [`Widget`] is the object-safe rendering contract used throughout the crate.
4 +
//! This module also provides simple wrappers such as `Clear`, `Fill`, and
5 +
//! `Block` that are broadly useful and do not belong to a more specific
6 +
//! layout or text module.
7 +
8 +
use std::fmt;
9 +
use std::fmt::Write as _;
10 +
use std::ops::Deref;
11 +
12 +
use crate::layout::Rect;
13 +
use crate::{Border, Buffer, Cell, Color, Constraint, Line, Paint, Size, Style};
14 +
15 +
/// Something that can render into a [`Buffer`].
16 +
pub trait Widget: fmt::Debug + Send + Sync {
17 +
    /// Returns the widget size under a parent constraint.
18 +
    fn size(&self, parent: Constraint) -> Size;
19 +
20 +
    /// Renders the widget into an area.
21 +
    fn render(&self, area: Rect, buf: &mut Buffer);
22 +
23 +
    /// Returns the number of columns occupied by this widget.
24 +
    fn columns(&self, parent: Constraint) -> usize {
25 +
        self.size(parent).cols
26 +
    }
27 +
28 +
    /// Returns the number of rows occupied by this widget.
29 +
    fn rows(&self, parent: Constraint) -> usize {
30 +
        self.size(parent).rows
31 +
    }
32 +
33 +
    /// Renders this widget into a fresh buffer sized from the given constraints.
34 +
    fn to_buffer(&self, constraints: Constraint) -> Buffer {
35 +
        let size = self.size(constraints);
36 +
        let area = Rect::from_size(size);
37 +
        let mut buffer = Buffer::empty(area);
38 +
39 +
        self.render(area, &mut buffer);
40 +
41 +
        buffer
42 +
    }
43 +
44 +
    /// Returns a plain string representation of this widget.
45 +
    #[must_use]
46 +
    fn display(&self, constraints: Constraint) -> String {
47 +
        let buffer = self.to_buffer(constraints);
48 +
        let mut out = String::new();
49 +
50 +
        for line in buffer.lines() {
51 +
            out.push_str(&line);
52 +
            out.push('\n');
53 +
        }
54 +
        out
55 +
    }
56 +
57 +
    /// Returns a string representation with terminal styling escapes.
58 +
    #[must_use]
59 +
    fn display_styled(&self, constraints: Constraint) -> String {
60 +
        let buffer = self.to_buffer(constraints);
61 +
        let area = buffer.area();
62 +
        let mut out = String::new();
63 +
64 +
        for y in area.y..area.bottom() {
65 +
            for x in area.x..area.right() {
66 +
                let Some(cell) = buffer.get(x, y) else {
67 +
                    continue;
68 +
                };
69 +
                if !cell.is_continuation() {
70 +
                    let _ = write!(out, "{}", cell.paint().styled());
71 +
                }
72 +
            }
73 +
            out.push('\n');
74 +
        }
75 +
        out
76 +
    }
77 +
}
78 +
79 +
impl Widget for Box<dyn Widget + '_> {
80 +
    fn size(&self, parent: Constraint) -> Size {
81 +
        self.deref().size(parent)
82 +
    }
83 +
84 +
    fn render(&self, area: Rect, buf: &mut Buffer) {
85 +
        self.deref().render(area, buf);
86 +
    }
87 +
}
88 +
89 +
impl<T: Widget + ?Sized> Widget for &T {
90 +
    fn size(&self, parent: Constraint) -> Size {
91 +
        (*self).size(parent)
92 +
    }
93 +
94 +
    fn render(&self, area: Rect, buf: &mut Buffer) {
95 +
        (*self).render(area, buf);
96 +
    }
97 +
}
98 +
99 +
/// Clears an area.
100 +
#[derive(Debug, Clone, Copy, Default)]
101 +
pub struct Clear;
102 +
103 +
impl Widget for Clear {
104 +
    fn size(&self, parent: Constraint) -> Size {
105 +
        parent.bounded_size()
106 +
    }
107 +
108 +
    fn render(&self, area: Rect, buf: &mut Buffer) {
109 +
        buf.fill(area, crate::buffer::Cell::blank());
110 +
    }
111 +
}
112 +
113 +
/// Fills an area with one glyph and style.
114 +
#[derive(Debug, Clone)]
115 +
pub struct Fill {
116 +
    /// Fill cell.
117 +
    cell: Cell,
118 +
}
119 +
120 +
impl Fill {
121 +
    /// Creates a fill widget from a glyph and style.
122 +
    pub fn new(glyph: impl AsRef<str>, style: Style) -> Self {
123 +
        Self {
124 +
            cell: Cell::new(glyph, style),
125 +
        }
126 +
    }
127 +
128 +
    /// Creates a fill widget from a cell.
129 +
    pub fn cell(cell: Cell) -> Self {
130 +
        Self { cell }
131 +
    }
132 +
}
133 +
134 +
impl Widget for Fill {
135 +
    fn size(&self, parent: Constraint) -> Size {
136 +
        parent.bounded_size()
137 +
    }
138 +
139 +
    fn render(&self, area: Rect, buf: &mut Buffer) {
140 +
        buf.fill(area, self.cell.clone());
141 +
    }
142 +
}
143 +
144 +
/// Bordered widget wrapper.
145 +
#[derive(Debug, Clone)]
146 +
pub struct Block<W> {
147 +
    child: W,
148 +
    border: Option<Border>,
149 +
    title: Option<Line>,
150 +
}
151 +
152 +
impl<W> Block<W> {
153 +
    /// Creates a block around a child.
154 +
    pub fn new(child: W) -> Self {
155 +
        Self {
156 +
            child,
157 +
            border: None,
158 +
            title: None,
159 +
        }
160 +
    }
161 +
162 +
    /// Sets the border color.
163 +
    pub fn border(mut self, color: Color) -> Self {
164 +
        self.border = Some(Border::new(color));
165 +
        self
166 +
    }
167 +
168 +
    /// Sets the border style.
169 +
    pub fn border_style(mut self, border: Border) -> Self {
170 +
        self.border = Some(border);
171 +
        self
172 +
    }
173 +
174 +
    /// Sets the title.
175 +
    pub fn title(mut self, title: impl Into<Line>) -> Self {
176 +
        self.title = Some(title.into());
177 +
        self
178 +
    }
179 +
}
180 +
181 +
impl<W: Widget> Widget for Block<W> {
182 +
    fn size(&self, parent: Constraint) -> Size {
183 +
        let mut size = self.child.size(parent);
184 +
        if self.border.is_some() {
185 +
            size.cols = size.cols.saturating_add(2);
186 +
            size.rows = size.rows.saturating_add(2);
187 +
        }
188 +
        size.constrain(parent)
189 +
    }
190 +
191 +
    fn render(&self, area: Rect, buf: &mut Buffer) {
192 +
        if area.is_empty() {
193 +
            return;
194 +
        }
195 +
        let Some(border) = self.border else {
196 +
            self.child.render(area, buf);
197 +
            return;
198 +
        };
199 +
        border.draw(area, buf);
200 +
201 +
        if let Some(title) = self.title.clone()
202 +
            && area.cols > 4
203 +
        {
204 +
            let title = title.truncated(area.cols.saturating_sub(4), "…");
205 +
            buf.set_line(area.x + 2, area.y, &title);
206 +
        }
207 +
        self.child.render(area.inner(1), buf);
208 +
    }
209 +
}
210 +
211 +
impl From<Paint<String>> for Fill {
212 +
    fn from(paint: Paint<String>) -> Self {
213 +
        Self::new(paint.content(), paint.style())
214 +
    }
215 +
}
216 +
217 +
#[cfg(test)]
218 +
mod tests {
219 +
    use super::*;
220 +
    use crate::{Constraint, Label};
221 +
222 +
    #[test]
223 +
    fn line_widgets_render_into_buffer() {
224 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 6, 2));
225 +
226 +
        Label::new("hello").render(buffer.area(), &mut buffer);
227 +
228 +
        assert_eq!(buffer.lines(), vec!["hello ", "      "]);
229 +
        assert_eq!(Label::new("hello").size(Constraint::UNBOUNDED).cols, 5);
230 +
    }
231 +
232 +
    #[test]
233 +
    fn widget_display_renders_through_buffer() {
234 +
        let display = Fill::new("x", Style::default()).display(Constraint::tight(4));
235 +
236 +
        assert_eq!(display, "xxxx\n");
237 +
    }
238 +
239 +
    #[test]
240 +
    fn block_draws_border_and_child() {
241 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 8, 3));
242 +
243 +
        Block::new(Label::new("x"))
244 +
            .border(Color::Unset)
245 +
            .title("t")
246 +
            .render(buffer.area(), &mut buffer);
247 +
248 +
        assert_eq!(buffer.lines(), vec!["╭─t────╮", "│x     │", "╰──────╯"]);
249 +
    }
250 +
251 +
    #[test]
252 +
    fn clear_and_fill_widgets_cover_their_area() {
253 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 2));
254 +
255 +
        Fill::new("x", Style::default()).render(buffer.area(), &mut buffer);
256 +
        Clear.render(Rect::new(1, 0, 3, 1), &mut buffer);
257 +
258 +
        assert_eq!(buffer.lines(), vec!["x   x", "xxxxx"]);
259 +
    }
260 +
261 +
    #[test]
262 +
    fn block_without_border_renders_child_directly() {
263 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 1));
264 +
265 +
        Block::new(Label::new("abc")).render(buffer.area(), &mut buffer);
266 +
267 +
        assert_eq!(buffer.lines(), vec!["abc  "]);
268 +
    }
269 +
270 +
    #[test]
271 +
    fn block_handles_degenerate_border_areas() {
272 +
        let mut one = Buffer::empty(Rect::new(0, 0, 1, 1));
273 +
        let mut row = Buffer::empty(Rect::new(0, 0, 4, 1));
274 +
        let mut column = Buffer::empty(Rect::new(0, 0, 1, 3));
275 +
276 +
        Block::new(Label::new("x"))
277 +
            .border(Color::Unset)
278 +
            .render(one.area(), &mut one);
279 +
        Block::new(Label::new("x"))
280 +
            .border(Color::Unset)
281 +
            .render(row.area(), &mut row);
282 +
        Block::new(Label::new("x"))
283 +
            .border(Color::Unset)
284 +
            .render(column.area(), &mut column);
285 +
286 +
        assert_eq!(one.lines(), vec!["╭"]);
287 +
        assert_eq!(row.lines(), vec!["╭──╮"]);
288 +
        assert_eq!(column.lines(), vec!["╭", "│", "╰"]);
289 +
    }
290 +
291 +
    #[test]
292 +
    fn line_widget_truncates_to_area_width_and_height() {
293 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 4, 1));
294 +
295 +
        vec![Line::new("abcdef"), Line::new("hidden")].render(buffer.area(), &mut buffer);
296 +
297 +
        assert_eq!(buffer.lines(), vec!["abc…"]);
298 +
    }
299 +
}
crates/tui-termion/Cargo.toml added +15 -0
1 +
[package]
2 +
name = "rustik-tui-termion"
3 +
version.workspace = true
4 +
edition.workspace = true
5 +
description = "Rustik is a rust development kit for minimal, high performance tools. Termion integration for the rustik-tui crate."
6 +
homepage = "https://crates.io/crates/rustik-tui-termion"
7 +
documentation = "https://docs.rs/rustik-tui-termion"
8 +
license.workspace = true
9 +
10 +
[dependencies]
11 +
termion.workspace = true
12 +
rustik-tui-core.workspace = true
13 +
14 +
[lints]
15 +
workspace = true
crates/tui-termion/README.md added +15 -0
1 +
# rustik-tui-termion
2 +
3 +
*Rustik is a Rust development kit for minimal, high performance tools.*
4 +
5 +
Termion backend integration for `rustik-tui`-style terminal UIs.
6 +
7 +
The crate provides:
8 +
9 +
- `TermionBackend` for rendering into any `Write` target
10 +
- conversion utilities for termion events and input (`event`, `key_event`, `mouse_event`)
11 +
- a `run` helper to wire raw terminal sessions to a `rustik_tui_core::App`
12 +
13 +
## License
14 +
15 +
MIT. See [LICENSE](../../LICENSE).
crates/tui-termion/src/lib.rs added +363 -0
1 +
//! Termion integration for the `rustik_tui` crate.
2 +
//!
3 +
//! This crate keeps terminal I/O and termion event conversion outside the core
4 +
//! crate. It provides a concrete backend plus a `run` helper for wiring raw
5 +
//! terminal sessions to the core app/update/render loop.
6 +
//!
7 +
#![deny(unsafe_code)]
8 +
#![warn(missing_docs)]
9 +
#![warn(clippy::unwrap_used)]
10 +
11 +
use std::io::{self, Write};
12 +
13 +
use rustik_tui_core as tui_core;
14 +
use tui_core::backend::Backend;
15 +
use tui_core::buffer::DirtyRun;
16 +
use tui_core::layout::Point;
17 +
use tui_core::{Event, Key, Mouse, MouseButton, PaintMode, Size};
18 +
19 +
/// Runs an application on stdout using termion.
20 +
pub use term::run;
21 +
22 +
/// Termion session helpers.
23 +
pub mod term;
24 +
25 +
/// Termion-backed terminal output.
26 +
#[derive(Debug)]
27 +
pub struct TermionBackend<W> {
28 +
    writer: W,
29 +
    paint: PaintMode,
30 +
}
31 +
32 +
impl<W> TermionBackend<W> {
33 +
    /// Creates a backend from a writer.
34 +
    pub fn new(writer: W) -> Self {
35 +
        Self::with_paint(writer, PaintMode::Styled)
36 +
    }
37 +
38 +
    /// Creates a backend from a writer and paint mode.
39 +
    pub fn with_paint(writer: W, paint: PaintMode) -> Self {
40 +
        Self { writer, paint }
41 +
    }
42 +
43 +
    /// Creates a backend that writes no ANSI styling escapes.
44 +
    pub fn plain(writer: W) -> Self {
45 +
        Self::with_paint(writer, PaintMode::Plain)
46 +
    }
47 +
48 +
    /// Returns the current paint mode.
49 +
    pub const fn paint_mode(&self) -> PaintMode {
50 +
        self.paint
51 +
    }
52 +
53 +
    /// Sets the paint mode.
54 +
    pub fn set_paint_mode(&mut self, paint: PaintMode) {
55 +
        self.paint = paint;
56 +
    }
57 +
58 +
    /// Returns the wrapped writer.
59 +
    pub fn into_inner(self) -> W {
60 +
        self.writer
61 +
    }
62 +
63 +
    /// Returns a mutable writer reference.
64 +
    pub fn writer_mut(&mut self) -> &mut W {
65 +
        &mut self.writer
66 +
    }
67 +
}
68 +
69 +
impl<W: Write> Backend for TermionBackend<W> {
70 +
    type Error = io::Error;
71 +
72 +
    fn size(&mut self) -> Result<Size, Self::Error> {
73 +
        let (cols, rows) = termion::terminal_size()?;
74 +
75 +
        Ok(Size::new(cols as usize, rows as usize))
76 +
    }
77 +
78 +
    fn draw(&mut self, runs: &[DirtyRun<'_>]) -> Result<(), Self::Error> {
79 +
        for run in runs {
80 +
            write!(
81 +
                self.writer,
82 +
                "{}",
83 +
                termion::cursor::Goto(coord(run.x), coord(run.y))
84 +
            )?;
85 +
            for cell in run.cells {
86 +
                if cell.is_continuation() {
87 +
                    continue;
88 +
                }
89 +
                let paint = cell.paint();
90 +
                write!(self.writer, "{}", paint.rendered(self.paint))?;
91 +
            }
92 +
        }
93 +
        Ok(())
94 +
    }
95 +
96 +
    fn clear(&mut self) -> Result<(), Self::Error> {
97 +
        write!(self.writer, "{}", termion::clear::All)
98 +
    }
99 +
100 +
    fn flush(&mut self) -> Result<(), Self::Error> {
101 +
        self.writer.flush()
102 +
    }
103 +
104 +
    fn set_cursor_position(&mut self, point: Point) -> Result<(), Self::Error> {
105 +
        write!(
106 +
            self.writer,
107 +
            "{}",
108 +
            termion::cursor::Goto(coord(point.x), coord(point.y))
109 +
        )
110 +
    }
111 +
112 +
    fn set_cursor_visible(&mut self, visible: bool) -> Result<(), Self::Error> {
113 +
        if visible {
114 +
            write!(self.writer, "{}", termion::cursor::Show)
115 +
        } else {
116 +
            write!(self.writer, "{}", termion::cursor::Hide)
117 +
        }
118 +
    }
119 +
}
120 +
121 +
/// Converts a termion event into a typed `rustik_tui` event.
122 +
pub fn event(event: termion::event::Event) -> Event<()> {
123 +
    match event {
124 +
        termion::event::Event::Key(key) => Event::Key(key_event(key)),
125 +
        termion::event::Event::Mouse(mouse) => Event::Mouse(mouse_event(mouse)),
126 +
        termion::event::Event::Unsupported(_) => Event::Unsupported,
127 +
    }
128 +
}
129 +
130 +
/// Converts a termion key into a typed `rustik_tui` key.
131 +
pub fn key_event(key: termion::event::Key) -> Key {
132 +
    match key {
133 +
        termion::event::Key::Backspace => Key::Backspace,
134 +
        termion::event::Key::Left => Key::Left,
135 +
        termion::event::Key::Right => Key::Right,
136 +
        termion::event::Key::Up => Key::Up,
137 +
        termion::event::Key::Down => Key::Down,
138 +
        termion::event::Key::Home => Key::Home,
139 +
        termion::event::Key::End => Key::End,
140 +
        termion::event::Key::PageUp => Key::PageUp,
141 +
        termion::event::Key::PageDown => Key::PageDown,
142 +
        termion::event::Key::BackTab => Key::BackTab,
143 +
        termion::event::Key::Delete => Key::Delete,
144 +
        termion::event::Key::Insert => Key::Insert,
145 +
        termion::event::Key::F(n) => Key::F(n),
146 +
        termion::event::Key::Char('\n') => Key::Enter,
147 +
        termion::event::Key::Char('\t') => Key::Tab,
148 +
        termion::event::Key::Char(ch) => Key::Char(ch),
149 +
        termion::event::Key::Alt(ch) => Key::Alt(ch),
150 +
        termion::event::Key::Ctrl(ch) => Key::Ctrl(ch),
151 +
        termion::event::Key::Null => Key::Null,
152 +
        termion::event::Key::Esc => Key::Esc,
153 +
        _ => Key::Unknown,
154 +
    }
155 +
}
156 +
157 +
/// Converts a termion mouse event into a typed `rustik_tui` mouse event.
158 +
pub fn mouse_event(event: termion::event::MouseEvent) -> Mouse {
159 +
    match event {
160 +
        termion::event::MouseEvent::Press(button, x, y) => Mouse::Press {
161 +
            button: mouse_button(button),
162 +
            at: point(x, y),
163 +
        },
164 +
        termion::event::MouseEvent::Release(x, y) => Mouse::Release { at: point(x, y) },
165 +
        termion::event::MouseEvent::Hold(x, y) => Mouse::Hold { at: point(x, y) },
166 +
    }
167 +
}
168 +
169 +
/// Converts a termion mouse button into a typed `rustik_tui` mouse button.
170 +
pub fn mouse_button(button: termion::event::MouseButton) -> MouseButton {
171 +
    match button {
172 +
        termion::event::MouseButton::Left => MouseButton::Left,
173 +
        termion::event::MouseButton::Right => MouseButton::Right,
174 +
        termion::event::MouseButton::Middle => MouseButton::Middle,
175 +
        termion::event::MouseButton::WheelUp => MouseButton::WheelUp,
176 +
        termion::event::MouseButton::WheelDown => MouseButton::WheelDown,
177 +
        _ => MouseButton::Unknown,
178 +
    }
179 +
}
180 +
181 +
/// Converts a zero-based coordinate into a terminal coordinate.
182 +
fn coord(value: usize) -> u16 {
183 +
    u16::try_from(value.saturating_add(1)).unwrap_or(u16::MAX)
184 +
}
185 +
186 +
/// Converts one-based terminal coordinates to zero-based points.
187 +
fn point(x: u16, y: u16) -> Point {
188 +
    Point::new(x.saturating_sub(1) as usize, y.saturating_sub(1) as usize)
189 +
}
190 +
191 +
#[cfg(test)]
192 +
#[allow(clippy::unwrap_used)]
193 +
mod tests {
194 +
    use super::*;
195 +
    use rustik_tui_core as tui_core;
196 +
    use tui_core::backend::Backend;
197 +
    use tui_core::{Buffer, Color, Rect, Style};
198 +
199 +
    #[test]
200 +
    fn termion_backend_writes_dirty_runs_with_one_based_coordinates() {
201 +
        let cells = [tui_core::buffer::Cell::new("x", Style::default())];
202 +
        let run = DirtyRun {
203 +
            x: 2,
204 +
            y: 3,
205 +
            cells: &cells,
206 +
        };
207 +
        let mut backend = TermionBackend::new(Vec::new());
208 +
209 +
        backend.draw(&[run]).unwrap();
210 +
        backend.flush().unwrap();
211 +
        let out = String::from_utf8(backend.into_inner()).unwrap();
212 +
213 +
        assert!(out.starts_with("\x1B[4;3H"));
214 +
        assert!(out.ends_with('x'));
215 +
    }
216 +
217 +
    #[test]
218 +
    fn termion_backend_paint_mode_is_explicit() {
219 +
        let cells = [tui_core::buffer::Cell::new("x", Color::Red.style())];
220 +
        let run = DirtyRun {
221 +
            x: 0,
222 +
            y: 0,
223 +
            cells: &cells,
224 +
        };
225 +
226 +
        let mut styled = TermionBackend::new(Vec::new());
227 +
        styled.draw(&[run]).unwrap();
228 +
        assert_eq!(styled.paint_mode(), PaintMode::Styled);
229 +
        assert!(
230 +
            String::from_utf8(styled.into_inner())
231 +
                .unwrap()
232 +
                .contains("\x1B[31m")
233 +
        );
234 +
235 +
        let mut plain = TermionBackend::new(Vec::new());
236 +
        plain.set_paint_mode(PaintMode::Plain);
237 +
        assert_eq!(
238 +
            TermionBackend::plain(Vec::<u8>::new()).paint_mode(),
239 +
            PaintMode::Plain
240 +
        );
241 +
        plain.draw(&[run]).unwrap();
242 +
        let out = String::from_utf8(plain.into_inner()).unwrap();
243 +
244 +
        assert_eq!(out, "\x1B[1;1Hx");
245 +
    }
246 +
247 +
    #[test]
248 +
    fn termion_backend_does_not_write_wide_continuation_cells() {
249 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 4, 1));
250 +
        buffer.reset_dirty();
251 +
        buffer.set_str(0, 0, "🍍a", Style::default());
252 +
        let runs = buffer.dirty_runs();
253 +
        let mut backend = TermionBackend::new(Vec::new());
254 +
255 +
        backend.draw(&runs).unwrap();
256 +
        let out = String::from_utf8(backend.into_inner()).unwrap();
257 +
258 +
        assert!(out.ends_with("🍍a"));
259 +
        assert!(!out.ends_with("🍍 a"));
260 +
    }
261 +
262 +
    #[test]
263 +
    fn termion_backend_cursor_and_visibility_commands_are_written() {
264 +
        let mut backend = TermionBackend::new(Vec::new());
265 +
266 +
        backend.set_cursor_visible(false).unwrap();
267 +
        backend.set_cursor_position(Point::new(1, 2)).unwrap();
268 +
        backend.set_cursor_visible(true).unwrap();
269 +
        let out = String::from_utf8(backend.into_inner()).unwrap();
270 +
271 +
        assert!(out.contains("\x1B[?25l"));
272 +
        assert!(out.contains("\x1B[3;2H"));
273 +
        assert!(out.contains("\x1B[?25h"));
274 +
    }
275 +
276 +
    #[test]
277 +
    fn termion_keys_are_typed() {
278 +
        assert_eq!(key_event(termion::event::Key::Char('\n')), Key::Enter);
279 +
        assert_eq!(key_event(termion::event::Key::Ctrl('c')), Key::Ctrl('c'));
280 +
    }
281 +
282 +
    #[test]
283 +
    fn all_common_termion_keys_are_mapped() {
284 +
        assert_eq!(key_event(termion::event::Key::Backspace), Key::Backspace);
285 +
        assert_eq!(key_event(termion::event::Key::Left), Key::Left);
286 +
        assert_eq!(key_event(termion::event::Key::Right), Key::Right);
287 +
        assert_eq!(key_event(termion::event::Key::Up), Key::Up);
288 +
        assert_eq!(key_event(termion::event::Key::Down), Key::Down);
289 +
        assert_eq!(key_event(termion::event::Key::Home), Key::Home);
290 +
        assert_eq!(key_event(termion::event::Key::End), Key::End);
291 +
        assert_eq!(key_event(termion::event::Key::PageUp), Key::PageUp);
292 +
        assert_eq!(key_event(termion::event::Key::PageDown), Key::PageDown);
293 +
        assert_eq!(key_event(termion::event::Key::BackTab), Key::BackTab);
294 +
        assert_eq!(key_event(termion::event::Key::Delete), Key::Delete);
295 +
        assert_eq!(key_event(termion::event::Key::Insert), Key::Insert);
296 +
        assert_eq!(key_event(termion::event::Key::F(5)), Key::F(5));
297 +
        assert_eq!(key_event(termion::event::Key::Char('\t')), Key::Tab);
298 +
        assert_eq!(key_event(termion::event::Key::Alt('x')), Key::Alt('x'));
299 +
        assert_eq!(key_event(termion::event::Key::Null), Key::Null);
300 +
        assert_eq!(key_event(termion::event::Key::Esc), Key::Esc);
301 +
    }
302 +
303 +
    #[test]
304 +
    fn termion_events_are_mapped() {
305 +
        let key = termion::event::Event::Key(termion::event::Key::Char('x'));
306 +
        let mouse = termion::event::Event::Mouse(termion::event::MouseEvent::Release(2, 3));
307 +
        let unsupported = termion::event::Event::Unsupported(vec![1, 2, 3]);
308 +
309 +
        assert_eq!(event(key), Event::Key(Key::Char('x')));
310 +
        assert_eq!(
311 +
            event(mouse),
312 +
            Event::Mouse(Mouse::Release {
313 +
                at: Point::new(1, 2),
314 +
            })
315 +
        );
316 +
        assert_eq!(event(unsupported), Event::Unsupported);
317 +
    }
318 +
319 +
    #[test]
320 +
    fn termion_mouse_events_are_zero_based() {
321 +
        assert_eq!(
322 +
            mouse_event(termion::event::MouseEvent::Press(
323 +
                termion::event::MouseButton::Left,
324 +
                1,
325 +
                2,
326 +
            )),
327 +
            Mouse::Press {
328 +
                button: MouseButton::Left,
329 +
                at: Point::new(0, 1),
330 +
            }
331 +
        );
332 +
        assert_eq!(
333 +
            mouse_event(termion::event::MouseEvent::Hold(3, 4)),
334 +
            Mouse::Hold {
335 +
                at: Point::new(2, 3),
336 +
            }
337 +
        );
338 +
    }
339 +
340 +
    #[test]
341 +
    fn mouse_buttons_are_mapped() {
342 +
        assert_eq!(
343 +
            mouse_button(termion::event::MouseButton::Left),
344 +
            MouseButton::Left
345 +
        );
346 +
        assert_eq!(
347 +
            mouse_button(termion::event::MouseButton::Right),
348 +
            MouseButton::Right
349 +
        );
350 +
        assert_eq!(
351 +
            mouse_button(termion::event::MouseButton::Middle),
352 +
            MouseButton::Middle
353 +
        );
354 +
        assert_eq!(
355 +
            mouse_button(termion::event::MouseButton::WheelUp),
356 +
            MouseButton::WheelUp
357 +
        );
358 +
        assert_eq!(
359 +
            mouse_button(termion::event::MouseButton::WheelDown),
360 +
            MouseButton::WheelDown
361 +
        );
362 +
    }
363 +
}
crates/tui-termion/src/term.rs added +167 -0
1 +
//! Termion terminal session helpers.
2 +
//!
3 +
//! This module owns the raw-screen setup and event iterator plumbing needed to
4 +
//! run a `rustik_tui` app on a real terminal. Keeping it outside the core crate avoids
5 +
//! tying widget rendering to termion.
6 +
7 +
use std::io;
8 +
use std::io::IsTerminal;
9 +
use std::io::Write as _;
10 +
use std::sync::mpsc;
11 +
use std::thread;
12 +
13 +
use termion::input::{MouseTerminal, TermRead};
14 +
use termion::raw::{IntoRawMode, RawTerminal};
15 +
use termion::screen::{AlternateScreen, IntoAlternateScreen};
16 +
17 +
use rustik_tui_core as tui_core;
18 +
use tui_core::app::{App, Control};
19 +
use tui_core::event::Event;
20 +
use tui_core::terminal::Terminal;
21 +
use tui_core::{Constraint, Size, Widget};
22 +
23 +
use crate::TermionBackend;
24 +
25 +
/// Raw alternate stdout screen.
26 +
pub type StdoutScreen = AlternateScreen<MouseTerminal<RawTerminal<io::Stdout>>>;
27 +
28 +
/// Creates a raw alternate-screen backend on stdout.
29 +
pub fn screen() -> io::Result<TermionBackend<StdoutScreen>> {
30 +
    let screen = MouseTerminal::from(io::stdout().into_raw_mode()?).into_alternate_screen()?;
31 +
32 +
    Ok(TermionBackend::new(screen))
33 +
}
34 +
35 +
/// Returns typed events from an input stream.
36 +
pub fn events_from<R: io::Read>(input: R) -> impl Iterator<Item = io::Result<Event<()>>> {
37 +
    input.events().map(|event| event.map(crate::event))
38 +
}
39 +
40 +
/// Returns typed events from stdin.
41 +
pub fn events() -> impl Iterator<Item = io::Result<Event<()>>> {
42 +
    events_from(io::stdin())
43 +
}
44 +
45 +
/// Returns the current terminal viewport size.
46 +
pub fn viewport() -> Option<Size> {
47 +
    termion::terminal_size()
48 +
        .map(|(cols, rows)| Size::new(cols as usize, rows as usize))
49 +
        .ok()
50 +
}
51 +
52 +
/// Returns the stdout-backed widget constraint.
53 +
pub fn stdout_constraint() -> Option<Constraint> {
54 +
    if io::stdout().is_terminal() {
55 +
        Some(Constraint::max(viewport().unwrap_or(Size::MAX)))
56 +
    } else {
57 +
        None
58 +
    }
59 +
}
60 +
61 +
/// Prints a widget to stdout.
62 +
pub fn print<W: Widget + ?Sized>(widget: &W) {
63 +
    let constraint = stdout_constraint().unwrap_or_default();
64 +
65 +
    write_to_stdout(widget, constraint).ok();
66 +
}
67 +
68 +
/// Writes a widget to stdout under the given constraint.
69 +
pub fn write_to_stdout<W: Widget + ?Sized>(widget: &W, constraints: Constraint) -> io::Result<()> {
70 +
    let mut stdout = io::stdout();
71 +
    for line in widget.display(constraints).lines() {
72 +
        writeln!(stdout, "{}", line.trim_end())?;
73 +
    }
74 +
    Ok(())
75 +
}
76 +
77 +
/// Runs an application on stdout using termion.
78 +
pub fn run<A>(app: &mut A) -> io::Result<()>
79 +
where
80 +
    A: App<Event = ()>,
81 +
{
82 +
    let backend = screen()?;
83 +
    let mut terminal = Terminal::new(backend)?;
84 +
85 +
    terminal.clear()?;
86 +
    terminal.set_cursor_visible(false)?;
87 +
88 +
    let result = run_loop(app, &mut terminal);
89 +
    let cursor = terminal.set_cursor_visible(true);
90 +
91 +
    result.and(cursor)
92 +
}
93 +
94 +
/// Runs the application event loop.
95 +
fn run_loop<A>(app: &mut A, terminal: &mut Terminal<TermionBackend<StdoutScreen>>) -> io::Result<()>
96 +
where
97 +
    A: App<Event = ()>,
98 +
{
99 +
    terminal.draw(|frame| app.render(frame))?;
100 +
101 +
    let events = event_receiver();
102 +
103 +
    while let Ok(event) = events.recv() {
104 +
        let mut redraw = false;
105 +
        if update(app, event?, &mut redraw) == Control::Quit {
106 +
            break;
107 +
        }
108 +
        while let Ok(event) = events.try_recv() {
109 +
            if update(app, event?, &mut redraw) == Control::Quit {
110 +
                return Ok(());
111 +
            }
112 +
        }
113 +
        if redraw {
114 +
            terminal.draw(|frame| app.render(frame))?;
115 +
        }
116 +
    }
117 +
    Ok(())
118 +
}
119 +
120 +
/// Spawns a blocking stdin reader and returns its event channel.
121 +
fn event_receiver() -> mpsc::Receiver<io::Result<Event<()>>> {
122 +
    let (tx, rx) = mpsc::channel();
123 +
    thread::spawn(move || {
124 +
        for event in events() {
125 +
            if tx.send(event).is_err() {
126 +
                break;
127 +
            }
128 +
        }
129 +
    });
130 +
    rx
131 +
}
132 +
133 +
/// Applies one event and records whether the caller should redraw.
134 +
fn update<A>(app: &mut A, event: Event<()>, redraw: &mut bool) -> Control
135 +
where
136 +
    A: App<Event = ()>,
137 +
{
138 +
    match app.update(event) {
139 +
        Control::Continue | Control::Wait => Control::Continue,
140 +
        Control::Redraw => {
141 +
            *redraw = true;
142 +
            Control::Redraw
143 +
        }
144 +
        Control::Quit => Control::Quit,
145 +
    }
146 +
}
147 +
148 +
#[cfg(test)]
149 +
#[allow(clippy::unwrap_used)]
150 +
mod tests {
151 +
    use std::io::Cursor;
152 +
153 +
    use super::*;
154 +
    use rustik_tui_core as tui_core;
155 +
    use tui_core::Key;
156 +
157 +
    #[test]
158 +
    fn events_from_maps_termion_input_stream() {
159 +
        let events = events_from(Cursor::new([b'a', b'\n', 0x1b]))
160 +
            .collect::<io::Result<Vec<_>>>()
161 +
            .unwrap();
162 +
163 +
        assert_eq!(events[0], Event::Key(Key::Char('a')));
164 +
        assert_eq!(events[1], Event::Key(Key::Enter));
165 +
        assert_eq!(events[2], Event::Key(Key::Esc));
166 +
    }
167 +
}
crates/tui-widgets/Cargo.toml added +14 -0
1 +
[package]
2 +
name = "rustik-tui-widgets"
3 +
version.workspace = true
4 +
edition.workspace = true
5 +
description = "Rustik is a rust development kit for minimal, high performance tools. Higher-level widgets for the rustik-tui crate."
6 +
homepage = "https://crates.io/crates/rustik-tui-widgets"
7 +
documentation = "https://docs.rs/rustik-tui-widgets"
8 +
license.workspace = true
9 +
10 +
[dependencies]
11 +
rustik-tui-core = { workspace = true }
12 +
13 +
[lints]
14 +
workspace = true
crates/tui-widgets/README.md added +12 -0
1 +
# rustik-tui-widgets
2 +
3 +
*Rustik is a Rust development kit for minimal, high performance tools.*
4 +
5 +
Higher-level widgets built on top of `rustik-tui-core`.
6 +
7 +
It depends on `rustik-tui-core` and is normally pulled in via feature flags in
8 +
facade crates.
9 +
10 +
## License
11 +
12 +
MIT. See [LICENSE](../../LICENSE).
crates/tui-widgets/src/lib.rs added +24 -0
1 +
//! Higher-level widgets built on the core `rustik_tui_core` crate.
2 +
//!
3 +
//! This crate contains stateful and composite widgets that depend on the core
4 +
//! rendering primitives from `rustik_tui_core`: selectable lists, vertical scrolling, and
5 +
//! scrollbar rendering. Keeping them separate leaves the core crate focused on
6 +
//! buffers, styled text, layout, app/runtime traits, and small layout widgets.
7 +
//!
8 +
#![deny(unsafe_code)]
9 +
#![warn(missing_docs)]
10 +
#![warn(clippy::unwrap_used)]
11 +
12 +
/// Selectable list widget.
13 +
pub mod list;
14 +
/// Scrollbar rendering.
15 +
pub mod scrollbar;
16 +
/// Scrollable line widget.
17 +
pub mod scrollview;
18 +
/// Scroll viewport primitives.
19 +
pub mod viewport;
20 +
21 +
pub use list::{List, Selection};
22 +
pub use scrollbar::{Scrollbar, ScrollbarStyle};
23 +
pub use scrollview::{ScrollMetrics, ScrollView};
24 +
pub use viewport::{Placement, Scroll, View, Viewport};
crates/tui-widgets/src/list.rs added +245 -0
1 +
//! Selectable list widget.
2 +
//!
3 +
//! `List` renders rows with a selected index, optional empty state, viewport
4 +
//! placement, and scrollbar styling. The separate [`Selection`] type owns the
5 +
//! clamped index movement so callers can keep list state outside the widget.
6 +
7 +
use crate::{Placement, ScrollView, ScrollbarStyle, View, Viewport};
8 +
use rustik_tui_core as tui_core;
9 +
use tui_core::{Buffer, Color, Constraint, Line, Rect, Size, Style, Widget};
10 +
11 +
/// Default selected-row style for an active list.
12 +
pub const DEFAULT_SELECTED_STYLE_ACTIVE: Style = Style::new(Color::Unset).bg(Color::Blue);
13 +
/// Default selected-row style for an inactive list.
14 +
pub const DEFAULT_SELECTED_STYLE_INACTIVE: Style = Style::new(Color::Unset).bg(Color::Fixed(238));
15 +
16 +
/// Stateful selected row for a list.
17 +
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
18 +
pub struct Selection {
19 +
    /// The selected row.
20 +
    pub selected: usize,
21 +
}
22 +
23 +
impl Selection {
24 +
    /// Creates a selection at the first row.
25 +
    pub const fn new() -> Self {
26 +
        Self { selected: 0 }
27 +
    }
28 +
29 +
    /// Creates a selection at `selected`.
30 +
    pub const fn at(selected: usize) -> Self {
31 +
        Self { selected }
32 +
    }
33 +
34 +
    /// Selects a row, clamped to `len`.
35 +
    pub fn select(&mut self, selected: usize, len: usize) -> bool {
36 +
        let previous = self.selected;
37 +
        self.selected = selected.min(len.saturating_sub(1));
38 +
        self.selected != previous
39 +
    }
40 +
41 +
    /// Moves the selection by `delta`, clamped to `len`.
42 +
    pub fn move_by(&mut self, delta: isize, len: usize) -> bool {
43 +
        if len == 0 {
44 +
            return false;
45 +
        }
46 +
        let previous = self.selected;
47 +
        let last = len - 1;
48 +
49 +
        self.selected = if delta.is_negative() {
50 +
            self.selected.saturating_sub(delta.unsigned_abs())
51 +
        } else {
52 +
            self.selected.saturating_add(delta as usize).min(last)
53 +
        };
54 +
        self.selected != previous
55 +
    }
56 +
57 +
    /// Selects the first row.
58 +
    pub fn select_first(&mut self) -> bool {
59 +
        let previous = self.selected;
60 +
        self.selected = 0;
61 +
        self.selected != previous
62 +
    }
63 +
64 +
    /// Selects the last row.
65 +
    pub fn select_last(&mut self, len: usize) -> bool {
66 +
        let previous = self.selected;
67 +
        self.selected = len.saturating_sub(1);
68 +
        self.selected != previous
69 +
    }
70 +
71 +
    /// Returns a viewport that keeps the selection visible.
72 +
    pub fn view(self, len: usize, rows: usize, placement: Placement) -> View {
73 +
        let mut viewport = Viewport::new();
74 +
        viewport.scroll_to_row(self.selected, len, rows, placement);
75 +
        viewport.view(len, rows)
76 +
    }
77 +
}
78 +
79 +
/// A line-oriented selectable list.
80 +
#[derive(Debug, Clone)]
81 +
pub struct List {
82 +
    /// Rendered rows in source order.
83 +
    lines: Vec<Line>,
84 +
    /// Selected row index before clamping to the rendered row count.
85 +
    selected: Option<usize>,
86 +
    /// Whether the selected row should use the active selection style.
87 +
    active: bool,
88 +
    /// Style applied to the selected row while the list is active.
89 +
    selected_style_active: Style,
90 +
    /// Style applied to the selected row while the list is inactive.
91 +
    selected_style_inactive: Style,
92 +
    /// Placeholder line rendered when the list has no rows.
93 +
    empty: Option<Line>,
94 +
    /// Policy used to place the selected row inside the viewport.
95 +
    placement: Placement,
96 +
    /// Explicit first visible row, overriding selection-based placement.
97 +
    offset: Option<usize>,
98 +
    /// Style used by the list scrollbar.
99 +
    scrollbar: ScrollbarStyle,
100 +
}
101 +
102 +
impl List {
103 +
    /// Creates a list from render lines.
104 +
    pub fn new(lines: impl IntoIterator<Item = Line>) -> Self {
105 +
        Self {
106 +
            lines: lines.into_iter().collect(),
107 +
            selected: None,
108 +
            active: true,
109 +
            selected_style_active: DEFAULT_SELECTED_STYLE_ACTIVE,
110 +
            selected_style_inactive: DEFAULT_SELECTED_STYLE_INACTIVE,
111 +
            empty: None,
112 +
            placement: Placement::Minimal,
113 +
            offset: None,
114 +
            scrollbar: ScrollbarStyle::default(),
115 +
        }
116 +
    }
117 +
118 +
    /// Sets the selected row.
119 +
    pub fn selected(mut self, selected: usize) -> Self {
120 +
        self.selected = Some(selected);
121 +
        self
122 +
    }
123 +
124 +
    /// Sets whether the list has active focus.
125 +
    pub fn active(mut self, active: bool) -> Self {
126 +
        self.active = active;
127 +
        self
128 +
    }
129 +
130 +
    /// Sets the selected row styles.
131 +
    pub fn selected_styles(mut self, active: Style, inactive: Style) -> Self {
132 +
        self.selected_style_active = active;
133 +
        self.selected_style_inactive = inactive;
134 +
        self
135 +
    }
136 +
137 +
    /// Sets the empty-list line.
138 +
    pub fn empty(mut self, line: impl Into<Line>) -> Self {
139 +
        self.empty = Some(line.into());
140 +
        self
141 +
    }
142 +
143 +
    /// Sets the selected-row placement policy.
144 +
    pub const fn placement(mut self, placement: Placement) -> Self {
145 +
        self.placement = placement;
146 +
        self
147 +
    }
148 +
149 +
    /// Sets the first visible row.
150 +
    pub const fn offset(mut self, offset: usize) -> Self {
151 +
        self.offset = Some(offset);
152 +
        self
153 +
    }
154 +
155 +
    /// Sets the vertical scrollbar style.
156 +
    pub fn scrollbar(mut self, style: ScrollbarStyle) -> Self {
157 +
        self.scrollbar = style;
158 +
        self
159 +
    }
160 +
}
161 +
162 +
impl Widget for List {
163 +
    fn size(&self, parent: Constraint) -> Size {
164 +
        Size::new(parent.max.cols, parent.max.rows).constrain(parent)
165 +
    }
166 +
167 +
    fn render(&self, area: Rect, buf: &mut Buffer) {
168 +
        if area.is_empty() {
169 +
            return;
170 +
        }
171 +
        if self.lines.is_empty() {
172 +
            if let Some(line) = self.empty.clone() {
173 +
                let x = area.x + 1.min(area.cols);
174 +
                let y = area.y + 1.min(area.rows.saturating_sub(1));
175 +
                buf.set_line(x, y, &line.padded(area.right().saturating_sub(x)));
176 +
            }
177 +
            return;
178 +
        }
179 +
180 +
        let selection = self.selected.map(Selection::at).unwrap_or_default();
181 +
        let view = if let Some(offset) = self.offset {
182 +
            View::new(offset, self.lines.len(), area.rows)
183 +
        } else {
184 +
            selection.view(self.lines.len(), area.rows, self.placement)
185 +
        };
186 +
        let selected = self
187 +
            .selected
188 +
            .map(|selected| selected.min(self.lines.len() - 1));
189 +
        let selected_style = if self.active {
190 +
            self.selected_style_active
191 +
        } else {
192 +
            self.selected_style_inactive
193 +
        };
194 +
        let rows = |cols| {
195 +
            self.lines
196 +
                .iter()
197 +
                .enumerate()
198 +
                .map(|(index, line)| {
199 +
                    if selected == Some(index) {
200 +
                        line.clone().style(selected_style).padded(cols)
201 +
                    } else {
202 +
                        line.clone()
203 +
                    }
204 +
                })
205 +
                .collect()
206 +
        };
207 +
        let scroll = ScrollView::new(area, view.offset, rows).scrollbar(self.scrollbar.clone());
208 +
209 +
        scroll.render(area, buf);
210 +
    }
211 +
}
212 +
213 +
#[cfg(test)]
214 +
mod tests {
215 +
    use super::*;
216 +
217 +
    #[test]
218 +
    fn selection_moves_with_clamped_bounds() {
219 +
        let mut selection = Selection::new();
220 +
221 +
        assert!(selection.move_by(2, 5));
222 +
        assert_eq!(selection.selected, 2);
223 +
        assert!(selection.move_by(10, 5));
224 +
        assert_eq!(selection.selected, 4);
225 +
        assert!(selection.move_by(-10, 5));
226 +
        assert_eq!(selection.selected, 0);
227 +
        assert!(!selection.move_by(1, 0));
228 +
    }
229 +
230 +
    #[test]
231 +
    fn list_keeps_selection_visible_and_styles_row() {
232 +
        let list = List::new(["zero", "one", "two", "three"].into_iter().map(Line::new))
233 +
            .selected(3)
234 +
            .placement(Placement::Minimal);
235 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 2));
236 +
237 +
        list.render(buffer.area(), &mut buffer);
238 +
239 +
        assert_eq!(buffer.lines(), vec!["two │", "thr…┃"]);
240 +
        assert_eq!(
241 +
            buffer.get(0, 1).map(|cell| cell.style().bg_color()),
242 +
            Some(Color::Blue)
243 +
        );
244 +
    }
245 +
}
crates/tui-widgets/src/scrollbar.rs added +193 -0
1 +
//! Scrollbar rendering.
2 +
//!
3 +
//! `Scrollbar` turns a [`View`](crate::View) into a one-column visual indicator.
4 +
//! Track and thumb are full [`Cell`](rustik_tui_core::Cell) values so glyph and style
5 +
//! stay configurable together.
6 +
7 +
use std::ops::Range;
8 +
9 +
use crate::View;
10 +
use rustik_tui_core as tui_core;
11 +
use tui_core::{Buffer, Cell, Color, Constraint, Rect, Size, Style, Widget};
12 +
13 +
/// Default scrollbar track glyph.
14 +
pub const DEFAULT_TRACK: &str = "│";
15 +
/// Default scrollbar thumb glyph.
16 +
pub const DEFAULT_THUMB: &str = "┃";
17 +
/// Default scrollbar track style.
18 +
pub const DEFAULT_TRACK_STYLE: Style = Style::new(Color::Unset);
19 +
/// Default scrollbar thumb style.
20 +
pub const DEFAULT_THUMB_STYLE: Style = Style::new(Color::Unset);
21 +
22 +
/// Vertical scrollbar for a [`View`].
23 +
#[derive(Debug, Clone, PartialEq, Eq)]
24 +
pub struct Scrollbar {
25 +
    /// View used to derive thumb position and size.
26 +
    pub view: View,
27 +
    /// Cells used to render the track and thumb.
28 +
    pub style: ScrollbarStyle,
29 +
}
30 +
31 +
/// Reusable scrollbar cells.
32 +
#[derive(Debug, Clone, PartialEq, Eq)]
33 +
pub struct ScrollbarStyle {
34 +
    track: Cell,
35 +
    thumb: Cell,
36 +
}
37 +
38 +
impl ScrollbarStyle {
39 +
    /// Creates a scrollbar style from track and thumb cells.
40 +
    pub fn new(track: Cell, thumb: Cell) -> Self {
41 +
        Self { track, thumb }
42 +
    }
43 +
44 +
    /// Returns the track cell.
45 +
    pub const fn track(&self) -> &Cell {
46 +
        &self.track
47 +
    }
48 +
49 +
    /// Returns the thumb cell.
50 +
    pub const fn thumb(&self) -> &Cell {
51 +
        &self.thumb
52 +
    }
53 +
}
54 +
55 +
impl Default for ScrollbarStyle {
56 +
    fn default() -> Self {
57 +
        Self {
58 +
            track: Cell::new(DEFAULT_TRACK, DEFAULT_TRACK_STYLE),
59 +
            thumb: Cell::new(DEFAULT_THUMB, DEFAULT_THUMB_STYLE),
60 +
        }
61 +
    }
62 +
}
63 +
64 +
impl Scrollbar {
65 +
    /// Creates a scrollbar for a view.
66 +
    pub fn new(view: View) -> Self {
67 +
        Self {
68 +
            view,
69 +
            style: ScrollbarStyle::default(),
70 +
        }
71 +
    }
72 +
73 +
    /// Sets both cells from a reusable style.
74 +
    pub fn style(mut self, style: ScrollbarStyle) -> Self {
75 +
        self.style = style;
76 +
        self
77 +
    }
78 +
79 +
    /// Returns the thumb row range for a rendered height.
80 +
    pub fn thumb_range(&self, rows: usize) -> Range<usize> {
81 +
        if rows == 0 {
82 +
            return 0..0;
83 +
        }
84 +
        if !self.view.is_scrollable() {
85 +
            return 0..rows;
86 +
        }
87 +
        let thumb_rows =
88 +
            proportional(rows, self.view.visible_rows, self.view.content_rows).clamp(1, rows);
89 +
        let travel = rows - thumb_rows;
90 +
        let start = if self.view.max_offset() == 0 {
91 +
            0
92 +
        } else {
93 +
            proportional(travel, self.view.offset, self.view.max_offset())
94 +
        };
95 +
        start..start + thumb_rows
96 +
    }
97 +
}
98 +
99 +
impl Widget for Scrollbar {
100 +
    fn size(&self, parent: Constraint) -> Size {
101 +
        let rows = if parent.max.rows == usize::MAX {
102 +
            self.view.visible_rows
103 +
        } else {
104 +
            parent.max.rows
105 +
        };
106 +
        Size::new(1, rows).constrain(parent)
107 +
    }
108 +
109 +
    fn render(&self, area: Rect, buf: &mut Buffer) {
110 +
        if area.is_empty() {
111 +
            return;
112 +
        }
113 +
        let thumb = self.thumb_range(area.rows);
114 +
115 +
        for row in 0..area.rows {
116 +
            let cell = if thumb.contains(&row) {
117 +
                self.style.thumb.clone()
118 +
            } else {
119 +
                self.style.track.clone()
120 +
            };
121 +
            buf.set(area.x, area.y + row, cell);
122 +
        }
123 +
    }
124 +
}
125 +
126 +
/// Scales a part-over-whole ratio into a terminal row count.
127 +
fn proportional(total: usize, part: usize, whole: usize) -> usize {
128 +
    if whole == 0 {
129 +
        return 0;
130 +
    }
131 +
    total.saturating_mul(part) / whole
132 +
}
133 +
134 +
#[cfg(test)]
135 +
mod tests {
136 +
    use super::*;
137 +
    use rustik_tui_core as tui_core;
138 +
    use tui_core::{Color, Style};
139 +
140 +
    #[test]
141 +
    fn thumb_range_fills_area_when_content_fits() {
142 +
        let scrollbar = Scrollbar::new(View::new(0, 3, 5));
143 +
144 +
        assert_eq!(scrollbar.thumb_range(5), 0..5);
145 +
    }
146 +
147 +
    #[test]
148 +
    fn thumb_range_tracks_scroll_position() {
149 +
        let top = Scrollbar::new(View::new(0, 100, 10));
150 +
        let middle = Scrollbar::new(View::new(45, 100, 10));
151 +
        let bottom = Scrollbar::new(View::new(90, 100, 10));
152 +
153 +
        assert_eq!(top.thumb_range(10), 0..1);
154 +
        assert_eq!(middle.thumb_range(10), 4..5);
155 +
        assert_eq!(bottom.thumb_range(10), 9..10);
156 +
    }
157 +
158 +
    #[test]
159 +
    fn scrollbar_renders_track_and_thumb_glyphs() {
160 +
        let style = ScrollbarStyle::new(
161 +
            Cell::new("·", Style::new(Color::Unset)),
162 +
            Cell::new("█", Style::new(Color::Unset)),
163 +
        );
164 +
        let scrollbar = Scrollbar::new(View::new(40, 100, 20)).style(style);
165 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 1, 5));
166 +
167 +
        scrollbar.render(buffer.area(), &mut buffer);
168 +
169 +
        assert_eq!(buffer.lines(), vec!["·", "·", "█", "·", "·"]);
170 +
    }
171 +
172 +
    #[test]
173 +
    fn scrollbar_keeps_track_and_thumb_styles_separate() {
174 +
        let style = ScrollbarStyle::new(
175 +
            Cell::new("·", Style::new(Color::Fixed(236))),
176 +
            Cell::new("█", Style::new(Color::White)),
177 +
        );
178 +
        let scrollbar = Scrollbar::new(View::new(2, 10, 4)).style(style);
179 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 1, 4));
180 +
181 +
        scrollbar.render(buffer.area(), &mut buffer);
182 +
183 +
        assert_eq!(buffer.lines(), vec!["·", "█", "·", "·"]);
184 +
        assert_eq!(
185 +
            buffer.get(0, 0).map(|cell| cell.style().fg_color()),
186 +
            Some(Color::Fixed(236))
187 +
        );
188 +
        assert_eq!(
189 +
            buffer.get(0, 1).map(|cell| cell.style().fg_color()),
190 +
            Some(Color::White)
191 +
        );
192 +
    }
193 +
}
crates/tui-widgets/src/scrollview.rs added +169 -0
1 +
//! Scrollable line widget.
2 +
//!
3 +
//! `ScrollView` renders a slice of width-sensitive lines for a given offset and
4 +
//! draws a scrollbar when content exceeds the visible area. It is the
5 +
//! widget-level bridge between viewport math and actual line rendering.
6 +
7 +
use crate::{Scrollbar, ScrollbarStyle, View};
8 +
use rustik_tui_core as tui_core;
9 +
use tui_core::{Buffer, Constraint, Line, Rect, Size, Widget};
10 +
11 +
/// Scrollable line metrics for a rendered area.
12 +
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13 +
pub struct ScrollMetrics {
14 +
    /// Number of content rows.
15 +
    pub content_rows: usize,
16 +
    /// Number of visible rows.
17 +
    pub visible_rows: usize,
18 +
    /// Visible view after offset clamping.
19 +
    pub view: View,
20 +
}
21 +
22 +
impl ScrollMetrics {
23 +
    /// Returns the largest valid scroll offset for the rendered view.
24 +
    pub fn max_offset(self) -> usize {
25 +
        self.view.max_offset()
26 +
    }
27 +
}
28 +
29 +
impl Default for ScrollMetrics {
30 +
    fn default() -> Self {
31 +
        Self {
32 +
            content_rows: 0,
33 +
            visible_rows: 0,
34 +
            view: View::new(0, 0, 0),
35 +
        }
36 +
    }
37 +
}
38 +
39 +
/// A scrollable collection of lines.
40 +
#[derive(Debug, Clone)]
41 +
pub struct ScrollView {
42 +
    lines: Vec<Line>,
43 +
    offset: usize,
44 +
    scrollbar: ScrollbarStyle,
45 +
}
46 +
47 +
impl ScrollView {
48 +
    /// Creates a scroll view from prebuilt render lines.
49 +
    pub fn from_lines(lines: impl IntoIterator<Item = Line>) -> Self {
50 +
        Self {
51 +
            lines: lines.into_iter().collect(),
52 +
            offset: 0,
53 +
            scrollbar: ScrollbarStyle::default(),
54 +
        }
55 +
    }
56 +
57 +
    /// Builds a scroll view for an area from a width-sensitive line producer.
58 +
    ///
59 +
    /// The producer is called again with one fewer column when a vertical
60 +
    /// scrollbar is needed.
61 +
    pub fn new(area: Rect, offset: usize, mut lines: impl FnMut(usize) -> Vec<Line>) -> Self {
62 +
        let rendered = if area.cols > 2 {
63 +
            let rendered = lines(area.cols - 1);
64 +
            if rendered.len() > area.rows {
65 +
                rendered
66 +
            } else {
67 +
                lines(area.cols)
68 +
            }
69 +
        } else {
70 +
            lines(area.cols)
71 +
        };
72 +
73 +
        Self {
74 +
            lines: rendered,
75 +
            offset,
76 +
            scrollbar: ScrollbarStyle::default(),
77 +
        }
78 +
    }
79 +
80 +
    /// Sets the first visible row.
81 +
    pub const fn offset(mut self, offset: usize) -> Self {
82 +
        self.offset = offset;
83 +
        self
84 +
    }
85 +
86 +
    /// Sets the vertical scrollbar style.
87 +
    pub fn scrollbar(mut self, style: ScrollbarStyle) -> Self {
88 +
        self.scrollbar = style;
89 +
        self
90 +
    }
91 +
92 +
    /// Returns metrics for a rendered area.
93 +
    pub fn metrics(&self, area: Rect) -> ScrollMetrics {
94 +
        let (text_area, _) = self.areas(area);
95 +
        let text_rows = text_area.rows;
96 +
        let view = View::new(self.offset, self.lines.len(), text_rows);
97 +
98 +
        ScrollMetrics {
99 +
            content_rows: self.lines.len(),
100 +
            visible_rows: text_rows,
101 +
            view,
102 +
        }
103 +
    }
104 +
105 +
    /// Splits the render area into text and scrollbar rectangles.
106 +
    ///
107 +
    /// The rightmost column is reserved whenever content overflows vertically
108 +
    /// and the area is wide enough to spare it.
109 +
    fn areas(&self, area: Rect) -> (Rect, Option<Rect>) {
110 +
        if self.lines.len() > area.rows && area.cols > 2 {
111 +
            (
112 +
                Rect::new(area.x, area.y, area.cols - 1, area.rows),
113 +
                Some(Rect::new(area.right() - 1, area.y, 1, area.rows)),
114 +
            )
115 +
        } else {
116 +
            (area, None)
117 +
        }
118 +
    }
119 +
}
120 +
121 +
impl Widget for ScrollView {
122 +
    fn size(&self, parent: Constraint) -> Size {
123 +
        Size::new(parent.max.cols, parent.max.rows).constrain(parent)
124 +
    }
125 +
126 +
    fn render(&self, area: Rect, buf: &mut Buffer) {
127 +
        if area.is_empty() {
128 +
            return;
129 +
        }
130 +
        let (text_area, scrollbar_area) = self.areas(area);
131 +
        let view = View::new(self.offset, self.lines.len(), text_area.rows);
132 +
133 +
        view.render_lines(&self.lines, text_area, buf);
134 +
135 +
        if let Some(area) = scrollbar_area {
136 +
            Scrollbar::new(view)
137 +
                .style(self.scrollbar.clone())
138 +
                .render(area, buf);
139 +
        }
140 +
    }
141 +
}
142 +
143 +
#[cfg(test)]
144 +
mod tests {
145 +
    use super::*;
146 +
    use rustik_tui_core::{Cell, Color, Style};
147 +
148 +
    #[test]
149 +
    fn scroll_view_rebuilds_width_sensitive_lines_when_scrollbar_is_needed() {
150 +
        let style = ScrollbarStyle::new(
151 +
            Cell::new("|", Style::new(Color::Unset)),
152 +
            Cell::new("#", Style::new(Color::Unset)),
153 +
        );
154 +
        let view = ScrollView::new(Rect::new(0, 0, 4, 2), 1, |cols| {
155 +
            (0..3)
156 +
                .map(|row| Line::new(format!("{row}:{cols}")))
157 +
                .collect()
158 +
        })
159 +
        .scrollbar(style);
160 +
        let metrics = view.metrics(Rect::new(0, 0, 4, 2));
161 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 4, 2));
162 +
163 +
        view.render(buffer.area(), &mut buffer);
164 +
165 +
        assert_eq!(metrics.content_rows, 3);
166 +
        assert_eq!(metrics.visible_rows, 2);
167 +
        assert_eq!(buffer.lines(), vec!["1:3|", "2:3#"]);
168 +
    }
169 +
}
crates/tui-widgets/src/viewport.rs added +440 -0
1 +
//! Scroll viewport primitives.
2 +
//!
3 +
//! This module contains the pure scrolling model: visible ranges, clamped
4 +
//! offsets, placement rules, and projection between content rows and screen
5 +
//! rows. Widgets use these primitives to keep focus visible without mixing
6 +
//! scrolling policy into rendering code.
7 +
8 +
use std::ops::Range;
9 +
10 +
use rustik_tui_core as tui_core;
11 +
use tui_core::{Buffer, Line, Rect};
12 +
13 +
/// Scroll movement request.
14 +
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15 +
pub enum Scroll {
16 +
    /// Move by a signed number of rows.
17 +
    Lines(isize),
18 +
    /// Move by a signed number of viewport pages.
19 +
    Pages(isize),
20 +
    /// Move to the first content row.
21 +
    Top,
22 +
    /// Move to the last content row.
23 +
    Bottom,
24 +
}
25 +
26 +
/// Placement policy for making content visible.
27 +
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
28 +
pub enum Placement {
29 +
    /// Scroll only enough to make the row or range visible.
30 +
    Minimal,
31 +
    /// Center the row or range when possible.
32 +
    Center,
33 +
    /// Preserve scroll until the row or range crosses a viewport margin.
34 +
    Margin {
35 +
        /// Rows to keep visible before the row or range.
36 +
        before: usize,
37 +
        /// Rows to keep visible after the row or range.
38 +
        after: usize,
39 +
    },
40 +
}
41 +
42 +
/// Stateful vertical scroll position.
43 +
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
44 +
pub struct Viewport {
45 +
    /// The first visible content row.
46 +
    pub offset: usize,
47 +
}
48 +
49 +
impl Viewport {
50 +
    /// Creates a viewport at the top of its content.
51 +
    pub const fn new() -> Self {
52 +
        Self { offset: 0 }
53 +
    }
54 +
55 +
    /// Creates a viewport with an initial scroll offset.
56 +
    pub const fn from_offset(offset: usize) -> Self {
57 +
        Self { offset }
58 +
    }
59 +
60 +
    /// Sets the first visible content row, clamped to the content size.
61 +
    pub fn set_offset(&mut self, offset: usize, content_rows: usize, visible_rows: usize) {
62 +
        self.offset = offset.min(max_offset(content_rows, visible_rows));
63 +
    }
64 +
65 +
    /// Clamps the current offset to the content size.
66 +
    pub fn clamp(&mut self, content_rows: usize, visible_rows: usize) {
67 +
        self.set_offset(self.offset, content_rows, visible_rows);
68 +
    }
69 +
70 +
    /// Applies a scroll movement and returns whether the offset changed.
71 +
    pub fn scroll(&mut self, scroll: Scroll, content_rows: usize, visible_rows: usize) -> bool {
72 +
        let next = match scroll {
73 +
            Scroll::Lines(rows) => signed_offset(self.offset, rows),
74 +
            Scroll::Pages(pages) => {
75 +
                let rows = pages.saturating_mul(signed_rows(visible_rows));
76 +
                signed_offset(self.offset, rows)
77 +
            }
78 +
            Scroll::Top => 0,
79 +
            Scroll::Bottom => max_offset(content_rows, visible_rows),
80 +
        };
81 +
        let previous = self.offset;
82 +
83 +
        self.set_offset(next, content_rows, visible_rows);
84 +
        self.offset != previous
85 +
    }
86 +
87 +
    /// Scrolls up by `rows` rows.
88 +
    pub fn scroll_up(&mut self, rows: usize, content_rows: usize, visible_rows: usize) -> bool {
89 +
        let rows = isize::try_from(rows).unwrap_or(isize::MAX);
90 +
91 +
        self.scroll(Scroll::Lines(-rows), content_rows, visible_rows)
92 +
    }
93 +
94 +
    /// Scrolls down by `rows` rows.
95 +
    pub fn scroll_down(&mut self, rows: usize, content_rows: usize, visible_rows: usize) -> bool {
96 +
        let rows = isize::try_from(rows).unwrap_or(isize::MAX);
97 +
98 +
        self.scroll(Scroll::Lines(rows), content_rows, visible_rows)
99 +
    }
100 +
101 +
    /// Scrolls up by one viewport page.
102 +
    pub fn page_up(&mut self, content_rows: usize, visible_rows: usize) -> bool {
103 +
        self.scroll(Scroll::Pages(-1), content_rows, visible_rows)
104 +
    }
105 +
106 +
    /// Scrolls down by one viewport page.
107 +
    pub fn page_down(&mut self, content_rows: usize, visible_rows: usize) -> bool {
108 +
        self.scroll(Scroll::Pages(1), content_rows, visible_rows)
109 +
    }
110 +
111 +
    /// Moves to the first content row.
112 +
    pub fn top(&mut self) -> bool {
113 +
        let changed = self.offset != 0;
114 +
115 +
        self.offset = 0;
116 +
        changed
117 +
    }
118 +
119 +
    /// Moves to the last content row.
120 +
    pub fn bottom(&mut self, content_rows: usize, visible_rows: usize) -> bool {
121 +
        self.scroll(Scroll::Bottom, content_rows, visible_rows)
122 +
    }
123 +
124 +
    /// Scrolls to make a content row visible.
125 +
    pub fn scroll_to_row(
126 +
        &mut self,
127 +
        row: usize,
128 +
        content_rows: usize,
129 +
        visible_rows: usize,
130 +
        placement: Placement,
131 +
    ) -> bool {
132 +
        self.scroll_to_range(
133 +
            row..row.saturating_add(1),
134 +
            content_rows,
135 +
            visible_rows,
136 +
            placement,
137 +
        )
138 +
    }
139 +
140 +
    /// Scrolls to make a content range visible.
141 +
    pub fn scroll_to_range(
142 +
        &mut self,
143 +
        range: Range<usize>,
144 +
        content_rows: usize,
145 +
        visible_rows: usize,
146 +
        placement: Placement,
147 +
    ) -> bool {
148 +
        let Some(range) = normalize_range(range, content_rows) else {
149 +
            return false;
150 +
        };
151 +
        let previous = self.offset;
152 +
        let next = match placement {
153 +
            Placement::Minimal => minimal_offset(self.offset, range, visible_rows),
154 +
            Placement::Center => centered_offset(range, visible_rows),
155 +
            Placement::Margin { before, after } => {
156 +
                margin_offset(self.offset, range, visible_rows, before, after)
157 +
            }
158 +
        };
159 +
        self.set_offset(next, content_rows, visible_rows);
160 +
        self.offset != previous
161 +
    }
162 +
163 +
    /// Returns an immutable description of the visible window.
164 +
    pub fn view(self, content_rows: usize, visible_rows: usize) -> View {
165 +
        View::new(self.offset, content_rows, visible_rows)
166 +
    }
167 +
}
168 +
169 +
/// Immutable visible window over vertical content.
170 +
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
171 +
pub struct View {
172 +
    /// First visible content row.
173 +
    pub offset: usize,
174 +
    /// Total content height.
175 +
    pub content_rows: usize,
176 +
    /// Viewport height.
177 +
    pub visible_rows: usize,
178 +
}
179 +
180 +
impl View {
181 +
    /// Creates a clamped visible window.
182 +
    pub fn new(offset: usize, content_rows: usize, visible_rows: usize) -> Self {
183 +
        Self {
184 +
            offset: offset.min(max_offset(content_rows, visible_rows)),
185 +
            content_rows,
186 +
            visible_rows,
187 +
        }
188 +
    }
189 +
190 +
    /// Returns the largest valid offset.
191 +
    pub const fn max_offset(self) -> usize {
192 +
        max_offset(self.content_rows, self.visible_rows)
193 +
    }
194 +
195 +
    /// Returns whether any rows can be scrolled.
196 +
    pub const fn is_scrollable(self) -> bool {
197 +
        self.max_offset() > 0
198 +
    }
199 +
200 +
    /// Returns whether the first content row is visible.
201 +
    pub const fn is_at_top(self) -> bool {
202 +
        self.offset == 0
203 +
    }
204 +
205 +
    /// Returns whether the last content row is visible.
206 +
    pub const fn is_at_bottom(self) -> bool {
207 +
        self.offset == self.max_offset()
208 +
    }
209 +
210 +
    /// Returns the visible content-row range.
211 +
    pub fn range(self) -> Range<usize> {
212 +
        let end = self
213 +
            .offset
214 +
            .saturating_add(self.visible_rows)
215 +
            .min(self.content_rows);
216 +
217 +
        self.offset..end
218 +
    }
219 +
220 +
    /// Returns the local row for a content row.
221 +
    pub fn project(self, content_row: usize) -> Option<usize> {
222 +
        self.range()
223 +
            .contains(&content_row)
224 +
            .then(|| content_row - self.offset)
225 +
    }
226 +
227 +
    /// Returns the content row for a local row.
228 +
    pub fn content_row(self, local_row: usize) -> Option<usize> {
229 +
        if local_row >= self.visible_rows {
230 +
            return None;
231 +
        }
232 +
        let row = self.offset.saturating_add(local_row);
233 +
234 +
        (row < self.content_rows).then_some(row)
235 +
    }
236 +
237 +
    /// Renders visible lines into an area.
238 +
    pub fn render_lines<'a>(
239 +
        self,
240 +
        lines: impl IntoIterator<Item = &'a Line>,
241 +
        area: Rect,
242 +
        buf: &mut Buffer,
243 +
    ) {
244 +
        let range = self.range();
245 +
        let visible = lines
246 +
            .into_iter()
247 +
            .skip(range.start)
248 +
            .take(range.end.saturating_sub(range.start));
249 +
250 +
        Line::renders(visible.cloned(), area, buf);
251 +
    }
252 +
}
253 +
254 +
/// Returns the largest valid scroll offset.
255 +
pub const fn max_offset(content_rows: usize, visible_rows: usize) -> usize {
256 +
    content_rows.saturating_sub(visible_rows)
257 +
}
258 +
259 +
/// Clamps a requested content range to existing rows.
260 +
fn normalize_range(range: Range<usize>, content_rows: usize) -> Option<Range<usize>> {
261 +
    let start = range.start.min(content_rows);
262 +
    let end = range.end.min(content_rows);
263 +
264 +
    (start < end).then_some(start..end)
265 +
}
266 +
267 +
/// Returns the smallest scroll change that makes a range visible.
268 +
fn minimal_offset(offset: usize, range: Range<usize>, visible_rows: usize) -> usize {
269 +
    let end = offset.saturating_add(visible_rows);
270 +
271 +
    if range.start < offset {
272 +
        range.start
273 +
    } else if range.end > end {
274 +
        range.end.saturating_sub(visible_rows)
275 +
    } else {
276 +
        offset
277 +
    }
278 +
}
279 +
280 +
/// Returns an offset that places a range near the center of the viewport.
281 +
fn centered_offset(range: Range<usize>, visible_rows: usize) -> usize {
282 +
    let size = range.end - range.start;
283 +
    let center = range.start + size / 2;
284 +
285 +
    center.saturating_sub(visible_rows / 2)
286 +
}
287 +
288 +
/// Returns an offset that keeps a range inside preferred viewport margins.
289 +
fn margin_offset(
290 +
    offset: usize,
291 +
    range: Range<usize>,
292 +
    visible_rows: usize,
293 +
    before: usize,
294 +
    after: usize,
295 +
) -> usize {
296 +
    let start = offset.saturating_add(before.min(visible_rows));
297 +
    let end = offset.saturating_add(visible_rows.saturating_sub(after.min(visible_rows)));
298 +
299 +
    if range.start < start {
300 +
        range.start.saturating_sub(before)
301 +
    } else if range.end > end {
302 +
        range.end.saturating_add(after).saturating_sub(visible_rows)
303 +
    } else {
304 +
        offset
305 +
    }
306 +
}
307 +
308 +
/// Applies a signed scroll delta without underflowing.
309 +
fn signed_offset(offset: usize, delta: isize) -> usize {
310 +
    if delta.is_negative() {
311 +
        offset.saturating_sub(delta.unsigned_abs())
312 +
    } else {
313 +
        offset.saturating_add(delta as usize)
314 +
    }
315 +
}
316 +
317 +
/// Converts a row count into a signed delta without wrapping.
318 +
fn signed_rows(rows: usize) -> isize {
319 +
    isize::try_from(rows).unwrap_or(isize::MAX)
320 +
}
321 +
322 +
#[cfg(test)]
323 +
mod tests {
324 +
    use super::*;
325 +
326 +
    #[test]
327 +
    fn view_clamps_offset_and_reports_visible_range() {
328 +
        let view = View::new(8, 10, 4);
329 +
330 +
        assert_eq!(view.offset, 6);
331 +
        assert_eq!(view.max_offset(), 6);
332 +
        assert_eq!(view.range(), 6..10);
333 +
        assert!(view.is_scrollable());
334 +
        assert!(!view.is_at_top());
335 +
        assert!(view.is_at_bottom());
336 +
    }
337 +
338 +
    #[test]
339 +
    fn view_projects_between_content_and_local_rows() {
340 +
        let view = View::new(3, 8, 3);
341 +
342 +
        assert_eq!(view.project(2), None);
343 +
        assert_eq!(view.project(3), Some(0));
344 +
        assert_eq!(view.project(5), Some(2));
345 +
        assert_eq!(view.project(6), None);
346 +
        assert_eq!(view.content_row(0), Some(3));
347 +
        assert_eq!(view.content_row(2), Some(5));
348 +
        assert_eq!(view.content_row(3), None);
349 +
    }
350 +
351 +
    #[test]
352 +
    fn viewport_scrolls_and_clamps_to_content() {
353 +
        let mut viewport = Viewport::new();
354 +
355 +
        assert!(viewport.scroll_down(2, 10, 4));
356 +
        assert_eq!(viewport.offset, 2);
357 +
        assert!(viewport.page_down(10, 4));
358 +
        assert_eq!(viewport.offset, 6);
359 +
        assert!(!viewport.page_down(10, 4));
360 +
        assert!(viewport.scroll_up(3, 10, 4));
361 +
        assert_eq!(viewport.offset, 3);
362 +
        assert!(viewport.page_up(10, 4));
363 +
        assert_eq!(viewport.offset, 0);
364 +
    }
365 +
366 +
    #[test]
367 +
    fn viewport_reclamps_when_content_shrinks() {
368 +
        let mut viewport = Viewport::from_offset(12);
369 +
370 +
        viewport.clamp(20, 5);
371 +
        assert_eq!(viewport.offset, 12);
372 +
        viewport.clamp(4, 5);
373 +
        assert_eq!(viewport.offset, 0);
374 +
    }
375 +
376 +
    #[test]
377 +
    fn scroll_to_range_minimal_scrolls_only_when_needed() {
378 +
        let mut viewport = Viewport::from_offset(20);
379 +
380 +
        assert!(!viewport.scroll_to_range(22..25, 100, 10, Placement::Minimal));
381 +
        assert_eq!(viewport.offset, 20);
382 +
        assert!(viewport.scroll_to_range(12..14, 100, 10, Placement::Minimal));
383 +
        assert_eq!(viewport.offset, 12);
384 +
        assert!(viewport.scroll_to_range(30..33, 100, 10, Placement::Minimal));
385 +
        assert_eq!(viewport.offset, 23);
386 +
    }
387 +
388 +
    #[test]
389 +
    fn scroll_to_range_centers_focus_when_possible() {
390 +
        let mut viewport = Viewport::new();
391 +
392 +
        assert!(viewport.scroll_to_range(40..42, 100, 10, Placement::Center));
393 +
        assert_eq!(viewport.offset, 36);
394 +
        assert!(viewport.scroll_to_row(4, 100, 10, Placement::Center));
395 +
        assert_eq!(viewport.offset, 0);
396 +
    }
397 +
398 +
    #[test]
399 +
    fn scroll_to_range_margin_preserves_middle_band() {
400 +
        let mut viewport = Viewport::from_offset(20);
401 +
        let placement = Placement::Margin {
402 +
            before: 3,
403 +
            after: 3,
404 +
        };
405 +
406 +
        assert!(!viewport.scroll_to_range(24..26, 100, 12, placement));
407 +
        assert_eq!(viewport.offset, 20);
408 +
        assert!(viewport.scroll_to_range(21..22, 100, 12, placement));
409 +
        assert_eq!(viewport.offset, 18);
410 +
        assert!(viewport.scroll_to_range(29..31, 100, 12, placement));
411 +
        assert_eq!(viewport.offset, 22);
412 +
    }
413 +
414 +
    #[test]
415 +
    fn render_lines_projects_visible_content() {
416 +
        let lines = ["zero", "one", "two", "three"]
417 +
            .into_iter()
418 +
            .map(Line::new)
419 +
            .collect::<Vec<_>>();
420 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 2));
421 +
422 +
        View::new(1, 4, 2).render_lines(&lines, buffer.area(), &mut buffer);
423 +
424 +
        assert_eq!(buffer.lines(), vec!["one  ", "two  "]);
425 +
    }
426 +
427 +
    #[test]
428 +
    fn rendered_view_keeps_only_visible_rows() {
429 +
        let lines = ["a", "b", "c"]
430 +
            .into_iter()
431 +
            .map(Line::new)
432 +
            .collect::<Vec<_>>();
433 +
        let view = View::new(1, lines.len(), 2);
434 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 1, 2));
435 +
436 +
        view.render_lines(&lines, buffer.area(), &mut buffer);
437 +
438 +
        assert_eq!(buffer.lines(), vec!["b", "c"]);
439 +
    }
440 +
}
crates/tui/Cargo.toml added +27 -0
1 +
[package]
2 +
name = "rustik-tui"
3 +
version.workspace = true
4 +
edition.workspace = true
5 +
description = "Rustik is a rust development kit for minimal, high performance tools. Rustik TUI facade crate."
6 +
homepage = "https://crates.io/crates/rustik-tui"
7 +
documentation = "https://docs.rs/rustik-tui"
8 +
license.workspace = true
9 +
10 +
[features]
11 +
default = []
12 +
widgets = ["dep:rustik-tui-widgets"]
13 +
14 +
[dependencies]
15 +
rustik-tui-core = { workspace = true }
16 +
rustik-tui-widgets = { workspace = true, optional = true }
17 +
18 +
[lints]
19 +
workspace = true
20 +
21 +
[dev-dependencies]
22 +
rustik-tui-termion = { workspace = true }
23 +
rustik-tui-widgets = { workspace = true }
24 +
25 +
[[bench]]
26 +
name = "render"
27 +
harness = false
crates/tui/README.md added +23 -0
1 +
# rustik-tui
2 +
3 +
Rustik is a Rust development kit for minimal, high performance tools.
4 +
5 +
Facade crate for the Rustik TUI workspace.
6 +
7 +
This crate always re-exports `rustik-tui-core` and exposes
8 +
`rustik-tui-widgets` under the `widgets` feature.
9 +
10 +
## Usage
11 +
```toml
12 +
[dependencies]
13 +
rustik-tui = "0.1.0"
14 +
```
15 +
16 +
```toml
17 +
[dependencies]
18 +
rustik-tui = { version = "0.1.0", features = ["widgets"] }
19 +
```
20 +
21 +
## License
22 +
23 +
MIT. See [LICENSE](../../LICENSE).
crates/tui/benches/render.rs added +359 -0
1 +
//! Render benchmark for core TUI widgets and layout.
2 +
//!
3 +
//! Builds a deterministic scene and computes a checksum to catch rendering
4 +
//! regressions across benchmark runs.
5 +
use std::hint::black_box;
6 +
use std::time::{Duration, Instant};
7 +
8 +
use rustik_tui as tui;
9 +
use rustik_tui_widgets::{List, ScrollView, ScrollbarStyle, Selection, Viewport};
10 +
11 +
use tui::{
12 +
    Border, Buffer, Cell, Color, Fill, HStack, Label, Length, Line, Rect, Style, Table,
13 +
    TableOptions, VStack, Widget,
14 +
};
15 +
16 +
const WORKLOAD: &str = "render";
17 +
const AREA: Rect = Rect::new(0, 0, 640, 480);
18 +
const DEFAULT_FRAMES: usize = 2_000;
19 +
const LIST_ROWS: usize = 2_048;
20 +
const TABLE_ROWS: usize = 320;
21 +
const LOG_ROWS: usize = 4_096;
22 +
23 +
const ACTIVE_BORDER: Color = Color::Blue;
24 +
const INACTIVE_BORDER: Color = Color::Fixed(239);
25 +
const TABLE_BORDER: Color = Color::Fixed(236);
26 +
const DIM_TEXT: Color = Color::Fixed(244);
27 +
const HOT_TEXT: Color = Color::Yellow;
28 +
const OK_TEXT: Color = Color::Green;
29 +
const WARN_TEXT: Color = Color::Red;
30 +
const SELECTED_ACTIVE: Style = Style::new(Color::Unset).bg(Color::Blue);
31 +
const SELECTED_INACTIVE: Style = Style::new(Color::Unset).bg(Color::Fixed(238));
32 +
const DIVIDER_STYLE: Style = Style::new(Color::Fixed(239));
33 +
const FILL_STYLE: Style = Style::new(Color::Fixed(236));
34 +
35 +
fn main() {
36 +
    let args = Args::parse();
37 +
    let (elapsed, checksum) = run_headless(args.frames);
38 +
39 +
    black_box(checksum);
40 +
    report(args.frames, elapsed, checksum);
41 +
    if let Some(expected) = args.check {
42 +
        assert_eq!(
43 +
            checksum, expected,
44 +
            "deterministic render checksum changed for {WORKLOAD}"
45 +
        );
46 +
    }
47 +
}
48 +
49 +
fn run_headless(frames: usize) -> (Duration, usize) {
50 +
    let mut bench = Bench::new();
51 +
    let mut buffer = Buffer::empty(AREA);
52 +
53 +
    let start = Instant::now();
54 +
    let mut checksum = 0usize;
55 +
    for frame in 0..frames {
56 +
        buffer.clear();
57 +
        checksum ^= bench.frame(frame, AREA, &mut buffer);
58 +
        buffer.reset_dirty();
59 +
    }
60 +
61 +
    (start.elapsed(), checksum)
62 +
}
63 +
64 +
struct Args {
65 +
    frames: usize,
66 +
    check: Option<usize>,
67 +
}
68 +
69 +
impl Args {
70 +
    fn parse() -> Self {
71 +
        Self::parse_from(std::env::args().skip(1))
72 +
    }
73 +
74 +
    fn parse_from(args: impl IntoIterator<Item = String>) -> Self {
75 +
        let mut frames = DEFAULT_FRAMES;
76 +
        let mut check = None;
77 +
        let mut args = args.into_iter();
78 +
79 +
        while let Some(arg) = args.next() {
80 +
            match arg.as_str() {
81 +
                "--frames" => {
82 +
                    if let Some(value) = args.next().and_then(|value| value.parse().ok()) {
83 +
                        frames = value;
84 +
                    }
85 +
                }
86 +
                "--check" => {
87 +
                    if let Some(value) = args.next() {
88 +
                        check = parse_hex(&value);
89 +
                    }
90 +
                }
91 +
                "--help" | "-h" => {
92 +
                    println!(
93 +
                        "usage: cargo bench -p rustik-tui --bench render -- [--frames N] [--check HEX]"
94 +
                    );
95 +
                    std::process::exit(0);
96 +
                }
97 +
                value => {
98 +
                    if let Ok(value) = value.parse() {
99 +
                        frames = value;
100 +
                    }
101 +
                }
102 +
            }
103 +
        }
104 +
105 +
        Self { frames, check }
106 +
    }
107 +
}
108 +
109 +
fn parse_hex(value: &str) -> Option<usize> {
110 +
    usize::from_str_radix(value.trim_start_matches("0x"), 16).ok()
111 +
}
112 +
113 +
struct Bench {
114 +
    files: Vec<Line>,
115 +
    logs: Vec<String>,
116 +
    selection: Selection,
117 +
    viewport: Viewport,
118 +
}
119 +
120 +
impl Bench {
121 +
    fn new() -> Self {
122 +
        Self {
123 +
            files: files(),
124 +
            logs: logs(),
125 +
            selection: Selection::new(),
126 +
            viewport: Viewport::new(),
127 +
        }
128 +
    }
129 +
130 +
    fn frame(&mut self, frame: usize, area: Rect, buffer: &mut Buffer) -> usize {
131 +
        self.selection.select(frame % LIST_ROWS, LIST_ROWS);
132 +
        self.viewport
133 +
            .set_offset(frame * 3 % (LOG_ROWS - area.rows), LOG_ROWS, area.rows);
134 +
135 +
        render_dashboard(
136 +
            frame,
137 +
            self.selection.selected,
138 +
            self.viewport.view(LOG_ROWS, area.rows).offset,
139 +
            &self.files,
140 +
            &self.logs,
141 +
            area,
142 +
            buffer,
143 +
        );
144 +
145 +
        sample_buffer(buffer, frame)
146 +
    }
147 +
}
148 +
149 +
fn render_dashboard(
150 +
    frame: usize,
151 +
    selected: usize,
152 +
    log_offset: usize,
153 +
    files: &[Line],
154 +
    logs: &[String],
155 +
    area: Rect,
156 +
    buffer: &mut Buffer,
157 +
) {
158 +
    let active = !frame.is_multiple_of(3);
159 +
    let list = List::new(files.iter().cloned())
160 +
        .selected(selected)
161 +
        .active(active)
162 +
        .selected_styles(SELECTED_ACTIVE, SELECTED_INACTIVE)
163 +
        .scrollbar(scrollbar_style(DIM_TEXT, HOT_TEXT));
164 +
    let table = stats_table(frame, selected);
165 +
    let preview = preview_lines(frame, selected);
166 +
    let scroll = ScrollView::new(area, log_offset, |cols| log_lines(logs, cols))
167 +
        .scrollbar(scrollbar_style(DIM_TEXT, OK_TEXT));
168 +
    let summary = HStack::default()
169 +
        .child(Label::new("frame").fg(DIM_TEXT))
170 +
        .child(Label::from(format!("{frame:08}")).fg(HOT_TEXT))
171 +
        .spacer()
172 +
        .child(Label::new("selected").fg(DIM_TEXT))
173 +
        .child(Label::from(format!("{selected:04}")).fg(OK_TEXT));
174 +
175 +
    let left = VStack::default()
176 +
        .border(Some(Border::new(if active {
177 +
            ACTIVE_BORDER
178 +
        } else {
179 +
            INACTIVE_BORDER
180 +
        })))
181 +
        .child(summary)
182 +
        .divider_cell(Cell::new("─", DIVIDER_STYLE))
183 +
        .fill(list);
184 +
    let middle = VStack::default()
185 +
        .border(Some(Border::new(TABLE_BORDER)))
186 +
        .child(Label::new("render metrics").fg(HOT_TEXT))
187 +
        .divider()
188 +
        .child_with_height(table, Length::Fixed(24))
189 +
        .divider_cell(Cell::new("┄", DIVIDER_STYLE))
190 +
        .child_with_height(preview, Length::Fixed(18))
191 +
        .fill(Fill::new("·", FILL_STYLE));
192 +
    let right = VStack::default()
193 +
        .border(Some(Border::new(INACTIVE_BORDER)))
194 +
        .child(Label::new("scrolling log").fg(DIM_TEXT))
195 +
        .divider()
196 +
        .fill(scroll);
197 +
198 +
    HStack::default()
199 +
        .child(left)
200 +
        .child(middle)
201 +
        .child(right)
202 +
        .render(area, buffer);
203 +
}
204 +
205 +
fn scrollbar_style(track: Color, thumb: Color) -> ScrollbarStyle {
206 +
    ScrollbarStyle::new(
207 +
        Cell::new("┆", Style::new(track).bg(Color::Fixed(235))),
208 +
        Cell::new("█", Style::new(thumb).bg(Color::Fixed(235))),
209 +
    )
210 +
}
211 +
212 +
fn stats_table(frame: usize, selected: usize) -> Table<5, Label> {
213 +
    let mut table = Table::new(TableOptions::bordered());
214 +
215 +
    table.header(labels(["name", "value", "delta", "state", "note"]));
216 +
    table.divider();
217 +
    for row in 0..TABLE_ROWS {
218 +
        let value = frame.wrapping_mul(row + 17) % 1_000_003;
219 +
        let delta = value as isize - selected as isize;
220 +
        let state = match row % 4 {
221 +
            0 => Label::new("hot").fg(WARN_TEXT),
222 +
            1 => Label::new("warm").fg(HOT_TEXT),
223 +
            2 => Label::new("ok").fg(OK_TEXT),
224 +
            _ => Label::new("idle").fg(DIM_TEXT),
225 +
        };
226 +
        table.push([
227 +
            Label::from(format!("counter-{row:03}")),
228 +
            Label::from(format!("{value:08}")),
229 +
            Label::from(format!("{delta:+07}")),
230 +
            state,
231 +
            Label::from(format!("bucket {}", (row + selected) % 97)),
232 +
        ]);
233 +
        if row % 40 == 39 {
234 +
            table.divider_with_sigil("┄");
235 +
        }
236 +
    }
237 +
238 +
    table
239 +
}
240 +
241 +
fn labels<const N: usize>(items: [&str; N]) -> [Label; N] {
242 +
    items.map(Label::new)
243 +
}
244 +
245 +
fn preview_lines(frame: usize, selected: usize) -> Vec<Line> {
246 +
    (0..128)
247 +
        .map(|row| {
248 +
            let width = 24 + (row + selected + frame) % 96;
249 +
            Line::spaced([
250 +
                Label::from(format!("{row:03}")).fg(DIM_TEXT),
251 +
                Label::new("│").fg(INACTIVE_BORDER),
252 +
                Label::from("▸".repeat(row % 5 + 1)).fg(HOT_TEXT),
253 +
                Label::from("x".repeat(width)),
254 +
            ])
255 +
        })
256 +
        .collect()
257 +
}
258 +
259 +
fn log_lines(logs: &[String], cols: usize) -> Vec<Line> {
260 +
    logs.iter()
261 +
        .enumerate()
262 +
        .map(|(index, line)| {
263 +
            let tag = match index % 5 {
264 +
                0 => Label::new("TRACE").fg(DIM_TEXT),
265 +
                1 => Label::new("INFO ").fg(OK_TEXT),
266 +
                2 => Label::new("WARN ").fg(HOT_TEXT),
267 +
                3 => Label::new("ERROR").fg(WARN_TEXT),
268 +
                _ => Label::new("DEBUG").fg(DIM_TEXT),
269 +
            };
270 +
            Line::spaced([
271 +
                tag,
272 +
                Label::from(format!("{index:04}")).fg(DIM_TEXT),
273 +
                Label::from(line.clone()).bg(if cols.is_multiple_of(2) {
274 +
                    Color::Unset
275 +
                } else {
276 +
                    Color::Fixed(235)
277 +
                }),
278 +
            ])
279 +
        })
280 +
        .collect()
281 +
}
282 +
283 +
fn files() -> Vec<Line> {
284 +
    (0..LIST_ROWS)
285 +
        .map(|row| {
286 +
            let color = match row % 6 {
287 +
                0 => OK_TEXT,
288 +
                1 => HOT_TEXT,
289 +
                2 => WARN_TEXT,
290 +
                _ => DIM_TEXT,
291 +
            };
292 +
            Line::spaced([
293 +
                Label::from(format!("{row:04}")).fg(DIM_TEXT),
294 +
                Label::new("src").fg(INACTIVE_BORDER),
295 +
                Label::from(format!("module_{:02}/component_{row:04}.rs", row % 41)).fg(color),
296 +
                Label::from(format!("{} cols", 40 + row % 180)).fg(DIM_TEXT),
297 +
            ])
298 +
        })
299 +
        .collect()
300 +
}
301 +
302 +
fn logs() -> Vec<String> {
303 +
    (0..LOG_ROWS)
304 +
        .map(|row| {
305 +
            format!(
306 +
                "render pass {row:04}: table rows={TABLE_ROWS}, list rows={LIST_ROWS}, unicode=╭─╮ λ ❤️ {}",
307 +
                "payload ".repeat(row % 11 + 1)
308 +
            )
309 +
        })
310 +
        .collect()
311 +
}
312 +
313 +
fn sample_buffer(buffer: &Buffer, frame: usize) -> usize {
314 +
    let area = buffer.area();
315 +
    let mut checksum = frame;
316 +
    for row in (0..area.rows).step_by(7) {
317 +
        for col in (0..area.cols).step_by(11) {
318 +
            if let Some(cell) = buffer.get(area.x + col, area.y + row) {
319 +
                checksum = checksum.wrapping_mul(16_777_619) ^ cell.glyph().len();
320 +
                checksum ^= color_id(cell.style().fg_color());
321 +
                checksum ^= color_id(cell.style().bg_color()).rotate_left(7);
322 +
            }
323 +
        }
324 +
    }
325 +
    checksum
326 +
}
327 +
328 +
fn color_id(color: Color) -> usize {
329 +
    match color {
330 +
        Color::Unset => 0,
331 +
        Color::Black => 1,
332 +
        Color::Red => 2,
333 +
        Color::Green => 3,
334 +
        Color::Yellow => 4,
335 +
        Color::Blue => 5,
336 +
        Color::Magenta => 6,
337 +
        Color::Cyan => 7,
338 +
        Color::White => 8,
339 +
        Color::Fixed(value) => 0x100 + usize::from(value),
340 +
        Color::RGB(r, g, b) => {
341 +
            0x1_0000 + (usize::from(r) << 16) + (usize::from(g) << 8) + usize::from(b)
342 +
        }
343 +
    }
344 +
}
345 +
346 +
fn report(frames: usize, elapsed: Duration, checksum: usize) {
347 +
    let seconds = elapsed.as_secs_f64();
348 +
    let fps = frames as f64 / seconds;
349 +
    let cells = AREA.cols * AREA.rows * frames;
350 +
    let mcells = cells as f64 / seconds / 1_000_000.0;
351 +
352 +
    println!("{WORKLOAD}");
353 +
    println!("  frames:   {frames}");
354 +
    println!("  area:     {}x{}", AREA.cols, AREA.rows);
355 +
    println!("  elapsed:  {:.3}s", seconds);
356 +
    println!("  rate:     {:.1} frames/s", fps);
357 +
    println!("  buffer:   {:.1} Mcells/s", mcells);
358 +
    println!("  checksum: {checksum:#x}");
359 +
}
crates/tui/src/lib.rs added +36 -0
1 +
//! Small immediate-mode terminal UI library.
2 +
//!
3 +
//! The default crate surface re-exports the core rendering primitives from
4 +
//! `rustik_tui_core`: buffers, styled text, layout, app/runtime traits, terminal
5 +
//! backends, and small layout widgets. Enable the `widgets` feature to also
6 +
//! re-export the higher-level widgets from `rustik_tui_widgets`.
7 +
//!
8 +
#![deny(unsafe_code)]
9 +
#![warn(missing_docs)]
10 +
#![warn(clippy::unwrap_used)]
11 +
12 +
pub use rustik_tui_core::*;
13 +
14 +
/// Higher-level widgets re-exported when the `widgets` feature is enabled.
15 +
#[cfg(feature = "widgets")]
16 +
pub mod widgets {
17 +
    pub use rustik_tui_widgets::*;
18 +
}
19 +
20 +
#[cfg(feature = "widgets")]
21 +
pub use rustik_tui_widgets::*;
22 +
23 +
#[cfg(test)]
24 +
mod tests {
25 +
    #[test]
26 +
    fn facade_reexports_core_primitives() {
27 +
        let _ = crate::Buffer::empty(crate::Rect::new(0, 0, 1, 1));
28 +
    }
29 +
30 +
    #[cfg(feature = "widgets")]
31 +
    #[test]
32 +
    fn widgets_feature_reexports_widget_types() {
33 +
        let _ = crate::List::new([crate::Line::new("row")]);
34 +
        let _ = crate::Viewport::new();
35 +
    }
36 +
}
src/lib.rs added +11 -0
1 +
//! Umbrella crate that re-exports the `rustik-tui` facade crate.
2 +
//!
3 +
//! Use `rustik::tui::*` for the full facade API. Enable `widgets` to forward
4 +
//! to `rustik-tui`’s optional `widgets` feature.
5 +
//!
6 +
#![deny(unsafe_code)]
7 +
#![warn(missing_docs)]
8 +
#![warn(clippy::unwrap_used)]
9 +
10 +
/// Re-export of the facade crate.
11 +
pub use rustik_tui as tui;