accounting/src/output/cli/tui_to_ansi.rs

95 lines
3.0 KiB
Rust

use ratatui::{
style::{Color, Modifier},
text::{Span, Text},
};
pub fn span_to_ansi(span: &Span) -> String {
let mut styled_string = String::new();
if let Some(color) = span.style.fg {
if let Color::Rgb(r, g, b) = color {
styled_string.push_str(&format!("\x1b[38;2;{};{};{}m", r, g, b));
} else {
styled_string.push_str(&format!(
"\x1b[{}m",
match color {
Color::Black => "30",
Color::Red => "31",
Color::Green => "32",
Color::Yellow => "33",
Color::Blue => "34",
Color::Magenta => "35",
Color::Cyan => "36",
Color::Gray => "37",
Color::DarkGray => "90",
Color::LightRed => "91",
Color::LightGreen => "92",
Color::LightYellow => "93",
Color::LightBlue => "94",
Color::LightMagenta => "95",
Color::LightCyan => "96",
Color::White => "97",
_ => "39",
}
));
}
}
if let Some(color) = span.style.bg {
if let Color::Rgb(r, g, b) = color {
styled_string.push_str(&format!("\x1b[48;2;{};{};{}m", r, g, b));
} else {
styled_string.push_str(&format!(
"\x1b[{}m",
match color {
Color::Black => "40",
Color::Red => "41",
Color::Green => "42",
Color::Yellow => "43",
Color::Blue => "44",
Color::Magenta => "45",
Color::Cyan => "46",
Color::Gray => "47",
Color::DarkGray => "100",
Color::LightRed => "101",
Color::LightGreen => "102",
Color::LightYellow => "103",
Color::LightBlue => "104",
Color::LightMagenta => "105",
Color::LightCyan => "106",
Color::White => "107",
_ => "49",
}
));
}
}
if span.style.add_modifier.contains(Modifier::BOLD) {
styled_string.push_str("\x1b[1m");
}
if span.style.add_modifier.contains(Modifier::ITALIC) {
styled_string.push_str("\x1b[3m");
}
if span.style.add_modifier.contains(Modifier::UNDERLINED) {
styled_string.push_str("\x1b[4m");
}
styled_string.push_str(&span.content);
styled_string.push_str("\x1b[0m"); // Reset style
styled_string
}
pub fn text_to_ansi(text: &Text) -> String {
text.lines
.iter()
.map(|line| {
line.spans
.iter()
.map(|span| span_to_ansi(span))
.collect::<Vec<_>>()
.join("")
})
.collect::<Vec<_>>()
.join("\n")
}