use alloc::string::{String, ToString};
use denise::Role;
use denise_render::Canvas;
use denise_text::TextStyle;
use crate::widget::{PaintCtx, Widget};
use crate::widgets::style::{Align, draw_aligned};
#[derive(Clone, Debug)]
pub struct Label {
text: String,
role: Role,
align: (Align, Align),
style: TextStyle,
}
impl Label {
pub fn new(text: impl Into<String>) -> Self {
Self {
text: text.into(),
role: Role::BaseContent,
align: (Align::Start, Align::Center),
style: TextStyle::built_in(16),
}
}
pub fn with_role(mut self, role: Role) -> Self {
self.role = role;
self
}
pub fn with_align(mut self, horizontal: Align, vertical: Align) -> Self {
self.align = (horizontal, vertical);
self
}
pub fn with_style(mut self, style: TextStyle) -> Self {
self.style = style;
self
}
pub fn with_size(mut self, size_px: u16) -> Self {
self.style.size_px = size_px;
self
}
#[inline]
pub const fn style(&self) -> TextStyle {
self.style
}
#[inline]
pub fn text(&self) -> &str {
&self.text
}
pub fn set_text(&mut self, text: impl Into<String>) {
self.text = text.into();
}
pub fn set_style(&mut self, style: TextStyle) {
self.style = style;
}
pub fn set_role(&mut self, role: Role) {
self.role = role;
}
pub fn update(&mut self, text: &str) -> bool {
let changed = self.text != text;
if changed {
self.text = text.to_string();
}
changed
}
}
impl<M: 'static> Widget<M> for Label {
fn paint(&self, ctx: &mut PaintCtx<'_>, canvas: &mut Canvas<'_>) {
let color = ctx.theme.color(self.role);
draw_aligned(
canvas, ctx.text, self.style, ctx.bounds, self.align, &self.text, color,
);
}
}