Skip to main content

mln_expression/
formatted.rs

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