line_ui/element/
text.rs

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