Skip to main content

comb/core/
text.rs

1//! Styled text: a [`Span`] is a run of one style, a [`Line`] is a row of spans.
2
3use unicode_width::UnicodeWidthStr;
4
5use crate::core::style::Style;
6
7#[derive(Clone, Debug, Default)]
8pub struct Span {
9    pub content: String,
10    pub style: Style,
11}
12
13impl Span {
14    pub fn raw(content: impl Into<String>) -> Self {
15        Span {
16            content: content.into(),
17            style: Style::new(),
18        }
19    }
20
21    pub fn styled(content: impl Into<String>, style: Style) -> Self {
22        Span {
23            content: content.into(),
24            style,
25        }
26    }
27
28    pub fn width(&self) -> usize {
29        UnicodeWidthStr::width(self.content.as_str())
30    }
31}
32
33#[derive(Clone, Debug, Default)]
34pub struct Line {
35    pub spans: Vec<Span>,
36}
37
38impl Line {
39    pub fn new() -> Self {
40        Line { spans: Vec::new() }
41    }
42
43    pub fn from_spans(spans: Vec<Span>) -> Self {
44        Line { spans }
45    }
46
47    pub fn push(&mut self, span: Span) {
48        self.spans.push(span);
49    }
50
51    pub fn width(&self) -> usize {
52        self.spans.iter().map(Span::width).sum()
53    }
54}
55
56impl From<&str> for Line {
57    fn from(s: &str) -> Self {
58        Line::from_spans(vec![Span::raw(s)])
59    }
60}
61
62impl From<String> for Line {
63    fn from(s: String) -> Self {
64        Line::from_spans(vec![Span::raw(s)])
65    }
66}
67
68impl From<Span> for Line {
69    fn from(s: Span) -> Self {
70        Line::from_spans(vec![s])
71    }
72}
73
74impl From<Vec<Span>> for Line {
75    fn from(spans: Vec<Span>) -> Self {
76        Line::from_spans(spans)
77    }
78}