mln_expression/
format_section_override.rs1use std::sync::Arc;
6
7use feature::Value as MbglValue;
8use mln_util::Color;
9
10use crate::expression::{EvalResult, EvaluationContext, Expr, GlobalStateMap, Node, Output, SharedExpr};
11use crate::value::Value;
12
13#[derive(Clone, PartialEq, mln_wire::Wire)]
15pub enum OverrideDefault {
16 Constant(Color),
17 Expression {
20 expression: SharedExpr,
21 captured_global_state: Option<Arc<GlobalStateMap>>,
22 },
23}
24
25#[derive(Clone, PartialEq, mln_wire::Wire)]
26pub struct FormatSectionOverride {
27 default_value: OverrideDefault,
28 property_name: String,
29}
30
31impl FormatSectionOverride {
32 #[must_use]
34 pub fn new_expr(default_value: OverrideDefault, property_name: String) -> Expr {
35 Expr::new(Node::FormatSectionOverride(Box::new(FormatSectionOverride { default_value, property_name })))
36 }
37
38 #[must_use]
39 pub fn default_value(&self) -> &OverrideDefault {
40 &self.default_value
41 }
42
43 #[must_use]
44 pub fn property_name(&self) -> &str {
45 &self.property_name
46 }
47
48 pub(crate) fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a Expr)) {
49 if let OverrideDefault::Expression { expression, .. } = &self.default_value {
50 visit(expression);
51 }
52 }
53
54 pub(crate) fn eval_color(&self, context: &EvaluationContext<'_>) -> EvalResult<Color> {
55 if let Some(Value::Object(section)) = context.formatted_section
56 && let Some(hit) = section.get(&self.property_name)
57 {
58 return Color::from_value(hit.clone());
59 }
60 match &self.default_value {
61 OverrideDefault::Expression { expression, captured_global_state } => {
62 if context.global_state.is_none()
66 && let Some(state) = captured_global_state
67 {
68 let mut context_with_state = *context;
69 context_with_state.global_state = Some(state);
70 return expression.eval_color(&context_with_state);
71 }
72 expression.eval_color(context)
73 }
74 OverrideDefault::Constant(color) => Ok(*color),
75 }
76 }
77
78 pub(crate) fn serialize(&self) -> MbglValue {
79 let mut serialized = vec![MbglValue::String("format-section-override".to_owned())];
80 self.each_child(&mut |child| serialized.push(child.serialize()));
81 MbglValue::Array(serialized)
82 }
83}