use std::sync::Arc;
use toml_edit::{InlineTable, Item, TableLike, Value};
use crate::{
alpha::{AlphaInputs, AlphaTarget},
input::PlotInput,
kind::{Capability, Marker},
recipe::{
codec::{field, invalid, table, Codec},
figure::plot_kind,
style::{is_style, style_theme, text_field},
Recipe,
},
spec::{BarSpacing, LegendComposition, LegendPolicy, LinePathStyle, PlotKind, RawOverlay},
NumericFormat, Result, Text, Theme,
};
use crate::recipe::schema::{self as grammar, Schema};
use super::{
authored,
opacity::{AlphaStyle, TARGETS},
PlotDescription,
};
mod layers;
mod numbers;
pub(super) type StyleEdit = Box<dyn FnOnce(&mut PlotDescription) -> Result<()>>;
const FIELDS: &[&str] = &[
"scope",
"kind",
"theme",
"title",
"subtitle",
"caption",
"x_label",
"y_label",
"color_label",
"raincloud_hue_label",
"raw_overlay",
"line_path_style",
"interaction_connectors",
"legend",
"legend_composition",
"bar_spacing",
"point_outline_visible",
"markers_visible",
"color_by_sign",
"zero_line",
"text_layouts",
"axes",
"color_label_format",
"estimate_labels",
"total_format",
"heatmap_annotations",
"categorical_color_scale",
"continuous_color_scale",
"significance_mark_style",
"interaction_styles",
"guides",
"point_layers",
"bar_point_layers",
"panel_text_annotations",
"heatmap_null_row_annotations",
"waterfall_labels",
"point_alpha",
"line_alpha",
"fill_alpha",
"endpoints",
"fixed_color",
];
pub(crate) struct PlotStyle {
kind: PlotKind,
theme: Option<Arc<Theme>>,
basic: StyleEdit,
numbers: StyleEdit,
layers: StyleEdit,
alpha: Vec<(AlphaTarget, AlphaStyle)>,
}
fn capture_prose(description: &PlotDescription, fields: &mut InlineTable) {
let payload = &description.payload;
for (key, text) in [
("title", &description.title),
("subtitle", &description.subtitle),
("caption", &payload.caption),
("x_label", &payload.x_label),
("y_label", &payload.y_label),
("color_label", &payload.color_label),
("raincloud_hue_label", &payload.raincloud_hue_label),
] {
let appearance = text.appearance_only();
if appearance != Text::UNSET {
fields.insert(key, appearance.encode());
}
}
}
fn capture_basic(description: &PlotDescription, fields: &mut InlineTable) {
let payload = &description.payload;
authored(
fields,
"raw_overlay",
&description.raw_overlay,
&RawOverlay::default(),
);
authored(
fields,
"line_path_style",
&description.line_path_style,
&LinePathStyle::default(),
);
if let Some(value) = description.interaction_connectors {
fields.insert("interaction_connectors", value.encode());
}
authored(
fields,
"legend_composition",
&description.legend_composition,
&LegendComposition::default(),
);
authored(
fields,
"legend",
&payload.legend_policy,
&LegendPolicy::Automatic,
);
authored(
fields,
"bar_spacing",
&payload.bar_spacing,
&BarSpacing::default(),
);
authored(
fields,
"point_outline_visible",
&payload.point_outline_visible,
&true,
);
authored(fields, "markers_visible", &payload.markers_visible, &true);
authored(fields, "color_by_sign", &payload.color_by_sign, &false);
authored(fields, "zero_line", &payload.zero_line, &false);
authored(
fields,
"text_layouts",
&payload.text_layouts,
&crate::text::roles::TextRoles::default(),
);
if let Some(value) = &payload.categorical_color_scale {
fields.insert("categorical_color_scale", value.encode());
}
if let Some(value) = &payload.continuous_color_scale {
fields.insert("continuous_color_scale", value.encode());
}
if let Some(value) = &description.significance_mark_style {
fields.insert("significance_mark_style", value.encode());
}
if let Some(value) = &payload.interaction_styles {
fields.insert("interaction_styles", value.encode());
}
if let PlotInput::Dumbbell { endpoints, .. } = payload.input.as_ref() {
let mut appearance = InlineTable::new();
appearance.insert("left_color", endpoints.left_color().encode());
appearance.insert("right_color", endpoints.right_color().encode());
fields.insert("endpoints", appearance.into());
}
if let Some(color) = description.beeswarm_fixed_color() {
fields.insert("fixed_color", color.encode());
}
}
fn alpha_capability(target: AlphaTarget) -> Capability {
match target {
AlphaTarget::Point => Capability::PointAlpha,
AlphaTarget::Line => Capability::LineAlpha,
AlphaTarget::Fill => Capability::FillAlpha,
}
}
fn capture_alpha(kind: PlotKind, alpha: &AlphaInputs, fields: &mut InlineTable) -> Result<()> {
for (name, target) in TARGETS {
if alpha_capability(target).admits(kind) && !alpha.get(target).is_theme() {
fields.insert(name, AlphaStyle::capture(alpha.get(target))?);
}
}
Ok(())
}
fn read_prose(fields: &dyn TableLike) -> Result<StyleEdit> {
let title = text_field(fields, "title")?;
let subtitle = text_field(fields, "subtitle")?;
let caption = text_field(fields, "caption")?;
let x_label = text_field(fields, "x_label")?;
let y_label = text_field(fields, "y_label")?;
let color_label = text_field(fields, "color_label")?;
let raincloud_hue_label = text_field(fields, "raincloud_hue_label")?;
Ok(Box::new(move |description| {
if color_label != Text::UNSET && description.color_col().is_none() {
return Err(invalid(
"color label style requires an actual numeric color role",
));
}
description.title.apply_appearance(title);
description.subtitle.apply_appearance(subtitle);
let payload = description.payload_mut();
payload.caption.apply_appearance(caption);
payload.x_label.apply_appearance(x_label);
payload.y_label.apply_appearance(y_label);
payload.color_label.apply_appearance(color_label);
payload
.raincloud_hue_label
.apply_appearance(raincloud_hue_label);
Ok(())
}))
}
const ENDPOINT_STYLE_FIELDS: &[grammar::Field] = &[
grammar::mandatory::<crate::Color>("left_color"),
grammar::mandatory::<crate::Color>("right_color"),
];
fn input_paint(fields: &dyn TableLike, kind: PlotKind) -> Result<StyleEdit> {
let endpoints = fields
.get("endpoints")
.map(|item| {
let fields = grammar::record_fields(item, ENDPOINT_STYLE_FIELDS)?;
Ok::<_, crate::Error>((
field::<crate::Color>(fields, "left_color", None)?,
field::<crate::Color>(fields, "right_color", None)?,
))
})
.transpose()?;
let color = field::<Option<crate::Color>>(fields, "fixed_color", Some(None))?;
if endpoints.is_some() && kind != PlotKind::Dumbbell {
return Err(invalid("endpoint paint requires Dumbbell content"));
}
if fields.contains_key("fixed_color") && kind != PlotKind::Beeswarm {
return Err(invalid("fixed color style requires Beeswarm content"));
}
Ok(Box::new(move |description| {
if let Some((left, right)) = endpoints {
let PlotInput::Dumbbell { endpoints, .. } =
Arc::make_mut(&mut description.payload_mut().input)
else {
unreachable!("validated endpoint owner")
};
*endpoints = crate::plots::DumbbellEndpoints::new(
endpoints.left_label(),
left,
endpoints.right_label(),
right,
)?;
}
if kind == PlotKind::Beeswarm {
let PlotInput::Beeswarm { color: target, .. } =
Arc::make_mut(&mut description.payload_mut().input)
else {
unreachable!("validated beeswarm owner")
};
if matches!(target, Some(crate::scales::ColorSource::Numeric(_))) {
if color.is_some() {
return Err(invalid(
"fixed color style would replace a numeric color domain",
));
}
} else {
*target = color.map(crate::scales::ColorSource::Fixed);
}
}
Ok(())
}))
}
fn read_basic(fields: &dyn TableLike, kind: PlotKind) -> Result<StyleEdit> {
let prose = read_prose(fields)?;
let input = input_paint(fields, kind)?;
let raw_overlay = field(fields, "raw_overlay", Some(RawOverlay::default()))?;
let line_path_style = field(fields, "line_path_style", Some(LinePathStyle::default()))?;
let interaction_connectors = fields
.get("interaction_connectors")
.map(|item| bool::decode(item, None))
.transpose()?;
let legend_composition = field(
fields,
"legend_composition",
Some(LegendComposition::default()),
)?;
let legend = field(fields, "legend", Some(LegendPolicy::Automatic))?;
let bar_spacing = field(fields, "bar_spacing", Some(BarSpacing::default()))?;
let outline = field(fields, "point_outline_visible", Some(true))?;
let markers = field(fields, "markers_visible", Some(true))?;
let color_by_sign = field(fields, "color_by_sign", Some(false))?;
let zero_line = field(fields, "zero_line", Some(false))?;
let layouts = field(
fields,
"text_layouts",
Some(crate::text::roles::TextRoles::default()),
)?;
let categorical = field(fields, "categorical_color_scale", Some(None))?;
let continuous = field(fields, "continuous_color_scale", Some(None))?;
let significance = field(fields, "significance_mark_style", Some(None))?;
let interaction = field(fields, "interaction_styles", Some(None))?;
let color_unit = fields
.get("color_label_format")
.map(NumericFormat::from_style_value)
.transpose()?
.and_then(|format| format.unit_reference().map(str::to_owned));
Ok(Box::new(move |description| {
if continuous
.as_ref()
.is_some_and(|scale: &crate::scales::ContinuousColorScale| {
scale.get_domain().is_some() || scale.get_center().is_some()
})
{
let target_unit = description
.color_label_format_spec()
.and_then(|format| format.unit_reference());
if color_unit.as_deref() != target_unit {
return Err(invalid(
"explicit color scale has an incompatible literal unit reference",
));
}
}
prose(description)?;
input(description)?;
description.raw_overlay = raw_overlay;
description.line_path_style = line_path_style;
description.interaction_connectors = interaction_connectors;
description.legend_composition = legend_composition;
description.significance_mark_style = significance;
let payload = description.payload_mut();
payload.legend_policy = legend;
payload.bar_spacing = bar_spacing;
payload.point_outline_visible = outline;
payload.markers_visible = markers;
payload.color_by_sign = color_by_sign;
payload.zero_line = zero_line;
payload.text_layouts = layouts;
payload.categorical_color_scale = categorical;
payload.continuous_color_scale = continuous;
payload.interaction_styles = interaction;
Ok(())
}))
}
pub(crate) fn schema(ctx: &mut Schema, root: bool) -> serde_json::Value {
let owner = if root {
"PlotStyleRoot"
} else {
"PlotStyleChild"
};
ctx.named(owner, |ctx| {
let native = super::native_properties(ctx);
let properties = FIELDS
.iter()
.map(|&field| {
let shape = match field {
"scope" => grammar::literal("style"),
"title"
| "subtitle"
| "caption"
| "x_label"
| "y_label"
| "color_label"
| "raincloud_hue_label" => crate::recipe::style::text_schema(ctx),
"color_label_format" | "estimate_labels" | "total_format" => {
NumericFormat::style_schema(ctx)
}
"heatmap_annotations" => grammar::any_of([
grammar::literal("hidden"),
NumericFormat::style_schema(ctx),
]),
"point_alpha" | "line_alpha" | "fill_alpha" => {
super::opacity::style_schema(ctx)
}
"endpoints" => grammar::record(ctx, ENDPOINT_STYLE_FIELDS),
"fixed_color" => ctx.reference::<Option<crate::Color>>(),
"axes" => grammar::primitive("object"),
field => layers::schema(ctx, field)
.unwrap_or_else(|| native["properties"][field].clone()),
};
assert!(!shape.is_null(), "missing style schema field {field}");
(field, shape)
})
.collect::<Vec<_>>();
let required = if root {
&["scope", "kind", "theme"][..]
} else {
&["scope", "kind"]
};
let base = grammar::object(properties, required);
let families =
grammar::one_of(crate::recipe::figure::FAMILIES.iter().map(|(kind, name)| {
let forbidden = FIELDS
.iter()
.copied()
.filter(|field| {
!super::admission::permits(*kind, field)
|| (*field == "endpoints" && *kind != PlotKind::Dumbbell)
|| (*field == "fixed_color" && *kind != PlotKind::Beeswarm)
})
.collect::<Vec<_>>();
grammar::with(
serde_json::json!({"properties":{
"kind":grammar::literal(*name),
"axes":numbers::schema(ctx,*kind),
"text_layouts":super::text_layouts_schema(ctx,*kind),
}}),
grammar::forbidden(&forbidden),
)
}));
grammar::with(base, families)
})
}
impl PlotStyle {
pub(crate) fn read(item: &Item, path: &str, root: bool) -> Result<Self> {
let fields = table(item, FIELDS)?;
if !is_style(item) {
return Err(invalid(format!("{path}: expected style scope")));
}
let kind = plot_kind(&field::<String>(fields, "kind", None)?)?;
super::admission::validate_family(fields, kind, path)?;
let theme = style_theme(fields, root)?;
let basic = read_basic(fields, kind)?;
let numbers = numbers::read(fields, kind)?;
let layers = layers::read(fields)?;
let mut alpha = Vec::new();
for (name, target) in TARGETS {
if alpha_capability(target).admits(kind) {
alpha.push((
target,
AlphaStyle::read(fields.get(name)).map_err(|error| error.with_prefix(name))?,
));
}
}
Ok(Self {
kind,
theme,
basic,
numbers,
layers,
alpha,
})
}
pub(crate) fn apply(self, description: &mut PlotDescription) -> Result<()> {
if self.kind != description.kind() {
return Err(invalid(format!(
"style for {} requires a compatible {} owner, got {}",
self.kind.name(),
self.kind.name(),
description.kind().name()
)));
}
description.payload_mut().theme = self.theme;
(self.basic)(description)?;
(self.numbers)(description)?;
(self.layers)(description)?;
for (target, style) in self.alpha {
let previous = description.payload.alpha.get(target);
let next = style.apply(previous)?;
if next != *previous {
description.replace_alpha(target, next);
}
}
description.validate_configuration(description.kind())
}
}
impl PlotDescription {
pub(crate) fn capture_style(&self, root: bool) -> Result<Value> {
let mut fields = InlineTable::new();
fields.insert("scope", "style".into());
fields.insert("kind", self.kind().name().into());
let fallback = Theme::publication();
let theme = if root {
Some(
self.payload
.theme
.as_deref()
.or(self.payload.default_theme.as_deref())
.unwrap_or(&fallback),
)
} else {
self.payload.theme.as_deref()
};
if let Some(theme) = theme {
fields.insert("theme", theme.encode());
}
capture_prose(self, &mut fields);
capture_basic(self, &mut fields);
numbers::capture(self, &mut fields)?;
layers::capture(self, &mut fields);
capture_alpha(self.kind(), &self.payload.alpha, &mut fields)?;
Ok(fields.into())
}
}
pub(crate) fn apply_plot_recipe<K: Marker>(
target: &mut crate::Plot<K>,
recipe: &Recipe,
) -> Result<()> {
let style = PlotStyle::read(recipe.style_root("plot")?, "plot", true)?;
style.apply(&mut target.description)?;
crate::recipe::figure::check_plot(&target.description)
}
pub(crate) fn project(item: &Item, parent: Option<&Theme>, root: bool) -> Result<Value> {
use crate::recipe::style::{
copy_fields, effective_theme, project_existing_style, project_text,
};
if is_style(item) {
return Ok(project_existing_style(item, parent, root)?.into());
}
let source = item
.as_table_like()
.ok_or_else(|| invalid("expected a Plot declaration"))?;
let kind = plot_kind(&field::<String>(source, "kind", None)?)?;
let mut style = InlineTable::new();
style.insert("scope", "style".into());
style.insert("kind", kind.name().into());
if root {
style.insert("theme", effective_theme(source, parent)?.encode());
} else {
copy_fields(source, &mut style, &["theme"])?;
}
project_text(
source,
&mut style,
&[
"title",
"subtitle",
"caption",
"x_label",
"y_label",
"color_label",
"raincloud_hue_label",
],
)?;
copy_fields(
source,
&mut style,
&[
"raw_overlay",
"line_path_style",
"interaction_connectors",
"legend",
"legend_composition",
"bar_spacing",
"point_outline_visible",
"markers_visible",
"color_by_sign",
"zero_line",
"text_layouts",
"categorical_color_scale",
"continuous_color_scale",
"significance_mark_style",
"interaction_styles",
],
)?;
if let Some(input) = source.get("input") {
if let Some(endpoints) = input.get("endpoints").and_then(Item::as_table_like) {
let mut paint = InlineTable::new();
copy_fields(endpoints, &mut paint, &["left_color", "right_color"])?;
style.insert("endpoints", paint.into());
}
if kind == PlotKind::Beeswarm {
if let Some(samples) = input.get("samples").and_then(Item::as_table_like) {
copy_fields(samples, &mut style, &["fixed_color"])?;
}
}
}
numbers::project(source, kind, &mut style)?;
layers::project(source, &mut style)?;
for (name, _) in TARGETS {
if let Some(item) = source.get(name) {
style.insert(name, super::opacity::project_style(item)?);
}
}
Ok(style.into())
}