chore: remove usage of prelude (#1390)

This helps make the doc examples more explicit about what is being used.
It will also makes it a bit easier to do future refactoring of Ratatui,
into several crates, as the ambiguity of where types are coming from
will be reduced.

Additionally, several doc examples have been simplified to use Stylize,
and necessary imports are no longer hidden.

This doesn't remove the prelude. Only the internal usages.
This commit is contained in:
Josh McKinney 2024-09-28 11:47:45 -07:00 committed by GitHub
parent bc10af5931
commit 5ad623c29b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
64 changed files with 1390 additions and 505 deletions

View file

@ -2,8 +2,7 @@ use criterion::{criterion_group, Bencher, BenchmarkId, Criterion};
use rand::Rng;
use ratatui::{
buffer::Buffer,
layout::Rect,
prelude::Direction,
layout::{Direction, Rect},
widgets::{Bar, BarChart, BarGroup, Widget},
};

View file

@ -27,7 +27,7 @@
//! ```rust,no_run
//! use std::io::stdout;
//!
//! use ratatui::prelude::*;
//! use ratatui::{backend::CrosstermBackend, Terminal};
//!
//! let backend = CrosstermBackend::new(stdout());
//! let mut terminal = Terminal::new(backend)?;
@ -187,8 +187,10 @@ pub trait Backend {
/// # Example
///
/// ```rust
/// # use ratatui::backend::{Backend, TestBackend};
/// # use ratatui::backend::{TestBackend};
/// # let mut backend = TestBackend::new(80, 25);
/// use ratatui::backend::Backend;
///
/// backend.hide_cursor()?;
/// // do something with hidden cursor
/// backend.show_cursor()?;
@ -222,9 +224,10 @@ pub trait Backend {
/// # Example
///
/// ```rust
/// # use ratatui::backend::{Backend, TestBackend};
/// # use ratatui::layout::Position;
/// # use ratatui::backend::{TestBackend};
/// # let mut backend = TestBackend::new(80, 25);
/// use ratatui::{backend::Backend, layout::Position};
///
/// backend.set_cursor_position(Position { x: 10, y: 20 })?;
/// assert_eq!(backend.get_cursor_position()?, Position { x: 10, y: 20 });
/// # std::io::Result::Ok(())
@ -254,8 +257,10 @@ pub trait Backend {
/// # Example
///
/// ```rust,no_run
/// # use ratatui::backend::{Backend, TestBackend};
/// # use ratatui::backend::{TestBackend};
/// # let mut backend = TestBackend::new(80, 25);
/// use ratatui::backend::Backend;
///
/// backend.clear()?;
/// # std::io::Result::Ok(())
/// ```
@ -270,8 +275,10 @@ pub trait Backend {
/// # Example
///
/// ```rust,no_run
/// # use ratatui::{prelude::*, backend::{TestBackend, ClearType}};
/// # use ratatui::{backend::{TestBackend}};
/// # let mut backend = TestBackend::new(80, 25);
/// use ratatui::backend::{Backend, ClearType};
///
/// backend.clear_region(ClearType::All)?;
/// # std::io::Result::Ok(())
/// ```
@ -302,8 +309,10 @@ pub trait Backend {
/// # Example
///
/// ```rust
/// # use ratatui::{prelude::*, backend::TestBackend};
/// let backend = TestBackend::new(80, 25);
/// # use ratatui::{backend::{TestBackend}};
/// # let backend = TestBackend::new(80, 25);
/// use ratatui::{backend::Backend, layout::Size};
///
/// assert_eq!(backend.size()?, Size::new(80, 25));
/// # std::io::Result::Ok(())
/// ```

View file

@ -44,15 +44,11 @@ use crate::{
/// ```rust,no_run
/// use std::io::{stderr, stdout};
///
/// use ratatui::{
/// crossterm::{
/// terminal::{
/// disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
/// },
/// ExecutableCommand,
/// },
/// prelude::*,
/// use crossterm::{
/// terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
/// ExecutableCommand,
/// };
/// use ratatui::{backend::CrosstermBackend, Terminal};
///
/// let mut backend = CrosstermBackend::new(stdout());
/// // or
@ -101,8 +97,10 @@ where
/// # Example
///
/// ```rust,no_run
/// # use std::io::stdout;
/// # use ratatui::prelude::*;
/// use std::io::stdout;
///
/// use ratatui::backend::CrosstermBackend;
///
/// let backend = CrosstermBackend::new(stdout());
/// ```
pub const fn new(writer: W) -> Self {

View file

@ -40,8 +40,9 @@ use crate::{
/// use std::io::{stderr, stdout};
///
/// use ratatui::{
/// prelude::*,
/// backend::TermionBackend,
/// termion::{raw::IntoRawMode, screen::IntoAlternateScreen},
/// Terminal,
/// };
///
/// let writer = stdout().into_raw_mode()?.into_alternate_screen()?;
@ -84,8 +85,10 @@ where
/// # Example
///
/// ```rust,no_run
/// # use std::io::stdout;
/// # use ratatui::prelude::*;
/// use std::io::stdout;
///
/// use ratatui::backend::TermionBackend;
///
/// let backend = TermionBackend::new(stdout());
/// ```
pub const fn new(writer: W) -> Self {

View file

@ -38,7 +38,7 @@ use crate::{
/// # Example
///
/// ```rust,no_run
/// use ratatui::prelude::*;
/// use ratatui::{backend::TermwizBackend, Terminal};
///
/// let backend = TermwizBackend::new()?;
/// let mut terminal = Terminal::new(backend)?;
@ -78,7 +78,8 @@ impl TermwizBackend {
/// # Example
///
/// ```rust,no_run
/// # use ratatui::prelude::*;
/// use ratatui::backend::TermwizBackend;
///
/// let backend = TermwizBackend::new()?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```

View file

@ -24,7 +24,7 @@ use crate::{
/// # Example
///
/// ```rust
/// use ratatui::{backend::TestBackend, prelude::*};
/// use ratatui::backend::{Backend, TestBackend};
///
/// let mut backend = TestBackend::new(10, 2);
/// backend.clear()?;
@ -247,7 +247,7 @@ impl Backend for TestBackend {
Ok(())
}
fn clear_region(&mut self, clear_type: super::ClearType) -> io::Result<()> {
fn clear_region(&mut self, clear_type: ClearType) -> io::Result<()> {
let region = match clear_type {
ClearType::All => return self.clear(),
ClearType::AfterCursor => {

View file

@ -41,7 +41,11 @@ macro_rules! assert_buffer_eq {
#[allow(deprecated)]
#[cfg(test)]
mod tests {
use crate::prelude::*;
use crate::{
buffer::Buffer,
layout::Rect,
style::{Color, Style},
};
#[test]
fn assert_buffer_eq_does_not_panic_on_equal_buffers() {

View file

@ -6,7 +6,12 @@ use std::{
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
use crate::{buffer::Cell, layout::Position, prelude::*};
use crate::{
buffer::Cell,
layout::{Position, Rect},
style::Style,
text::{Line, Span},
};
/// A buffer that maps to the desired content of the terminal after the draw call
///
@ -163,7 +168,11 @@ impl Buffer {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, buffer::Cell, layout::Position};
/// use ratatui::{
/// buffer::{Buffer, Cell},
/// layout::{Position, Rect},
/// };
///
/// let mut buffer = Buffer::empty(Rect::new(0, 0, 10, 10));
///
/// assert_eq!(buffer.cell(Position::new(0, 0)), Some(&Cell::default()));
@ -190,7 +199,11 @@ impl Buffer {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, buffer::Cell, layout::Position};
/// use ratatui::{
/// buffer::{Buffer, Cell},
/// layout::{Position, Rect},
/// style::{Color, Style},
/// };
/// let mut buffer = Buffer::empty(Rect::new(0, 0, 10, 10));
///
/// if let Some(cell) = buffer.cell_mut(Position::new(0, 0)) {
@ -214,7 +227,8 @@ impl Buffer {
/// # Examples
///
/// ```
/// # use ratatui::prelude::*;
/// use ratatui::{buffer::Buffer, layout::Rect};
///
/// let buffer = Buffer::empty(Rect::new(200, 100, 10, 10));
/// // Global coordinates to the top corner of this buffer's area
/// assert_eq!(buffer.index_of(200, 100), 0);
@ -225,7 +239,8 @@ impl Buffer {
/// Panics when given an coordinate that is outside of this Buffer's area.
///
/// ```should_panic
/// # use ratatui::prelude::*;
/// use ratatui::{buffer::Buffer, layout::Rect};
///
/// let buffer = Buffer::empty(Rect::new(200, 100, 10, 10));
/// // Top coordinate is outside of the buffer in global coordinate space, as the Buffer's area
/// // starts at (200, 100).
@ -266,7 +281,8 @@ impl Buffer {
/// # Examples
///
/// ```
/// # use ratatui::prelude::*;
/// use ratatui::{buffer::Buffer, layout::Rect};
///
/// let rect = Rect::new(200, 100, 10, 10);
/// let buffer = Buffer::empty(rect);
/// assert_eq!(buffer.pos_of(0), (200, 100));
@ -278,7 +294,8 @@ impl Buffer {
/// Panics when given an index that is outside the Buffer's content.
///
/// ```should_panic
/// # use ratatui::prelude::*;
/// use ratatui::{buffer::Buffer, layout::Rect};
///
/// let rect = Rect::new(0, 0, 10, 10); // 100 cells in total
/// let buffer = Buffer::empty(rect);
/// // Index 100 is the 101th cell, which lies outside of the area of this Buffer.
@ -377,6 +394,8 @@ impl Buffer {
///
/// `style` accepts any type that is convertible to [`Style`] (e.g. [`Style`], [`Color`], or
/// your own type that implements [`Into<Style>`]).
///
/// [`Color`]: crate::style::Color
pub fn set_style<S: Into<Style>>(&mut self, area: Rect, style: S) {
let style = style.into();
let area = self.area.intersection(area);
@ -504,7 +523,11 @@ impl<P: Into<Position>> Index<P> for Buffer {
/// # Examples
///
/// ```
/// # use ratatui::{prelude::*, buffer::Cell, layout::Position};
/// use ratatui::{
/// buffer::{Buffer, Cell},
/// layout::{Position, Rect},
/// };
///
/// let buf = Buffer::empty(Rect::new(0, 0, 10, 10));
/// let cell = &buf[(0, 0)];
/// let cell = &buf[Position::new(0, 0)];
@ -530,7 +553,11 @@ impl<P: Into<Position>> IndexMut<P> for Buffer {
/// # Examples
///
/// ```
/// # use ratatui::{prelude::*, buffer::Cell, layout::Position};
/// use ratatui::{
/// buffer::{Buffer, Cell},
/// layout::{Position, Rect},
/// };
///
/// let mut buf = Buffer::empty(Rect::new(0, 0, 10, 10));
/// buf[(0, 0)].set_symbol("A");
/// buf[Position::new(0, 0)].set_symbol("B");
@ -622,6 +649,7 @@ mod tests {
use rstest::{fixture, rstest};
use super::*;
use crate::style::{Color, Modifier, Stylize};
#[test]
fn debug_empty_buffer() {

View file

@ -1,6 +1,6 @@
use compact_str::CompactString;
use crate::prelude::*;
use crate::style::{Color, Modifier, Style};
/// A buffer cell
#[derive(Debug, Clone, Eq, PartialEq, Hash)]

View file

@ -17,5 +17,5 @@ pub use flex::Flex;
pub use layout::Layout;
pub use margin::Margin;
pub use position::Position;
pub use rect::*;
pub use rect::{Columns, Offset, Positions, Rect, Rows};
pub use size::Size;

View file

@ -26,7 +26,8 @@ use strum::EnumIs;
/// `Constraint` provides helper methods to create lists of constraints from various input formats.
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::layout::Constraint;
///
/// // Create a layout with specified lengths for each element
/// let constraints = Constraint::from_lengths([10, 20, 10]);
///
@ -223,7 +224,8 @@ impl Constraint {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::layout::{Constraint, Layout, Rect};
///
/// # let area = Rect::default();
/// let constraints = Constraint::from_lengths([1, 2, 3]);
/// let layout = Layout::default().constraints(constraints).split(area);
@ -240,7 +242,8 @@ impl Constraint {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::layout::{Constraint, Layout, Rect};
///
/// # let area = Rect::default();
/// let constraints = Constraint::from_ratios([(1, 4), (1, 2), (1, 4)]);
/// let layout = Layout::default().constraints(constraints).split(area);
@ -257,7 +260,8 @@ impl Constraint {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::layout::{Constraint, Layout, Rect};
///
/// # let area = Rect::default();
/// let constraints = Constraint::from_percentages([25, 50, 25]);
/// let layout = Layout::default().constraints(constraints).split(area);
@ -274,7 +278,8 @@ impl Constraint {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::layout::{Constraint, Layout, Rect};
///
/// # let area = Rect::default();
/// let constraints = Constraint::from_maxes([1, 2, 3]);
/// let layout = Layout::default().constraints(constraints).split(area);
@ -291,7 +296,8 @@ impl Constraint {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::layout::{Constraint, Layout, Rect};
///
/// # let area = Rect::default();
/// let constraints = Constraint::from_mins([1, 2, 3]);
/// let layout = Layout::default().constraints(constraints).split(area);
@ -308,7 +314,8 @@ impl Constraint {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::layout::{Constraint, Layout, Rect};
///
/// # let area = Rect::default();
/// let constraints = Constraint::from_fills([1, 2, 3]);
/// let layout = Layout::default().constraints(constraints).split(area);
@ -330,7 +337,8 @@ impl From<u16> for Constraint {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::layout::{Constraint, Direction, Layout, Rect};
///
/// # let area = Rect::default();
/// let layout = Layout::new(Direction::Vertical, [1, 2, 3]).split(area);
/// let layout = Layout::horizontal([1, 2, 3]).split(area);

View file

@ -1,7 +1,7 @@
use strum::{Display, EnumIs, EnumString};
#[allow(unused_imports)]
use super::constraint::Constraint;
use crate::layout::Constraint;
/// Defines the options for layout flex justify content in a container.
///

View file

@ -12,8 +12,7 @@ use self::strengths::{
ALL_SEGMENT_GROW, FILL_GROW, GROW, LENGTH_SIZE_EQ, MAX_SIZE_EQ, MAX_SIZE_LE, MIN_SIZE_EQ,
MIN_SIZE_GE, PERCENTAGE_SIZE_EQ, RATIO_SIZE_EQ, SPACER_SIZE_EQ, SPACE_GROW,
};
use super::Flex;
use crate::prelude::*;
use crate::layout::{Constraint, Direction, Flex, Margin, Rect};
type Rects = Rc<[Rect]>;
type Segments = Rects;
@ -87,7 +86,11 @@ thread_local! {
/// # Example
///
/// ```rust
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// layout::{Constraint, Direction, Layout, Rect},
/// widgets::Paragraph,
/// Frame,
/// };
///
/// fn render(frame: &mut Frame, area: Rect) {
/// let layout = Layout::new(
@ -141,7 +144,8 @@ impl Layout {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::layout::{Constraint, Direction, Layout};
///
/// Layout::new(
/// Direction::Horizontal,
/// [Constraint::Length(5), Constraint::Min(0)],
@ -174,7 +178,8 @@ impl Layout {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::layout::{Constraint, Layout};
///
/// let layout = Layout::vertical([Constraint::Length(5), Constraint::Min(0)]);
/// ```
pub fn vertical<I>(constraints: I) -> Self
@ -193,7 +198,8 @@ impl Layout {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::layout::{Constraint, Layout};
///
/// let layout = Layout::horizontal([Constraint::Length(5), Constraint::Min(0)]);
/// ```
pub fn horizontal<I>(constraints: I) -> Self
@ -221,7 +227,8 @@ impl Layout {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::layout::{Constraint, Direction, Layout, Rect};
///
/// let layout = Layout::default()
/// .direction(Direction::Horizontal)
/// .constraints([Constraint::Length(5), Constraint::Min(0)])
@ -255,7 +262,8 @@ impl Layout {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::layout::{Constraint, Layout, Rect};
///
/// let layout = Layout::default()
/// .constraints([
/// Constraint::Percentage(20),
@ -299,7 +307,8 @@ impl Layout {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::layout::{Constraint, Layout, Rect};
///
/// let layout = Layout::default()
/// .constraints([Constraint::Min(0)])
/// .margin(2)
@ -320,7 +329,8 @@ impl Layout {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::layout::{Constraint, Layout, Rect};
///
/// let layout = Layout::default()
/// .constraints([Constraint::Min(0)])
/// .horizontal_margin(2)
@ -338,7 +348,8 @@ impl Layout {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::layout::{Constraint, Layout, Rect};
///
/// let layout = Layout::default()
/// .constraints([Constraint::Min(0)])
/// .vertical_margin(2)
@ -369,7 +380,8 @@ impl Layout {
/// In this example, the items in the layout will be aligned to the start.
///
/// ```rust
/// # use ratatui::layout::{Flex, Layout, Constraint::*};
/// use ratatui::layout::{Constraint::*, Flex, Layout};
///
/// let layout = Layout::horizontal([Length(20), Length(20), Length(20)]).flex(Flex::Start);
/// ```
///
@ -377,7 +389,8 @@ impl Layout {
/// space.
///
/// ```rust
/// # use ratatui::layout::{Flex, Layout, Constraint::*};
/// use ratatui::layout::{Constraint::*, Flex, Layout};
///
/// let layout = Layout::horizontal([Length(20), Length(20), Length(20)]).flex(Flex::Legacy);
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -397,7 +410,8 @@ impl Layout {
/// In this example, the spacing between each item in the layout is set to 2 cells.
///
/// ```rust
/// # use ratatui::layout::{Layout, Constraint::*};
/// use ratatui::layout::{Constraint::*, Layout};
///
/// let layout = Layout::horizontal([Length(20), Length(20), Length(20)]).spacing(2);
/// ```
///
@ -426,7 +440,8 @@ impl Layout {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::{layout::{Layout, Constraint}, Frame};
///
/// # fn render(frame: &mut Frame) {
/// let area = frame.area();
/// let layout = Layout::vertical([Constraint::Length(1), Constraint::Min(0)]);
@ -458,7 +473,8 @@ impl Layout {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::{layout::{Layout, Constraint}, Frame};
///
/// # fn render(frame: &mut Frame) {
/// let area = frame.area();
/// let layout = Layout::vertical([Constraint::Length(1), Constraint::Min(0)]);
@ -497,7 +513,7 @@ impl Layout {
/// # Examples
///
/// ```
/// # use ratatui::prelude::*;
/// use ratatui::layout::{Constraint, Direction, Layout, Rect};
/// let layout = Layout::default()
/// .direction(Direction::Vertical)
/// .constraints([Constraint::Length(5), Constraint::Min(0)])
@ -529,7 +545,8 @@ impl Layout {
/// # Examples
///
/// ```
/// # use ratatui::prelude::*;
/// use ratatui::layout::{Constraint, Direction, Layout, Rect};
///
/// let (areas, spacers) = Layout::default()
/// .direction(Direction::Vertical)
/// .constraints([Constraint::Length(5), Constraint::Min(0)])
@ -1293,9 +1310,9 @@ mod tests {
use rstest::rstest;
use crate::{
layout::flex::Flex,
prelude::{Constraint::*, *},
widgets::Paragraph,
buffer::Buffer,
layout::{Constraint, Constraint::*, Direction, Flex, Layout, Rect},
widgets::{Paragraph, Widget},
};
/// Test that the given constraints applied to the given area result in the expected layout.

View file

@ -4,8 +4,7 @@ use std::{
fmt,
};
use super::{Position, Size};
use crate::prelude::*;
use crate::layout::{Margin, Position, Size};
mod iter;
pub use iter::*;
@ -27,7 +26,7 @@ pub struct Rect {
pub height: u16,
}
/// Amounts by which to move a [`Rect`](super::Rect).
/// Amounts by which to move a [`Rect`](crate::layout::Rect).
///
/// Positive numbers move to the right/bottom and negative to the left/top.
///
@ -205,7 +204,8 @@ impl Rect {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, layout::Position};
/// use ratatui::layout::{Position, Rect};
///
/// let rect = Rect::new(1, 2, 3, 4);
/// assert!(rect.contains(Position { x: 1, y: 2 }));
/// ````
@ -234,7 +234,8 @@ impl Rect {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::{layout::Rect, Frame};
///
/// # fn render(frame: &mut Frame) {
/// let area = frame.area();
/// let rect = Rect::new(0, 0, 100, 100).clamp(area);
@ -254,7 +255,8 @@ impl Rect {
/// # Example
///
/// ```
/// # use ratatui::prelude::*;
/// use ratatui::{buffer::Buffer, layout::Rect, text::Line, widgets::Widget};
///
/// fn render(area: Rect, buf: &mut Buffer) {
/// for row in area.rows() {
/// Line::raw("Hello, world!").render(row, buf);
@ -270,7 +272,11 @@ impl Rect {
/// # Example
///
/// ```
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// buffer::Buffer,
/// layout::Rect,
/// widgets::{Block, Borders, Widget},
/// };
/// fn render(area: Rect, buf: &mut Buffer) {
/// if let Some(left) = area.columns().next() {
/// Block::new().borders(Borders::LEFT).render(left, buf);
@ -288,7 +294,8 @@ impl Rect {
/// # Example
///
/// ```
/// # use ratatui::prelude::*;
/// use ratatui::{buffer::Buffer, layout::Rect};
///
/// fn render(area: Rect, buf: &mut Buffer) {
/// for position in area.positions() {
/// buf[(position.x, position.y)].set_symbol("x");
@ -304,7 +311,8 @@ impl Rect {
/// # Examples
///
/// ```
/// # use ratatui::prelude::*;
/// use ratatui::layout::Rect;
///
/// let rect = Rect::new(1, 2, 3, 4);
/// let position = rect.as_position();
/// ````
@ -352,6 +360,7 @@ mod tests {
use rstest::rstest;
use super::*;
use crate::layout::{Constraint, Layout};
#[test]
fn to_string() {

View file

@ -1,4 +1,4 @@
use crate::prelude::*;
use crate::layout::{Position, Rect};
/// An iterator over rows within a `Rect`.
pub struct Rows {

View file

@ -1,7 +1,7 @@
#![warn(missing_docs)]
use std::fmt;
use crate::prelude::*;
use crate::layout::Rect;
/// A simple size struct
///

View file

@ -23,7 +23,6 @@ pub use crate::backend::CrosstermBackend;
pub use crate::backend::TermionBackend;
#[cfg(feature = "termwiz")]
pub use crate::backend::TermwizBackend;
pub(crate) use crate::widgets::{StatefulWidgetRef, WidgetRef};
pub use crate::{
backend::{self, Backend},
buffer::{self, Buffer},

View file

@ -13,7 +13,10 @@
//! ## Example
//!
//! ```
//! use ratatui::prelude::*;
//! use ratatui::{
//! style::{Color, Modifier, Style},
//! text::Span,
//! };
//!
//! let heading_style = Style::new()
//! .fg(Color::Black)
@ -41,7 +44,11 @@
//! ## Example
//!
//! ```
//! use ratatui::{prelude::*, widgets::*};
//! use ratatui::{
//! style::{Color, Modifier, Style, Stylize},
//! text::Span,
//! widgets::Paragraph,
//! };
//!
//! assert_eq!(
//! "hello".red().on_blue().bold(),
@ -92,7 +99,7 @@ bitflags! {
/// ## Examples
///
/// ```rust
/// use ratatui::{prelude::*};
/// use ratatui::style::Modifier;
///
/// let m = Modifier::BOLD | Modifier::ITALIC;
/// ```
@ -128,7 +135,7 @@ impl fmt::Debug for Modifier {
/// Style lets you control the main characteristics of the displayed elements.
///
/// ```rust
/// use ratatui::prelude::*;
/// use ratatui::style::{Color, Modifier, Style};
///
/// Style::default()
/// .fg(Color::Black)
@ -139,7 +146,8 @@ impl fmt::Debug for Modifier {
/// Styles can also be created with a [shorthand notation](crate::style#using-style-shorthands).
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::style::{Style, Stylize};
///
/// Style::new().black().on_green().italic().bold();
/// ```
///
@ -149,7 +157,11 @@ impl fmt::Debug for Modifier {
/// anywhere that accepts `Into<Style>`.
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::{
/// style::{Color, Modifier, Style},
/// text::Line,
/// };
///
/// Line::styled("hello", Style::new().fg(Color::Red));
/// // simplifies to
/// Line::styled("hello", Color::Red);
@ -164,7 +176,11 @@ impl fmt::Debug for Modifier {
/// just S3.
///
/// ```rust
/// use ratatui::prelude::*;
/// use ratatui::{
/// buffer::Buffer,
/// layout::Rect,
/// style::{Color, Modifier, Style},
/// };
///
/// let styles = [
/// Style::default()
@ -200,7 +216,11 @@ impl fmt::Debug for Modifier {
/// reset all properties until that point use [`Style::reset`].
///
/// ```
/// use ratatui::prelude::*;
/// use ratatui::{
/// buffer::Buffer,
/// layout::Rect,
/// style::{Color, Modifier, Style},
/// };
///
/// let styles = [
/// Style::default()
@ -325,7 +345,8 @@ impl Style {
/// ## Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::style::{Color, Style};
///
/// let style = Style::default().fg(Color::Blue);
/// let diff = Style::default().fg(Color::Red);
/// assert_eq!(style.patch(diff), Style::default().fg(Color::Red));
@ -341,7 +362,8 @@ impl Style {
/// ## Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::style::{Color, Style};
///
/// let style = Style::default().bg(Color::Blue);
/// let diff = Style::default().bg(Color::Red);
/// assert_eq!(style.patch(diff), Style::default().bg(Color::Red));
@ -365,7 +387,8 @@ impl Style {
/// ## Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::style::{Color, Modifier, Style};
///
/// let style = Style::default()
/// .underline_color(Color::Blue)
/// .add_modifier(Modifier::UNDERLINED);
@ -393,7 +416,8 @@ impl Style {
/// ## Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::style::{Modifier, Style};
///
/// let style = Style::default().add_modifier(Modifier::BOLD);
/// let diff = Style::default().add_modifier(Modifier::ITALIC);
/// let patched = style.patch(diff);
@ -414,7 +438,8 @@ impl Style {
/// ## Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::style::{Modifier, Style};
///
/// let style = Style::default().add_modifier(Modifier::BOLD | Modifier::ITALIC);
/// let diff = Style::default().remove_modifier(Modifier::ITALIC);
/// let patched = style.patch(diff);
@ -436,7 +461,8 @@ impl Style {
///
/// ## Examples
/// ```
/// # use ratatui::prelude::*;
/// use ratatui::style::{Color, Modifier, Style};
///
/// let style_1 = Style::default().fg(Color::Yellow);
/// let style_2 = Style::default().bg(Color::Red);
/// let combined = style_1.patch(style_2);
@ -473,7 +499,8 @@ impl From<Color> for Style {
/// # Example
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::style::{Color, Style};
///
/// let style = Style::from(Color::Red);
/// ```
fn from(color: Color) -> Self {
@ -487,7 +514,8 @@ impl From<(Color, Color)> for Style {
/// # Example
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::style::{Color, Style};
///
/// // red foreground, blue background
/// let style = Style::from((Color::Red, Color::Blue));
/// // default foreground, blue background
@ -509,7 +537,8 @@ impl From<Modifier> for Style {
/// # Example
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::style::{Style, Modifier};
///
/// // add bold and italic
/// let style = Style::from(Modifier::BOLD|Modifier::ITALIC);
fn from(modifier: Modifier) -> Self {
@ -523,7 +552,8 @@ impl From<(Modifier, Modifier)> for Style {
/// # Example
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::style::{Modifier, Style};
///
/// // add bold and italic, remove dim
/// let style = Style::from((Modifier::BOLD | Modifier::ITALIC, Modifier::DIM));
/// ```
@ -542,7 +572,8 @@ impl From<(Color, Modifier)> for Style {
/// # Example
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::style::{Color, Modifier, Style};
///
/// // red foreground, add bold and italic
/// let style = Style::from((Color::Red, Modifier::BOLD | Modifier::ITALIC));
/// ```
@ -559,7 +590,8 @@ impl From<(Color, Color, Modifier)> for Style {
/// # Example
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::style::{Color, Modifier, Style};
///
/// // red foreground, blue background, add bold and italic
/// let style = Style::from((Color::Red, Color::Blue, Modifier::BOLD | Modifier::ITALIC));
/// ```
@ -575,7 +607,8 @@ impl From<(Color, Color, Modifier, Modifier)> for Style {
/// # Example
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::style::{Color, Modifier, Style};
///
/// // red foreground, blue background, add bold and italic, remove dim
/// let style = Style::from((
/// Color::Red,

View file

@ -44,7 +44,7 @@ use crate::style::stylize::{ColorDebug, ColorDebugKind};
/// ```
/// use std::str::FromStr;
///
/// use ratatui::prelude::*;
/// use ratatui::style::Color;
///
/// assert_eq!(Color::from_str("red"), Ok(Color::Red));
/// assert_eq!("red".parse(), Ok(Color::Red));
@ -168,7 +168,9 @@ impl<'de> serde::Deserialize<'de> for Color {
/// # Examples
///
/// ```
/// use ratatui::prelude::*;
/// use std::str::FromStr;
///
/// use ratatui::style::Color;
///
/// #[derive(Debug, serde::Deserialize)]
/// struct Theme {
@ -263,7 +265,7 @@ impl std::error::Error for ParseColorError {}
/// ```
/// use std::str::FromStr;
///
/// use ratatui::prelude::*;
/// use ratatui::style::Color;
///
/// let color: Color = Color::from_str("blue").unwrap();
/// assert_eq!(color, Color::Blue);
@ -379,7 +381,7 @@ impl Color {
/// # Examples
///
/// ```
/// use ratatui::prelude::*;
/// use ratatui::style::Color;
///
/// let color: Color = Color::from_hsl(360.0, 100.0, 100.0);
/// assert_eq!(color, Color::Rgb(255, 255, 255));

View file

@ -403,8 +403,10 @@
//! # Example
//!
//! ```rust
//! # use ratatui::prelude::*;
//! use ratatui::style::palette::material::{BLUE, RED};
//! use ratatui::style::{
//! palette::material::{BLUE, RED},
//! Color,
//! };
//!
//! assert_eq!(RED.c500, Color::Rgb(244, 67, 54));
//! assert_eq!(BLUE.c500, Color::Rgb(33, 150, 243));
@ -412,7 +414,7 @@
//!
//! [`matdesign-color` crate]: https://crates.io/crates/matdesign-color
use crate::prelude::*;
use crate::style::Color;
/// A palette of colors for use in Material design with accent colors
///

View file

@ -268,14 +268,16 @@
//! # Example
//!
//! ```rust
//! # use ratatui::prelude::*;
//! use ratatui::style::palette::tailwind::{BLUE, RED};
//! use ratatui::style::{
//! palette::tailwind::{BLUE, RED},
//! Color,
//! };
//!
//! assert_eq!(RED.c500, Color::Rgb(239, 68, 68));
//! assert_eq!(BLUE.c500, Color::Rgb(59, 130, 246));
//! ```
use crate::prelude::*;
use crate::style::Color;
pub struct Palette {
pub c50: Color,

View file

@ -7,7 +7,7 @@ use ::palette::{
};
use palette::{stimulus::IntoStimulus, Srgb};
use super::Color;
use crate::style::Color;
/// Convert an [`palette::Srgb`] color to a [`Color`].
///

View file

@ -196,7 +196,11 @@ macro_rules! modifier {
///
/// # Examples
/// ```
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// style::{Color, Modifier, Style, Stylize},
/// text::Line,
/// widgets::{Block, Paragraph},
/// };
///
/// let span = "hello".red().on_blue().bold();
/// let line = Line::from(vec![

View file

@ -155,7 +155,7 @@ pub enum Marker {
}
pub mod scrollbar {
use super::{block, line};
use crate::symbols::{block, line};
/// Scrollbar Set
/// ```text

View file

@ -1,4 +1,4 @@
use super::{block, line};
use crate::symbols::{block, line};
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub struct Set {

View file

@ -13,7 +13,7 @@
//! ```rust,no_run
//! use std::io::stdout;
//!
//! use ratatui::{prelude::*, widgets::Paragraph};
//! use ratatui::{backend::CrosstermBackend, widgets::Paragraph, Terminal};
//!
//! let backend = CrosstermBackend::new(stdout());
//! let mut terminal = Terminal::new(backend)?;

View file

@ -1,4 +1,8 @@
use crate::prelude::*;
use crate::{
buffer::Buffer,
layout::{Position, Rect},
widgets::{StatefulWidget, StatefulWidgetRef, Widget, WidgetRef},
};
/// A consistent view into the terminal state for rendering a single frame.
///
@ -10,6 +14,7 @@ use crate::prelude::*;
/// to the terminal. This avoids drawing redundant cells.
///
/// [`Buffer`]: crate::buffer::Buffer
/// [`Terminal::draw`]: crate::Terminal::draw
#[derive(Debug, Hash)]
pub struct Frame<'a> {
/// Where should the cursor be after drawing this frame?
@ -31,6 +36,8 @@ pub struct Frame<'a> {
/// `CompletedFrame` represents the state of the terminal after all changes performed in the last
/// [`Terminal::draw`] call have been applied. Therefore, it is only valid until the next call to
/// [`Terminal::draw`].
///
/// [`Terminal::draw`]: crate::Terminal::draw
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct CompletedFrame<'a> {
/// The buffer that was used to draw the last frame.
@ -73,10 +80,12 @@ impl Frame<'_> {
/// # Example
///
/// ```rust
/// # use ratatui::{backend::TestBackend, prelude::*, widgets::Block};
/// # use ratatui::{backend::TestBackend, Terminal};
/// # let backend = TestBackend::new(5, 5);
/// # let mut terminal = Terminal::new(backend).unwrap();
/// # let mut frame = terminal.get_frame();
/// use ratatui::{layout::Rect, widgets::Block};
///
/// let block = Block::new();
/// let area = Rect::new(0, 0, 5, 5);
/// frame.render_widget(block, area);
@ -96,10 +105,12 @@ impl Frame<'_> {
///
/// ```rust
/// # #[cfg(feature = "unstable-widget-ref")] {
/// # use ratatui::{backend::TestBackend, prelude::*, widgets::Block};
/// # use ratatui::{backend::TestBackend, Terminal};
/// # let backend = TestBackend::new(5, 5);
/// # let mut terminal = Terminal::new(backend).unwrap();
/// # let mut frame = terminal.get_frame();
/// use ratatui::{layout::Rect, widgets::Block};
///
/// let block = Block::new();
/// let area = Rect::new(0, 0, 5, 5);
/// frame.render_widget_ref(block, area);
@ -122,10 +133,15 @@ impl Frame<'_> {
/// # Example
///
/// ```rust
/// # use ratatui::{backend::TestBackend, prelude::*, widgets::*};
/// # use ratatui::{backend::TestBackend, Terminal};
/// # let backend = TestBackend::new(5, 5);
/// # let mut terminal = Terminal::new(backend).unwrap();
/// # let mut frame = terminal.get_frame();
/// use ratatui::{
/// layout::Rect,
/// widgets::{List, ListItem, ListState},
/// };
///
/// let mut state = ListState::default().with_selected(Some(1));
/// let list = List::new(vec![ListItem::new("Item 1"), ListItem::new("Item 2")]);
/// let area = Rect::new(0, 0, 5, 5);
@ -153,10 +169,15 @@ impl Frame<'_> {
///
/// ```rust
/// # #[cfg(feature = "unstable-widget-ref")] {
/// # use ratatui::{backend::TestBackend, prelude::*, widgets::*};
/// # use ratatui::{backend::TestBackend, Terminal};
/// # let backend = TestBackend::new(5, 5);
/// # let mut terminal = Terminal::new(backend).unwrap();
/// # let mut frame = terminal.get_frame();
/// use ratatui::{
/// layout::Rect,
/// widgets::{List, ListItem, ListState},
/// };
///
/// let mut state = ListState::default().with_selected(Some(1));
/// let list = List::new(vec![ListItem::new("Item 1"), ListItem::new("Item 2")]);
/// let area = Rect::new(0, 0, 5, 5);
@ -178,6 +199,10 @@ impl Frame<'_> {
/// Note that this will interfere with calls to [`Terminal::hide_cursor`],
/// [`Terminal::show_cursor`], and [`Terminal::set_cursor_position`]. Pick one of the APIs and
/// stick with it.
///
/// [`Terminal::hide_cursor`]: crate::Terminal::hide_cursor
/// [`Terminal::show_cursor`]: crate::Terminal::show_cursor
/// [`Terminal::set_cursor_position`]: crate::Terminal::set_cursor_position
pub fn set_cursor_position<P: Into<Position>>(&mut self, position: P) {
self.cursor_position = Some(position.into());
}
@ -188,6 +213,10 @@ impl Frame<'_> {
/// Note that this will interfere with calls to [`Terminal::hide_cursor`],
/// [`Terminal::show_cursor`], and [`Terminal::set_cursor_position`]. Pick one of the APIs and
/// stick with it.
///
/// [`Terminal::hide_cursor`]: crate::Terminal::hide_cursor
/// [`Terminal::show_cursor`]: crate::Terminal::show_cursor
/// [`Terminal::set_cursor_position`]: crate::Terminal::set_cursor_position
#[deprecated = "the method set_cursor_position indicates more clearly what about the cursor to set"]
pub fn set_cursor(&mut self, x: u16, y: u16) {
self.set_cursor_position(Position { x, y });
@ -215,7 +244,7 @@ impl Frame<'_> {
/// # Examples
///
/// ```rust
/// # use ratatui::{backend::TestBackend, prelude::*, widgets::*};
/// # use ratatui::{backend::TestBackend, Terminal};
/// # let backend = TestBackend::new(5, 5);
/// # let mut terminal = Terminal::new(backend).unwrap();
/// # let mut frame = terminal.get_frame();

View file

@ -5,8 +5,7 @@ use crossterm::{
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use super::TerminalOptions;
use crate::{backend::CrosstermBackend, Terminal};
use crate::{backend::CrosstermBackend, terminal::TerminalOptions, Terminal};
/// A type alias for the default terminal type.
///

View file

@ -1,7 +1,10 @@
use std::io;
use crate::{
backend::ClearType, buffer::Cell, prelude::*, CompletedFrame, TerminalOptions, Viewport,
backend::{Backend, ClearType},
buffer::{Buffer, Cell},
layout::{Position, Rect, Size},
CompletedFrame, Frame, TerminalOptions, Viewport,
};
/// An interface to interact and draw [`Frame`]s on the user's terminal.
@ -30,10 +33,9 @@ use crate::{
/// # Examples
///
/// ```rust,no_run
/// # use ratatui::prelude::*;
/// use std::io::stdout;
///
/// use ratatui::widgets::Paragraph;
/// use ratatui::{backend::CrosstermBackend, widgets::Paragraph, Terminal};
///
/// let backend = CrosstermBackend::new(stdout());
/// let mut terminal = Terminal::new(backend)?;
@ -107,8 +109,10 @@ where
/// # Example
///
/// ```rust,no_run
/// # use std::io::stdout;
/// # use ratatui::prelude::*;
/// use std::io::stdout;
///
/// use ratatui::{backend::CrosstermBackend, Terminal};
///
/// let backend = CrosstermBackend::new(stdout());
/// let terminal = Terminal::new(backend)?;
/// # std::io::Result::Ok(())
@ -127,8 +131,10 @@ where
/// # Example
///
/// ```rust
/// # use std::io::stdout;
/// # use ratatui::{prelude::*, backend::TestBackend, Viewport, TerminalOptions};
/// use std::io::stdout;
///
/// use ratatui::{backend::CrosstermBackend, layout::Rect, Terminal, TerminalOptions, Viewport};
///
/// let backend = CrosstermBackend::new(stdout());
/// let viewport = Viewport::Fixed(Rect::new(0, 0, 10, 10));
/// let terminal = Terminal::with_options(backend, TerminalOptions { viewport })?;
@ -276,10 +282,9 @@ where
/// # Examples
///
/// ```
/// # use ratatui::layout::Position;
/// # let backend = ratatui::backend::TestBackend::new(10, 10);
/// # let mut terminal = ratatui::Terminal::new(backend)?;
/// use ratatui::widgets::Paragraph;
/// use ratatui::{layout::Position, widgets::Paragraph};
///
/// // with a closure
/// terminal.draw(|frame| {
@ -552,7 +557,13 @@ where
/// ## Insert a single line before the current viewport
///
/// ```rust
/// # use ratatui::{backend::TestBackend, prelude::*, widgets::*};
/// use ratatui::{
/// backend::TestBackend,
/// style::{Color, Style},
/// text::{Line, Span},
/// widgets::{Paragraph, Widget},
/// Terminal,
/// };
/// # let backend = TestBackend::new(10, 10);
/// # let mut terminal = Terminal::new(backend).unwrap();
/// terminal.insert_before(1, |buf| {

View file

@ -1,6 +1,6 @@
use std::fmt;
use crate::prelude::*;
use crate::layout::Rect;
/// Represents the viewport of the terminal. The viewport is the area of the terminal that is
/// currently visible to the user. It can be either fullscreen, inline or fixed.
@ -14,6 +14,8 @@ use crate::prelude::*;
/// by a [`Rect`].
///
/// See [`Terminal::with_options`] for more information.
///
/// [`Terminal::with_options`]: crate::Terminal::with_options
#[derive(Debug, Default, Clone, Eq, PartialEq, Hash)]
pub enum Viewport {
/// The viewport is fullscreen

View file

@ -19,7 +19,11 @@
//! its `title` property (which is a [`Line`] under the hood):
//!
//! ```rust
//! use ratatui::{prelude::*, widgets::*};
//! use ratatui::{
//! style::{Color, Style},
//! text::{Line, Span},
//! widgets::Block,
//! };
//!
//! // A simple string with no styling.
//! // Converted to Line(vec![

View file

@ -1,4 +1,4 @@
use crate::{prelude::*, style::Styled};
use crate::style::{Style, Styled};
const NBSP: &str = "\u{00a0}";
const ZWSP: &str = "\u{200b}";
@ -19,6 +19,8 @@ impl<'a> StyledGrapheme<'a> {
///
/// `style` accepts any type that is convertible to [`Style`] (e.g. [`Style`], [`Color`], or
/// your own type that implements [`Into<Style>`]).
///
/// [`Color`]: crate::style::Color
pub fn new<S: Into<Style>>(symbol: &'a str, style: S) -> Self {
Self {
symbol,
@ -48,6 +50,7 @@ impl<'a> Styled for StyledGrapheme<'a> {
#[cfg(test)]
mod tests {
use super::*;
use crate::style::Stylize;
#[test]
fn new() {

View file

@ -4,7 +4,13 @@ use std::{borrow::Cow, fmt};
use unicode_truncate::UnicodeTruncateStr;
use crate::{prelude::*, style::Styled, text::StyledGrapheme};
use crate::{
buffer::Buffer,
layout::{Alignment, Rect},
style::{Style, Styled},
text::{Span, StyledGrapheme, Text},
widgets::{Widget, WidgetRef},
};
/// A line of text, consisting of one or more [`Span`]s.
///
@ -69,7 +75,10 @@ use crate::{prelude::*, style::Styled, text::StyledGrapheme};
/// [`Style`].
///
/// ```rust
/// use ratatui::prelude::*;
/// use ratatui::{
/// style::{Color, Modifier, Style, Stylize},
/// text::{Line, Span},
/// };
///
/// let style = Style::new().yellow();
/// let line = Line::raw("Hello, world!").style(style);
@ -93,7 +102,11 @@ use crate::{prelude::*, style::Styled, text::StyledGrapheme};
/// methods of the [`Stylize`] trait.
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::{
/// style::{Color, Modifier, Style, Stylize},
/// text::Line,
/// };
///
/// let line = Line::from("Hello world!").style(Style::new().yellow().italic());
/// let line = Line::from("Hello world!").style(Color::Yellow);
/// let line = Line::from("Hello world!").style((Color::Yellow, Color::Black));
@ -108,7 +121,8 @@ use crate::{prelude::*, style::Styled, text::StyledGrapheme};
/// ignored and the line is truncated.
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::{layout::Alignment, text::Line};
///
/// let line = Line::from("Hello world!").alignment(Alignment::Right);
/// let line = Line::from("Hello world!").centered();
/// let line = Line::from("Hello world!").left_aligned();
@ -120,7 +134,15 @@ use crate::{prelude::*, style::Styled, text::StyledGrapheme};
/// `Line` implements the [`Widget`] trait, which means it can be rendered to a [`Buffer`].
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::{
/// buffer::Buffer,
/// layout::Rect,
/// style::{Style, Stylize},
/// text::Line,
/// widgets::Widget,
/// Frame,
/// };
///
/// # fn render(area: Rect, buf: &mut Buffer) {
/// // in another widget's render method
/// let line = Line::from("Hello world!").style(Style::new().yellow().italic());
@ -139,7 +161,14 @@ use crate::{prelude::*, style::Styled, text::StyledGrapheme};
/// provides more functionality.
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// buffer::Buffer,
/// layout::Rect,
/// style::Stylize,
/// text::Line,
/// widgets::{Paragraph, Widget, Wrap},
/// };
///
/// # fn render(area: Rect, buf: &mut Buffer) {
/// let line = Line::from("Hello world!").yellow().italic();
/// Paragraph::new(line)
@ -149,6 +178,7 @@ use crate::{prelude::*, style::Styled, text::StyledGrapheme};
/// ```
///
/// [`Paragraph`]: crate::widgets::Paragraph
/// [`Stylize`]: crate::style::Stylize
#[derive(Default, Clone, Eq, PartialEq, Hash)]
pub struct Line<'a> {
/// The style of this line of text.
@ -199,8 +229,10 @@ impl<'a> Line<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// # use std::borrow::Cow;
/// use std::borrow::Cow;
///
/// use ratatui::text::Line;
///
/// Line::raw("test content");
/// Line::raw(String::from("test content"));
/// Line::raw(Cow::from("test content"));
@ -228,13 +260,20 @@ impl<'a> Line<'a> {
/// Any newlines in the content are removed.
///
/// ```rust
/// # use ratatui::prelude::*;
/// # use std::borrow::Cow;
/// use std::borrow::Cow;
///
/// use ratatui::{
/// style::{Style, Stylize},
/// text::Line,
/// };
///
/// let style = Style::new().yellow().italic();
/// Line::styled("My text", style);
/// Line::styled(String::from("My text"), style);
/// Line::styled(Cow::from("test content"), style);
/// ```
///
/// [`Color`]: crate::style::Color
pub fn styled<T, S>(content: T, style: S) -> Self
where
T: Into<Cow<'a, str>>,
@ -255,7 +294,8 @@ impl<'a> Line<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::{style::Stylize, text::Line};
///
/// let line = Line::default().spans(vec!["Hello".blue(), " world!".green()]);
/// let line = Line::default().spans([1, 2, 3].iter().map(|i| format!("Item {}", i)));
/// ```
@ -282,9 +322,15 @@ impl<'a> Line<'a> {
///
/// # Examples
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::{
/// style::{Style, Stylize},
/// text::Line,
/// };
///
/// let mut line = Line::from("foo").style(Style::new().red());
/// ```
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
self.style = style.into();
@ -300,7 +346,8 @@ impl<'a> Line<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::{layout::Alignment, text::Line};
///
/// let mut line = Line::from("Hi, what's up?");
/// assert_eq!(None, line.alignment);
/// assert_eq!(
@ -325,7 +372,8 @@ impl<'a> Line<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::text::Line;
///
/// let line = Line::from("Hi, what's up?").left_aligned();
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -342,7 +390,8 @@ impl<'a> Line<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::text::Line;
///
/// let line = Line::from("Hi, what's up?").centered();
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -359,7 +408,8 @@ impl<'a> Line<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::text::Line;
///
/// let line = Line::from("Hi, what's up?").right_aligned();
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -372,7 +422,8 @@ impl<'a> Line<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::{style::Stylize, text::Line};
///
/// let line = Line::from(vec!["Hello".blue(), " world!".green()]);
/// assert_eq!(12, line.width());
/// ```
@ -393,7 +444,10 @@ impl<'a> Line<'a> {
/// ```rust
/// use std::iter::Iterator;
///
/// use ratatui::{prelude::*, text::StyledGrapheme};
/// use ratatui::{
/// style::{Color, Style},
/// text::{Line, StyledGrapheme},
/// };
///
/// let line = Line::styled("Text", Style::default().fg(Color::Yellow));
/// let style = Style::default().fg(Color::Green).bg(Color::Black);
@ -408,6 +462,8 @@ impl<'a> Line<'a> {
/// ]
/// );
/// ```
///
/// [`Color`]: crate::style::Color
pub fn styled_graphemes<S: Into<Style>>(
&'a self,
base_style: S,
@ -432,13 +488,19 @@ impl<'a> Line<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::{
/// style::{Color, Modifier},
/// text::Line,
/// };
///
/// let line = Line::styled("My text", Modifier::ITALIC);
///
/// let styled_line = Line::styled("My text", (Color::Yellow, Modifier::ITALIC));
///
/// assert_eq!(styled_line, line.patch_style(Color::Yellow));
/// ```
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn patch_style<S: Into<Style>>(mut self, style: S) -> Self {
self.style = self.style.patch(style);
@ -454,8 +516,12 @@ impl<'a> Line<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// # let style = Style::default().yellow();
/// use ratatui::{
/// style::{Style, Stylize},
/// text::Line,
/// };
///
/// let line = Line::styled("My text", style);
///
/// assert_eq!(Style::reset(), line.reset_style().style);
@ -483,7 +549,8 @@ impl<'a> Line<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::text::{Line, Span};
///
/// let mut line = Line::from("Hello, ");
/// line.push_span(Span::raw("world!"));
/// line.push_span(" How are you?");
@ -749,6 +816,7 @@ mod tests {
use rstest::{fixture, rstest};
use super::*;
use crate::style::{Color, Modifier, Stylize};
#[fixture]
fn small_buf() -> Buffer {

View file

@ -1,6 +1,6 @@
use std::{borrow::Cow, fmt};
use super::Text;
use crate::text::Text;
/// A wrapper around a string that is masked when displayed.
///
@ -10,7 +10,12 @@ use super::Text;
/// # Examples
///
/// ```rust
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// buffer::Buffer,
/// layout::Rect,
/// text::Masked,
/// widgets::{Paragraph, Widget},
/// };
///
/// let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 1));
/// let password = Masked::new("12345", 'x');

View file

@ -3,7 +3,13 @@ use std::{borrow::Cow, fmt};
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
use crate::{prelude::*, style::Styled, text::StyledGrapheme};
use crate::{
buffer::Buffer,
layout::Rect,
style::{Style, Styled},
text::{Line, StyledGrapheme},
widgets::{Widget, WidgetRef},
};
/// Represents a part of a line that is contiguous and where all characters share the same style.
///
@ -36,7 +42,7 @@ use crate::{prelude::*, style::Styled, text::StyledGrapheme};
/// any type convertible to [`Cow<str>`].
///
/// ```rust
/// use ratatui::prelude::*;
/// use ratatui::text::Span;
///
/// let span = Span::raw("test content");
/// let span = Span::raw(String::from("test content"));
@ -50,7 +56,10 @@ use crate::{prelude::*, style::Styled, text::StyledGrapheme};
/// the [`Stylize`] trait.
///
/// ```rust
/// use ratatui::prelude::*;
/// use ratatui::{
/// style::{Style, Stylize},
/// text::Span,
/// };
///
/// let span = Span::styled("test content", Style::new().green());
/// let span = Span::styled(String::from("test content"), Style::new().green());
@ -64,7 +73,7 @@ use crate::{prelude::*, style::Styled, text::StyledGrapheme};
/// defined in the [`Stylize`] trait.
///
/// ```rust
/// use ratatui::prelude::*;
/// use ratatui::{style::Stylize, text::Span};
///
/// let span = Span::raw("test content").green().on_yellow().italic();
/// let span = Span::raw(String::from("test content"))
@ -78,7 +87,7 @@ use crate::{prelude::*, style::Styled, text::StyledGrapheme};
/// wrapping and alignment for you.
///
/// ```rust
/// use ratatui::prelude::*;
/// use ratatui::{style::Stylize, Frame};
///
/// # fn render_frame(frame: &mut Frame) {
/// frame.render_widget("test content".green().on_yellow().italic(), frame.area());
@ -114,7 +123,8 @@ impl<'a> Span<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::text::Span;
///
/// Span::raw("test content");
/// Span::raw(String::from("test content"));
/// ```
@ -139,11 +149,17 @@ impl<'a> Span<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::{
/// style::{Style, Stylize},
/// text::Span,
/// };
///
/// let style = Style::new().yellow().on_green().italic();
/// Span::styled("test content", style);
/// Span::styled(String::from("test content"), style);
/// ```
///
/// [`Color`]: crate::style::Color
pub fn styled<T, S>(content: T, style: S) -> Self
where
T: Into<Cow<'a, str>>,
@ -165,7 +181,8 @@ impl<'a> Span<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::text::Span;
///
/// let mut span = Span::default().content("content");
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -190,9 +207,15 @@ impl<'a> Span<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::{
/// style::{Style, Stylize},
/// text::Span,
/// };
///
/// let mut span = Span::default().style(Style::new().green());
/// ```
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
self.style = style.into();
@ -209,11 +232,17 @@ impl<'a> Span<'a> {
/// # Example
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::{
/// style::{Style, Stylize},
/// text::Span,
/// };
///
/// let span = Span::styled("test content", Style::new().green().italic())
/// .patch_style(Style::new().red().on_yellow().bold());
/// assert_eq!(span.style, Style::new().red().on_yellow().italic().bold());
/// ```
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn patch_style<S: Into<Style>>(mut self, style: S) -> Self {
self.style = self.style.patch(style);
@ -229,7 +258,11 @@ impl<'a> Span<'a> {
/// # Example
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::{
/// style::{Style, Stylize},
/// text::Span,
/// };
///
/// let span = Span::styled(
/// "Test Content",
/// Style::new().dark_gray().on_yellow().italic(),
@ -260,7 +293,10 @@ impl<'a> Span<'a> {
/// ```rust
/// use std::iter::Iterator;
///
/// use ratatui::{prelude::*, text::StyledGrapheme};
/// use ratatui::{
/// style::{Style, Stylize},
/// text::{Span, StyledGrapheme},
/// };
///
/// let span = Span::styled("Test", Style::new().green().italic());
/// let style = Style::new().red().on_yellow();
@ -275,6 +311,8 @@ impl<'a> Span<'a> {
/// ],
/// );
/// ```
///
/// [`Color`]: crate::style::Color
pub fn styled_graphemes<S: Into<Style>>(
&'a self,
base_style: S,
@ -292,7 +330,8 @@ impl<'a> Span<'a> {
/// # Example
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::style::Stylize;
///
/// let line = "Test Content".green().italic().into_left_aligned_line();
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -311,7 +350,8 @@ impl<'a> Span<'a> {
/// # Example
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::style::Stylize;
///
/// let line = "Test Content".green().italic().into_centered_line();
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -330,7 +370,8 @@ impl<'a> Span<'a> {
/// # Example
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::style::Stylize;
///
/// let line = "Test Content".green().italic().into_right_aligned_line();
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -464,10 +505,10 @@ impl fmt::Display for Span<'_> {
#[cfg(test)]
mod tests {
use buffer::Cell;
use rstest::fixture;
use super::*;
use crate::{buffer::Cell, layout::Alignment, style::Stylize};
#[fixture]
fn small_buf() -> Buffer {

View file

@ -1,7 +1,13 @@
#![warn(missing_docs)]
use std::{borrow::Cow, fmt};
use crate::{prelude::*, style::Styled};
use crate::{
buffer::Buffer,
layout::{Alignment, Rect},
style::{Style, Styled},
text::{Line, Span},
widgets::{Widget, WidgetRef},
};
/// A string split over one or more lines.
///
@ -62,7 +68,10 @@ use crate::{prelude::*, style::Styled};
/// ```rust
/// use std::{borrow::Cow, iter};
///
/// use ratatui::prelude::*;
/// use ratatui::{
/// style::{Color, Modifier, Style, Stylize},
/// text::{Line, Span, Text},
/// };
///
/// let style = Style::new().yellow().italic();
/// let text = Text::raw("The first line\nThe second line").style(style);
@ -99,7 +108,11 @@ use crate::{prelude::*, style::Styled};
/// [`Stylize`] trait.
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::{
/// style::{Color, Modifier, Style, Stylize},
/// text::{Line, Text},
/// };
///
/// let text = Text::from("The first line\nThe second line").style(Style::new().yellow().italic());
/// let text = Text::from("The first line\nThe second line")
/// .yellow()
@ -116,7 +129,11 @@ use crate::{prelude::*, style::Styled};
/// Lines composing the text can also be individually aligned with [`Line::alignment`].
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::{
/// layout::Alignment,
/// text::{Line, Text},
/// };
///
/// let text = Text::from("The first line\nThe second line").alignment(Alignment::Right);
/// let text = Text::from("The first line\nThe second line").right_aligned();
/// let text = Text::from(vec![
@ -132,7 +149,9 @@ use crate::{prelude::*, style::Styled};
/// [`Frame`].
///
/// ```rust
/// # use ratatui::prelude::*;
/// # use ratatui::{buffer::Buffer, layout::Rect};
/// use ratatui::{text::Text, widgets::Widget, Frame};
///
/// // within another widget's `render` method:
/// # fn render(area: Rect, buf: &mut Buffer) {
/// let text = Text::from("The first line\nThe second line");
@ -152,7 +171,13 @@ use crate::{prelude::*, style::Styled};
/// provides more functionality.
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// buffer::Buffer,
/// layout::Rect,
/// text::Text,
/// widgets::{Paragraph, Widget, Wrap},
/// };
///
/// # fn render(area: Rect, buf: &mut Buffer) {
/// let text = Text::from("The first line\nThe second line");
/// let paragraph = Paragraph::new(text)
@ -163,6 +188,8 @@ use crate::{prelude::*, style::Styled};
/// ```
///
/// [`Paragraph`]: crate::widgets::Paragraph
/// [`Stylize`]: crate::style::Stylize
/// [`Frame`]: crate::Frame
#[derive(Default, Clone, Eq, PartialEq, Hash)]
pub struct Text<'a> {
/// The alignment of this text.
@ -197,7 +224,8 @@ impl<'a> Text<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::text::Text;
///
/// Text::raw("The first line\nThe second line");
/// Text::raw(String::from("The first line\nThe second line"));
/// ```
@ -222,13 +250,19 @@ impl<'a> Text<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::{
/// style::{Color, Modifier, Style},
/// text::Text,
/// };
///
/// let style = Style::default()
/// .fg(Color::Yellow)
/// .add_modifier(Modifier::ITALIC);
/// Text::styled("The first line\nThe second line", style);
/// Text::styled(String::from("The first line\nThe second line"), style);
/// ```
///
/// [`Color`]: crate::style::Color
pub fn styled<T, S>(content: T, style: S) -> Self
where
T: Into<Cow<'a, str>>,
@ -242,7 +276,8 @@ impl<'a> Text<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::text::Text;
///
/// let text = Text::from("The first line\nThe second line");
/// assert_eq!(15, text.width());
/// ```
@ -255,7 +290,8 @@ impl<'a> Text<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::text::Text;
///
/// let text = Text::from("The first line\nThe second line");
/// assert_eq!(2, text.height());
/// ```
@ -276,9 +312,15 @@ impl<'a> Text<'a> {
///
/// # Examples
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::{
/// style::{Style, Stylize},
/// text::Text,
/// };
///
/// let mut line = Text::from("foo").style(Style::new().red());
/// ```
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
self.style = style.into();
@ -302,7 +344,11 @@ impl<'a> Text<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::{
/// style::{Color, Modifier},
/// text::Text,
/// };
///
/// let raw_text = Text::styled("The first line\nThe second line", Modifier::ITALIC);
/// let styled_text = Text::styled(
/// String::from("The first line\nThe second line"),
@ -313,6 +359,9 @@ impl<'a> Text<'a> {
/// let raw_text = raw_text.patch_style(Color::Yellow);
/// assert_eq!(raw_text, styled_text);
/// ```
///
/// [`Color`]: crate::style::Color
/// [`Stylize`]: crate::style::Stylize
#[must_use = "method moves the value of self and returns the modified value"]
pub fn patch_style<S: Into<Style>>(mut self, style: S) -> Self {
self.style = self.style.patch(style);
@ -328,7 +377,11 @@ impl<'a> Text<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::{
/// style::{Color, Modifier, Style},
/// text::Text,
/// };
///
/// let text = Text::styled(
/// "The first line\nThe second line",
/// (Color::Yellow, Modifier::ITALIC),
@ -355,7 +408,8 @@ impl<'a> Text<'a> {
/// Set alignment to the whole text.
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::{layout::Alignment, text::Text};
///
/// let mut text = Text::from("Hi, what's up?");
/// assert_eq!(None, text.alignment);
/// assert_eq!(
@ -367,7 +421,11 @@ impl<'a> Text<'a> {
/// Set a default alignment and override it on a per line basis.
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::{
/// layout::Alignment,
/// text::{Line, Text},
/// };
///
/// let text = Text::from(vec![
/// Line::from("left").alignment(Alignment::Left),
/// Line::from("default"),
@ -404,7 +462,8 @@ impl<'a> Text<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::text::Text;
///
/// let text = Text::from("Hi, what's up?").left_aligned();
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -423,7 +482,8 @@ impl<'a> Text<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::text::Text;
///
/// let text = Text::from("Hi, what's up?").centered();
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -442,7 +502,8 @@ impl<'a> Text<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::text::Text;
///
/// let text = Text::from("Hi, what's up?").right_aligned();
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -468,7 +529,8 @@ impl<'a> Text<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::text::{Line, Span, Text};
///
/// let mut text = Text::from("Hello, world!");
/// text.push_line(Line::from("How are you?"));
/// text.push_line(Span::from("How are you?"));
@ -486,7 +548,8 @@ impl<'a> Text<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::prelude::*;
/// use ratatui::text::{Span, Text};
///
/// let mut text = Text::from("Hello, world!");
/// text.push_span(Span::from("How are you?"));
/// text.push_span("How are you?");
@ -708,6 +771,7 @@ mod tests {
use rstest::{fixture, rstest};
use super::*;
use crate::style::{Color, Modifier, Stylize};
#[fixture]
fn small_buf() -> Buffer {

View file

@ -83,7 +83,11 @@ use crate::{buffer::Buffer, layout::Rect, style::Style};
/// # Examples
///
/// ```rust,no_run
/// use ratatui::{backend::TestBackend, prelude::*, widgets::*};
/// use ratatui::{
/// backend::TestBackend,
/// widgets::{Clear, Widget},
/// Terminal,
/// };
/// # let backend = TestBackend::new(5, 5);
/// # let mut terminal = Terminal::new(backend).unwrap();
///
@ -95,7 +99,7 @@ use crate::{buffer::Buffer, layout::Rect, style::Style};
/// It's common to render widgets inside other widgets:
///
/// ```rust
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{buffer::Buffer, layout::Rect, text::Line, widgets::Widget};
///
/// struct MyWidget;
///
@ -133,7 +137,11 @@ pub trait Widget {
/// ```rust,no_run
/// use std::io;
///
/// use ratatui::{backend::TestBackend, prelude::*, widgets::*};
/// use ratatui::{
/// backend::TestBackend,
/// widgets::{List, ListItem, ListState, StatefulWidget, Widget},
/// Terminal,
/// };
///
/// // Let's say we have some events to display.
/// struct Events {
@ -257,7 +265,12 @@ pub trait StatefulWidget {
///
/// ```rust
/// # #[cfg(feature = "unstable-widget-ref")] {
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// buffer::Buffer,
/// layout::Rect,
/// text::Line,
/// widgets::{Widget, WidgetRef},
/// };
///
/// struct Greeting;
///
@ -332,7 +345,12 @@ impl<W: WidgetRef> Widget for &W {
///
/// ```rust
/// # #[cfg(feature = "unstable-widget-ref")] {
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// buffer::Buffer,
/// layout::Rect,
/// text::Line,
/// widgets::{Widget, WidgetRef},
/// };
///
/// struct Parent {
/// child: Option<Child>,
@ -381,7 +399,13 @@ impl<W: WidgetRef> WidgetRef for Option<W> {
///
/// ```rust
/// # #[cfg(feature = "unstable-widget-ref")] {
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// buffer::Buffer,
/// layout::Rect,
/// style::Stylize,
/// text::Line,
/// widgets::{StatefulWidget, StatefulWidgetRef, Widget},
/// };
///
/// struct PersonalGreeting;
///

View file

@ -1,4 +1,11 @@
use crate::{prelude::*, style::Styled, widgets::Block};
use crate::{
buffer::Buffer,
layout::{Direction, Rect},
style::{Style, Styled},
symbols::{self},
text::Line,
widgets::{block::BlockExt, Block, Widget, WidgetRef},
};
mod bar;
mod bar_group;
@ -42,7 +49,10 @@ pub use bar_group::BarGroup;
/// The first group is added by an array slice (`&[(&str, u64)]`).
/// The second group is added by a [`BarGroup`] instance.
/// ```
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// style::{Style, Stylize},
/// widgets::{Bar, BarChart, BarGroup, Block},
/// };
///
/// BarChart::default()
/// .block(Block::bordered().title("BarChart"))
@ -113,7 +123,8 @@ impl<'a> BarChart<'a> {
/// The first group is added by an array slice (`&[(&str, u64)]`).
/// The second group is added by a [`BarGroup`] instance.
/// ```
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::{Bar, BarChart, BarGroup};
///
/// BarChart::default()
/// .data(&[("B0", 0), ("B1", 2), ("B2", 4), ("B3", 3)])
/// .data(BarGroup::default().bars(&[Bar::default().value(10), Bar::default().value(20)]));
@ -143,7 +154,7 @@ impl<'a> BarChart<'a> {
/// This example shows the default behavior when `max` is not set.
/// The maximum value in the dataset is taken (here, `100`).
/// ```
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::BarChart;
/// BarChart::default().data(&[("foo", 1), ("bar", 2), ("baz", 100)]);
/// // Renders
/// // █
@ -154,7 +165,8 @@ impl<'a> BarChart<'a> {
/// This example shows a custom max value.
/// The maximum height being `2`, `bar` & `baz` render as the max.
/// ```
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::BarChart;
///
/// BarChart::default()
/// .data(&[("foo", 1), ("bar", 2), ("baz", 100)])
/// .max(2);
@ -176,6 +188,8 @@ impl<'a> BarChart<'a> {
///
/// It is also possible to set individually the style of each [`Bar`].
/// In this case the default style will be patched by the individual style
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn bar_style<S: Into<Style>>(mut self, style: S) -> Self {
self.bar_style = style.into();
@ -204,7 +218,8 @@ impl<'a> BarChart<'a> {
///
/// This shows two bars with a gap of `3`. Notice the labels will always stay under the bar.
/// ```
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::BarChart;
///
/// BarChart::default()
/// .data(&[("foo", 1), ("bar", 2)])
/// .bar_gap(3);
@ -239,6 +254,8 @@ impl<'a> BarChart<'a> {
/// # See also
///
/// [`Bar::value_style`] to set the value style individually.
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn value_style<S: Into<Style>>(mut self, style: S) -> Self {
self.value_style = style.into();
@ -256,6 +273,8 @@ impl<'a> BarChart<'a> {
/// # See also
///
/// [`Bar::label`] to set the label style individually.
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn label_style<S: Into<Style>>(mut self, style: S) -> Self {
self.label_style = style.into();
@ -275,6 +294,8 @@ impl<'a> BarChart<'a> {
/// your own type that implements [`Into<Style>`]).
///
/// The style will be applied to everything that isn't styled (borders, bars, labels, ...).
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
self.style = style.into();
@ -615,7 +636,12 @@ mod tests {
use itertools::iproduct;
use super::*;
use crate::widgets::BorderType;
use crate::{
layout::Alignment,
style::{Color, Modifier, Stylize},
text::Span,
widgets::BorderType,
};
#[test]
fn default() {

View file

@ -1,7 +1,6 @@
use unicode_width::UnicodeWidthStr;
use crate::prelude::*;
use crate::{buffer::Buffer, layout::Rect, style::Style, text::Line, widgets::Widget};
/// A bar to be shown by the [`BarChart`](crate::widgets::BarChart) widget.
///
/// Here is an explanation of a `Bar`'s components.
@ -17,13 +16,16 @@ use crate::prelude::*;
/// The following example creates a bar with the label "Bar 1", a value "10",
/// red background and a white value foreground.
/// ```
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// style::{Style, Stylize},
/// widgets::Bar,
/// };
///
/// Bar::default()
/// .label("Bar 1".into())
/// .value(10)
/// .style(Style::default().fg(Color::Red))
/// .value_style(Style::default().bg(Color::Red).fg(Color::White))
/// .style(Style::new().red())
/// .value_style(Style::new().red().on_white())
/// .text_value("10°C".to_string());
/// ```
#[derive(Debug, Default, Clone, Eq, PartialEq, Hash)]
@ -74,6 +76,8 @@ impl<'a> Bar<'a> {
/// your own type that implements [`Into<Style>`]).
///
/// This will apply to every non-styled element. It can be seen and used as a default value.
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
self.style = style.into();
@ -88,6 +92,8 @@ impl<'a> Bar<'a> {
/// # See also
///
/// [`Bar::value`] to set the value.
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn value_style<S: Into<Style>>(mut self, style: S) -> Self {
self.value_style = style.into();

View file

@ -1,12 +1,17 @@
use super::Bar;
use crate::prelude::*;
use crate::{
buffer::Buffer,
layout::{Alignment, Rect},
style::Style,
text::Line,
widgets::{barchart::Bar, Widget},
};
/// A group of bars to be shown by the Barchart.
///
/// # Examples
///
/// ```
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::{Bar, BarGroup};
///
/// BarGroup::default()
/// .label("Group 1".into())

View file

@ -8,7 +8,14 @@
use itertools::Itertools;
use strum::{Display, EnumString};
use crate::{prelude::*, style::Styled, symbols::border, widgets::Borders};
use crate::{
buffer::Buffer,
layout::{Alignment, Rect},
style::{Style, Styled},
symbols::border,
text::Line,
widgets::{Borders, Widget, WidgetRef},
};
mod padding;
pub mod title;
@ -67,7 +74,10 @@ pub use title::{Position, Title};
/// # Examples
///
/// ```
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// style::{Color, Style},
/// widgets::{Block, BorderType, Borders},
/// };
///
/// Block::new()
/// .border_type(BorderType::Rounded)
@ -79,12 +89,9 @@ pub use title::{Position, Title};
///
/// You may also use multiple titles like in the following:
/// ```
/// use ratatui::{
/// prelude::*,
/// widgets::{
/// block::{Position, Title},
/// Block,
/// },
/// use ratatui::widgets::{
/// block::{Position, Title},
/// Block,
/// };
///
/// Block::new()
@ -94,10 +101,7 @@ pub use title::{Position, Title};
///
/// You can also pass it as parameters of another widget so that the block surrounds them:
/// ```
/// use ratatui::{
/// prelude::*,
/// widgets::{Block, Borders, List},
/// };
/// use ratatui::widgets::{Block, Borders, List};
///
/// let surrounding_block = Block::default()
/// .borders(Borders::ALL)
@ -220,7 +224,8 @@ impl<'a> Block<'a> {
/// Create a new block with [all borders](Borders::ALL) shown
///
/// ```
/// # use ratatui::widgets::{Block, Borders};
/// use ratatui::widgets::{Block, Borders};
///
/// assert_eq!(Block::bordered(), Block::new().borders(Borders::ALL));
/// ```
pub const fn bordered() -> Self {
@ -268,8 +273,8 @@ impl<'a> Block<'a> {
/// - Two titles with the same alignment (notice the left titles are separated)
/// ```
/// use ratatui::{
/// prelude::*,
/// widgets::{block::*, *},
/// text::Line,
/// widgets::{Block, Borders},
/// };
///
/// Block::new()
@ -320,7 +325,8 @@ impl<'a> Block<'a> {
/// # Example
///
/// ```
/// # use ratatui::{ prelude::*, widgets::* };
/// use ratatui::{ widgets::Block, text::Line };
///
/// Block::bordered()
/// .title_top("Left1") // By default in the top left corner
/// .title_top(Line::from("Left2").left_aligned())
@ -348,7 +354,8 @@ impl<'a> Block<'a> {
/// # Example
///
/// ```
/// # use ratatui::{ prelude::*, widgets::* };
/// use ratatui::{ widgets::Block, text::Line };
///
/// Block::bordered()
/// .title_bottom("Left1") // By default in the top left corner
/// .title_bottom(Line::from("Left2").left_aligned())
@ -377,6 +384,8 @@ impl<'a> Block<'a> {
///
/// `style` accepts any type that is convertible to [`Style`] (e.g. [`Style`], [`Color`], or
/// your own type that implements [`Into<Style>`]).
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn title_style<S: Into<Style>>(mut self, style: S) -> Self {
self.titles_style = style.into();
@ -392,10 +401,7 @@ impl<'a> Block<'a> {
/// This example aligns all titles in the center except the "right" title which explicitly sets
/// [`Alignment::Right`].
/// ```
/// use ratatui::{
/// prelude::*,
/// widgets::{block::*, *},
/// };
/// use ratatui::{layout::Alignment, text::Line, widgets::Block};
///
/// Block::new()
/// .title_alignment(Alignment::Center)
@ -419,13 +425,7 @@ impl<'a> Block<'a> {
/// This example positions all titles on the bottom except the "top" title which explicitly sets
/// [`Position::Top`].
/// ```
/// use ratatui::{
/// prelude::*,
/// widgets::{
/// block::{Position, Title},
/// Block,
/// },
/// };
/// use ratatui::widgets::{block::Position, Block};
///
/// Block::new()
/// .title_position(Position::Bottom)
@ -454,9 +454,14 @@ impl<'a> Block<'a> {
///
/// This example shows a `Block` with blue borders.
/// ```
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// style::{Style, Stylize},
/// widgets::Block,
/// };
/// Block::bordered().border_style(Style::new().blue());
/// ```
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn border_style<S: Into<Style>>(mut self, style: S) -> Self {
self.border_style = style.into();
@ -479,7 +484,11 @@ impl<'a> Block<'a> {
/// # Example
///
/// ```
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// style::{Color, Style, Stylize},
/// widgets::{Block, Paragraph},
/// };
///
/// let block = Block::new().style(Style::new().red().on_black());
///
/// // For border and title you can additionally apply styles on top of the block level style.
@ -496,6 +505,7 @@ impl<'a> Block<'a> {
/// ```
///
/// [`Paragraph`]: crate::widgets::Paragraph
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
self.style = style.into();
@ -510,7 +520,7 @@ impl<'a> Block<'a> {
///
/// Display left and right borders.
/// ```
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::{Block, Borders};
/// Block::new().borders(Borders::LEFT | Borders::RIGHT);
/// ```
///
@ -531,7 +541,7 @@ impl<'a> Block<'a> {
/// # Examples
///
/// ```
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::{Block, BorderType};
/// Block::bordered()
/// .border_type(BorderType::Rounded)
/// .title("Block");
@ -553,7 +563,8 @@ impl<'a> Block<'a> {
/// # Examples
///
/// ```
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{widgets::Block, symbols};
///
/// Block::bordered().border_set(symbols::border::DOUBLE).title("Block");
/// // Renders
/// // ╔Block╗
@ -573,7 +584,8 @@ impl<'a> Block<'a> {
///
/// This renders a `Block` with no padding (the default).
/// ```
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::{Block, Padding};
///
/// Block::bordered().padding(Padding::ZERO);
/// // Renders
/// // ┌───────┐
@ -584,7 +596,8 @@ impl<'a> Block<'a> {
/// This example shows a `Block` with padding left and right ([`Padding::horizontal`]).
/// Notice the two spaces before and after the content.
/// ```
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::{Block, Padding};
///
/// Block::bordered().padding(Padding::horizontal(2));
/// // Renders
/// // ┌───────────┐
@ -603,7 +616,8 @@ impl<'a> Block<'a> {
///
/// Draw a block nested within another block
/// ```
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{widgets::Block, Frame};
///
/// # fn render_nested_block(frame: &mut Frame) {
/// let outer_block = Block::bordered().title("Outer");
/// let inner_block = Block::bordered().title("Inner");
@ -990,6 +1004,7 @@ mod tests {
use strum::ParseError;
use super::*;
use crate::style::{Color, Modifier, Stylize};
#[test]
fn create_with_all_borders() {

View file

@ -10,7 +10,7 @@
/// # Example
///
/// ```
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::Padding;
///
/// Padding::uniform(1);
/// Padding::horizontal(2);

View file

@ -31,14 +31,14 @@ use crate::{layout::Alignment, text::Line};
///
/// Blue title on a white background (via [`Stylize`](crate::style::Stylize) trait).
/// ```
/// use ratatui::{prelude::*, widgets::block::*};
/// use ratatui::{style::Stylize, widgets::block::Title};
///
/// Title::from("Title".blue().on_white());
/// ```
///
/// Title with multiple styles (see [`Line`] and [`Stylize`](crate::style::Stylize)).
/// ```
/// use ratatui::{prelude::*, widgets::block::*};
/// use ratatui::{style::Stylize, text::Line, widgets::block::Title};
///
/// Title::from(Line::from(vec!["Q".white().underlined(), "uit".gray()]));
/// ```
@ -46,7 +46,7 @@ use crate::{layout::Alignment, text::Line};
/// Complete example
/// ```
/// use ratatui::{
/// prelude::*,
/// layout::Alignment,
/// widgets::{
/// block::{Position, Title},
/// Block,
@ -84,7 +84,10 @@ pub struct Title<'a> {
/// # Example
///
/// ```
/// use ratatui::widgets::{block::*, *};
/// use ratatui::widgets::{
/// block::{Position, Title},
/// Block,
/// };
///
/// Block::new().title(Title::from("title").position(Position::Bottom));
/// ```

View file

@ -60,7 +60,11 @@ impl fmt::Debug for Borders {
/// ## Examples
///
/// ```
/// # use ratatui::{border, prelude::*, widgets::*};
/// use ratatui::{
/// border,
/// widgets::{Block, Borders},
/// };
///
/// Block::new()
/// .title("Construct Borders and use them in place")
/// .borders(border!(TOP, BOTTOM));
@ -69,7 +73,7 @@ impl fmt::Debug for Borders {
/// `border!` can be called with any number of individual sides:
///
/// ```
/// # use ratatui::{border, prelude::*, widgets::*};
/// use ratatui::{border, widgets::Borders};
/// let right_open = border!(TOP, LEFT, BOTTOM);
/// assert_eq!(right_open, Borders::TOP | Borders::LEFT | Borders::BOTTOM);
/// ```
@ -77,7 +81,8 @@ impl fmt::Debug for Borders {
/// Single borders work but using `Borders::` directly would be simpler.
///
/// ```
/// # use ratatui::{border, prelude::*, widgets::*};
/// use ratatui::{border, widgets::Borders};
///
/// assert_eq!(border!(TOP), Borders::TOP);
/// assert_eq!(border!(ALL), Borders::ALL);
/// assert_eq!(border!(), Borders::NONE);

View file

@ -12,7 +12,13 @@ use std::collections::HashMap;
use time::{Date, Duration, OffsetDateTime};
use crate::{prelude::*, widgets::Block};
use crate::{
buffer::Buffer,
layout::{Alignment, Constraint, Layout, Rect},
style::Style,
text::{Line, Span},
widgets::{block::BlockExt, Block, Widget, WidgetRef},
};
/// Display a month calendar for the month containing `display_date`
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
@ -46,6 +52,8 @@ impl<'a, DS: DateStyler> Monthly<'a, DS> {
///
/// `style` accepts any type that is convertible to [`Style`] (e.g. [`Style`], [`Color`], or
/// your own type that implements [`Into<Style>`]).
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn show_surrounding<S: Into<Style>>(mut self, style: S) -> Self {
self.show_surrounding = Some(style.into());
@ -56,6 +64,8 @@ impl<'a, DS: DateStyler> Monthly<'a, DS> {
///
/// `style` accepts any type that is convertible to [`Style`] (e.g. [`Style`], [`Color`], or
/// your own type that implements [`Into<Style>`]).
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn show_weekdays_header<S: Into<Style>>(mut self, style: S) -> Self {
self.show_weekday = Some(style.into());
@ -66,6 +76,8 @@ impl<'a, DS: DateStyler> Monthly<'a, DS> {
///
/// `style` accepts any type that is convertible to [`Style`] (e.g. [`Style`], [`Color`], or
/// your own type that implements [`Into<Style>`]).
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn show_month_header<S: Into<Style>>(mut self, style: S) -> Self {
self.show_month = Some(style.into());
@ -76,6 +88,8 @@ impl<'a, DS: DateStyler> Monthly<'a, DS> {
///
/// `style` accepts any type that is convertible to [`Style`] (e.g. [`Style`], [`Color`], or
/// your own type that implements [`Into<Style>`]).
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn default_style<S: Into<Style>>(mut self, style: S) -> Self {
self.default_style = style.into();
@ -201,6 +215,8 @@ impl CalendarEventStore {
///
/// `style` accepts any type that is convertible to [`Style`] (e.g. [`Style`], [`Color`], or
/// your own type that implements [`Into<Style>`]).
///
/// [`Color`]: crate::style::Color
pub fn today<S: Into<Style>>(style: S) -> Self {
let mut res = Self::default();
res.add(
@ -216,6 +232,8 @@ impl CalendarEventStore {
///
/// `style` accepts any type that is convertible to [`Style`] (e.g. [`Style`], [`Color`], or
/// your own type that implements [`Into<Style>`]).
///
/// [`Color`]: crate::style::Color
pub fn add<S: Into<Style>>(&mut self, date: Date, style: S) {
// to simplify style nonsense, last write wins
let _ = self.0.insert(date, style.into());
@ -250,6 +268,7 @@ mod tests {
use time::Month;
use super::*;
use crate::style::Color;
#[test]
fn event_store() {

View file

@ -30,7 +30,14 @@ pub use self::{
points::Points,
rectangle::Rectangle,
};
use crate::{prelude::*, symbols::Marker, text::Line as TextLine, widgets::Block};
use crate::{
buffer::Buffer,
layout::Rect,
style::{Color, Style},
symbols::{self, Marker},
text::Line as TextLine,
widgets::{block::BlockExt, Block, Widget, WidgetRef},
};
/// Something that can be drawn on a [`Canvas`].
///
@ -356,7 +363,10 @@ impl<'a, 'b> Painter<'a, 'b> {
/// # Examples
///
/// ```
/// use ratatui::{prelude::*, widgets::canvas::*};
/// use ratatui::{
/// symbols,
/// widgets::canvas::{Context, Painter},
/// };
///
/// let mut ctx = Context::new(2, 2, [1.0, 2.0], [0.0, 2.0], symbols::Marker::Braille);
/// let mut painter = Painter::from(&mut ctx);
@ -399,7 +409,11 @@ impl<'a, 'b> Painter<'a, 'b> {
/// # Example
///
/// ```
/// use ratatui::{prelude::*, widgets::canvas::*};
/// use ratatui::{
/// style::Color,
/// symbols,
/// widgets::canvas::{Context, Painter},
/// };
///
/// let mut ctx = Context::new(1, 1, [0.0, 2.0], [0.0, 2.0], symbols::Marker::Braille);
/// let mut painter = Painter::from(&mut ctx);
@ -425,7 +439,7 @@ impl<'a, 'b> From<&'a mut Context<'b>> for Painter<'a, 'b> {
/// This is used by the [`Canvas`] widget to draw shapes on the grid. It can be useful to think of
/// this as similar to the [`Frame`] struct that is used to draw widgets on the terminal.
///
/// [`Frame`]: crate::prelude::Frame
/// [`Frame`]: crate::Frame
#[derive(Debug)]
pub struct Context<'a> {
x_bounds: [f64; 2],
@ -449,7 +463,7 @@ impl<'a> Context<'a> {
/// example, if you want to draw a map of the world, you might want to use the following bounds:
///
/// ```
/// use ratatui::{prelude::*, widgets::canvas::*};
/// use ratatui::{symbols, widgets::canvas::Context};
///
/// let ctx = Context::new(
/// 100,
@ -513,6 +527,8 @@ impl<'a> Context<'a> {
///
/// Note that the text is always printed on top of the canvas and is **not** affected by the
/// layers.
///
/// [`Text`]: crate::text::Text
pub fn print<T>(&mut self, x: f64, y: f64, line: T)
where
T: Into<TextLine<'a>>,
@ -563,7 +579,10 @@ impl<'a> Context<'a> {
/// ```
/// use ratatui::{
/// style::Color,
/// widgets::{canvas::*, *},
/// widgets::{
/// canvas::{Canvas, Line, Map, MapResolution, Rectangle},
/// Block,
/// },
/// };
///
/// Canvas::default()
@ -698,7 +717,7 @@ where
/// # Examples
///
/// ```
/// use ratatui::{prelude::*, widgets::canvas::*};
/// use ratatui::{symbols, widgets::canvas::Canvas};
///
/// Canvas::default()
/// .marker(symbols::Marker::Braille)

View file

@ -65,7 +65,12 @@ mod tests {
use strum::ParseError;
use super::*;
use crate::{prelude::*, symbols::Marker, widgets::canvas::Canvas};
use crate::{
buffer::Buffer,
layout::Rect,
symbols::Marker,
widgets::{canvas::Canvas, Widget},
};
#[test]
fn map_resolution_to_string() {

View file

@ -3,7 +3,7 @@ use crate::{
widgets::canvas::{Line, Painter, Shape},
};
/// A rectangle to draw on a [`Canvas`](super::Canvas)
/// A rectangle to draw on a [`Canvas`](crate::widgets::canvas::Canvas)
///
/// Sizes used here are **not** in terminal cell. This is much more similar to the
/// mathematic coordinate system.
@ -66,7 +66,13 @@ impl Shape for Rectangle {
#[cfg(test)]
mod tests {
use super::*;
use crate::{prelude::*, symbols::Marker, widgets::canvas::Canvas};
use crate::{
buffer::Buffer,
layout::{Margin, Rect},
style::{Style, Stylize},
symbols::Marker,
widgets::{canvas::Canvas, Widget},
};
#[test]
fn draw_block_lines() {

View file

@ -3,12 +3,15 @@ use std::{cmp::max, ops::Not};
use strum::{Display, EnumString};
use crate::{
layout::Flex,
prelude::*,
style::Styled,
buffer::Buffer,
layout::{Alignment, Constraint, Flex, Layout, Position, Rect},
style::{Color, Style, Styled},
symbols::{self},
text::Line,
widgets::{
block::BlockExt,
canvas::{Canvas, Line as CanvasLine, Points},
Block,
Block, Widget, WidgetRef,
},
};
@ -25,7 +28,11 @@ use crate::{
/// # Example
///
/// ```rust
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// style::{Style, Stylize},
/// widgets::Axis,
/// };
///
/// let axis = Axis::default()
/// .title("X Axis")
/// .style(Style::default().gray())
@ -94,7 +101,8 @@ impl<'a> Axis<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{style::Stylize, widgets::Axis};
///
/// let axis = Axis::default()
/// .bounds([0.0, 50.0])
/// .labels(["0".bold(), "25".into(), "50".bold()]);
@ -122,7 +130,8 @@ impl<'a> Axis<'a> {
/// like so
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{style::Stylize, widgets::Axis};
///
/// let axis = Axis::default().red();
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -297,7 +306,11 @@ impl LegendPosition {
/// This example draws a red line between two points.
///
/// ```rust
/// use ratatui::{prelude::*, symbols::Marker, widgets::*};
/// use ratatui::{
/// style::Stylize,
/// symbols::Marker,
/// widgets::{Dataset, GraphType},
/// };
///
/// let dataset = Dataset::default()
/// .name("dataset 1")
@ -401,7 +414,8 @@ impl<'a> Dataset<'a> {
/// like so
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{style::Stylize, widgets::Dataset};
///
/// let dataset = Dataset::default().red();
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -452,7 +466,11 @@ struct ChartLayout {
/// # Examples
///
/// ```
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// style::{Style, Stylize},
/// symbols,
/// widgets::{Axis, Block, Chart, Dataset, GraphType},
/// };
///
/// // Create the datasets to fill the chart with
/// let datasets = vec![
@ -521,17 +539,19 @@ impl<'a> Chart<'a> {
/// This creates a simple chart with one [`Dataset`]
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// # let data_points = vec![];
/// use ratatui::widgets::{Chart, Dataset};
///
/// let data_points = vec![];
/// let chart = Chart::new(vec![Dataset::default().data(&data_points)]);
/// ```
///
/// This creates a chart with multiple [`Dataset`]s
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// # let data_points = vec![];
/// # let data_points2 = vec![];
/// use ratatui::widgets::{Chart, Dataset};
///
/// let data_points = vec![];
/// let data_points2 = vec![];
/// let chart = Chart::new(vec![
/// Dataset::default().data(&data_points),
/// Dataset::default().data(&data_points2),
@ -581,7 +601,8 @@ impl<'a> Chart<'a> {
/// # Example
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::{Axis, Chart};
///
/// let chart = Chart::new(vec![]).x_axis(
/// Axis::default()
/// .title("X Axis")
@ -604,7 +625,8 @@ impl<'a> Chart<'a> {
/// # Example
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::{Axis, Chart};
///
/// let chart = Chart::new(vec![]).y_axis(
/// Axis::default()
/// .title("Y Axis")
@ -635,7 +657,8 @@ impl<'a> Chart<'a> {
/// its height is greater than 25% of the total widget height.
///
/// ```
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{layout::Constraint, widgets::Chart};
///
/// let constraints = (Constraint::Ratio(1, 3), Constraint::Ratio(1, 4));
/// let chart = Chart::new(vec![]).hidden_legend_constraints(constraints);
/// ```
@ -644,7 +667,8 @@ impl<'a> Chart<'a> {
/// first one is always true.
///
/// ```
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{layout::Constraint, widgets::Chart};
///
/// let constraints = (Constraint::Min(0), Constraint::Ratio(1, 4));
/// let chart = Chart::new(vec![]).hidden_legend_constraints(constraints);
/// ```
@ -653,7 +677,8 @@ impl<'a> Chart<'a> {
/// [`Chart::legend_position`].
///
/// ```
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{layout::Constraint, widgets::Chart};
///
/// let constraints = (Constraint::Length(0), Constraint::Ratio(1, 4));
/// let chart = Chart::new(vec![]).hidden_legend_constraints(constraints);
/// ```
@ -685,14 +710,16 @@ impl<'a> Chart<'a> {
/// Show the legend on the top left corner.
///
/// ```
/// # use ratatui::widgets::{Chart, LegendPosition};
/// use ratatui::widgets::{Chart, LegendPosition};
///
/// let chart: Chart = Chart::new(vec![]).legend_position(Some(LegendPosition::TopLeft));
/// ```
///
/// Hide the legend altogether
///
/// ```
/// # use ratatui::widgets::{Chart, LegendPosition};
/// use ratatui::widgets::{Chart, LegendPosition};
///
/// let chart = Chart::new(vec![]).legend_position(None);
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -1134,6 +1161,7 @@ mod tests {
use strum::ParseError;
use super::*;
use crate::style::{Modifier, Stylize};
struct LegendTestCase {
chart_area: Rect,

View file

@ -1,4 +1,8 @@
use crate::prelude::*;
use crate::{
buffer::Buffer,
layout::Rect,
widgets::{Widget, WidgetRef},
};
/// A widget to clear/reset a certain area to allow overdrawing (e.g. for popups).
///
@ -8,7 +12,11 @@ use crate::prelude::*;
/// # Examples
///
/// ```
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// layout::Rect,
/// widgets::{Block, Clear},
/// Frame,
/// };
///
/// fn draw_on_clear(f: &mut Frame, area: Rect) {
/// let block = Block::bordered().title("Block");
@ -43,7 +51,7 @@ impl WidgetRef for Clear {
#[cfg(test)]
mod tests {
use super::*;
use crate::{buffer::Buffer, layout::Rect, widgets::Widget};
#[test]
fn render() {
let mut buffer = Buffer::with_lines(["xxxxxxxxxxxxxxx"; 7]);

View file

@ -1,4 +1,11 @@
use crate::{prelude::*, style::Styled, widgets::Block};
use crate::{
buffer::Buffer,
layout::Rect,
style::{Color, Style, Styled},
symbols::{self},
text::{Line, Span},
widgets::{block::BlockExt, Block, Widget, WidgetRef},
};
/// A widget to display a progress bar.
///
@ -16,16 +23,14 @@ use crate::{prelude::*, style::Styled, widgets::Block};
/// # Example
///
/// ```
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// style::{Style, Stylize},
/// widgets::{Block, Gauge},
/// };
///
/// Gauge::default()
/// .block(Block::bordered().title("Progress"))
/// .gauge_style(
/// Style::default()
/// .fg(Color::White)
/// .bg(Color::Black)
/// .add_modifier(Modifier::ITALIC),
/// )
/// .gauge_style(Style::new().white().on_black().italic())
/// .percent(20);
/// ```
///
@ -242,16 +247,15 @@ fn get_unicode_block<'a>(frac: f64) -> &'a str {
/// # Examples:
///
/// ```
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// style::{Style, Stylize},
/// symbols,
/// widgets::{Block, LineGauge},
/// };
///
/// LineGauge::default()
/// .block(Block::bordered().title("Progress"))
/// .filled_style(
/// Style::default()
/// .fg(Color::White)
/// .bg(Color::Black)
/// .add_modifier(Modifier::BOLD),
/// )
/// .filled_style(Style::new().white().on_black().bold())
/// .line_set(symbols::line::THICK)
/// .ratio(0.4);
/// ```
@ -443,7 +447,10 @@ impl<'a> Styled for LineGauge<'a> {
#[cfg(test)]
mod tests {
use super::*;
use crate::{
style::{Color, Modifier, Style, Stylize},
symbols,
};
#[test]
#[should_panic = "Percentage should be between 0 and 100 inclusively"]
fn gauge_invalid_percentage() {

View file

@ -1,4 +1,4 @@
use crate::prelude::*;
use crate::{style::Style, text::Text};
/// A single item in a [`List`]
///
@ -19,14 +19,15 @@ use crate::prelude::*;
/// You can create [`ListItem`]s from simple `&str`
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::ListItem;
/// let item = ListItem::new("Item 1");
/// ```
///
/// Anything that can be converted to [`Text`] can be a [`ListItem`].
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{text::Line, widgets::ListItem};
///
/// let item1: ListItem = "Item 1".into();
/// let item2: ListItem = Line::raw("Item 2").into();
/// ```
@ -34,7 +35,8 @@ use crate::prelude::*;
/// A [`ListItem`] styled with [`Stylize`]
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{style::Stylize, widgets::ListItem};
///
/// let item = ListItem::new("Item 1").red().on_white();
/// ```
///
@ -42,7 +44,12 @@ use crate::prelude::*;
/// [`Text`]
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// style::Stylize,
/// text::{Span, Text},
/// widgets::ListItem,
/// };
///
/// let mut text = Text::default();
/// text.extend(["Item".blue(), Span::raw(" "), "1".bold().red()]);
/// let item = ListItem::new(text);
@ -51,12 +58,15 @@ use crate::prelude::*;
/// A right-aligned `ListItem`
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// ListItem::new(Text::from("foo").alignment(Alignment::Right));
/// use ratatui::{text::Text, widgets::ListItem};
///
/// ListItem::new(Text::from("foo").right_aligned());
/// ```
///
/// [`List`]: crate::widgets::List
/// [`Stylize`]: crate::style::Stylize
/// [`Line`]: crate::text::Line
/// [`Line::alignment`]: crate::text::Line::alignment
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct ListItem<'a> {
pub(crate) content: Text<'a>,
@ -73,22 +83,25 @@ impl<'a> ListItem<'a> {
/// You can create [`ListItem`]s from simple `&str`
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::ListItem;
///
/// let item = ListItem::new("Item 1");
/// ```
///
/// Anything that can be converted to [`Text`] can be a [`ListItem`].
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{text::Line, widgets::ListItem};
///
/// let item1: ListItem = "Item 1".into();
/// let item2: ListItem = Line::raw("Item 2").into();
/// ```
///
/// You can also create multilines item
/// You can also create multiline items
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::ListItem;
///
/// let item = ListItem::new("Multi-line\nitem");
/// ```
///
@ -118,7 +131,11 @@ impl<'a> ListItem<'a> {
/// # Example
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// style::{Style, Stylize},
/// widgets::ListItem,
/// };
///
/// let item = ListItem::new("Item 1").style(Style::new().red().italic());
/// ```
///
@ -127,12 +144,14 @@ impl<'a> ListItem<'a> {
/// concisely.
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{style::Stylize, widgets::ListItem};
///
/// let item = ListItem::new("Item 1").red().italic();
/// ```
///
/// [`Styled`]: crate::style::Styled
/// [`ListState`]: crate::widgets::list::ListState
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
self.style = style.into();
@ -146,7 +165,8 @@ impl<'a> ListItem<'a> {
/// One line item
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::ListItem;
///
/// let item = ListItem::new("Item 1");
/// assert_eq!(item.height(), 1);
/// ```
@ -154,7 +174,8 @@ impl<'a> ListItem<'a> {
/// Two lines item (note the `\n`)
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::ListItem;
///
/// let item = ListItem::new("Multi-line\nitem");
/// assert_eq!(item.height(), 2);
/// ```
@ -167,13 +188,15 @@ impl<'a> ListItem<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::ListItem;
///
/// let item = ListItem::new("12345");
/// assert_eq!(item.width(), 5);
/// ```
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::ListItem;
///
/// let item = ListItem::new("12345\n1234567");
/// assert_eq!(item.width(), 7);
/// ```
@ -198,6 +221,10 @@ mod tests {
use pretty_assertions::assert_eq;
use super::*;
use crate::{
style::{Color, Modifier, Stylize},
text::{Line, Span},
};
#[test]
fn new_from_str() {

View file

@ -1,10 +1,8 @@
use strum::{Display, EnumString};
use super::ListItem;
use crate::{
prelude::*,
style::Styled,
widgets::{Block, HighlightSpacing},
style::{Style, Styled},
widgets::{Block, HighlightSpacing, ListItem},
};
/// A widget to display several items among which one can be selected (optional)
@ -41,14 +39,20 @@ use crate::{
/// # Examples
///
/// ```
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// layout::Rect,
/// style::{Style, Stylize},
/// widgets::{Block, List, ListDirection, ListItem},
/// Frame,
/// };
///
/// # fn ui(frame: &mut Frame) {
/// # let area = Rect::default();
/// let items = ["Item 1", "Item 2", "Item 3"];
/// let list = List::new(items)
/// .block(Block::bordered().title("List"))
/// .style(Style::default().fg(Color::White))
/// .highlight_style(Style::default().add_modifier(Modifier::ITALIC))
/// .style(Style::new().white())
/// .highlight_style(Style::new().italic())
/// .highlight_symbol(">>")
/// .repeat_highlight_symbol(true)
/// .direction(ListDirection::BottomToTop);
@ -60,7 +64,13 @@ use crate::{
/// # Stateful example
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// layout::Rect,
/// style::{Style, Stylize},
/// widgets::{Block, List, ListState},
/// Frame,
/// };
///
/// # fn ui(frame: &mut Frame) {
/// # let area = Rect::default();
/// // This should be stored outside of the function in your application state.
@ -68,7 +78,7 @@ use crate::{
/// let items = ["Item 1", "Item 2", "Item 3"];
/// let list = List::new(items)
/// .block(Block::bordered().title("List"))
/// .highlight_style(Style::new().add_modifier(Modifier::REVERSED))
/// .highlight_style(Style::new().reversed())
/// .highlight_symbol(">>")
/// .repeat_highlight_symbol(true);
///
@ -88,6 +98,9 @@ use crate::{
/// [`ListState`]: crate::widgets::list::ListState
/// [scroll]: crate::widgets::list::ListState::offset
/// [select]: crate::widgets::list::ListState::select
/// [`Text::alignment`]: crate::text::Text::alignment
/// [`StatefulWidget`]: crate::widgets::StatefulWidget
/// [`Widget`]: crate::widgets::Widget
#[derive(Debug, Clone, Eq, PartialEq, Hash, Default)]
pub struct List<'a> {
/// An optional block to wrap the widget in
@ -135,17 +148,23 @@ impl<'a> List<'a> {
/// From a slice of [`&str`]
///
/// ```
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::List;
///
/// let list = List::new(["Item 1", "Item 2"]);
/// ```
///
/// From [`Text`]
///
/// ```
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// style::{Style, Stylize},
/// text::Text,
/// widgets::List,
/// };
///
/// let list = List::new([
/// Text::styled("Item 1", Style::default().red()),
/// Text::styled("Item 2", Style::default().red()),
/// Text::styled("Item 1", Style::new().red()),
/// Text::styled("Item 2", Style::new().red()),
/// ]);
/// ```
///
@ -153,10 +172,13 @@ impl<'a> List<'a> {
/// [`List::items`] fluent setter.
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::List;
///
/// let empty_list = List::default();
/// let filled_list = empty_list.items(["Item 1"]);
/// ```
///
/// [`Text`]: crate::text::Text
pub fn new<T>(items: T) -> Self
where
T: IntoIterator,
@ -181,9 +203,12 @@ impl<'a> List<'a> {
/// # Example
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::List;
///
/// let list = List::default().items(["Item 1", "Item 2"]);
/// ```
///
/// [`Text`]: crate::text::Text
#[must_use = "method moves the value of self and returns the modified value"]
pub fn items<T>(mut self, items: T) -> Self
where
@ -203,8 +228,9 @@ impl<'a> List<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// # let items = ["Item 1"];
/// use ratatui::widgets::{Block, List};
///
/// let items = ["Item 1"];
/// let block = Block::bordered().title("List");
/// let list = List::new(items).block(block);
/// ```
@ -227,8 +253,12 @@ impl<'a> List<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// # let items = ["Item 1"];
/// use ratatui::{
/// style::{Style, Stylize},
/// widgets::List,
/// };
///
/// let items = ["Item 1"];
/// let list = List::new(items).style(Style::new().red().italic());
/// ```
///
@ -238,10 +268,13 @@ impl<'a> List<'a> {
/// [`Stylize`]: crate::style::Stylize
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// # let items = ["Item 1"];
/// use ratatui::{style::Stylize, widgets::List};
///
/// let items = ["Item 1"];
/// let list = List::new(items).red().italic();
/// ```
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
self.style = style.into();
@ -257,8 +290,9 @@ impl<'a> List<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// # let items = ["Item 1", "Item 2"];
/// use ratatui::widgets::List;
///
/// let items = ["Item 1", "Item 2"];
/// let list = List::new(items).highlight_symbol(">>");
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -281,10 +315,16 @@ impl<'a> List<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// # let items = ["Item 1", "Item 2"];
/// use ratatui::{
/// style::{Style, Stylize},
/// widgets::List,
/// };
///
/// let items = ["Item 1", "Item 2"];
/// let list = List::new(items).highlight_style(Style::new().red().italic());
/// ```
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn highlight_style<S: Into<Style>>(mut self, style: S) -> Self {
self.highlight_style = style.into();
@ -323,8 +363,9 @@ impl<'a> List<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// # let items = ["Item 1"];
/// use ratatui::widgets::{HighlightSpacing, List};
///
/// let items = ["Item 1"];
/// let list = List::new(items).highlight_spacing(HighlightSpacing::Always);
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -345,8 +386,9 @@ impl<'a> List<'a> {
/// Bottom to top
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// # let items = ["Item 1"];
/// use ratatui::widgets::{List, ListDirection};
///
/// let items = ["Item 1"];
/// let list = List::new(items).direction(ListDirection::BottomToTop);
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -364,8 +406,9 @@ impl<'a> List<'a> {
/// A padding value of 1 will keep 1 item above and 1 item bellow visible if possible
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// # let items = ["Item 1"];
/// use ratatui::widgets::List;
///
/// let items = ["Item 1"];
/// let list = List::new(items).scroll_padding(1);
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -423,6 +466,7 @@ mod tests {
use pretty_assertions::assert_eq;
use super::*;
use crate::style::{Color, Modifier, Stylize};
#[test]
fn collect_list_from_iterator() {

View file

@ -1,8 +1,12 @@
use unicode_width::UnicodeWidthStr;
use crate::{
prelude::{Buffer, Rect, StatefulWidget, StatefulWidgetRef, Widget, WidgetRef},
widgets::{block::BlockExt, List, ListDirection, ListState},
buffer::Buffer,
layout::Rect,
widgets::{
block::BlockExt, List, ListDirection, ListState, StatefulWidget, StatefulWidgetRef, Widget,
WidgetRef,
},
};
impl Widget for List<'_> {
@ -273,8 +277,12 @@ mod tests {
use super::*;
use crate::{
prelude::*,
widgets::{Block, HighlightSpacing, ListItem},
backend,
layout::{Alignment, Rect},
style::{Color, Modifier, Style, Stylize},
text::Line,
widgets::{Block, HighlightSpacing, ListItem, StatefulWidget, Widget},
Terminal,
};
#[fixture]

View file

@ -20,10 +20,15 @@
/// # Example
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// layout::Rect,
/// widgets::{List, ListState},
/// Frame,
/// };
///
/// # fn ui(frame: &mut Frame) {
/// # let area = Rect::default();
/// # let items = ["Item 1"];
/// let items = ["Item 1"];
/// let list = List::new(items);
///
/// // This should be stored outside of the function in your application state.
@ -52,7 +57,8 @@ impl ListState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::ListState;
///
/// let state = ListState::default().with_offset(1);
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -68,7 +74,8 @@ impl ListState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::ListState;
///
/// let state = ListState::default().with_selected(Some(1));
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -82,7 +89,8 @@ impl ListState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::ListState;
///
/// let state = ListState::default();
/// assert_eq!(state.offset(), 0);
/// ```
@ -95,7 +103,8 @@ impl ListState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::ListState;
///
/// let mut state = ListState::default();
/// *state.offset_mut() = 1;
/// ```
@ -110,8 +119,9 @@ impl ListState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// let state = TableState::default();
/// use ratatui::widgets::ListState;
///
/// let state = ListState::default();
/// assert_eq!(state.selected(), None);
/// ```
pub const fn selected(&self) -> Option<usize> {
@ -125,7 +135,8 @@ impl ListState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::ListState;
///
/// let mut state = ListState::default();
/// *state.selected_mut() = Some(1);
/// ```
@ -140,7 +151,8 @@ impl ListState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::ListState;
///
/// let mut state = ListState::default();
/// state.select(Some(1));
/// ```
@ -159,7 +171,8 @@ impl ListState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::ListState;
///
/// let mut state = ListState::default();
/// state.select_next();
/// ```
@ -176,7 +189,8 @@ impl ListState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::ListState;
///
/// let mut state = ListState::default();
/// state.select_previous();
/// ```
@ -193,7 +207,8 @@ impl ListState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::ListState;
///
/// let mut state = ListState::default();
/// state.select_first();
/// ```
@ -209,7 +224,8 @@ impl ListState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::ListState;
///
/// let mut state = ListState::default();
/// state.select_last();
/// ```
@ -226,7 +242,8 @@ impl ListState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::ListState;
///
/// let mut state = ListState::default();
/// state.scroll_down_by(4);
/// ```
@ -244,7 +261,8 @@ impl ListState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::ListState;
///
/// let mut state = ListState::default();
/// state.scroll_up_by(4);
/// ```

View file

@ -1,12 +1,14 @@
use unicode_width::UnicodeWidthStr;
use crate::{
prelude::*,
style::Styled,
text::StyledGrapheme,
buffer::Buffer,
layout::{Alignment, Position, Rect},
style::{Style, Styled},
text::{Line, StyledGrapheme, Text},
widgets::{
block::BlockExt,
reflow::{LineComposer, LineTruncator, WordWrapper, WrappedLine},
Block,
Block, Widget, WidgetRef,
},
};
@ -59,7 +61,12 @@ const fn get_line_offset(line_width: u16, text_area_width: u16, alignment: Align
/// # Example
///
/// ```
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// layout::Alignment,
/// style::{Style, Stylize},
/// text::{Line, Span},
/// widgets::{Block, Paragraph, Wrap},
/// };
///
/// let text = vec![
/// Line::from(vec![
@ -76,6 +83,8 @@ const fn get_line_offset(line_width: u16, text_area_width: u16, alignment: Align
/// .alignment(Alignment::Center)
/// .wrap(Wrap { trim: true });
/// ```
///
/// [`Span`]: crate::text::Span
#[derive(Debug, Default, Clone, Eq, PartialEq, Hash)]
pub struct Paragraph<'a> {
/// A block to wrap the widget in
@ -97,7 +106,10 @@ pub struct Paragraph<'a> {
/// ## Examples
///
/// ```
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// text::Text,
/// widgets::{Paragraph, Wrap},
/// };
///
/// let bullet_points = Text::from(
/// r#"Some indented points:
@ -139,7 +151,12 @@ impl<'a> Paragraph<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// style::{Style, Stylize},
/// text::{Line, Text},
/// widgets::Paragraph,
/// };
///
/// let paragraph = Paragraph::new("Hello, world!");
/// let paragraph = Paragraph::new(String::from("Hello, world!"));
/// let paragraph = Paragraph::new(Text::raw("Hello, world!"));
@ -165,7 +182,8 @@ impl<'a> Paragraph<'a> {
/// # Example
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::{Block, Paragraph};
///
/// let paragraph = Paragraph::new("Hello, world!").block(Block::bordered().title("Paragraph"));
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -185,9 +203,15 @@ impl<'a> Paragraph<'a> {
/// # Example
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// style::{Style, Stylize},
/// widgets::Paragraph,
/// };
///
/// let paragraph = Paragraph::new("Hello, world!").style(Style::new().red().on_white());
/// ```
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
self.style = style.into();
@ -201,7 +225,8 @@ impl<'a> Paragraph<'a> {
/// # Example
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::{Paragraph, Wrap};
///
/// let paragraph = Paragraph::new("Hello, world!").wrap(Wrap { trim: true });
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -238,7 +263,8 @@ impl<'a> Paragraph<'a> {
/// # Example
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{layout::Alignment, widgets::Paragraph};
///
/// let paragraph = Paragraph::new("Hello World").alignment(Alignment::Center);
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -254,7 +280,8 @@ impl<'a> Paragraph<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::Paragraph;
///
/// let paragraph = Paragraph::new("Hello World").left_aligned();
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -269,7 +296,8 @@ impl<'a> Paragraph<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::Paragraph;
///
/// let paragraph = Paragraph::new("Hello World").centered();
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -284,7 +312,8 @@ impl<'a> Paragraph<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::Paragraph;
///
/// let paragraph = Paragraph::new("Hello World").right_aligned();
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -305,7 +334,8 @@ impl<'a> Paragraph<'a> {
/// # Example
///
/// ```ignore
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{widgets::{Paragraph, Wrap}};
///
/// let paragraph = Paragraph::new("Hello World")
/// .wrap(Wrap { trim: false });
/// assert_eq!(paragraph.line_count(20), 1);
@ -359,7 +389,8 @@ impl<'a> Paragraph<'a> {
/// # Example
///
/// ```ignore
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{widgets::Paragraph};
///
/// let paragraph = Paragraph::new("Hello World");
/// assert_eq!(paragraph.line_width(), 11);
///
@ -473,7 +504,12 @@ mod test {
use super::*;
use crate::{
backend::TestBackend,
widgets::{block::Position, Borders},
buffer::Buffer,
layout::{Alignment, Rect},
style::{Color, Modifier, Style, Stylize},
text::{Line, Span, Text},
widgets::{block::Position, Borders, Widget},
Terminal,
};
/// Tests the [`Paragraph`] widget against the expected [`Buffer`] by rendering it onto an equal

View file

@ -12,8 +12,11 @@ use strum::{Display, EnumString};
use unicode_width::UnicodeWidthStr;
use crate::{
prelude::*,
buffer::Buffer,
layout::Rect,
style::Style,
symbols::scrollbar::{Set, DOUBLE_HORIZONTAL, DOUBLE_VERTICAL},
widgets::StatefulWidget,
};
/// A widget to display a scrollbar
@ -39,7 +42,15 @@ use crate::{
/// # Examples
///
/// ```rust
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// layout::{Margin, Rect},
/// text::Line,
/// widgets::{
/// Block, Borders, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState,
/// StatefulWidget,
/// },
/// Frame,
/// };
///
/// # fn render_paragraph_with_scrollbar(frame: &mut Frame, area: Rect) {
/// let vertical_scroll = 0; // from app state
@ -254,6 +265,8 @@ impl<'a> Scrollbar<'a> {
/// your own type that implements [`Into<Style>`]).
///
/// This is a fluent setter method which must be chained or used as it consumes self
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn thumb_style<S: Into<Style>>(mut self, thumb_style: S) -> Self {
self.thumb_style = thumb_style.into();
@ -279,6 +292,8 @@ impl<'a> Scrollbar<'a> {
/// your own type that implements [`Into<Style>`]).
///
/// This is a fluent setter method which must be chained or used as it consumes self
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn track_style<S: Into<Style>>(mut self, track_style: S) -> Self {
self.track_style = track_style.into();
@ -304,6 +319,8 @@ impl<'a> Scrollbar<'a> {
/// your own type that implements [`Into<Style>`]).
///
/// This is a fluent setter method which must be chained or used as it consumes self
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn begin_style<S: Into<Style>>(mut self, begin_style: S) -> Self {
self.begin_style = begin_style.into();
@ -329,6 +346,8 @@ impl<'a> Scrollbar<'a> {
/// your own type that implements [`Into<Style>`]).
///
/// This is a fluent setter method which must be chained or used as it consumes self
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn end_style<S: Into<Style>>(mut self, end_style: S) -> Self {
self.end_style = end_style.into();
@ -382,6 +401,8 @@ impl<'a> Scrollbar<'a> {
/// ```
///
/// This is a fluent setter method which must be chained or used as it consumes self
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
let style = style.into();
@ -621,6 +642,7 @@ mod tests {
use strum::ParseError;
use super::*;
use crate::{text::Text, widgets::Widget};
#[test]
fn scroll_direction_to_string() {

View file

@ -2,7 +2,13 @@ use std::cmp::min;
use strum::{Display, EnumString};
use crate::{prelude::*, style::Styled, widgets::Block};
use crate::{
buffer::Buffer,
layout::Rect,
style::{Style, Styled},
symbols::{self},
widgets::{block::BlockExt, Block, Widget, WidgetRef},
};
/// Widget to render a sparkline over one or more lines.
///
@ -21,7 +27,10 @@ use crate::{prelude::*, style::Styled, widgets::Block};
/// # Examples
///
/// ```
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// style::{Style, Stylize},
/// widgets::{Block, RenderDirection, Sparkline},
/// };
///
/// Sparkline::default()
/// .block(Block::bordered().title("Sparkline"))
@ -73,6 +82,8 @@ impl<'a> Sparkline<'a> {
/// your own type that implements [`Into<Style>`]).
///
/// The foreground corresponds to the bars while the background is everything else.
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
self.style = style.into();
@ -84,7 +95,8 @@ impl<'a> Sparkline<'a> {
/// # Example
///
/// ```
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{layout::Rect, widgets::Sparkline, Frame};
///
/// # fn ui(frame: &mut Frame) {
/// # let area = Rect::default();
/// let sparkline = Sparkline::default().data(&[1, 2, 3]);
@ -211,7 +223,10 @@ mod tests {
use strum::ParseError;
use super::*;
use crate::buffer::Cell;
use crate::{
buffer::Cell,
style::{Color, Modifier, Stylize},
};
#[test]
fn render_direction_to_string() {

View file

@ -1,4 +1,10 @@
use crate::{prelude::*, style::Styled};
use crate::{
buffer::Buffer,
layout::Rect,
style::{Style, Styled},
text::Text,
widgets::WidgetRef,
};
/// A [`Cell`] contains the [`Text`] to be displayed in a [`Row`] of a [`Table`].
///
@ -16,13 +22,17 @@ use crate::{prelude::*, style::Styled};
/// ```rust
/// use std::borrow::Cow;
///
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// style::Stylize,
/// text::{Line, Span, Text},
/// widgets::Cell,
/// };
///
/// Cell::from("simple string");
/// Cell::from(Span::from("span"));
/// Cell::from(Line::from(vec![
/// Span::raw("a vec of "),
/// Span::styled("spans", Style::default().add_modifier(Modifier::BOLD)),
/// Span::from("a vec of "),
/// Span::from("spans").bold(),
/// ]));
/// Cell::from(Text::from("a text"));
/// Cell::from(Text::from(Cow::Borrowed("hello")));
@ -32,12 +42,14 @@ use crate::{prelude::*, style::Styled};
/// to set the style of the cell concisely.
///
/// ```rust
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{style::Stylize, widgets::Cell};
///
/// Cell::new("Cell 1").red().italic();
/// ```
///
/// [`Row`]: super::Row
/// [`Table`]: super::Table
/// [`Row`]: crate::widgets::Row
/// [`Table`]: crate::widgets::Table
/// [`Stylize`]: crate::style::Stylize
#[derive(Debug, Default, Clone, Eq, PartialEq, Hash)]
pub struct Cell<'a> {
content: Text<'a>,
@ -52,12 +64,17 @@ impl<'a> Cell<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// style::Stylize,
/// text::{Line, Span, Text},
/// widgets::Cell,
/// };
///
/// Cell::new("simple string");
/// Cell::new(Span::from("span"));
/// Cell::new(Line::from(vec![
/// Span::raw("a vec of "),
/// Span::styled("spans", Style::default().add_modifier(Modifier::BOLD)),
/// Span::from("spans").bold(),
/// ]));
/// Cell::new(Text::from("a text"));
/// ```
@ -80,12 +97,17 @@ impl<'a> Cell<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// style::Stylize,
/// text::{Line, Span, Text},
/// widgets::Cell,
/// };
///
/// Cell::default().content("simple string");
/// Cell::default().content(Span::from("span"));
/// Cell::default().content(Line::from(vec![
/// Span::raw("a vec of "),
/// Span::styled("spans", Style::new().bold()),
/// Span::from("spans").bold(),
/// ]));
/// Cell::default().content(Text::from("a text"));
/// ```
@ -111,7 +133,11 @@ impl<'a> Cell<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// style::{Style, Stylize},
/// widgets::Cell,
/// };
///
/// Cell::new("Cell 1").style(Style::new().red().italic());
/// ```
///
@ -119,11 +145,14 @@ impl<'a> Cell<'a> {
/// the [`Stylize`] trait to set the style of the widget more concisely.
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{style::Stylize, widgets::Cell};
///
/// Cell::new("Cell 1").red().italic();
/// ```
///
/// [`Row`]: super::Row
/// [`Row`]: crate::widgets::Row
/// [`Color`]: crate::style::Color
/// [`Stylize`]: crate::style::Stylize
#[must_use = "method moves the value of self and returns the modified value"]
pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
self.style = style.into();
@ -165,6 +194,7 @@ impl<'a> Styled for Cell<'a> {
#[cfg(test)]
mod tests {
use super::*;
use crate::style::{Color, Modifier, Stylize};
#[test]
fn new() {

View file

@ -1,5 +1,7 @@
use super::Cell;
use crate::{prelude::*, style::Styled};
use crate::{
style::{Style, Styled},
widgets::table::Cell,
};
/// A single row of data to be displayed in a [`Table`] widget.
///
@ -16,7 +18,7 @@ use crate::{prelude::*, style::Styled};
/// You can create `Row`s from simple strings.
///
/// ```rust
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::Row;
///
/// Row::new(vec!["Cell1", "Cell2", "Cell3"]);
/// ```
@ -24,11 +26,14 @@ use crate::{prelude::*, style::Styled};
/// If you need a bit more control over individual cells, you can explicitly create [`Cell`]s:
///
/// ```rust
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// style::Stylize,
/// widgets::{Cell, Row},
/// };
///
/// Row::new(vec![
/// Cell::from("Cell1"),
/// Cell::from("Cell2").style(Style::default().fg(Color::Yellow)),
/// Cell::from("Cell2").red().italic(),
/// ]);
/// ```
///
@ -37,7 +42,7 @@ use crate::{prelude::*, style::Styled};
/// ```rust
/// use std::borrow::Cow;
///
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::{Cell, Row};
///
/// Row::new(vec![
/// Cow::Borrowed("hello"),
@ -57,12 +62,15 @@ use crate::{prelude::*, style::Styled};
/// to set the style of the row concisely.
///
/// ```rust
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{style::Stylize, widgets::Row};
///
/// let cells = vec!["Cell1", "Cell2", "Cell3"];
/// Row::new(cells).red().italic();
/// ```
///
/// [`Table`]: super::Table
/// [`Table`]: crate::widgets::Table
/// [`Text`]: crate::text::Text
/// [`Stylize`]: crate::style::Stylize
#[derive(Debug, Default, Clone, Eq, PartialEq, Hash)]
pub struct Row<'a> {
pub(crate) cells: Vec<Cell<'a>>,
@ -81,7 +89,8 @@ impl<'a> Row<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::{Cell, Row};
///
/// let row = Row::new(vec!["Cell 1", "Cell 2", "Cell 3"]);
/// let row = Row::new(vec![
/// Cell::new("Cell 1"),
@ -111,7 +120,8 @@ impl<'a> Row<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::{Cell, Row};
///
/// let row = Row::default().cells(vec!["Cell 1", "Cell 2", "Cell 3"]);
/// let row = Row::default().cells(vec![
/// Cell::new("Cell 1"),
@ -140,7 +150,8 @@ impl<'a> Row<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::Row;
///
/// let cells = vec!["Cell 1\nline 2", "Cell 2", "Cell 3"];
/// let row = Row::new(cells).height(2);
/// ```
@ -159,8 +170,9 @@ impl<'a> Row<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// # let cells = vec!["Cell 1", "Cell 2", "Cell 3"];
/// use ratatui::widgets::Row;
/// let cells = vec!["Cell 1", "Cell 2", "Cell 3"];
///
/// let row = Row::default().top_margin(1);
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -178,8 +190,9 @@ impl<'a> Row<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// # let cells = vec!["Cell 1", "Cell 2", "Cell 3"];
/// use ratatui::widgets::Row;
///
/// let cells = vec!["Cell 1", "Cell 2", "Cell 3"];
/// let row = Row::default().bottom_margin(1);
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -201,7 +214,10 @@ impl<'a> Row<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// style::{Style, Stylize},
/// widgets::Row,
/// };
/// let cells = vec!["Cell 1", "Cell 2", "Cell 3"];
/// let row = Row::new(cells).style(Style::new().red().italic());
/// ```
@ -210,10 +226,15 @@ impl<'a> Row<'a> {
/// the [`Stylize`] trait to set the style of the widget more concisely.
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{style::Stylize, widgets::Row};
///
/// let cells = vec!["Cell 1", "Cell 2", "Cell 3"];
/// let row = Row::new(cells).red().italic();
/// ```
///
/// [`Color`]: crate::style::Color
/// [`Stylize`]: crate::style::Stylize
/// [`Text`]: crate::text::Text
#[must_use = "method moves the value of self and returns the modified value"]
pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
self.style = style.into();
@ -257,6 +278,7 @@ mod tests {
use std::vec;
use super::*;
use crate::style::{Color, Modifier, Stylize};
#[test]
fn new() {

View file

@ -1,9 +1,18 @@
use itertools::Itertools;
#[allow(unused_imports)] // `Cell` is used in the doc comment but not the code
use super::Cell;
use super::{HighlightSpacing, Row, TableState};
use crate::{layout::Flex, prelude::*, style::Styled, widgets::Block};
use crate::widgets::table::Cell;
use crate::{
buffer::Buffer,
layout::{Constraint, Flex, Layout, Rect},
style::{Style, Styled},
text::Text,
widgets::{
block::BlockExt,
table::{HighlightSpacing, Row, TableState},
Block, StatefulWidget, StatefulWidgetRef, Widget, WidgetRef,
},
};
/// A widget to display data in formatted columns.
///
@ -55,7 +64,11 @@ use crate::{layout::Flex, prelude::*, style::Styled, widgets::Block};
/// # Example
///
/// ```rust
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// layout::Constraint,
/// style::{Style, Stylize},
/// widgets::{Block, Row, Table},
/// };
///
/// let rows = [Row::new(vec!["Cell1", "Cell2", "Cell3"])];
/// // Columns widths are constrained in the same way as Layout...
@ -90,7 +103,12 @@ use crate::{layout::Flex, prelude::*, style::Styled, widgets::Block};
/// bottom margin, and style. See [`Row`] for more details.
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// style::{Style, Stylize},
/// text::{Line, Span},
/// widgets::{Cell, Row, Table},
/// };
///
/// // a Row can be created from simple strings.
/// let row = Row::new(vec!["Row11", "Row12", "Row13"]);
///
@ -100,11 +118,8 @@ use crate::{layout::Flex, prelude::*, style::Styled, widgets::Block};
/// // If you need more control over the styling, create Cells directly
/// let row = Row::new(vec![
/// Cell::from("Row31"),
/// Cell::from("Row32").style(Style::default().fg(Color::Yellow)),
/// Cell::from(Line::from(vec![
/// Span::raw("Row"),
/// Span::styled("33", Style::default().fg(Color::Green)),
/// ])),
/// Cell::from("Row32").style(Style::new().yellow()),
/// Cell::from(Line::from(vec![Span::raw("Row"), Span::from("33").green()])),
/// ]);
///
/// // If a Row need to display some content over multiple lines, specify the height.
@ -120,14 +135,19 @@ use crate::{layout::Flex, prelude::*, style::Styled, widgets::Block};
/// details.
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// style::{Style, Stylize},
/// text::{Line, Span, Text},
/// widgets::Cell,
/// };
///
/// Cell::from("simple string");
/// Cell::from("simple styled span".red());
/// Cell::from(Span::raw("raw span"));
/// Cell::from(Span::styled("styled span", Style::new().red()));
/// Cell::from(Line::from(vec![
/// Span::raw("a vec of "),
/// Span::styled("spans", Style::new().bold()),
/// Span::from("spans").bold(),
/// ]));
/// Cell::from(Text::from("text"));
/// ```
@ -137,7 +157,10 @@ use crate::{layout::Flex, prelude::*, style::Styled, widgets::Block};
/// These default columns widths can be overridden using the `Table::widths` method.
///
/// ```rust
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// layout::Constraint,
/// widgets::{Row, Table},
/// };
///
/// let text = "Mary had a\nlittle lamb.";
///
@ -152,7 +175,11 @@ use crate::{layout::Flex, prelude::*, style::Styled, widgets::Block};
/// the [`Stylize`] trait to set the style of the widget more concisely.
///
/// ```rust
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// layout::Constraint,
/// style::Stylize,
/// widgets::{Row, Table},
/// };
///
/// let rows = [Row::new(vec!["Cell1", "Cell2", "Cell3"])];
/// let widths = [
@ -169,7 +196,13 @@ use crate::{layout::Flex, prelude::*, style::Styled, widgets::Block};
/// user to scroll through the rows and select one of them.
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// layout::{Constraint, Rect},
/// style::{Style, Stylize},
/// widgets::{Block, Row, Table, TableState},
/// Frame,
/// };
///
/// # fn ui(frame: &mut Frame) {
/// # let area = Rect::default();
/// // Note: TableState should be stored in your application state (not constructed in your render
@ -187,12 +220,15 @@ use crate::{layout::Flex, prelude::*, style::Styled, widgets::Block};
/// ];
/// let table = Table::new(rows, widths)
/// .block(Block::new().title("Table"))
/// .highlight_style(Style::new().add_modifier(Modifier::REVERSED))
/// .highlight_style(Style::new().reversed())
/// .highlight_symbol(">>");
///
/// frame.render_stateful_widget(table, area, &mut table_state);
/// # }
/// ```
///
/// [`Frame::render_widget`]: crate::Frame::render_widget
/// [`Stylize`]: crate::style::Stylize
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Table<'a> {
/// Data to display in each row
@ -261,7 +297,11 @@ impl<'a> Table<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// layout::Constraint,
/// widgets::{Row, Table},
/// };
///
/// let rows = [
/// Row::new(vec!["Cell1", "Cell2"]),
/// Row::new(vec!["Cell3", "Cell4"]),
@ -302,7 +342,8 @@ impl<'a> Table<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::{Row, Table};
///
/// let rows = [
/// Row::new(vec!["Cell1", "Cell2"]),
/// Row::new(vec!["Cell3", "Cell4"]),
@ -327,7 +368,8 @@ impl<'a> Table<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::{Cell, Row, Table};
///
/// let header = Row::new(vec![
/// Cell::from("Header Cell 1"),
/// Cell::from("Header Cell 2"),
@ -349,7 +391,8 @@ impl<'a> Table<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::{Cell, Row, Table};
///
/// let footer = Row::new(vec![
/// Cell::from("Footer Cell 1"),
/// Cell::from("Footer Cell 2"),
@ -376,7 +419,11 @@ impl<'a> Table<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// layout::Constraint,
/// widgets::{Cell, Row, Table},
/// };
///
/// let table = Table::default().widths([Constraint::Length(5), Constraint::Length(5)]);
/// let table = Table::default().widths(vec![Constraint::Length(5); 2]);
///
@ -403,9 +450,13 @@ impl<'a> Table<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// # let rows = [Row::new(vec!["Cell1", "Cell2"])];
/// # let widths = [Constraint::Length(5), Constraint::Length(5)];
/// use ratatui::{
/// layout::Constraint,
/// widgets::{Row, Table},
/// };
///
/// let rows = [Row::new(vec!["Cell1", "Cell2"])];
/// let widths = [Constraint::Length(5), Constraint::Length(5)];
/// let table = Table::new(rows, widths).column_spacing(1);
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -424,9 +475,13 @@ impl<'a> Table<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// # let rows = [Row::new(vec!["Cell1", "Cell2"])];
/// # let widths = [Constraint::Length(5), Constraint::Length(5)];
/// use ratatui::{
/// layout::Constraint,
/// widgets::{Block, Cell, Row, Table},
/// };
///
/// let rows = [Row::new(vec!["Cell1", "Cell2"])];
/// let widths = [Constraint::Length(5), Constraint::Length(5)];
/// let block = Block::bordered().title("Table");
/// let table = Table::new(rows, widths).block(block);
/// ```
@ -449,7 +504,12 @@ impl<'a> Table<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// layout::Constraint,
/// style::{Style, Stylize},
/// widgets::{Row, Table},
/// };
///
/// # let rows = [Row::new(vec!["Cell1", "Cell2"])];
/// # let widths = [Constraint::Length(5), Constraint::Length(5)];
/// let table = Table::new(rows, widths).style(Style::new().red().italic());
@ -459,11 +519,19 @@ impl<'a> Table<'a> {
/// the [`Stylize`] trait to set the style of the widget more concisely.
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// layout::Constraint,
/// style::Stylize,
/// widgets::{Cell, Row, Table},
/// };
///
/// # let rows = [Row::new(vec!["Cell1", "Cell2"])];
/// # let widths = vec![Constraint::Length(5), Constraint::Length(5)];
/// let table = Table::new(rows, widths).red().italic();
/// ```
///
/// [`Color`]: crate::style::Color
/// [`Stylize`]: crate::style::Stylize
#[must_use = "method moves the value of self and returns the modified value"]
pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
self.style = style.into();
@ -483,11 +551,18 @@ impl<'a> Table<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// # let rows = [Row::new(vec!["Cell1", "Cell2"])];
/// # let widths = [Constraint::Length(5), Constraint::Length(5)];
/// use ratatui::{
/// layout::Constraint,
/// style::{Style, Stylize},
/// widgets::{Cell, Row, Table},
/// };
///
/// let rows = [Row::new(vec!["Cell1", "Cell2"])];
/// let widths = [Constraint::Length(5), Constraint::Length(5)];
/// let table = Table::new(rows, widths).highlight_style(Style::new().red().italic());
/// ```
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn highlight_style<S: Into<Style>>(mut self, highlight_style: S) -> Self {
self.highlight_style = highlight_style.into();
@ -501,7 +576,11 @@ impl<'a> Table<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// layout::Constraint,
/// widgets::{Cell, Row, Table},
/// };
///
/// # let rows = [Row::new(vec!["Cell1", "Cell2"])];
/// # let widths = [Constraint::Length(5), Constraint::Length(5)];
/// let table = Table::new(rows, widths).highlight_symbol(">>");
@ -533,9 +612,13 @@ impl<'a> Table<'a> {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// # let rows = [Row::new(vec!["Cell1", "Cell2"])];
/// # let widths = [Constraint::Length(5), Constraint::Length(5)];
/// use ratatui::{
/// layout::Constraint,
/// widgets::{HighlightSpacing, Row, Table},
/// };
///
/// let rows = [Row::new(vec!["Cell1", "Cell2"])];
/// let widths = [Constraint::Length(5), Constraint::Length(5)];
/// let table = Table::new(rows, widths).highlight_spacing(HighlightSpacing::Always);
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -557,8 +640,11 @@ impl<'a> Table<'a> {
/// Create a table that needs at least 30 columns to display. Any extra space will be assigned
/// to the last column.
/// ```
/// # use ratatui::layout::{Constraint, Flex};
/// # use ratatui::widgets::{Table, Row};
/// use ratatui::{
/// layout::{Constraint, Flex},
/// widgets::{Row, Table},
/// };
///
/// let widths = [
/// Constraint::Min(10),
/// Constraint::Min(10),
@ -868,7 +954,12 @@ mod tests {
use std::vec;
use super::*;
use crate::{layout::Constraint::*, style::Style, text::Line, widgets::Cell};
use crate::{
layout::Constraint::*,
style::{Color, Modifier, Style, Stylize},
text::Line,
widgets::Cell,
};
#[test]
fn new() {
@ -1033,11 +1124,10 @@ mod tests {
mod state {
use rstest::{fixture, rstest};
use super::TableState;
use crate::{
buffer::Buffer,
layout::{Constraint, Rect},
widgets::{Row, StatefulWidget, Table},
widgets::{Row, StatefulWidget, Table, TableState},
};
#[fixture]
@ -1088,6 +1178,7 @@ mod tests {
use rstest::rstest;
use super::*;
use crate::layout::Alignment;
#[test]
fn render_empty_area() {

View file

@ -21,11 +21,16 @@
/// # Example
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// layout::{Constraint, Rect},
/// widgets::{Row, Table, TableState},
/// Frame,
/// };
///
/// # fn ui(frame: &mut Frame) {
/// # let area = Rect::default();
/// # let rows = [Row::new(vec!["Cell1", "Cell2"])];
/// # let widths = [Constraint::Length(5), Constraint::Length(5)];
/// let rows = [Row::new(vec!["Cell1", "Cell2"])];
/// let widths = [Constraint::Length(5), Constraint::Length(5)];
/// let table = Table::new(rows, widths).widths(widths);
///
/// // Note: TableState should be stored in your application state (not constructed in your render
@ -57,7 +62,8 @@ impl TableState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::TableState;
///
/// let state = TableState::new();
/// ```
pub const fn new() -> Self {
@ -74,7 +80,8 @@ impl TableState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::TableState;
///
/// let state = TableState::new().with_offset(1);
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -90,7 +97,8 @@ impl TableState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::TableState;
///
/// let state = TableState::new().with_selected(Some(1));
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -107,7 +115,8 @@ impl TableState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::TableState;
///
/// let state = TableState::new();
/// assert_eq!(state.offset(), 0);
/// ```
@ -120,7 +129,8 @@ impl TableState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::TableState;
///
/// let mut state = TableState::default();
/// *state.offset_mut() = 1;
/// ```
@ -135,7 +145,8 @@ impl TableState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::TableState;
///
/// let state = TableState::new();
/// assert_eq!(state.selected(), None);
/// ```
@ -150,7 +161,8 @@ impl TableState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::TableState;
///
/// let mut state = TableState::default();
/// *state.selected_mut() = Some(1);
/// ```
@ -165,7 +177,8 @@ impl TableState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::TableState;
///
/// let mut state = TableState::default();
/// state.select(Some(1));
/// ```
@ -184,7 +197,8 @@ impl TableState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::TableState;
///
/// let mut state = TableState::default();
/// state.select_next();
/// ```
@ -201,7 +215,8 @@ impl TableState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::TableState;
///
/// let mut state = TableState::default();
/// state.select_previous();
/// ```
@ -218,7 +233,8 @@ impl TableState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::TableState;
///
/// let mut state = TableState::default();
/// state.select_first();
/// ```
@ -234,7 +250,8 @@ impl TableState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::TableState;
///
/// let mut state = TableState::default();
/// state.select_last();
/// ```
@ -251,7 +268,8 @@ impl TableState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::TableState;
///
/// let mut state = TableState::default();
/// state.scroll_down_by(4);
/// ```
@ -269,7 +287,8 @@ impl TableState {
/// # Examples
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// use ratatui::widgets::TableState;
///
/// let mut state = TableState::default();
/// state.scroll_up_by(4);
/// ```

View file

@ -1,4 +1,11 @@
use crate::{prelude::*, style::Styled, widgets::Block};
use crate::{
buffer::Buffer,
layout::Rect,
style::{Modifier, Style, Styled},
symbols::{self},
text::{Line, Span},
widgets::{block::BlockExt, Block, Widget, WidgetRef},
};
const DEFAULT_HIGHLIGHT_STYLE: Style = Style::new().add_modifier(Modifier::REVERSED);
@ -14,7 +21,11 @@ const DEFAULT_HIGHLIGHT_STYLE: Style = Style::new().add_modifier(Modifier::REVER
/// # Example
///
/// ```
/// use ratatui::{prelude::*, widgets::*};
/// use ratatui::{
/// style::{Style, Stylize},
/// symbols,
/// widgets::{Block, Tabs},
/// };
///
/// Tabs::new(vec!["Tab1", "Tab2", "Tab3", "Tab4"])
/// .block(Block::bordered().title("Tabs"))
@ -75,13 +86,15 @@ impl<'a> Tabs<'a> {
///
/// Basic titles.
/// ```
/// # use ratatui::{prelude::*, widgets::Tabs};
/// use ratatui::widgets::Tabs;
///
/// let tabs = Tabs::new(vec!["Tab 1", "Tab 2"]);
/// ```
///
/// Styled titles
/// ```
/// # use ratatui::{prelude::*, widgets::Tabs};
/// use ratatui::{style::Stylize, widgets::Tabs};
///
/// let tabs = Tabs::new(vec!["Tab 1".red(), "Tab 2".blue()]);
/// ```
pub fn new<Iter>(titles: Iter) -> Self
@ -126,6 +139,8 @@ impl<'a> Tabs<'a> {
/// This will set the given style on the entire render area.
/// More precise style can be applied to the titles by styling the ones given to [`Tabs::new`].
/// The selected tab can be styled differently using [`Tabs::highlight_style`].
///
/// [`Color`]: crate::style::Color
#[must_use = "method moves the value of self and returns the modified value"]
pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
self.style = style.into();
@ -139,6 +154,8 @@ impl<'a> Tabs<'a> {
///
/// Highlighted tab can be selected with [`Tabs::select`].
#[must_use = "method moves the value of self and returns the modified value"]
///
/// [`Color`]: crate::style::Color
pub fn highlight_style<S: Into<Style>>(mut self, style: S) -> Self {
self.highlight_style = style.into();
self
@ -152,12 +169,14 @@ impl<'a> Tabs<'a> {
///
/// Use a dot (`•`) as separator.
/// ```
/// # use ratatui::{prelude::*, widgets::Tabs, symbols};
/// use ratatui::{symbols, widgets::Tabs};
///
/// let tabs = Tabs::new(vec!["Tab 1", "Tab 2"]).divider(symbols::DOT);
/// ```
/// Use dash (`-`) as separator.
/// ```
/// # use ratatui::{prelude::*, widgets::Tabs};
/// use ratatui::widgets::Tabs;
///
/// let tabs = Tabs::new(vec!["Tab 1", "Tab 2"]).divider("-");
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -177,12 +196,14 @@ impl<'a> Tabs<'a> {
///
/// A space on either side of the tabs.
/// ```
/// # use ratatui::{prelude::*, widgets::Tabs};
/// use ratatui::widgets::Tabs;
///
/// let tabs = Tabs::new(vec!["Tab 1", "Tab 2"]).padding(" ", " ");
/// ```
/// Nothing on either side of the tabs.
/// ```
/// # use ratatui::{prelude::*, widgets::Tabs};
/// use ratatui::widgets::Tabs;
///
/// let tabs = Tabs::new(vec!["Tab 1", "Tab 2"]).padding("", "");
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -204,7 +225,8 @@ impl<'a> Tabs<'a> {
///
/// An arrow on the left of tabs.
/// ```
/// # use ratatui::{prelude::*, widgets::Tabs};
/// use ratatui::widgets::Tabs;
///
/// let tabs = Tabs::new(vec!["Tab 1", "Tab 2"]).padding_left("->");
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -224,7 +246,8 @@ impl<'a> Tabs<'a> {
///
/// An arrow on the right of tabs.
/// ```
/// # use ratatui::{prelude::*, widgets::Tabs};
/// use ratatui::widgets::Tabs;
///
/// let tabs = Tabs::new(vec!["Tab 1", "Tab 2"]).padding_right("<-");
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -333,6 +356,7 @@ where
#[cfg(test)]
mod tests {
use super::*;
use crate::style::{Color, Stylize};
#[test]
fn new() {

View file

@ -14,7 +14,16 @@
// not too happy about the redundancy in these tests,
// but if that helps readability then it's ok i guess /shrug
use ratatui::{backend::TestBackend, prelude::*, widgets::*};
use ratatui::{
backend::TestBackend,
layout::{Constraint, Direction, Layout},
text::Line,
widgets::{
Block, Borders, List, ListState, Row, Scrollbar, ScrollbarOrientation, ScrollbarState,
Table, TableState,
},
Terminal,
};
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
struct AppState {