use super::font::Font;
use crate::graphics::drawable::Drawable;
use crate::graphics::canvas::Canvas;
use crate::graphics::color::Color;
use wasm_bindgen::JsValue;
const PX_STR: &str = "px";
pub struct TextStyle {
pub italic: bool,
pub bold: bool,
pub underlined: bool,
pub color: Color
}
impl Default for TextStyle {
fn default() -> TextStyle {
TextStyle {
italic: false,
bold: false,
underlined: false,
color: Color::black()
}
}
}
pub struct Text<'a> {
pub coords: (usize, usize),
pub font: &'a Font,
pub text: String,
pub style: TextStyle,
pub character_size: (usize, &'a str)
}
impl<'a> Text<'a> {
pub fn new(font: &'a Font) -> Text<'a> {
Text {
coords: (0,0),
font,
text: String::new(),
style: TextStyle::default(),
character_size: (26, PX_STR)
}
}
pub fn new_with_text_and_coords(font: &'a Font, text: String, coords: (usize, usize)) -> Text<'a> {
Text {
coords,
font,
text,
style: TextStyle::default(),
character_size: (26, PX_STR)
}
}
pub fn new_with_options(font: &'a Font, text: String, coords: (usize, usize), style: TextStyle, character_size: (usize, &'a str)) -> Text<'a> {
Text {
coords,
font,
text,
style,
character_size
}
}
pub fn set_text(&mut self, text: String) {
self.text = text;
}
pub fn set_style(&mut self, style: TextStyle) {
self.style = style;
}
pub fn get_width(&self, mut canvas: &mut Canvas) -> f64 {
self.apply_style_on_canvas(&mut canvas);
canvas.context.measure_text(&self.text).unwrap().width()
}
fn apply_style_on_canvas(&self, canvas: &mut Canvas) {
let mut font = String::new();
if self.style.italic {
font.push_str("italic ");
}
if self.style.bold {
font.push_str("bold ");
}
if self.style.underlined {
unimplemented!("avoid underlined text for now");
}
font.push_str(&self.character_size.0.to_string());
font.push_str(self.character_size.1);
font.push_str(" '");
font.push_str(&self.font.name);
font.push_str("'");
canvas.context.set_font(&font);
canvas.context.set_fill_style(&JsValue::from_str(&self.style.color.to_string()));
}
}
impl<'a> Drawable for Text<'a> {
fn draw_on_canvas(&self, mut canvas: &mut Canvas) {
self.apply_style_on_canvas(&mut canvas);
canvas.fill_text(self.coords, &self.text, None);
}
}