use super::{truncate, width, width_method};
use crate::ansi::{Token, spans};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Position(pub f64);
impl Position {
pub const TOP: Self = Self(0.0);
pub const BOTTOM: Self = Self(1.0);
pub const LEFT: Self = Self(0.0);
pub const RIGHT: Self = Self(1.0);
pub const CENTER: Self = Self(0.5);
fn split(self, room: usize) -> (usize, usize) {
let before = round_clamped(to_f64(room) * self.0.clamp(0.0, 1.0), room);
(before, room - before)
}
}
pub(crate) fn to_f64(n: usize) -> f64 {
f64::from(u32::try_from(n).unwrap_or(u32::MAX))
}
pub(crate) fn round_clamped(v: f64, max: usize) -> usize {
let v = v.round();
let (mut low, mut high) = (0, max);
if v.is_nan() || v <= 0.0 {
return 0;
}
while low < high {
let mid = low + (high - low).div_ceil(2);
if to_f64(mid) <= v {
low = mid;
} else {
high = mid - 1;
}
}
low
}
#[must_use]
pub fn height(text: &str) -> usize {
text.split('\n').count()
}
#[must_use]
pub fn block_width(text: &str) -> usize {
text.split('\n').map(width).max().unwrap_or(0)
}
#[must_use]
pub fn join_horizontal(pos: Position, blocks: &[&str]) -> String {
if blocks.len() < 2 {
return blocks.concat();
}
let split: Vec<Vec<&str>> = blocks.iter().map(|b| b.split('\n').collect()).collect();
let tallest = split.iter().map(Vec::len).max().unwrap_or(0);
let columns: Vec<(Vec<&str>, usize)> = split
.into_iter()
.map(|lines| {
let wide = lines.iter().map(|l| width(l)).max().unwrap_or(0);
let (above, below) = pos.split(tallest - lines.len());
let mut placed = vec![""; above];
placed.extend(lines);
placed.extend(std::iter::repeat_n("", below));
(placed, wide)
})
.collect();
let rows: Vec<String> = (0..tallest)
.map(|i| {
let cells = columns
.iter()
.map(|(lines, wide)| pad_right(lines[i], *wide));
cells.collect::<String>()
})
.collect();
rows.join("\n")
}
#[must_use]
pub fn join_vertical(pos: Position, blocks: &[&str]) -> String {
if blocks.len() < 2 {
return blocks.concat();
}
let lines: Vec<&str> = blocks.iter().flat_map(|b| b.split('\n')).collect();
let widest = lines.iter().map(|l| width(l)).max().unwrap_or(0);
let placed: Vec<String> = lines
.iter()
.map(|l| {
let (left, right) = pos.split(widest - width(l));
format!("{}{l}{}", " ".repeat(left), " ".repeat(right))
})
.collect();
placed.join("\n")
}
fn pad_right(line: &str, columns: usize) -> String {
format!("{line}{}", " ".repeat(columns.saturating_sub(width(line))))
}
#[must_use]
pub fn truncate_with(text: &str, columns: usize, tail: &str) -> String {
if width(text) <= columns {
return text.to_string();
}
let room = columns.saturating_sub(width(tail));
let cut = truncate(text, room);
let body = cut.strip_suffix("\x1b[0m").unwrap_or(&cut);
format!("{body}{tail}\x1b[0m")
}
#[must_use]
pub fn cut(text: &str, left: usize, right: usize) -> String {
let mut out = String::new();
let mut at = 0;
for (token, raw) in spans(text, width_method()) {
match token {
Token::Text(_, w) => {
if at + w > left {
out.push_str(raw);
}
at += w;
}
Token::Control(_) => {}
_ => out.push_str(raw),
}
}
let room = right.saturating_sub(left);
if width(&out) <= room {
return out;
}
let cut = truncate(&out, room);
cut.strip_suffix("\x1b[0m")
.map_or_else(|| cut.clone(), str::to_string)
}
#[must_use]
pub fn wrap(text: &str, columns: usize) -> String {
if columns == 0 {
return text.to_string();
}
let lines: Vec<String> = text.split('\n').map(|l| wrap_line(l, columns)).collect();
lines.join("\n")
}
fn wrap_line(line: &str, columns: usize) -> String {
let mut wrap = Wrapper {
columns,
..Wrapper::default()
};
for (token, raw) in spans(line, width_method()) {
match token {
Token::Text(" ", _) => wrap.space(),
Token::Text(_, w) => wrap.cluster(raw, w),
_ => wrap.word.push_str(raw),
}
}
wrap.finish()
}
#[derive(Default)]
struct Wrapper {
columns: usize,
out: Vec<String>,
line: String,
line_width: usize,
word: String,
word_width: usize,
spaces: usize,
}
impl Wrapper {
fn space(&mut self) {
self.flush_word();
self.spaces += 1;
}
fn cluster(&mut self, raw: &str, w: usize) {
if self.word_width + w > self.columns {
self.flush_word();
self.break_line();
}
self.word.push_str(raw);
self.word_width += w;
}
fn flush_word(&mut self) {
if self.word.is_empty() {
return;
}
let gap = self.gap();
if self.line_width > 0 && self.line_width + gap + self.word_width > self.columns {
self.break_line();
} else {
self.line.push_str(&" ".repeat(gap));
self.line_width += gap;
}
self.line.push_str(&std::mem::take(&mut self.word));
self.line_width += std::mem::take(&mut self.word_width);
self.spaces = 0;
}
fn gap(&self) -> usize {
let after_break = self.line_width == 0 && !self.out.is_empty();
if after_break { 0 } else { self.spaces }
}
fn break_line(&mut self) {
if self.line_width > 0 || !self.line.is_empty() {
self.out.push(std::mem::take(&mut self.line));
}
self.line_width = 0;
self.spaces = 0;
}
fn finish(mut self) -> String {
self.flush_word();
if self.line_width + self.spaces <= self.columns {
self.line.push_str(&" ".repeat(self.spaces));
}
if !self.line.is_empty() || self.out.is_empty() {
self.out.push(self.line);
}
self.out.join("\n")
}
}