Skip to main content

telex/
widget.rs

1//! Custom widget trait for user-defined character-cell rendering.
2//!
3//! The `Widget` trait allows users to create custom views that render
4//! directly to the terminal buffer. This is an escape hatch for UIs
5//! that can't be composed from built-in widgets.
6//!
7//! # Example
8//! ```rust,ignore
9//! use telex::prelude::*;
10//! use telex::widget::Widget;
11//! use telex::buffer::{Buffer, Rect};
12//!
13//! struct PianoRoll { notes: Vec<u8> }
14//!
15//! impl Widget for PianoRoll {
16//!     fn render(&self, area: Rect, buf: &mut Buffer) {
17//!         for (i, &note) in self.notes.iter().enumerate() {
18//!             if i as u16 >= area.width { break; }
19//!             let ch = if note > 0 { '█' } else { '░' };
20//!             buf.set(area.x + i as u16, area.y, ch,
21//!                 crossterm::style::Color::White,
22//!                 crossterm::style::Color::Black);
23//!         }
24//!     }
25//! }
26//! ```
27
28use crate::buffer::{Buffer, Rect};
29
30/// Trait for custom character-cell widgets.
31///
32/// Implement this trait to create widgets that render directly to the
33/// terminal buffer. Use `View::custom()` to wrap your widget in a View.
34pub trait Widget {
35    /// Render the widget into the given area of the buffer.
36    fn render(&self, area: Rect, buf: &mut Buffer);
37
38    /// Whether this widget is focusable (receives keyboard input).
39    fn focusable(&self) -> bool {
40        false
41    }
42
43    /// Hint for the widget's preferred height given a width.
44    /// Returns None if the widget has no preferred height.
45    fn height_hint(&self, _width: u16) -> Option<u16> {
46        None
47    }
48
49    /// Hint for the widget's preferred width.
50    /// Returns None if the widget has no preferred width.
51    fn width_hint(&self) -> Option<u16> {
52        None
53    }
54}