1use std::collections::HashSet;
14
15use serde::{Deserialize, Serialize};
16use serde_json::{Map, Value};
17
18use super::{
19 ChartType, CustomNumberFormatConfig, DatetimeFormat, KeyValueOpts,
20 NumberSeriesStyleDefaultConfig,
21};
22use crate::utils::{CssKind, GradientStopSpec, canonicalize_gradient_stops};
23
24#[derive(Clone, Debug, Default, Deserialize, Serialize)]
29pub struct ColumnConfigSchema {
30 pub fields: Vec<ControlSpec>,
31}
32
33impl ColumnConfigSchema {
34 pub fn active_keys(&self) -> HashSet<String> {
40 let mut out = HashSet::new();
41 for spec in &self.fields {
42 for k in spec.serialized_keys() {
43 out.insert(k.to_string());
44 }
45 }
46 out
47 }
48
49 pub fn leaf_fields(&self) -> Vec<&ControlSpec> {
50 fn collect<'a>(fields: &'a [ControlSpec], out: &mut Vec<&'a ControlSpec>) {
51 for spec in fields {
52 match spec {
53 ControlSpec::Group { fields, .. } => collect(fields, out),
54 leaf => out.push(leaf),
55 }
56 }
57 }
58
59 let mut out = vec![];
60 collect(&self.fields, &mut out);
61 out
62 }
63}
64
65#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
67#[serde(rename_all = "snake_case")]
68pub enum NumberStat {
69 AbsMax,
71}
72
73#[derive(Clone, Debug, Deserialize, Serialize)]
79#[serde(tag = "kind")]
80pub enum ControlSpec {
81 Enum {
82 key: String,
83 variants: Vec<EnumVariant>,
84 default: String,
85 },
86
87 Font {
91 key: String,
92 default: String,
93
94 #[serde(default, skip_serializing_if = "Option::is_none")]
95 size: Option<FontSize>,
96
97 #[serde(default, skip_serializing_if = "Option::is_none")]
98 bold: Option<FontToggle>,
99
100 #[serde(default, skip_serializing_if = "Option::is_none")]
101 italic: Option<FontToggle>,
102 },
103 Alignment {
106 key: String,
107
108 #[serde(default, skip_serializing_if = "Option::is_none")]
112 default: Option<Alignment>,
113
114 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
116 corners: bool,
117 },
118 Bool {
119 key: String,
120 default: bool,
121 },
122 Number {
123 key: String,
124 default: f64,
125
126 #[serde(default, skip_serializing_if = "Option::is_none")]
128 include: Option<bool>,
129
130 #[serde(default, skip_serializing_if = "Option::is_none")]
131 min: Option<f64>,
132
133 #[serde(default, skip_serializing_if = "Option::is_none")]
134 max: Option<f64>,
135
136 #[serde(default, skip_serializing_if = "Option::is_none")]
137 step: Option<f64>,
138
139 #[serde(default, skip_serializing_if = "Option::is_none")]
142 default_stat: Option<NumberStat>,
143 },
144 String {
145 key: String,
146 default: String,
147 #[serde(default, skip_serializing_if = "Option::is_none")]
148 placeholder: Option<String>,
149 },
150 Color {
151 key: String,
152 default: String,
153 },
154 Palette {
155 key: String,
156 default: String,
157
158 #[serde(default, skip_serializing_if = "Option::is_none")]
159 max: Option<usize>,
160 },
161 GradientStops {
162 key: String,
163 default: String,
164
165 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
166 discrete: bool,
167 },
168 DatetimeFormat {
169 #[serde(default, skip_serializing_if = "Option::is_none")]
172 default: Option<DatetimeFormat>,
173 },
174 NumberSeriesStyle {
175 default: NumberSeriesStyleDefaultConfig,
176 },
177 Symbols {
178 default: KeyValueOpts,
179 },
180 NumberFormat {
181 #[serde(default, skip_serializing_if = "Option::is_none")]
184 default: Option<CustomNumberFormatConfig>,
185 },
186 AggregateDepth,
187
188 Group {
189 key: String,
190 #[serde(default)]
191 fields: Vec<ControlSpec>,
192 },
193}
194
195#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
199#[serde(rename_all = "kebab-case")]
200pub enum Alignment {
201 TopLeft,
202 Top,
203 TopRight,
204 Left,
205 Center,
206 Right,
207 BottomLeft,
208 Bottom,
209 BottomRight,
210}
211
212impl Alignment {
213 pub const ALL: [Alignment; 9] = [
215 Alignment::TopLeft,
216 Alignment::Top,
217 Alignment::TopRight,
218 Alignment::Left,
219 Alignment::Center,
220 Alignment::Right,
221 Alignment::BottomLeft,
222 Alignment::Bottom,
223 Alignment::BottomRight,
224 ];
225 pub const CORNERS: [Alignment; 4] = [
226 Alignment::TopLeft,
227 Alignment::TopRight,
228 Alignment::BottomLeft,
229 Alignment::BottomRight,
230 ];
231
232 pub fn is_corner(self) -> bool {
233 Self::CORNERS.contains(&self)
234 }
235
236 pub fn as_str(self) -> &'static str {
238 match self {
239 Alignment::TopLeft => "top-left",
240 Alignment::Top => "top",
241 Alignment::TopRight => "top-right",
242 Alignment::Left => "left",
243 Alignment::Center => "center",
244 Alignment::Right => "right",
245 Alignment::BottomLeft => "bottom-left",
246 Alignment::Bottom => "bottom",
247 Alignment::BottomRight => "bottom-right",
248 }
249 }
250
251 pub fn parse(src: &str) -> Option<Self> {
252 Self::ALL.into_iter().find(|x| x.as_str() == src)
253 }
254
255 pub fn humanized(self) -> String {
257 self.as_str()
258 .split('-')
259 .map(|word| {
260 let mut chars = word.chars();
261 match chars.next() {
262 Some(first) => first.to_uppercase().chain(chars).collect::<String>(),
263 None => String::new(),
264 }
265 })
266 .collect::<Vec<_>>()
267 .join(" ")
268 }
269}
270
271#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
274pub struct FontToggle {
275 pub key: String,
276 #[serde(default)]
277 pub default: bool,
278}
279
280#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
283pub struct FontSize {
284 pub key: String,
285 pub default: f64,
286
287 #[serde(default, skip_serializing_if = "Option::is_none")]
288 pub min: Option<f64>,
289
290 #[serde(default, skip_serializing_if = "Option::is_none")]
291 pub max: Option<f64>,
292
293 #[serde(default, skip_serializing_if = "Option::is_none")]
294 pub step: Option<f64>,
295}
296
297#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
298pub struct EnumVariant {
299 pub value: String,
300 #[serde(default, skip_serializing_if = "Option::is_none")]
301 pub label: Option<String>,
302}
303
304pub fn discrete_pair(stops: Vec<GradientStopSpec>) -> Vec<GradientStopSpec> {
307 let stops = canonicalize_gradient_stops(stops);
308 match (stops.first(), stops.last()) {
309 (Some(first), Some(last)) if stops.len() > 2 => vec![
310 GradientStopSpec {
311 color: first.color.clone(),
312 offset: 0.0,
313 },
314 GradientStopSpec {
315 color: last.color.clone(),
316 offset: 1.0,
317 },
318 ],
319 _ => stops,
320 }
321}
322
323impl ColumnConfigSchema {
324 pub fn canonicalize(self) -> Self {
325 self.canonicalize_defaults().group_format_controls()
326 }
327
328 pub fn resolve_stat_defaults(mut self, abs_max: Option<f64>) -> Self {
331 fn walk(fields: &mut [ControlSpec], abs_max: Option<f64>) {
332 for spec in fields {
333 match spec {
334 ControlSpec::Group { fields, .. } => walk(fields, abs_max),
335 ControlSpec::Number {
336 default,
337 default_stat: Some(NumberStat::AbsMax),
338 ..
339 } => {
340 if let Some(abs_max) = abs_max {
341 *default = abs_max;
342 }
343 },
344 _ => {},
345 }
346 }
347 }
348
349 walk(&mut self.fields, abs_max);
350 self
351 }
352
353 pub fn group_format_controls(mut self) -> Self {
354 fn is_format(spec: &ControlSpec) -> bool {
355 matches!(
356 spec,
357 ControlSpec::NumberFormat { .. } | ControlSpec::DatetimeFormat { .. }
358 )
359 }
360
361 fn walk(fields: &mut Vec<ControlSpec>) {
362 for spec in fields.iter_mut() {
363 if let ControlSpec::Group { key, fields } = spec
364 && key != "format"
365 {
366 walk(fields);
367 }
368 }
369
370 let first = fields.iter().position(is_format);
371 if let Some(first) = first {
372 let mut formats = vec![];
373 let mut i = first;
374 while i < fields.len() {
375 if is_format(&fields[i]) {
376 formats.push(fields.remove(i));
377 } else {
378 i += 1;
379 }
380 }
381
382 fields.insert(first, ControlSpec::Group {
383 key: "format".to_owned(),
384 fields: formats,
385 });
386 }
387 }
388
389 walk(&mut self.fields);
390 self
391 }
392
393 pub fn canonicalize_defaults(mut self) -> Self {
396 fn canonicalize_specs(fields: &mut Vec<ControlSpec>) {
397 fields.retain_mut(|spec| {
398 let (kind, key, default) = match spec {
399 ControlSpec::Group { fields, .. } => {
400 canonicalize_specs(fields);
401 return !fields.is_empty();
402 },
403 ControlSpec::Alignment {
404 key,
405 default: Some(default),
406 corners: true,
407 } if !default.is_corner() => {
408 tracing::error!(
409 "Dropping `{key}` — default `{}` is not a corner",
410 default.as_str()
411 );
412
413 return false;
414 },
415 ControlSpec::Color { key, default } => (CssKind::Color, key, default),
416 ControlSpec::Palette { key, default, .. } => (CssKind::Palette, key, default),
417 ControlSpec::GradientStops { key, default, .. } => {
418 (CssKind::Gradient, key, default)
419 },
420 _ => return true,
421 };
422
423 match kind.canonicalize(default) {
424 Ok(canonical) => {
425 *default = canonical;
426 true
427 },
428 Err(error) => {
429 tracing::error!("Dropping `{key}` — invalid schema default: {error}");
430 false
431 },
432 }
433 });
434 }
435
436 canonicalize_specs(&mut self.fields);
437 self
438 }
439
440 pub fn enum_variants_of(&self, key: &str) -> Option<&[EnumVariant]> {
442 self.leaf_fields().into_iter().find_map(|spec| match spec {
443 ControlSpec::Enum {
444 key: k, variants, ..
445 } if k == key => Some(variants.as_slice()),
446 _ => None,
447 })
448 }
449
450 pub fn css_kind_of(&self, key: &str) -> Option<CssKind> {
452 self.leaf_fields().into_iter().find_map(|spec| match spec {
453 ControlSpec::Color { key: k, .. } if k == key => Some(CssKind::Color),
454 ControlSpec::Palette { key: k, .. } if k == key => Some(CssKind::Palette),
455 ControlSpec::GradientStops { key: k, .. } if k == key => Some(CssKind::Gradient),
456 _ => None,
457 })
458 }
459}
460
461impl ControlSpec {
462 pub fn serialized_keys(&self) -> Vec<&str> {
468 match self {
469 ControlSpec::DatetimeFormat { .. } => vec!["date_format"],
470 ControlSpec::Font {
471 key,
472 size,
473 bold,
474 italic,
475 ..
476 } => [
477 Some(key.as_str()),
478 size.as_ref().map(|s| s.key.as_str()),
479 bold.as_ref().map(|t| t.key.as_str()),
480 italic.as_ref().map(|t| t.key.as_str()),
481 ]
482 .into_iter()
483 .flatten()
484 .collect(),
485 ControlSpec::NumberSeriesStyle { .. } => vec!["chart_type", "stack"],
486 ControlSpec::Symbols { .. } => vec!["symbols"],
487 ControlSpec::NumberFormat { .. } => vec!["number_format"],
488 ControlSpec::AggregateDepth => vec!["aggregate_depth"],
489 ControlSpec::Enum { key, .. }
490 | ControlSpec::Alignment { key, .. }
491 | ControlSpec::Bool { key, .. }
492 | ControlSpec::Number { key, .. }
493 | ControlSpec::String { key, .. }
494 | ControlSpec::Color { key, .. }
495 | ControlSpec::Palette { key, .. }
496 | ControlSpec::GradientStops { key, .. } => vec![key.as_str()],
497 ControlSpec::Group { fields, .. } => {
498 fields.iter().flat_map(|f| f.serialized_keys()).collect()
499 },
500 }
501 }
502}
503
504pub type OverrideValues = Map<String, Value>;
507
508impl ColumnConfigSchema {
509 pub fn apply_defaults(
513 &mut self,
514 layers: &[&Map<String, Value>],
515 is_float: bool,
516 ) -> (OverrideValues, Vec<(String, String)>) {
517 let (resolved, mut errors) = resolve_layers(layers);
518 let mut applied = OverrideValues::new();
519 fn walk(
520 fields: &mut [ControlSpec],
521 resolved: &OverrideValues,
522 is_float: bool,
523 applied: &mut OverrideValues,
524 errors: &mut Vec<(String, String)>,
525 ) {
526 for spec in fields {
527 if let ControlSpec::Group { fields, .. } = spec {
528 walk(fields, resolved, is_float, applied, errors);
529 continue;
530 }
531
532 let keys: Vec<String> = spec
533 .serialized_keys()
534 .into_iter()
535 .map(str::to_owned)
536 .collect();
537
538 for key in keys {
539 let Some(value) = resolved.get(&key) else {
540 continue;
541 };
542
543 match spec.apply_default(&key, value, is_float) {
544 Ok(Some(delivered)) => {
545 applied.insert(key, delivered);
546 },
547 Ok(None) => {},
548 Err(error) => errors.push((key, error)),
549 }
550 }
551 }
552 }
553
554 walk(
555 &mut self.fields,
556 &resolved,
557 is_float,
558 &mut applied,
559 &mut errors,
560 );
561
562 (applied, errors)
563 }
564}
565
566fn resolve_layers(layers: &[&Map<String, Value>]) -> (OverrideValues, Vec<(String, String)>) {
570 let mut resolved = OverrideValues::new();
571 let mut errors = vec![];
572 let mut date_format: Option<DatetimeFormat> = None;
573 let mut number_format: Option<CustomNumberFormatConfig> = None;
574 for layer in layers {
575 for (key, value) in layer.iter() {
576 match key.as_str() {
577 "date_format" => match serde_json::from_value::<DatetimeFormat>(value.clone())
578 .map_err(|e| e.to_string())
579 .and_then(|f| f.validate().map(|_| f))
580 {
581 Ok(format) => {
582 date_format = Some(date_format.unwrap_or_default().overlay(&format));
583 },
584 Err(error) => errors.push((key.clone(), error)),
585 },
586 "number_format" => {
587 match serde_json::from_value::<CustomNumberFormatConfig>(value.clone()) {
588 Ok(format) => {
589 number_format =
590 Some(number_format.unwrap_or_default().overlay(&format));
591 },
592 Err(error) => errors.push((key.clone(), error.to_string())),
593 }
594 },
595 _ => {
596 resolved.insert(key.clone(), value.clone());
597 },
598 }
599 }
600 }
601
602 if let Some(format) = date_format.and_then(|f| serde_json::to_value(f).ok()) {
603 resolved.insert("date_format".to_owned(), format);
604 }
605
606 if let Some(format) = number_format.and_then(|f| serde_json::to_value(f).ok()) {
607 resolved.insert("number_format".to_owned(), format);
608 }
609
610 (resolved, errors)
611}
612
613fn expect_str(value: &Value) -> Result<&str, String> {
614 value
615 .as_str()
616 .ok_or_else(|| format!("expected a string, got `{value}`"))
617}
618
619fn expect_bool(value: &Value) -> Result<bool, String> {
620 value
621 .as_bool()
622 .ok_or_else(|| format!("expected a boolean, got `{value}`"))
623}
624
625fn expect_number(value: &Value, min: Option<f64>, max: Option<f64>) -> Result<f64, String> {
626 let num = value
627 .as_f64()
628 .ok_or_else(|| format!("expected a number, got `{value}`"))?;
629
630 if min.is_some_and(|min| num < min) || max.is_some_and(|max| num > max) {
631 return Err(format!(
632 "{num} is outside {}..={}",
633 min.map(|x| x.to_string()).unwrap_or_default(),
634 max.map(|x| x.to_string()).unwrap_or_default()
635 ));
636 }
637
638 Ok(num)
639}
640
641impl ControlSpec {
642 pub fn apply_default(
646 &mut self,
647 key: &str,
648 value: &Value,
649 is_float: bool,
650 ) -> Result<Option<Value>, String> {
651 match self {
652 ControlSpec::Enum {
653 key: k,
654 variants,
655 default,
656 } if k == key => {
657 let value = expect_str(value)?;
658 if !variants.iter().any(|v| v.value == value) {
659 let expected = variants
660 .iter()
661 .map(|v| format!("`{}`", v.value))
662 .collect::<Vec<_>>()
663 .join(", ");
664
665 return Err(format!("`{value}` is not one of {expected}"));
666 }
667
668 *default = value.to_owned();
669 },
670 ControlSpec::Font {
671 key: k, default, ..
672 } if k == key => {
673 *default = expect_str(value)?.to_owned();
674 },
675 ControlSpec::Font {
676 size: Some(size), ..
677 } if size.key == key => {
678 size.default = expect_number(value, size.min, size.max)?;
679 },
680 ControlSpec::Font { bold, italic, .. }
681 if [&*bold, &*italic]
682 .into_iter()
683 .flatten()
684 .any(|toggle| toggle.key == key) =>
685 {
686 let value = expect_bool(value)?;
687 for toggle in [bold, italic].into_iter().flatten() {
688 if toggle.key == key {
689 toggle.default = value;
690 }
691 }
692 },
693 ControlSpec::Alignment {
694 key: k,
695 default,
696 corners,
697 } if k == key => {
698 let src = expect_str(value)?;
699 let alignment =
700 Alignment::parse(src).ok_or_else(|| format!("`{src}` is not an alignment"))?;
701
702 if *corners && !alignment.is_corner() {
703 return Err(format!("`{src}` is not a corner"));
704 }
705
706 *default = Some(alignment);
707 },
708 ControlSpec::Bool { key: k, default } if k == key => {
709 *default = expect_bool(value)?;
710 },
711 ControlSpec::Number {
712 key: k,
713 default,
714 min,
715 max,
716 default_stat,
717 ..
718 } if k == key => {
719 *default = expect_number(value, *min, *max)?;
720 *default_stat = None;
721 },
722 ControlSpec::String {
723 key: k, default, ..
724 } if k == key => {
725 *default = expect_str(value)?.to_owned();
726 },
727 ControlSpec::Color { key: k, default } if k == key => {
728 *default = CssKind::Color.canonicalize(expect_str(value)?)?;
729 return Ok(Some(Value::String(default.clone())));
730 },
731 ControlSpec::Palette {
732 key: k, default, ..
733 } if k == key => {
734 *default = CssKind::Palette.canonicalize(expect_str(value)?)?;
735 return Ok(Some(Value::String(default.clone())));
736 },
737 ControlSpec::GradientStops {
738 key: k, default, ..
739 } if k == key => {
740 *default = CssKind::Gradient.canonicalize(expect_str(value)?)?;
741 return Ok(Some(Value::String(default.clone())));
742 },
743 ControlSpec::DatetimeFormat { default } if key == "date_format" => {
744 let format: DatetimeFormat =
745 serde_json::from_value(value.clone()).map_err(|e| e.to_string())?;
746
747 *default = Some(default.clone().unwrap_or_default().overlay(&format));
748 },
749 ControlSpec::NumberFormat { default } if key == "number_format" => {
750 let format: CustomNumberFormatConfig =
751 serde_json::from_value(value.clone()).map_err(|e| e.to_string())?;
752
753 let resolved = default.clone().unwrap_or_default().overlay(&format);
754 resolved.validate(is_float)?;
755 *default = Some(resolved);
756 },
757 ControlSpec::NumberSeriesStyle { default } if key == "chart_type" => {
758 default.chart_type = serde_json::from_value::<ChartType>(value.clone())
759 .map_err(|e| e.to_string())?;
760 },
761 ControlSpec::NumberSeriesStyle { default } if key == "stack" => {
762 default.stack = Some(expect_bool(value)?);
763 },
764 ControlSpec::Symbols { .. } if key == "symbols" => {
765 return Err("`symbols` has no overridable default".to_owned());
766 },
767 ControlSpec::AggregateDepth if key == "aggregate_depth" => {
768 return Err("`aggregate_depth` has no overridable default".to_owned());
769 },
770 _ => return Ok(None),
771 }
772
773 Ok(Some(value.clone()))
774 }
775}
776
777#[derive(Clone, Debug, Deserialize, Serialize)]
782pub struct ColumnConfigFieldUpdate {
783 pub keys: Vec<String>,
784 pub value: serde_json::Map<String, Value>,
785}
786
787pub fn filter_to_schema(
791 config: &serde_json::Map<String, Value>,
792 active_keys: &HashSet<String>,
793) -> serde_json::Map<String, Value> {
794 config
795 .iter()
796 .filter(|(k, _)| active_keys.contains(k.as_str()))
797 .map(|(k, v)| (k.clone(), v.clone()))
798 .collect()
799}