line_ui/element/
into.rs

1/*
2 * Copyright (c) 2025 Jasmine Tai. All rights reserved.
3 */
4
5use crate::element::{BoxElement, Element, FixedWidth, Styled, Text};
6use crate::style::Style;
7
8/// A type that can be converted into an element.
9pub trait IntoElement<'s>: Sized {
10    /// The element type to be converted into.
11    type ElementType: Element<'s>;
12
13    /// Converts this type into an [`Element`].
14    fn into_element(self) -> Self::ElementType;
15
16    /// Convenience function to wrap this element in a [`FixedWidth`].
17    fn fixed_width(self, width: usize) -> FixedWidth<Self::ElementType> {
18        FixedWidth::new(width, self.into_element())
19    }
20
21    /// Convenience function to wrap this element in a [`Styled`].
22    fn styled(self, style: Style) -> Styled<Self::ElementType> {
23        Styled::new(style, self.into_element())
24    }
25
26    /// Convenience function to box this element.
27    fn boxed(self) -> BoxElement<'s> {
28        BoxElement::new(self.into_element())
29    }
30}
31
32impl<'s, E: Element<'s>> IntoElement<'s> for E {
33    type ElementType = Self;
34
35    fn into_element(self) -> Self::ElementType {
36        self
37    }
38}
39
40impl<'s> IntoElement<'s> for &'s str {
41    type ElementType = Text<'s>;
42
43    fn into_element(self) -> Self::ElementType {
44        Text::from(self)
45    }
46}
47
48#[cfg(test)]
49mod tests {
50    use crate::Renderer;
51
52    use super::*;
53
54    #[test]
55    fn non_static_lifetime() {
56        let string = "foo".to_owned();
57        let not_static = string[..].into_element();
58
59        let mut r = Renderer::new(vec![]);
60        let _ = r.render(&not_static);
61        let _ = r.render(not_static.fixed_width(42));
62        let _ = r.finish();
63    }
64}