[go: up one dir, main page]

Struct ratatui::text::Line

source ·
pub struct Line<'a> {
    pub spans: Vec<Span<'a>>,
    pub alignment: Option<Alignment>,
}

Fields§

§spans: Vec<Span<'a>>§alignment: Option<Alignment>

Implementations§

source§

impl<'a> Line<'a>

source

pub fn raw<T>(content: T) -> Line<'a>
where T: Into<Cow<'a, str>>,

Create a line with the default style.

Examples
Line::raw("test content");
Line::raw(String::from("test content"));
source

pub fn styled<T>(content: T, style: Style) -> Line<'a>
where T: Into<Cow<'a, str>>,

Create a line with a style.

Examples
let style = Style::default().fg(Color::Yellow).add_modifier(Modifier::ITALIC);
Line::styled("My text", style);
Line::styled(String::from("My text"), style);
source

pub fn width(&self) -> usize

Returns the width of the underlying string.

Examples
let line = Line::from(vec![
    Span::styled("My", Style::default().fg(Color::Yellow)),
    Span::raw(" text"),
]);
assert_eq!(7, line.width());
Examples found in repository?
examples/custom_widget.rs (line 103)
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
    fn render(self, area: Rect, buf: &mut Buffer) {
        let (background, text, shadow, highlight) = self.colors();
        buf.set_style(area, Style::new().bg(background).fg(text));

        // render top line if there's enough space
        if area.height > 2 {
            buf.set_string(
                area.x,
                area.y,
                "▔".repeat(area.width as usize),
                Style::new().fg(highlight).bg(background),
            );
        }
        // render bottom line if there's enough space
        if area.height > 1 {
            buf.set_string(
                area.x,
                area.y + area.height - 1,
                "▁".repeat(area.width as usize),
                Style::new().fg(shadow).bg(background),
            );
        }
        // render label centered
        buf.set_line(
            area.x + (area.width.saturating_sub(self.label.width() as u16)) / 2,
            area.y + (area.height.saturating_sub(1)) / 2,
            &self.label,
            area.width,
        );
    }
source

pub fn styled_graphemes( &'a self, base_style: Style ) -> impl Iterator<Item = StyledGrapheme<'a>>

Returns an iterator over the graphemes held by this line.

base_style is the Style that will be patched with each grapheme Style to get the resulting Style.

Examples
use std::iter::Iterator;
use ratatui::{prelude::*, text::StyledGrapheme};

let line = Line::styled("Text", Style::default().fg(Color::Yellow));
let style = Style::default().fg(Color::Green).bg(Color::Black);
assert_eq!(
    line.styled_graphemes(style).collect::<Vec<StyledGrapheme>>(),
    vec![
        StyledGrapheme::new("T", Style::default().fg(Color::Yellow).bg(Color::Black)),
        StyledGrapheme::new("e", Style::default().fg(Color::Yellow).bg(Color::Black)),
        StyledGrapheme::new("x", Style::default().fg(Color::Yellow).bg(Color::Black)),
        StyledGrapheme::new("t", Style::default().fg(Color::Yellow).bg(Color::Black)),
    ]
);
source

pub fn patch_style(&mut self, style: Style)

Patches the style of each Span in an existing Line, adding modifiers from the given style.

Examples
let style = Style::default().fg(Color::Yellow).add_modifier(Modifier::ITALIC);
let mut raw_line = Line::from(vec![
    Span::raw("My"),
    Span::raw(" text"),
]);
let mut styled_line = Line::from(vec![
    Span::styled("My", style),
    Span::styled(" text", style),
]);

assert_ne!(raw_line, styled_line);

raw_line.patch_style(style);
assert_eq!(raw_line, styled_line);
source

pub fn reset_style(&mut self)

Resets the style of each Span in the Line. Equivalent to calling patch_style(Style::reset()).

Examples
let mut line = Line::from(vec![
    Span::styled("My", Style::default().fg(Color::Yellow)),
    Span::styled(" text", Style::default().add_modifier(Modifier::BOLD)),
]);

line.reset_style();
assert_eq!(Style::reset(), line.spans[0].style);
assert_eq!(Style::reset(), line.spans[1].style);
source

pub fn alignment(self, alignment: Alignment) -> Self

Sets the target alignment for this line of text. Defaults to: None, meaning the alignment is determined by the rendering widget.

Examples
let mut line = Line::from("Hi, what's up?");
assert_eq!(None, line.alignment);
assert_eq!(Some(Alignment::Right), line.alignment(Alignment::Right).alignment)
Examples found in repository?
examples/barchart.rs (line 195)
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
fn create_groups<'a>(app: &'a App, combine_values_and_labels: bool) -> Vec<BarGroup<'a>> {
    app.months
        .iter()
        .enumerate()
        .map(|(i, &month)| {
            let bars: Vec<Bar> = app
                .companies
                .iter()
                .map(|c| {
                    let mut bar = Bar::default()
                        .value(c.revenue[i])
                        .style(c.bar_style)
                        .value_style(
                            Style::default()
                                .bg(c.bar_style.fg.unwrap())
                                .fg(Color::Black),
                        );

                    if combine_values_and_labels {
                        bar = bar.text_value(format!(
                            "{} ({:.1} M)",
                            c.label,
                            (c.revenue[i] as f64) / 1000.
                        ));
                    } else {
                        bar = bar
                            .text_value(format!("{:.1}", (c.revenue[i] as f64) / 1000.))
                            .label(c.label.into());
                    }
                    bar
                })
                .collect();
            BarGroup::default()
                .label(Line::from(month).alignment(Alignment::Center))
                .bars(&bars)
        })
        .collect()
}
More examples
Hide additional examples
examples/layout.rs (line 64)
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
fn ui(frame: &mut Frame) {
    let main_layout = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Length(4),  // text
            Length(50), // examples
            Min(0),     // fills remaining space
        ])
        .split(frame.size());

    // title
    frame.render_widget(
        Paragraph::new(vec![
            Line::from("Horizontal Layout Example. Press q to quit".dark_gray())
                .alignment(Alignment::Center),
            Line::from("Each line has 2 constraints, plus Min(0) to fill the remaining space."),
            Line::from("E.g. the second line of the Len/Min box is [Length(2), Min(2), Min(0)]"),
            Line::from("Note: constraint labels that don't fit are truncated"),
        ]),
        main_layout[0],
    );

    let example_rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Length(9),
            Length(9),
            Length(9),
            Length(9),
            Length(9),
            Min(0), // fills remaining space
        ])
        .split(main_layout[1]);
    let example_areas = example_rows
        .iter()
        .flat_map(|area| {
            Layout::default()
                .direction(Direction::Horizontal)
                .constraints([
                    Length(14),
                    Length(14),
                    Length(14),
                    Length(14),
                    Length(14),
                    Min(0), // fills remaining space
                ])
                .split(*area)
                .iter()
                .copied()
                .take(5) // ignore Min(0)
                .collect_vec()
        })
        .collect_vec();

    // the examples are a cartesian product of the following constraints
    // e.g. Len/Len, Len/Min, Len/Max, Len/Perc, Len/Ratio, Min/Len, Min/Min, ...
    let examples = [
        (
            "Len",
            vec![
                Length(0),
                Length(2),
                Length(3),
                Length(6),
                Length(10),
                Length(15),
            ],
        ),
        (
            "Min",
            vec![Min(0), Min(2), Min(3), Min(6), Min(10), Min(15)],
        ),
        (
            "Max",
            vec![Max(0), Max(2), Max(3), Max(6), Max(10), Max(15)],
        ),
        (
            "Perc",
            vec![
                Percentage(0),
                Percentage(25),
                Percentage(50),
                Percentage(75),
                Percentage(100),
                Percentage(150),
            ],
        ),
        (
            "Ratio",
            vec![
                Ratio(0, 4),
                Ratio(1, 4),
                Ratio(2, 4),
                Ratio(3, 4),
                Ratio(4, 4),
                Ratio(6, 4),
            ],
        ),
    ];

    for (i, (a, b)) in examples
        .iter()
        .cartesian_product(examples.iter())
        .enumerate()
    {
        let (name_a, examples_a) = a;
        let (name_b, examples_b) = b;
        let constraints = examples_a
            .iter()
            .copied()
            .zip(examples_b.iter().copied())
            .collect_vec();
        render_example_combination(
            frame,
            example_areas[i],
            &format!("{name_a}/{name_b}"),
            constraints,
        );
    }
}

Trait Implementations§

source§

impl<'a> Clone for Line<'a>

source§

fn clone(&self) -> Line<'a>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<'a> Debug for Line<'a>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<'a> Default for Line<'a>

source§

fn default() -> Line<'a>

Returns the “default value” for a type. Read more
source§

impl<'a> From<&'a str> for Line<'a>

source§

fn from(s: &'a str) -> Self

Converts to this type from the input type.
source§

impl<'a> From<Line<'a>> for String

source§

fn from(line: Line<'a>) -> String

Converts to this type from the input type.
source§

impl<'a> From<Line<'a>> for Text<'a>

source§

fn from(line: Line<'a>) -> Text<'a>

Converts to this type from the input type.
source§

impl<'a> From<Span<'a>> for Line<'a>

source§

fn from(span: Span<'a>) -> Self

Converts to this type from the input type.
source§

impl<'a> From<String> for Line<'a>

source§

fn from(s: String) -> Self

Converts to this type from the input type.
source§

impl<'a> From<Vec<Span<'a>>> for Line<'a>

source§

fn from(spans: Vec<Span<'a>>) -> Self

Converts to this type from the input type.
source§

impl<'a> Hash for Line<'a>

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl<'a> PartialEq for Line<'a>

source§

fn eq(&self, other: &Line<'a>) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<'a> Eq for Line<'a>

source§

impl<'a> StructuralEq for Line<'a>

source§

impl<'a> StructuralPartialEq for Line<'a>

Auto Trait Implementations§

§

impl<'a> RefUnwindSafe for Line<'a>

§

impl<'a> Send for Line<'a>

§

impl<'a> Sync for Line<'a>

§

impl<'a> Unpin for Line<'a>

§

impl<'a> UnwindSafe for Line<'a>

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.