pub struct Line<'a> {
pub spans: Vec<Span<'a>>,
pub style: Style,
pub alignment: Option<Alignment>,
}
Expand description
A line of text, consisting of one or more Span
s.
Line
s are used wherever text is displayed in the terminal and represent a single line of
text. When a Line
is rendered, it is rendered as a single line of text, with each Span
being rendered in order (left to right).
§Constructor Methods
Line::default
creates a line with empty content and the default style.Line::raw
creates a line with the given content and the default style.Line::styled
creates a line with the given content and style.
§Conversion Methods
Line::from
creates aLine
from aString
.Line::from
creates aLine
from a&str
.Line::from
creates aLine
from aVec
ofSpan
s.Line::from
creates aLine
from singleSpan
.String::from
converts a line into aString
.Line::from_iter
creates a line from an iterator of items that are convertible toSpan
.
§Setter Methods
These methods are fluent setters. They return a Line
with the property set.
Line::spans
sets the content of the line.Line::style
sets the style of the line.Line::alignment
sets the alignment of the line.Line::left_aligned
sets the alignment of the line toAlignment::Left
.Line::centered
sets the alignment of the line toAlignment::Center
.Line::right_aligned
sets the alignment of the line toAlignment::Right
.
§Iteration Methods
Line::iter
returns an iterator over the spans of this line.Line::iter_mut
returns a mutable iterator over the spans of this line.Line::into_iter
returns an iterator over the spans of this line.
§Other Methods
Line::patch_style
patches the style of the line, adding modifiers from the given style.Line::reset_style
resets the style of the line.Line::width
returns the unicode width of the content held by this line.Line::styled_graphemes
returns an iterator over the graphemes held by this line.Line::push_span
adds a span to the line.
§Compatibility Notes
Before v0.26.0, Line
did not have a style
field and instead relied on only the styles that
were set on each Span
contained in the spans
field. The Line::patch_style
method was
the only way to set the overall style for individual lines. For this reason, this field may not
be supported yet by all widgets (outside of the ratatui
crate itself).
§Examples
§Creating Lines
Line
s can be created from Span
s, String
s, and &str
s. They can be styled with a
Style
.
use ratatui::prelude::*;
let style = Style::new().yellow();
let line = Line::raw("Hello, world!").style(style);
let line = Line::styled("Hello, world!", style);
let line = Line::styled("Hello, world!", (Color::Yellow, Modifier::BOLD));
let line = Line::from("Hello, world!");
let line = Line::from(String::from("Hello, world!"));
let line = Line::from(vec![
Span::styled("Hello", Style::new().blue()),
Span::raw(" world!"),
]);
§Styling Lines
The line’s Style
is used by the rendering widget to determine how to style the line. Each
Span
in the line will be styled with the Style
of the line, and then with its own
Style
. If the line is longer than the available space, the style is applied to the entire
line, and the line is truncated. Line
also implements Styled
which means you can use the
methods of the Stylize
trait.
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));
let line = Line::from("Hello world!").style((Color::Yellow, Modifier::ITALIC));
let line = Line::from("Hello world!").yellow().italic();
§Aligning Lines
The line’s Alignment
is used by the rendering widget to determine how to align the line
within the available space. If the line is longer than the available space, the alignment is
ignored and the line is truncated.
let line = Line::from("Hello world!").alignment(Alignment::Right);
let line = Line::from("Hello world!").centered();
let line = Line::from("Hello world!").left_aligned();
let line = Line::from("Hello world!").right_aligned();
§Rendering Lines
Line
implements the Widget
trait, which means it can be rendered to a Buffer
.
// in another widget's render method
let line = Line::from("Hello world!").style(Style::new().yellow().italic());
line.render(area, buf);
// in a terminal.draw closure
let line = Line::from("Hello world!").style(Style::new().yellow().italic());
frame.render_widget(line, area);
§Rendering Lines with a Paragraph widget
Usually apps will use the Paragraph
widget instead of rendering a Line
directly as it
provides more functionality.
let line = Line::from("Hello world!").yellow().italic();
Paragraph::new(line)
.wrap(Wrap { trim: true })
.render(area, buf);
Fields§
§spans: Vec<Span<'a>>
The spans that make up this line of text.
style: Style
The style of this line of text.
alignment: Option<Alignment>
The alignment of this line of text.
Implementations§
source§impl<'a> Line<'a>
impl<'a> Line<'a>
sourcepub fn raw<T>(content: T) -> Self
pub fn raw<T>(content: T) -> Self
Create a line with the default style.
content
can be any type that is convertible to Cow<str>
(e.g. &str
, String
,
Cow<str>
, or your own type that implements Into<Cow<str>>
).
A Line
can specify a Style
, which will be applied before the style of each Span
in the line.
Any newlines in the content are removed.
§Examples
Line::raw("test content");
Line::raw(String::from("test content"));
Line::raw(Cow::from("test content"));
Examples found in repository?
More examples
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
fn render_spacer(spacer: Rect, buf: &mut Buffer) {
if spacer.width > 1 {
let corners_only = symbols::border::Set {
top_left: line::NORMAL.top_left,
top_right: line::NORMAL.top_right,
bottom_left: line::NORMAL.bottom_left,
bottom_right: line::NORMAL.bottom_right,
vertical_left: " ",
vertical_right: " ",
horizontal_top: " ",
horizontal_bottom: " ",
};
Block::bordered()
.border_set(corners_only)
.border_style(Style::reset().dark_gray())
.render(spacer, buf);
} else {
Paragraph::new(Text::from(vec![
Line::from(""),
Line::from("│"),
Line::from("│"),
Line::from(""),
]))
.style(Style::reset().dark_gray())
.render(spacer, buf);
}
let width = spacer.width;
let label = if width > 4 {
format!("{width} px")
} else if width > 2 {
format!("{width}")
} else {
String::new()
};
let text = Text::from(vec![
Line::raw(""),
Line::raw(""),
Line::styled(label, Style::reset().dark_gray()),
]);
Paragraph::new(text)
.style(Style::reset().dark_gray())
.alignment(Alignment::Center)
.render(spacer, buf);
}
sourcepub fn styled<T, S>(content: T, style: S) -> Self
pub fn styled<T, S>(content: T, style: S) -> Self
Create a line with the given style.
Cow<str>
, or your own type that implements Into<Cow<str>>
).
style
accepts any type that is convertible to Style
(e.g. Style
, Color
, or
your own type that implements Into<Style>
).
§Examples
Any newlines in the content are removed.
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);
Examples found in repository?
548 549 550 551 552 553 554 555 556 557 558 559
fn label(width: u16) -> impl Widget {
let long_label = format!("{width} px");
let short_label = format!("{width}");
let label = if long_label.len() < width as usize {
long_label
} else if short_label.len() < width as usize {
short_label
} else {
String::new()
};
Line::styled(label, Self::TEXT_COLOR).centered()
}
More examples
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
fn to_list_item(&self, index: usize) -> ListItem {
let bg_color = match index % 2 {
0 => NORMAL_ROW_COLOR,
_ => ALT_ROW_COLOR,
};
let line = match self.status {
Status::Todo => Line::styled(format!(" ☐ {}", self.todo), TEXT_COLOR),
Status::Completed => Line::styled(
format!(" ✓ {}", self.todo),
(COMPLETED_TEXT_COLOR, bg_color),
),
};
ListItem::new(line).bg(bg_color)
}
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
fn render_spacer(spacer: Rect, buf: &mut Buffer) {
if spacer.width > 1 {
let corners_only = symbols::border::Set {
top_left: line::NORMAL.top_left,
top_right: line::NORMAL.top_right,
bottom_left: line::NORMAL.bottom_left,
bottom_right: line::NORMAL.bottom_right,
vertical_left: " ",
vertical_right: " ",
horizontal_top: " ",
horizontal_bottom: " ",
};
Block::bordered()
.border_set(corners_only)
.border_style(Style::reset().dark_gray())
.render(spacer, buf);
} else {
Paragraph::new(Text::from(vec![
Line::from(""),
Line::from("│"),
Line::from("│"),
Line::from(""),
]))
.style(Style::reset().dark_gray())
.render(spacer, buf);
}
let width = spacer.width;
let label = if width > 4 {
format!("{width} px")
} else if width > 2 {
format!("{width}")
} else {
String::new()
};
let text = Text::from(vec![
Line::raw(""),
Line::raw(""),
Line::styled(label, Style::reset().dark_gray()),
]);
Paragraph::new(text)
.style(Style::reset().dark_gray())
.alignment(Alignment::Center)
.render(spacer, buf);
}
sourcepub fn spans<I>(self, spans: I) -> Self
pub fn spans<I>(self, spans: I) -> Self
Sets the spans of this line of text.
spans
accepts any iterator that yields items that are convertible to Span
(e.g.
&str
, String
, Span
, or your own type that implements Into<Span>
).
§Examples
let line = Line::default().spans(vec!["Hello".blue(), " world!".green()]);
let line = Line::default().spans([1, 2, 3].iter().map(|i| format!("Item {}", i)));
sourcepub fn style<S: Into<Style>>(self, style: S) -> Self
pub fn style<S: Into<Style>>(self, style: S) -> Self
Sets the style of this line of text.
Defaults to Style::default()
.
Note: This field was added in v0.26.0. Prior to that, the style of a line was determined
only by the style of each Span
contained in the line. For this reason, this field may
not be supported by all widgets (outside of the ratatui
crate itself).
style
accepts any type that is convertible to Style
(e.g. Style
, Color
, or
your own type that implements Into<Style>
).
§Examples
let mut line = Line::from("foo").style(Style::new().red());
Examples found in repository?
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
fn render_bottom_bar(area: Rect, buf: &mut Buffer) {
let keys = [
("H/←", "Left"),
("L/→", "Right"),
("K/↑", "Up"),
("J/↓", "Down"),
("D/Del", "Destroy"),
("Q/Esc", "Quit"),
];
let spans = keys
.iter()
.flat_map(|(key, desc)| {
let key = Span::styled(format!(" {key} "), THEME.key_binding.key);
let desc = Span::styled(format!(" {desc} "), THEME.key_binding.description);
[key, desc]
})
.collect_vec();
Line::from(spans)
.centered()
.style((Color::Indexed(236), Color::Indexed(232)))
.render(area, buf);
}
sourcepub fn alignment(self, alignment: Alignment) -> Self
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.
Setting the alignment of a Line generally overrides the alignment of its
parent Text or 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
)
sourcepub fn left_aligned(self) -> Self
pub fn left_aligned(self) -> Self
Left-aligns this line of text.
Convenience shortcut for Line::alignment(Alignment::Left)
.
Setting the alignment of a Line generally overrides the alignment of its
parent Text or Widget, with the default alignment being inherited from the parent.
§Examples
let line = Line::from("Hi, what's up?").left_aligned();
sourcepub fn centered(self) -> Self
pub fn centered(self) -> Self
Center-aligns this line of text.
Convenience shortcut for Line::alignment(Alignment::Center)
.
Setting the alignment of a Line generally overrides the alignment of its
parent Text or Widget, with the default alignment being inherited from the parent.
§Examples
let line = Line::from("Hi, what's up?").centered();
Examples found in repository?
More examples
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
fn render_bottom_bar(area: Rect, buf: &mut Buffer) {
let keys = [
("H/←", "Left"),
("L/→", "Right"),
("K/↑", "Up"),
("J/↓", "Down"),
("D/Del", "Destroy"),
("Q/Esc", "Quit"),
];
let spans = keys
.iter()
.flat_map(|(key, desc)| {
let key = Span::styled(format!(" {key} "), THEME.key_binding.key);
let desc = Span::styled(format!(" {desc} "), THEME.key_binding.description);
[key, desc]
})
.collect_vec();
Line::from(spans)
.centered()
.style((Color::Indexed(236), Color::Indexed(232)))
.render(area, buf);
}
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
fn swap_legend() -> impl Widget {
#[allow(unstable_name_collisions)]
Paragraph::new(
Line::from(
[
ConstraintName::Min,
ConstraintName::Max,
ConstraintName::Length,
ConstraintName::Percentage,
ConstraintName::Ratio,
ConstraintName::Fill,
]
.iter()
.enumerate()
.map(|(i, name)| {
format!(" {i}: {name} ", i = i + 1)
.fg(SLATE.c200)
.bg(name.color())
})
.intersperse(Span::from(" "))
.collect_vec(),
)
.centered(),
)
.wrap(Wrap { trim: false })
}
/// A bar like `<----- 80 px (gap: 2 px) ----->`
///
/// Only shows the gap when spacing is not zero
fn axis(&self, width: u16) -> impl Widget {
let label = if self.spacing != 0 {
format!("{} px (gap: {} px)", width, self.spacing)
} else {
format!("{width} px")
};
let bar_width = width.saturating_sub(2) as usize; // we want to `<` and `>` at the ends
let width_bar = format!("<{label:-^bar_width$}>");
Paragraph::new(width_bar).fg(Self::AXIS_COLOR).centered()
}
fn render_layout_blocks(&self, area: Rect, buf: &mut Buffer) {
let [user_constraints, area] = Layout::vertical([Length(3), Fill(1)])
.spacing(1)
.areas(area);
self.render_user_constraints_legend(user_constraints, buf);
let [start, center, end, space_around, space_between] =
Layout::vertical([Length(7); 5]).areas(area);
self.render_layout_block(Flex::Start, start, buf);
self.render_layout_block(Flex::Center, center, buf);
self.render_layout_block(Flex::End, end, buf);
self.render_layout_block(Flex::SpaceAround, space_around, buf);
self.render_layout_block(Flex::SpaceBetween, space_between, buf);
}
fn render_user_constraints_legend(&self, area: Rect, buf: &mut Buffer) {
let blocks = Layout::horizontal(
self.constraints
.iter()
.map(|_| Constraint::Fill(1))
.collect_vec(),
)
.split(area);
for (i, (area, constraint)) in blocks.iter().zip(self.constraints.iter()).enumerate() {
let selected = self.selected_index == i;
ConstraintBlock::new(*constraint, selected, true).render(*area, buf);
}
}
fn render_layout_block(&self, flex: Flex, area: Rect, buf: &mut Buffer) {
let [label_area, axis_area, blocks_area] =
Layout::vertical([Length(1), Max(1), Length(4)]).areas(area);
if label_area.height > 0 {
format!("Flex::{flex:?}").bold().render(label_area, buf);
}
self.axis(area.width).render(axis_area, buf);
let (blocks, spacers) = Layout::horizontal(&self.constraints)
.flex(flex)
.spacing(self.spacing)
.split_with_spacers(blocks_area);
for (i, (area, constraint)) in blocks.iter().zip(self.constraints.iter()).enumerate() {
let selected = self.selected_index == i;
ConstraintBlock::new(*constraint, selected, false).render(*area, buf);
}
for area in spacers.iter() {
SpacerBlock.render(*area, buf);
}
}
}
impl Widget for ConstraintBlock {
fn render(self, area: Rect, buf: &mut Buffer) {
match area.height {
1 => self.render_1px(area, buf),
2 => self.render_2px(area, buf),
_ => self.render_4px(area, buf),
}
}
}
impl ConstraintBlock {
const TEXT_COLOR: Color = SLATE.c200;
const fn new(constraint: Constraint, selected: bool, legend: bool) -> Self {
Self {
constraint,
legend,
selected,
}
}
fn label(&self, width: u16) -> String {
let long_width = format!("{width} px");
let short_width = format!("{width}");
// border takes up 2 columns
let available_space = width.saturating_sub(2) as usize;
let width_label = if long_width.len() < available_space {
long_width
} else if short_width.len() < available_space {
short_width
} else {
String::new()
};
format!("{}\n{}", self.constraint, width_label)
}
fn render_1px(&self, area: Rect, buf: &mut Buffer) {
let lighter_color = ConstraintName::from(self.constraint).lighter_color();
let main_color = ConstraintName::from(self.constraint).color();
let selected_color = if self.selected {
lighter_color
} else {
main_color
};
Block::default()
.fg(Self::TEXT_COLOR)
.bg(selected_color)
.render(area, buf);
}
fn render_2px(&self, area: Rect, buf: &mut Buffer) {
let lighter_color = ConstraintName::from(self.constraint).lighter_color();
let main_color = ConstraintName::from(self.constraint).color();
let selected_color = if self.selected {
lighter_color
} else {
main_color
};
Block::bordered()
.border_set(symbols::border::QUADRANT_OUTSIDE)
.border_style(Style::reset().fg(selected_color).reversed())
.render(area, buf);
}
fn render_4px(&self, area: Rect, buf: &mut Buffer) {
let lighter_color = ConstraintName::from(self.constraint).lighter_color();
let main_color = ConstraintName::from(self.constraint).color();
let selected_color = if self.selected {
lighter_color
} else {
main_color
};
let color = if self.legend {
selected_color
} else {
main_color
};
let label = self.label(area.width);
let block = Block::bordered()
.border_set(symbols::border::QUADRANT_OUTSIDE)
.border_style(Style::reset().fg(color).reversed())
.fg(Self::TEXT_COLOR)
.bg(color);
Paragraph::new(label)
.centered()
.fg(Self::TEXT_COLOR)
.bg(color)
.block(block)
.render(area, buf);
if !self.legend {
let border_color = if self.selected {
lighter_color
} else {
main_color
};
if let Some(last_row) = area.rows().last() {
buf.set_style(last_row, border_color);
}
}
}
}
impl Widget for SpacerBlock {
fn render(self, area: Rect, buf: &mut Buffer) {
match area.height {
1 => (),
2 => Self::render_2px(area, buf),
3 => Self::render_3px(area, buf),
_ => Self::render_4px(area, buf),
}
}
}
impl SpacerBlock {
const TEXT_COLOR: Color = SLATE.c500;
const BORDER_COLOR: Color = SLATE.c600;
/// A block with a corner borders
fn block() -> impl Widget {
let corners_only = symbols::border::Set {
top_left: line::NORMAL.top_left,
top_right: line::NORMAL.top_right,
bottom_left: line::NORMAL.bottom_left,
bottom_right: line::NORMAL.bottom_right,
vertical_left: " ",
vertical_right: " ",
horizontal_top: " ",
horizontal_bottom: " ",
};
Block::bordered()
.border_set(corners_only)
.border_style(Self::BORDER_COLOR)
}
/// A vertical line used if there is not enough space to render the block
fn line() -> impl Widget {
Paragraph::new(Text::from(vec![
Line::from(""),
Line::from("│"),
Line::from("│"),
Line::from(""),
]))
.style(Self::BORDER_COLOR)
}
/// A label that says "Spacer" if there is enough space
fn spacer_label(width: u16) -> impl Widget {
let label = if width >= 6 { "Spacer" } else { "" };
label.fg(Self::TEXT_COLOR).into_centered_line()
}
/// A label that says "8 px" if there is enough space
fn label(width: u16) -> impl Widget {
let long_label = format!("{width} px");
let short_label = format!("{width}");
let label = if long_label.len() < width as usize {
long_label
} else if short_label.len() < width as usize {
short_label
} else {
String::new()
};
Line::styled(label, Self::TEXT_COLOR).centered()
}
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 200 201 202 203 204 205 206 207 208 209 210 211
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).centered())
.bars(&bars)
})
.collect()
}
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 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
fn ui(frame: &mut Frame) {
let vertical = Layout::vertical([
Length(4), // text
Length(50), // examples
Min(0), // fills remaining space
]);
let [text_area, examples_area, _] = vertical.areas(frame.size());
// title
frame.render_widget(
Paragraph::new(vec![
Line::from("Horizontal Layout Example. Press q to quit".dark_gray()).centered(),
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"),
]),
text_area,
);
let example_rows = Layout::vertical([
Length(9),
Length(9),
Length(9),
Length(9),
Length(9),
Min(0), // fills remaining space
])
.split(examples_area);
let example_areas = example_rows
.iter()
.flat_map(|area| {
Layout::horizontal([
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,
);
}
}
sourcepub fn right_aligned(self) -> Self
pub fn right_aligned(self) -> Self
Right-aligns this line of text.
Convenience shortcut for Line::alignment(Alignment::Right)
.
Setting the alignment of a Line generally overrides the alignment of its
parent Text or Widget, with the default alignment being inherited from the parent.
§Examples
let line = Line::from("Hi, what's up?").right_aligned();
sourcepub fn width(&self) -> usize
pub fn width(&self) -> usize
Returns the width of the underlying string.
§Examples
let line = Line::from(vec!["Hello".blue(), " world!".green()]);
assert_eq!(12, line.width());
Examples found in repository?
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
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,
);
}
sourcepub fn styled_graphemes<S: Into<Style>>(
&'a self,
base_style: S
) -> impl Iterator<Item = StyledGrapheme<'a>>
pub fn styled_graphemes<S: Into<Style>>( &'a self, base_style: S ) -> 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
.
base_style
accepts any type that is convertible to Style
(e.g. Style
, Color
,
or your own type that implements Into<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)),
]
);
sourcepub fn patch_style<S: Into<Style>>(self, style: S) -> Self
pub fn patch_style<S: Into<Style>>(self, style: S) -> Self
Patches the style of this Line, adding modifiers from the given style.
This is useful for when you want to apply a style to a line that already has some styling.
In contrast to Line::style
, this method will not overwrite the existing style, but
instead will add the given style’s modifiers to this Line’s style.
style
accepts any type that is convertible to Style
(e.g. Style
, Color
, or
your own type that implements Into<Style>
).
This is a fluent setter method which must be chained or used as it consumes self
§Examples
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));
sourcepub fn reset_style(self) -> Self
pub fn reset_style(self) -> Self
Resets the style of this Line.
Equivalent to calling patch_style(Style::reset())
.
This is a fluent setter method which must be chained or used as it consumes self
§Examples
let line = Line::styled("My text", style);
assert_eq!(Style::reset(), line.reset_style().style);
sourcepub fn iter_mut(&mut self) -> IterMut<'_, Span<'a>>
pub fn iter_mut(&mut self) -> IterMut<'_, Span<'a>>
Returns a mutable iterator over the spans of this line.
sourcepub fn push_span<T: Into<Span<'a>>>(&mut self, span: T)
pub fn push_span<T: Into<Span<'a>>>(&mut self, span: T)
Adds a span to the line.
span
can be any type that is convertible into a Span
. For example, you can pass a
&str
, a String
, or a Span
.
§Examples
let mut line = Line::from("Hello, ");
line.push_span(Span::raw("world!"));
line.push_span(" How are you?");
Trait Implementations§
source§impl<'a, T> FromIterator<T> for Line<'a>
impl<'a, T> FromIterator<T> for Line<'a>
source§fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self
source§impl<'a> IntoIterator for &'a Line<'a>
impl<'a> IntoIterator for &'a Line<'a>
source§impl<'a> IntoIterator for &'a mut Line<'a>
impl<'a> IntoIterator for &'a mut Line<'a>
source§impl<'a> IntoIterator for Line<'a>
impl<'a> IntoIterator for Line<'a>
source§impl<'a> PartialEq for Line<'a>
impl<'a> PartialEq for Line<'a>
source§impl WidgetRef for Line<'_>
impl WidgetRef for Line<'_>
source§fn render_ref(&self, area: Rect, buf: &mut Buffer)
fn render_ref(&self, area: Rect, buf: &mut Buffer)
unstable-widget-ref
only.impl<'a> Eq for Line<'a>
impl<'a> StructuralPartialEq for Line<'a>
Auto Trait Implementations§
impl<'a> Freeze for Line<'a>
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> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
source§impl<T> IntoEither for T
impl<T> IntoEither for T
source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moresource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moresource§impl<'a, T, U> Stylize<'a, T> for Uwhere
U: Styled<Item = T>,
impl<'a, T, U> Stylize<'a, T> for Uwhere
U: Styled<Item = T>,
fn bg(self, color: Color) -> T
fn fg<S>(self, color: S) -> T
fn add_modifier(self, modifier: Modifier) -> T
fn remove_modifier(self, modifier: Modifier) -> T
fn reset(self) -> T
source§fn on_magenta(self) -> T
fn on_magenta(self) -> T
magenta
.source§fn on_dark_gray(self) -> T
fn on_dark_gray(self) -> T
dark_gray
.source§fn on_light_red(self) -> T
fn on_light_red(self) -> T
light_red
.source§fn light_green(self) -> T
fn light_green(self) -> T
light_green
.source§fn on_light_green(self) -> T
fn on_light_green(self) -> T
light_green
.source§fn light_yellow(self) -> T
fn light_yellow(self) -> T
light_yellow
.source§fn on_light_yellow(self) -> T
fn on_light_yellow(self) -> T
light_yellow
.source§fn light_blue(self) -> T
fn light_blue(self) -> T
light_blue
.source§fn on_light_blue(self) -> T
fn on_light_blue(self) -> T
light_blue
.source§fn light_magenta(self) -> T
fn light_magenta(self) -> T
light_magenta
.source§fn on_light_magenta(self) -> T
fn on_light_magenta(self) -> T
light_magenta
.source§fn light_cyan(self) -> T
fn light_cyan(self) -> T
light_cyan
.source§fn on_light_cyan(self) -> T
fn on_light_cyan(self) -> T
light_cyan
.source§fn not_italic(self) -> T
fn not_italic(self) -> T
ITALIC
modifier.source§fn underlined(self) -> T
fn underlined(self) -> T
UNDERLINED
modifier.source§fn not_underlined(self) -> T
fn not_underlined(self) -> T
UNDERLINED
modifier.source§fn slow_blink(self) -> T
fn slow_blink(self) -> T
SLOW_BLINK
modifier.source§fn not_slow_blink(self) -> T
fn not_slow_blink(self) -> T
SLOW_BLINK
modifier.source§fn rapid_blink(self) -> T
fn rapid_blink(self) -> T
RAPID_BLINK
modifier.source§fn not_rapid_blink(self) -> T
fn not_rapid_blink(self) -> T
RAPID_BLINK
modifier.source§fn not_reversed(self) -> T
fn not_reversed(self) -> T
REVERSED
modifier.HIDDEN
modifier.HIDDEN
modifier.source§fn crossed_out(self) -> T
fn crossed_out(self) -> T
CROSSED_OUT
modifier.source§fn not_crossed_out(self) -> T
fn not_crossed_out(self) -> T
CROSSED_OUT
modifier.source§impl<T> ToCompactString for Twhere
T: Display,
impl<T> ToCompactString for Twhere
T: Display,
source§fn to_compact_string(&self) -> CompactString
fn to_compact_string(&self) -> CompactString
CompactString
. Read more