use std::fmt;
use anstyle::Style;
use crate::cells::text_width;
use crate::sanitize::{is_clean, span_text};
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Span {
pub(crate) text: String,
pub(crate) style: Style,
}
impl Span {
#[must_use]
pub fn new(text: impl AsRef<str>, style: Style) -> Self {
let text = text.as_ref();
let text = if is_clean(text) {
text.to_owned()
} else {
span_text(text)
};
Self { text, style }
}
#[must_use]
pub fn text(&self) -> &str {
&self.text
}
#[must_use]
pub fn style(&self) -> Style {
self.style
}
#[must_use]
pub fn width(&self) -> u16 {
text_width(&self.text)
}
}
impl From<&str> for Span {
fn from(text: &str) -> Self {
Self::new(text, Style::new())
}
}
impl From<String> for Span {
fn from(text: String) -> Self {
let text = if is_clean(&text) {
text
} else {
span_text(&text)
};
Self {
text,
style: Style::new(),
}
}
}
impl fmt::Display for Span {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.text)
}
}