Skip to main content

mln_style/expression/forms/
format.rs

1use crate::color::Color;
2use crate::conversion::Convertible;
3use crate::expression::formatted::{
4    FontStack, Formatted, FormattedSection, K_FORMATTED_SECTION_FONT_SCALE, K_FORMATTED_SECTION_TEXT_COLOR,
5    K_FORMATTED_SECTION_TEXT_FONT, K_FORMATTED_SECTION_VERTICAL_ALIGN,
6};
7use crate::expression::parse::{ParseResult, ParsingContext};
8use crate::expression::type_::Type;
9use crate::expression::value::{Value, from_expression_value, to_string};
10use crate::expression::{EvaluationContext, EvaluationError, EvaluationResult, Expr, Node};
11use crate::feature::{Value as FeatureValue, ValueObject};
12use crate::types::VerticalAlign;
13
14/// A section of a `format` expression: its content and options.
15#[derive(Clone, PartialEq, mln_wire::Wire)]
16pub struct FormatExpressionSection {
17    /// Content can be expression that evaluates to String or Image.
18    pub(crate) content: Expr,
19
20    // Text related section options.
21    pub(crate) font_scale: Option<Expr>,
22    pub(crate) text_font: Option<Expr>,
23    pub text_color: Option<Expr>,
24
25    /// A string expression, for text and image sections.
26    pub(crate) vertical_align: Option<Expr>,
27}
28
29impl FormatExpressionSection {
30    #[must_use]
31    pub fn new(content: Expr) -> Self {
32        FormatExpressionSection { content, font_scale: None, text_font: None, text_color: None, vertical_align: None }
33    }
34
35    pub fn set_text_section_options(
36        &mut self,
37        font_scale: Option<Expr>,
38        text_font: Option<Expr>,
39        text_color: Option<Expr>,
40    ) {
41        if let Some(font_scale) = font_scale {
42            self.font_scale = Some(font_scale);
43        }
44        if let Some(text_font) = text_font {
45            self.text_font = Some(text_font);
46        }
47        if let Some(text_color) = text_color {
48            self.text_color = Some(text_color);
49        }
50    }
51}
52
53/// Evaluates a section's `vertical-align` option. A name that isn't one of
54/// the options aligns to the bottom, as when the option is missing.
55fn evaluate_vertical_align(
56    vertical_align: Option<&Expr>,
57    params: &EvaluationContext<'_>,
58) -> Result<Option<VerticalAlign>, EvaluationError> {
59    let Some(vertical_align) = vertical_align else {
60        return Ok(None);
61    };
62    Ok(match vertical_align.evaluate(params)? {
63        Value::String(name) => name.parse().ok(),
64        _ => None,
65    })
66}
67
68/// `["format", content, options, ...]`.
69#[derive(Clone, PartialEq, mln_wire::Wire)]
70pub struct FormatExpression {
71    sections: Vec<FormatExpressionSection>,
72}
73
74impl FormatExpression {
75    #[must_use]
76    pub fn new_expr(sections: Vec<FormatExpressionSection>) -> Expr {
77        Expr::new(Node::Format(Box::new(FormatExpression { sections })))
78    }
79
80    #[must_use]
81    pub fn sections(&self) -> &[FormatExpressionSection] {
82        &self.sections
83    }
84
85    pub(crate) fn parse(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
86        let args_length = value.array_length();
87        if args_length < 2 {
88            ctx.error("Expected at least one argument.".to_owned());
89            return None;
90        }
91
92        if value.array_member(1).is_object() {
93            ctx.error("First argument must be an image or text section.".to_owned());
94            return None;
95        }
96
97        let mut sections: Vec<FormatExpressionSection> = Vec::new();
98        let mut next_token_may_be_object = false;
99        for i in 1..args_length {
100            let arg = value.array_member(i);
101
102            if next_token_may_be_object && arg.is_object() {
103                next_token_may_be_object = false;
104
105                let mut font_scale = None;
106                if let Some(option) = arg.object_member(K_FORMATTED_SECTION_FONT_SCALE) {
107                    font_scale = Some(ctx.parse(&option, 1, Some(Type::Number), None)?);
108                }
109
110                let mut text_font = None;
111                if let Some(option) = arg.object_member(K_FORMATTED_SECTION_TEXT_FONT) {
112                    text_font = Some(ctx.parse(&option, 1, Some(Type::array(Type::String)), None)?);
113                }
114
115                let mut text_color = None;
116                if let Some(option) = arg.object_member(K_FORMATTED_SECTION_TEXT_COLOR) {
117                    text_color = Some(ctx.parse(&option, 1, Some(Type::Color), None)?);
118                }
119
120                let mut vertical_align = None;
121                if let Some(option) = arg.object_member(K_FORMATTED_SECTION_VERTICAL_ALIGN) {
122                    if let Some(name) = option.to_string()
123                        && name.parse::<VerticalAlign>().is_err()
124                    {
125                        ctx.error(format!(
126                            "'vertical-align' must be one of: 'bottom', 'center', 'top' but found '{name}' instead."
127                        ));
128                        return None;
129                    }
130                    vertical_align = Some(ctx.parse(&option, 1, Some(Type::String), None)?);
131                }
132
133                let Some(section) = sections.last_mut() else {
134                    ctx.error("First argument must be an image or text section.".to_owned());
135                    return None;
136                };
137                section.set_text_section_options(font_scale, text_font, text_color);
138                section.vertical_align = vertical_align;
139            } else {
140                let Some(parsed_arg) = ctx.parse(&arg, 1, Some(Type::Value), None) else {
141                    ctx.error("Cannot parse formatted section.".to_owned());
142                    return None;
143                };
144
145                next_token_may_be_object = true;
146                sections.push(FormatExpressionSection::new(parsed_arg));
147            }
148        }
149
150        Some(FormatExpression::new_expr(sections))
151    }
152
153    pub(crate) fn evaluate(&self, params: &EvaluationContext<'_>) -> EvaluationResult {
154        let mut evaluated_sections = Vec::new();
155        for section in &self.sections {
156            let content_result = section.content.evaluate(params)?;
157
158            if let Value::Image(image) = &content_result {
159                // Omit sections with empty image ids.
160                if !image.id().is_empty() {
161                    evaluated_sections.push(FormattedSection {
162                        vertical_align: evaluate_vertical_align(section.vertical_align.as_ref(), params)?,
163                        ..FormattedSection::from_image(image.clone())
164                    });
165                }
166                // Image sections take no text options.
167                continue;
168            }
169            // Any value converts to a string.
170            let evaluated_text = to_string(&content_result);
171
172            let mut evaluated_font_scale = None;
173            if let Some(font_scale) = &section.font_scale {
174                let font_scale_result = font_scale.evaluate(params)?;
175                let Some(font_scale_value) = font_scale_result.as_number() else {
176                    return Err(EvaluationError::type_mismatch(&Type::Number, &font_scale_result));
177                };
178                evaluated_font_scale = Some(font_scale_value);
179            }
180
181            let mut evaluated_text_font: Option<FontStack> = None;
182            if let Some(text_font) = &section.text_font {
183                let text_font_result = text_font.evaluate(params)?;
184                let Some(text_font_value) = from_expression_value::<Vec<String>>(&text_font_result) else {
185                    return Err(EvaluationError::new("Format text-font option must evaluate to an array of strings"));
186                };
187                evaluated_text_font = Some(text_font_value);
188            }
189
190            let mut evaluated_text_color = None;
191            if let Some(text_color) = &section.text_color {
192                let text_color_result = text_color.evaluate(params)?;
193
194                evaluated_text_color = from_expression_value::<Color>(&text_color_result);
195                if evaluated_text_color.is_none() {
196                    return Err(EvaluationError::new("Format text-color option must evaluate to Color"));
197                }
198            }
199            evaluated_sections.push(FormattedSection {
200                vertical_align: evaluate_vertical_align(section.vertical_align.as_ref(), params)?,
201                ..FormattedSection::new(evaluated_text, evaluated_font_scale, evaluated_text_font, evaluated_text_color)
202            });
203        }
204        Ok(Value::Formatted(Formatted::new(evaluated_sections)))
205    }
206
207    pub(crate) fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a Expr)) {
208        for section in &self.sections {
209            visit(&section.content);
210            if let Some(font_scale) = &section.font_scale {
211                visit(font_scale);
212            }
213            if let Some(text_font) = &section.text_font {
214                visit(text_font);
215            }
216            if let Some(text_color) = &section.text_color {
217                visit(text_color);
218            }
219            if let Some(vertical_align) = &section.vertical_align {
220                visit(vertical_align);
221            }
222        }
223    }
224
225    pub(crate) fn serialize(&self) -> FeatureValue {
226        let mut serialized = vec![FeatureValue::String("format".to_owned())];
227        for section in &self.sections {
228            serialized.push(section.content.serialize());
229            let mut options = ValueObject::new();
230            if let Some(font_scale) = &section.font_scale {
231                options.insert(K_FORMATTED_SECTION_FONT_SCALE.to_owned(), font_scale.serialize());
232            }
233            if let Some(text_font) = &section.text_font {
234                options.insert(K_FORMATTED_SECTION_TEXT_FONT.to_owned(), text_font.serialize());
235            }
236            if let Some(text_color) = &section.text_color {
237                options.insert(K_FORMATTED_SECTION_TEXT_COLOR.to_owned(), text_color.serialize());
238            }
239            if let Some(vertical_align) = &section.vertical_align {
240                options.insert(K_FORMATTED_SECTION_VERTICAL_ALIGN.to_owned(), vertical_align.serialize());
241            }
242            serialized.push(FeatureValue::Object(options));
243        }
244        FeatureValue::Array(serialized)
245    }
246}