use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Style;
use ratatui::text::{Line, Span};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
#[must_use]
pub fn cells(text: &str) -> usize {
text.width()
}
fn put(buf: &mut Buffer, x: u16, y: u16, text: &str, width: usize, style: Style) {
if buf.area().contains(ratatui::layout::Position { x, y }) {
buf.set_stringn(x, y, text, width, style);
}
}
fn fitting(word: &str, width: usize) -> (usize, usize) {
let mut used = 0;
let mut end = 0;
for (index, c) in word.char_indices() {
let wide = c.width().unwrap_or(0);
if used + wide > width && end > 0 {
break;
}
used += wide;
end = index + c.len_utf8();
}
(end, used)
}
struct Placed<'s> {
row: usize,
column: usize,
text: &'s str,
style: Style,
}
fn walk<'s>(spans: &'s [Span<'_>], width: u16, mut place: impl FnMut(Placed<'s>)) -> usize {
if width == 0 {
return 0;
}
let width = width as usize;
let mut row = 0usize;
let mut column = 0usize;
let mut placed = false;
let mut separator: Option<Style> = None;
for span in spans {
let mut rest: &'s str = span.content.as_ref();
while !rest.is_empty() {
let gap = rest
.find(|c: char| !c.is_whitespace())
.unwrap_or(rest.len());
if gap > 0 {
let breaks = rest[..gap].matches('\n').count();
if breaks > 0 {
row += breaks;
column = 0;
}
separator = Some(span.style);
rest = &rest[gap..];
continue;
}
let end = rest.find(char::is_whitespace).unwrap_or(rest.len());
let (mut word, after) = rest.split_at(end);
rest = after;
let mut wide = cells(word);
while wide > width {
if column > 0 {
row += 1;
column = 0;
}
let (cut, taken) = fitting(word, width);
if cut == word.len() {
break;
}
place(Placed {
row,
column: 0,
text: &word[..cut],
style: span.style,
});
row += 1;
word = &word[cut..];
wide = wide.saturating_sub(taken);
}
let room = width - column;
let wanted = wide + usize::from(column > 0);
if wanted > room && column > 0 {
row += 1;
column = 0;
}
if column > 0 {
place(Placed {
row,
column,
text: " ",
style: separator.unwrap_or(span.style),
});
column += 1;
}
separator = None;
place(Placed {
row,
column,
text: word,
style: span.style,
});
placed = true;
column += wide;
}
}
if row == 0 && !placed { 0 } else { row + 1 }
}
pub fn wrap_spans(spans: &[Span<'_>], width: u16) -> Vec<Line<'static>> {
let mut lines: Vec<Vec<Span<'static>>> = Vec::new();
let rows = walk(spans, width, |placed| {
if lines.len() <= placed.row {
lines.resize_with(placed.row + 1, Vec::new);
}
lines[placed.row].push(Span::styled(placed.text.to_string(), placed.style));
});
lines.resize_with(rows, Vec::new);
lines.into_iter().map(Line::from).collect()
}
pub fn wrap(text: &str, width: u16) -> Vec<String> {
let mut lines: Vec<String> = Vec::new();
let spans = [Span::raw(text)];
let rows = walk(&spans, width, |placed| {
if lines.len() <= placed.row {
lines.resize_with(placed.row + 1, String::new);
}
lines[placed.row].push_str(placed.text);
});
lines.resize_with(rows, String::new);
lines
}
pub fn height(text: &str, width: u16) -> u16 {
spans_height(&[Span::raw(text)], width)
}
pub fn spans_height(spans: &[Span<'_>], width: u16) -> u16 {
u16::try_from(walk(spans, width, |_| {})).unwrap_or(u16::MAX)
}
pub fn draw(text: &str, style: Style, area: Rect, buf: &mut Buffer) -> u16 {
draw_spans(&[Span::styled(text, style)], area, buf)
}
pub fn draw_spans(spans: &[Span<'_>], area: Rect, buf: &mut Buffer) -> u16 {
let rows = walk(spans, area.width, |placed| {
let (Ok(row), Ok(column)) = (u16::try_from(placed.row), u16::try_from(placed.column))
else {
return;
};
let room = area.width.saturating_sub(column) as usize;
if row >= area.height || room == 0 {
return;
}
put(
buf,
area.x.saturating_add(column),
area.y.saturating_add(row),
placed.text,
room,
placed.style,
);
});
u16::try_from(rows).unwrap_or(u16::MAX).min(area.height)
}
pub fn draw_line(line: &Line<'_>, area: Rect, buf: &mut Buffer) -> u16 {
draw_spans(&line.spans, area, buf)
}
pub fn line_height(line: &Line<'_>, width: u16) -> u16 {
spans_height(&line.spans, width)
}
#[cfg(test)]
mod tests {
use super::*;
use ratatui::style::Modifier;
#[test]
fn a_paragraph_wraps_on_words_and_counts_the_rows_it_took() {
assert_eq!(wrap("the quick brown fox", 10), ["the quick", "brown fox"]);
assert_eq!(height("the quick brown fox", 10), 2);
}
#[test]
fn nothing_to_say_costs_no_rows_rather_than_one_blank_one() {
assert_eq!(height("", 10), 0);
assert!(wrap("", 10).is_empty());
assert!(wrap("anything", 0).is_empty());
}
#[test]
fn an_authored_break_is_a_break() {
assert_eq!(wrap("one\ntwo", 20), ["one", "two"]);
}
#[test]
fn a_word_wider_than_the_region_is_cut_rather_than_overflowed() {
assert_eq!(
wrap("supercalifragilistic", 6),
["superc", "alifra", "gilist", "ic"]
);
}
#[test]
fn the_space_between_two_runs_belongs_to_the_run_that_held_it() {
let struck = Style::new().add_modifier(Modifier::CROSSED_OUT);
let spans = [Span::raw("lean "), Span::styled("gone", struck)];
let lines = wrap_spans(&spans, 20);
assert_eq!(lines.len(), 1);
let separator = lines[0]
.spans
.iter()
.find(|span| span.content.as_ref() == " ")
.expect("a separator between the two words");
assert!(!separator.style.add_modifier.contains(Modifier::CROSSED_OUT));
}
#[test]
fn a_drawing_stops_at_the_bottom_of_the_area_it_was_given() {
let mut buf = Buffer::empty(Rect::new(0, 0, 10, 2));
let used = draw(
"the quick brown fox jumps over",
Style::new(),
buf.area,
&mut buf,
);
assert_eq!(used, 2);
}
#[test]
fn a_wide_glyph_takes_two_cells_and_nothing_is_lost() {
let lines = wrap("日本語テキスト", 8);
assert_eq!(lines, ["日本語テ", "キスト"]);
assert_eq!(height("日本語テキスト", 8), 2);
assert_eq!(lines.concat(), "日本語テキスト");
let area = Rect::new(0, 0, 8, 2);
let mut buf = Buffer::empty(area);
assert_eq!(draw("日本語テキスト", Style::default(), area, &mut buf), 2);
let row = |y: u16| {
(0..8)
.map(|x| buf[(x, y)].symbol().to_string())
.collect::<String>()
};
assert_eq!(row(0).replace(' ', ""), "日本語テ");
assert_eq!(row(1).replace(' ', ""), "キスト");
}
#[test]
fn a_glyph_wider_than_the_line_is_taken_alone_rather_than_looped_on() {
assert_eq!(wrap("設定", 1), ["設", "定"]);
}
#[test]
fn an_accent_is_never_cut_from_its_letter() {
let accented = "cafe\u{301}s";
assert_eq!(wrap(accented, 4), ["cafe\u{301}", "s"]);
}
#[test]
fn spans_after_a_wide_glyph_start_where_it_ends() {
let area = Rect::new(0, 0, 10, 1);
let mut buf = Buffer::empty(area);
let spans = [Span::raw("設定"), Span::raw("x")];
draw_spans(&spans, area, &mut buf);
assert_eq!(buf[(5, 0)].symbol(), "x");
}
#[test]
fn drawing_outside_the_buffer_loses_the_overshoot_and_not_the_process() {
let mut buf = Buffer::empty(Rect::new(0, 0, 4, 2));
for area in [
Rect::new(0, 1, 4, 5),
Rect::new(3, 0, 10, 1),
Rect::new(9, 9, 4, 4),
] {
draw("one two three", Style::default(), area, &mut buf);
draw_spans(&[Span::raw("one two")], area, &mut buf);
}
}
}