use toml_edit::{InlineTable, Item, TableLike, Value};
use crate::{
elements::{BarPointLayer, GuideGeometry, GuideSpec, PointLayer},
recipe::{
codec::{array_items, field, invalid, Codec},
style::{capture_text, read_text, text_field},
},
spec::{HeatmapNullRowAnnotation, PlotTextAnnotation, WaterfallLabels},
Color, Result, Text,
};
use crate::recipe::schema::{self as grammar, Schema};
use super::{PlotDescription, StyleEdit};
const STYLE_GUIDE: &[grammar::Field] = &[
grammar::custom("kind", true, |_| {
grammar::choices(&["horizontal", "vertical", "segment"])
}),
grammar::optional::<Option<Color>>("color"),
grammar::optional::<Option<f32>>("width"),
grammar::optional::<Option<crate::style::LinePattern>>("pattern"),
];
const STYLE_POINT: &[grammar::Field] = &[
grammar::optional::<Option<Color>>("color"),
grammar::optional::<Option<u32>>("radius"),
grammar::optional::<Option<f64>>("alpha"),
grammar::custom("legend_label", false, crate::recipe::style::text_schema),
grammar::optional::<Option<crate::text::TextLayout>>("label_text_layout"),
];
const STYLE_BAR_POINT: &[grammar::Field] = &[
grammar::optional::<Option<Color>>("color"),
grammar::optional::<Option<u32>>("radius"),
];
const STYLE_NULL_ROW: &[grammar::Field] = &[
grammar::mandatory::<String>("row"),
grammar::custom("text", false, crate::recipe::style::text_schema),
];
const STYLE_WATERFALL: &[grammar::Field] = &[
grammar::custom("base", false, crate::recipe::style::text_schema),
grammar::custom("terminal", false, crate::recipe::style::text_schema),
];
pub(super) fn schema(ctx: &mut Schema, name: &str) -> Option<serde_json::Value> {
Some(match name {
"guides" => grammar::array(grammar::record(ctx, STYLE_GUIDE)),
"point_layers" => grammar::array(grammar::record(ctx, STYLE_POINT)),
"bar_point_layers" => grammar::array(grammar::record(ctx, STYLE_BAR_POINT)),
"panel_text_annotations" => grammar::array(crate::recipe::style::text_schema(ctx)),
"heatmap_null_row_annotations" => grammar::array(grammar::record(ctx, STYLE_NULL_ROW)),
"waterfall_labels" => grammar::record(ctx, STYLE_WATERFALL),
_ => return None,
})
}
fn ordered<T>(
fields: &dyn TableLike,
name: &str,
read: impl FnMut(&Item) -> Result<T>,
) -> Result<Vec<T>> {
fields.get(name).map_or_else(
|| Ok(Vec::new()),
|item| array_items(item)?.map(read).collect(),
)
}
fn put_array<T>(
fields: &mut InlineTable,
name: &str,
values: &[T],
capture: impl FnMut(&T) -> Value,
) {
if !values.is_empty() {
fields.insert(name, Value::Array(values.iter().map(capture).collect()));
}
}
fn guide_kind(guide: &GuideSpec) -> &'static str {
match guide.geometry() {
GuideGeometry::Horizontal { .. } => "horizontal",
GuideGeometry::Vertical { .. } => "vertical",
GuideGeometry::Segment { .. } => "segment",
}
}
struct GuideAppearance {
kind: String,
color: Option<Color>,
width: Option<f32>,
pattern: Option<crate::style::LinePattern>,
}
impl GuideAppearance {
fn read(item: &Item) -> Result<Self> {
let fields = grammar::record_fields(item, STYLE_GUIDE)?;
let kind: String = field(fields, "kind", None)?;
if !matches!(kind.as_str(), "horizontal" | "vertical" | "segment") {
return Err(invalid("unknown guide style role"));
}
let width = field(fields, "width", Some(None))?;
if let Some(width) = width {
crate::layers::validate_guide_width(width)?;
}
Ok(Self {
kind,
color: field(fields, "color", Some(None))?,
width,
pattern: field(fields, "pattern", Some(None))?,
})
}
fn capture(guide: &GuideSpec) -> Value {
let mut fields = InlineTable::new();
fields.insert("kind", guide_kind(guide).into());
optional(&mut fields, "color", guide.get_color().as_ref());
optional(&mut fields, "width", guide.get_width().as_ref());
optional(&mut fields, "pattern", guide.get_pattern().as_ref());
fields.into()
}
fn apply(self, guide: &mut GuideSpec) -> Result<()> {
if self.kind != guide_kind(guide) {
return Err(invalid(
"guide style requires the same actual geometry role",
));
}
guide.replace_visual(self.color, self.width, self.pattern);
Ok(())
}
}
fn optional<T: Codec>(fields: &mut InlineTable, key: &str, value: Option<&T>) {
if let Some(value) = value {
fields.insert(key, value.encode());
}
}
struct PointAppearance {
color: Option<Color>,
radius: Option<u32>,
alpha: Option<f64>,
legend: Option<Text>,
layout: Option<crate::text::TextLayout>,
}
impl PointAppearance {
fn read(item: &Item) -> Result<Self> {
let fields = grammar::record_fields(item, STYLE_POINT)?;
let radius = field(fields, "radius", Some(None))?;
if let Some(radius) = radius {
crate::layers::validate_point_radius("point-layer", radius)?;
}
let alpha = field::<Option<f64>>(fields, "alpha", Some(None))?
.map(crate::alpha::validated_alpha)
.transpose()?;
Ok(Self {
color: field(fields, "color", Some(None))?,
radius,
alpha,
legend: fields.get("legend_label").map(read_text).transpose()?,
layout: field(fields, "label_text_layout", Some(None))?,
})
}
fn capture(layer: &PointLayer) -> Value {
let mut fields = InlineTable::new();
optional(&mut fields, "color", layer.get_color().as_ref());
optional(&mut fields, "radius", layer.get_radius().as_ref());
optional(&mut fields, "alpha", layer.get_alpha().as_ref());
if let Some(legend) = layer.legend_content() {
fields.insert("legend_label", capture_text(legend));
}
optional(
&mut fields,
"label_text_layout",
layer.label_layout.as_ref(),
);
fields.into()
}
fn apply(self, layer: &mut PointLayer) -> Result<()> {
if self
.legend
.as_ref()
.is_some_and(|text| text != &Text::UNSET)
&& layer.legend_content().is_none()
{
return Err(invalid("point layer has no target legend-label role"));
}
if self.layout.is_some() && layer.label_values().is_none() {
return Err(invalid("point layer has no target observation-label role"));
}
layer.replace_visual(
self.color,
self.radius,
self.alpha,
self.legend.unwrap_or(Text::UNSET),
self.layout,
);
Ok(())
}
}
struct BarPointAppearance {
color: Option<Color>,
radius: Option<u32>,
}
impl BarPointAppearance {
fn read(item: &Item) -> Result<Self> {
let fields = grammar::record_fields(item, STYLE_BAR_POINT)?;
let radius = field(fields, "radius", Some(None))?;
if let Some(radius) = radius {
crate::layers::validate_point_radius("bar-point-layer", radius)?;
}
Ok(Self {
color: field(fields, "color", Some(None))?,
radius,
})
}
fn capture(layer: &BarPointLayer) -> Value {
let mut fields = InlineTable::new();
optional(&mut fields, "color", layer.get_color().as_ref());
optional(&mut fields, "radius", layer.get_radius().as_ref());
fields.into()
}
fn apply(self, layer: &mut BarPointLayer) {
layer.replace_visual(self.color, self.radius);
}
}
fn apply_ordered<P, T>(
role: &str,
patches: Vec<P>,
targets: &mut [T],
apply: impl Fn(P, &mut T) -> Result<()>,
) -> Result<()> {
if patches.len() > targets.len() {
return Err(invalid(format!(
"{role}: target lacks an authored style slot"
)));
}
for (index, (patch, target)) in patches.into_iter().zip(targets).enumerate() {
apply(patch, target).map_err(|error| error.with_prefix(&format!("{role}[{index}]")))?;
}
Ok(())
}
fn capture_null_row(annotation: &HeatmapNullRowAnnotation) -> Value {
let mut fields = InlineTable::new();
fields.insert("row", annotation.row_label().into());
fields.insert("text", capture_text(annotation.content()));
fields.into()
}
fn read_null_rows(fields: &dyn TableLike) -> Result<Vec<(String, Text)>> {
let values = ordered(fields, "heatmap_null_row_annotations", |item| {
let fields = grammar::record_fields(item, STYLE_NULL_ROW)?;
Ok((
field::<String>(fields, "row", None)?,
text_field(fields, "text")?,
))
})?;
let mut seen = std::collections::HashSet::new();
for (row, _) in &values {
if !seen.insert(row) {
return Err(invalid("duplicate null-row style target"));
}
}
Ok(values)
}
fn apply_null_rows(
patches: Vec<(String, Text)>,
targets: &mut [HeatmapNullRowAnnotation],
) -> Result<()> {
for (row, style) in patches {
let target = targets
.iter_mut()
.find(|annotation| annotation.row_label() == row)
.ok_or_else(|| invalid(format!("null-row style has no target for {row:?}")))?;
let mut text = target.content().clone();
text.apply_appearance(style);
*target = HeatmapNullRowAnnotation::new(row, text)?;
}
Ok(())
}
fn apply_waterfall(style: [Text; 2], target: &mut Option<WaterfallLabels>) -> Result<()> {
if let Some(labels) = target {
let [mut base, mut terminal] = labels.contents().map(Clone::clone);
let [base_style, terminal_style] = style;
base.apply_appearance(base_style);
terminal.apply_appearance(terminal_style);
*labels = WaterfallLabels::new(base, terminal)?;
} else if style.iter().any(|text| text != &Text::UNSET) {
return Err(invalid(
"waterfall label style requires target label owners",
));
}
Ok(())
}
pub(super) fn capture(description: &PlotDescription, fields: &mut InlineTable) {
let payload = &description.payload;
put_array(fields, "guides", &payload.guides, GuideAppearance::capture);
put_array(
fields,
"point_layers",
&payload.point_layers,
PointAppearance::capture,
);
put_array(
fields,
"bar_point_layers",
&payload.bar_point_layers,
BarPointAppearance::capture,
);
put_array(
fields,
"panel_text_annotations",
&payload.panel_text_annotations,
|annotation| capture_text(annotation.content()),
);
put_array(
fields,
"heatmap_null_row_annotations",
&payload.heatmap_null_row_annotations,
capture_null_row,
);
if let Some(labels) = &payload.waterfall_labels {
let [base, terminal] = labels.contents();
let mut style = InlineTable::new();
style.insert("base", capture_text(base));
style.insert("terminal", capture_text(terminal));
fields.insert("waterfall_labels", style.into());
}
}
pub(super) fn read(fields: &dyn TableLike) -> Result<StyleEdit> {
let guides = ordered(fields, "guides", GuideAppearance::read)?;
let points = ordered(fields, "point_layers", PointAppearance::read)?;
let bar_points = ordered(fields, "bar_point_layers", BarPointAppearance::read)?;
let annotations = ordered(fields, "panel_text_annotations", read_text)?;
let null_rows = read_null_rows(fields)?;
let waterfall = if let Some(item) = fields.get("waterfall_labels") {
let fields = grammar::record_fields(item, STYLE_WATERFALL)?;
[text_field(fields, "base")?, text_field(fields, "terminal")?]
} else {
[Text::UNSET, Text::UNSET]
};
Ok(Box::new(move |description| {
let payload = description.payload_mut();
apply_ordered(
"guides",
guides,
&mut payload.guides,
GuideAppearance::apply,
)?;
apply_ordered(
"point_layers",
points,
&mut payload.point_layers,
PointAppearance::apply,
)?;
apply_ordered(
"bar_point_layers",
bar_points,
&mut payload.bar_point_layers,
|style, target| {
style.apply(target);
Ok(())
},
)?;
apply_ordered(
"panel_text_annotations",
annotations,
&mut payload.panel_text_annotations,
|style, target: &mut PlotTextAnnotation| {
let mut text = target.content().clone();
text.apply_appearance(style);
*target = PlotTextAnnotation::at(target.position().clone(), text)?;
Ok(())
},
)?;
apply_null_rows(null_rows, &mut payload.heatmap_null_row_annotations)?;
apply_waterfall(waterfall, &mut payload.waterfall_labels)
}))
}
fn project_array(
source: &dyn TableLike,
target: &mut InlineTable,
name: &str,
read: impl FnMut(&Item) -> Result<Value>,
) -> Result<()> {
if let Some(item) = source.get(name) {
let array = array_items(item)?
.map(read)
.collect::<Result<toml_edit::Array>>()?;
if !array.is_empty() {
target.insert(name, array.into());
}
}
Ok(())
}
pub(super) fn project(source: &dyn TableLike, target: &mut InlineTable) -> Result<()> {
use crate::recipe::style::copy_fields;
project_array(source, target, "guides", |item| {
Ok(GuideAppearance::capture(&GuideSpec::decode(item, None)?))
})?;
project_array(source, target, "point_layers", |item| {
let fields = item
.as_table_like()
.ok_or_else(|| invalid("expected a point layer"))?;
let mut style = InlineTable::new();
copy_fields(
fields,
&mut style,
&["color", "radius", "alpha", "label_text_layout"],
)?;
if let Some(legend) = field::<Option<Text>>(fields, "legend_label", Some(None))? {
style.insert("legend_label", capture_text(&legend));
}
Ok(style.into())
})?;
project_array(source, target, "bar_point_layers", |item| {
let fields = item
.as_table_like()
.ok_or_else(|| invalid("expected a bar point layer"))?;
let mut style = InlineTable::new();
copy_fields(fields, &mut style, &["color", "radius"])?;
Ok(style.into())
})?;
project_array(source, target, "panel_text_annotations", |item| {
Ok(capture_text(
PlotTextAnnotation::decode(item, None)?.content(),
))
})?;
project_array(source, target, "heatmap_null_row_annotations", |item| {
Ok(capture_null_row(&HeatmapNullRowAnnotation::decode(
item, None,
)?))
})?;
if let Some(labels) = field::<Option<WaterfallLabels>>(source, "waterfall_labels", Some(None))?
{
let [base, terminal] = labels.contents();
let mut style = InlineTable::new();
style.insert("base", capture_text(base));
style.insert("terminal", capture_text(terminal));
target.insert("waterfall_labels", style.into());
}
Ok(())
}