Skip to main content

mln_style/expression/
formatted.rs

1use std::fmt;
2
3use crate::color::Color;
4use crate::conversion::{Convertible, Error};
5use crate::expression::image::Image;
6use crate::types::VerticalAlign;
7
8pub(crate) const K_FORMATTED_SECTION_FONT_SCALE: &str = "font-scale";
9pub(crate) const K_FORMATTED_SECTION_TEXT_FONT: &str = "text-font";
10pub const K_FORMATTED_SECTION_TEXT_COLOR: &str = "text-color";
11pub(crate) const K_FORMATTED_SECTION_VERTICAL_ALIGN: &str = "vertical-align";
12
13/// A list of font names.
14pub(crate) type FontStack = Vec<String>;
15
16#[derive(Clone, Debug, Default, PartialEq, mln_wire::Wire)]
17pub struct FormattedSection {
18    pub text: String,
19    pub image: Option<Image>,
20    pub font_scale: Option<f64>,
21    pub font_stack: Option<FontStack>,
22    pub text_color: Option<Color>,
23    /// Where the text or image sits in its line. `None` is
24    /// [`VerticalAlign::Bottom`].
25    pub vertical_align: Option<VerticalAlign>,
26}
27
28impl FormattedSection {
29    #[must_use]
30    pub fn new(
31        text: String,
32        font_scale: Option<f64>,
33        font_stack: Option<FontStack>,
34        text_color: Option<Color>,
35    ) -> Self {
36        FormattedSection { text, image: None, font_scale, font_stack, text_color, vertical_align: None }
37    }
38
39    #[must_use]
40    pub fn from_image(image: Image) -> Self {
41        FormattedSection { image: Some(image), ..Default::default() }
42    }
43}
44
45#[derive(Clone, Debug, Default, PartialEq, mln_wire::Wire)]
46pub struct Formatted {
47    pub sections: Vec<FormattedSection>,
48}
49
50/// The sections' text, concatenated.
51impl fmt::Display for Formatted {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        for section in &self.sections {
54            f.write_str(&section.text)?;
55        }
56        Ok(())
57    }
58}
59
60impl Formatted {
61    #[must_use]
62    pub fn from_plain(plain_u8_string: &str) -> Self {
63        Formatted { sections: vec![FormattedSection::new(plain_u8_string.to_owned(), None, None, None)] }
64    }
65
66    #[must_use]
67    pub fn new(sections: Vec<FormattedSection>) -> Self {
68        Formatted { sections }
69    }
70
71    #[must_use]
72    pub fn is_empty(&self) -> bool {
73        if self.sections.is_empty() {
74            return true;
75        }
76
77        !self
78            .sections
79            .iter()
80            .any(|section| !section.text.is_empty() || section.image.as_ref().is_some_and(|i| !i.is_empty()))
81    }
82}
83
84/// Converts a plain string. A `text-field` array is a `["format", ...]`
85/// expression, which the property value conversion parses before this.
86pub fn convert_formatted(value: &Convertible<'_>, error: &mut Error) -> Option<Formatted> {
87    if let Some(result) = value.to_string() {
88        Some(Formatted::from_plain(&result))
89    } else {
90        error.message = "value must be a string".to_owned();
91        None
92    }
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98
99    #[test]
100    fn formatted_text_is_empty_without_text_or_an_image() {
101        let text = |text: &str| FormattedSection::new(text.to_owned(), None, None, None);
102        let image = |name: &str| FormattedSection::from_image(Image::new(name));
103        // (sections, empty)
104        let cases = [
105            (vec![], true),
106            (vec![text("")], true),
107            (vec![text(""), text(""), text("")], true),
108            (vec![text(""), FormattedSection::from_image(Image::default()), text("")], true),
109            (vec![text(""), text("Formatted"), text("")], false),
110            (vec![text(""), image("Image")], false),
111        ];
112        for (sections, empty) in cases {
113            assert_eq!(Formatted::new(sections.clone()).is_empty(), empty, "{sections:?}");
114        }
115    }
116}