use crate::elements::{
view::{ColChar, Modifier, ViewElement},
Pixel, Vec2D,
};
use super::TextAlign;
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct Text {
pub pos: Vec2D,
pub content: String,
pub align: TextAlign,
pub modifier: Modifier,
}
impl Text {
#[must_use]
pub fn new(pos: Vec2D, content: &str, modifier: Modifier) -> Self {
assert!(
!content.contains('\n'),
"Text was created with a content string containing a \n character"
);
Self {
pos,
content: String::from(content),
align: TextAlign::Begin,
modifier,
}
}
#[must_use]
pub const fn with_align(self, align: TextAlign) -> Self {
let mut tmp = self;
tmp.align = align;
tmp
}
#[must_use]
pub fn draw(pos: Vec2D, content: &str, modifier: Modifier) -> Vec<Pixel> {
let mut pixels = vec![];
for (x, text_char) in (0isize..).zip(content.chars()) {
if text_char != ' ' {
pixels.push(Pixel::new(
pos + Vec2D::new(x, 0),
ColChar {
text_char,
modifier,
},
));
}
}
pixels
}
#[must_use]
pub fn draw_with_align(
pos: Vec2D,
content: &str,
align: TextAlign,
modifier: Modifier,
) -> Vec<Pixel> {
let pos = Vec2D::new(align.apply_to(pos.x, content.len() as isize), pos.y);
Self::draw(pos, content, modifier)
}
}
impl ViewElement for Text {
fn active_pixels(&self) -> Vec<Pixel> {
Self::draw_with_align(self.pos, &self.content, self.align, self.modifier)
}
}