yakui_widgets/widgets/
text.rs

1use std::borrow::Cow;
2
3use yakui_core::widget::Widget;
4use yakui_core::Response;
5
6use crate::pad;
7use crate::style::TextStyle;
8use crate::util::widget;
9
10use super::{Pad, RenderText};
11
12/**
13Puts text onto the screen.
14
15Responds with [TextResponse].
16
17## Examples
18```rust
19# let _handle = yakui_widgets::DocTest::start();
20# use yakui::widgets::Text;
21yakui::label("Default text label style");
22
23yakui::text(32.0, "Custom font size");
24
25let mut text = Text::new(32.0, "Title");
26text.style.color = yakui::Color::RED;
27text.show();
28```
29*/
30#[derive(Debug)]
31#[non_exhaustive]
32#[must_use = "yakui widgets do nothing if you don't `show` them"]
33pub struct Text {
34    pub text: Cow<'static, str>,
35    pub style: TextStyle,
36    pub padding: Pad,
37}
38
39impl Text {
40    pub fn new<S: Into<Cow<'static, str>>>(font_size: f32, text: S) -> Self {
41        let mut style = TextStyle::label();
42        style.font_size = font_size;
43
44        Self {
45            text: text.into(),
46            style,
47            padding: Pad::ZERO,
48        }
49    }
50
51    pub fn label(text: Cow<'static, str>) -> Self {
52        Self {
53            text,
54            style: TextStyle::label(),
55            padding: Pad::all(8.0),
56        }
57    }
58
59    pub fn show(self) -> Response<TextResponse> {
60        widget::<TextWidget>(self)
61    }
62}
63
64#[derive(Debug)]
65pub struct TextWidget {
66    props: Text,
67}
68
69pub type TextResponse = ();
70
71impl Widget for TextWidget {
72    type Props<'a> = Text;
73    type Response = TextResponse;
74
75    fn new() -> Self {
76        Self {
77            props: Text::new(0.0, Cow::Borrowed("")),
78        }
79    }
80
81    fn update(&mut self, props: Self::Props<'_>) -> Self::Response {
82        self.props = props;
83
84        let mut render = RenderText::label(self.props.text.clone());
85        render.style = self.props.style.clone();
86
87        pad(self.props.padding, || {
88            render.show();
89        });
90    }
91}