line_ui/element/
text.rs

1/*
2 * Copyright (c) 2025 Jasmine Tai. All rights reserved.
3 */
4
5use unicode_width::UnicodeWidthStr;
6
7use crate::element::Element;
8use crate::render::RenderChunk;
9
10/// An element that renders a piece of text.
11pub struct Text<'s> {
12    value: &'s str,
13    width: usize,
14}
15
16impl<'s> Text<'s> {
17    /// Creates a new [`Text`] from the given string.
18    pub fn new(value: &'s str) -> Self {
19        Text {
20            value,
21            width: value.width(),
22        }
23    }
24}
25
26impl<'s> From<&'s str> for Text<'s> {
27    fn from(value: &'s str) -> Self {
28        Text::new(value)
29    }
30}
31
32impl Element for Text<'_> {
33    fn width(&self) -> usize {
34        self.width
35    }
36
37    fn render(&self) -> impl DoubleEndedIterator<Item = RenderChunk<'_>> {
38        std::iter::once(RenderChunk::from(self.value))
39    }
40}
41
42#[test]
43fn basic() {
44    let element = Text::from("hello");
45    let render: Vec<_> = element.render().collect();
46    assert_eq!(render, ["hello".into()])
47}