use crate::{
Element, Hasher, Layout, MouseCursor, Node, Point, Rectangle, Style, Widget,
};
use std::hash::Hash;
#[derive(Debug, Clone)]
pub struct Text<Color> {
content: String,
size: Option<u16>,
color: Option<Color>,
style: Style,
horizontal_alignment: HorizontalAlignment,
vertical_alignment: VerticalAlignment,
}
impl<Color> Text<Color> {
pub fn new(label: &str) -> Self {
Text {
content: String::from(label),
size: None,
color: None,
style: Style::default().fill_width(),
horizontal_alignment: HorizontalAlignment::Left,
vertical_alignment: VerticalAlignment::Top,
}
}
pub fn size(mut self, size: u16) -> Self {
self.size = Some(size);
self
}
pub fn color(mut self, color: Color) -> Self {
self.color = Some(color);
self
}
pub fn width(mut self, width: u16) -> Self {
self.style = self.style.width(width);
self
}
pub fn height(mut self, height: u16) -> Self {
self.style = self.style.height(height);
self
}
pub fn horizontal_alignment(
mut self,
alignment: HorizontalAlignment,
) -> Self {
self.horizontal_alignment = alignment;
self
}
pub fn vertical_alignment(mut self, alignment: VerticalAlignment) -> Self {
self.vertical_alignment = alignment;
self
}
}
impl<Message, Renderer, Color> Widget<Message, Renderer> for Text<Color>
where
Color: Copy + std::fmt::Debug,
Renderer: self::Renderer<Color>,
{
fn node(&self, renderer: &Renderer) -> Node {
renderer.node(self.style, &self.content, self.size)
}
fn draw(
&self,
renderer: &mut Renderer,
layout: Layout<'_>,
_cursor_position: Point,
) -> MouseCursor {
renderer.draw(
layout.bounds(),
&self.content,
self.size,
self.color,
self.horizontal_alignment,
self.vertical_alignment,
);
MouseCursor::OutOfBounds
}
fn hash_layout(&self, state: &mut Hasher) {
self.style.hash(state);
self.content.hash(state);
self.size.hash(state);
}
}
pub trait Renderer<Color> {
fn node(&self, style: Style, content: &str, size: Option<u16>) -> Node;
fn draw(
&mut self,
bounds: Rectangle,
content: &str,
size: Option<u16>,
color: Option<Color>,
horizontal_alignment: HorizontalAlignment,
vertical_alignment: VerticalAlignment,
);
}
impl<'a, Message, Renderer, Color> From<Text<Color>>
for Element<'a, Message, Renderer>
where
Color: 'static + Copy + std::fmt::Debug,
Renderer: self::Renderer<Color>,
{
fn from(text: Text<Color>) -> Element<'a, Message, Renderer> {
Element::new(text)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HorizontalAlignment {
Left,
Center,
Right,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VerticalAlignment {
Top,
Center,
Bottom,
}