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