use num_bigint::BigUint;
use toml_edit::{InlineTable, Item, Value};
use crate::{
layout::{GridGap, Insets, Length, LengthUnit, RelativeSpacing},
scales::{
AccentPalette, ColorStop, DivergingGradient, PaletteCapacity, QualitativePalette,
SequentialGradient,
},
style::{LinePattern, OpaqueColor, PointShape},
text::{FontFamily, FontStack, TextAlignment, TextWeight},
theme::{
AnnotationTextRoles, AnnotationTheme, AxisSpacing, AxisTextRoles, AxisTheme, BandFillRoles,
BodyFillRoles, CategoryMarkGeometry, CellAnnotationGeometry, CellMarkRoles, ColorScales,
CompositionTextRoles, CompositionTheme, ConnectorStrokeRoles, ContrastTextRoles,
CurveStrokeRoles, DataFillTheme, DataLineRoles, DataLineTheme, DataOutlineTheme,
DensityFillRoles, EstimateAnnotationGeometry, FacetStripSpacing, FillRoles, FixedFillTheme,
FrameSides, FrameTheme, GradientLengths, GuideTextRoles, HeaderSpacing, LegendFrameTheme,
LegendSpacing, LegendTheme, MarkExtentTheme, MarkTheme, NeutralPaintRoles, OutlineTheme,
PointOutlineTheme, PointRadii, PointRoles, PointTheme, ReferenceStrokeRoles, RootTextRoles,
RootTitleSpacing, SignificanceGeometry, SizedPointTheme, SolidStrokeTheme, StrokeRoles,
StrokeTheme, SummaryStrokeRoles, SupplementalPointTheme, SurfaceTheme, TextPanelSpacing,
TextTheme, TickTheme, TypographyTheme, ValueShelfSpacing,
},
Color, Result, Theme,
};
use crate::recipe::schema::{self as grammar, Schema};
use super::codec::{
array, choice, default_field, encode_field, field, invalid, record, retained, table, Codec,
};
fn rgb(red: u8, green: u8, blue: u8) -> String {
format!("#{red:02X}{green:02X}{blue:02X}")
}
impl Codec for OpaqueColor {
fn schema(_: &mut Schema) -> serde_json::Value {
serde_json::json!({"type":"string","pattern":"^#[0-9a-fA-F]{6}$"})
}
fn encode(&self) -> Value {
rgb(self.red(), self.green(), self.blue()).encode()
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
Self::hex(
item.as_str()
.ok_or_else(|| invalid("expected opaque #RRGGBB"))?,
)
}
}
const COLOR_FIELDS: &[grammar::Field] = &[
grammar::mandatory::<OpaqueColor>("rgb"),
grammar::mandatory::<f64>("alpha"),
];
impl Codec for Color {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::any_of([
serde_json::json!({"type":"string","pattern":"^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$"}),
grammar::record(ctx, COLOR_FIELDS),
])
}
fn encode(&self) -> Value {
let color = rgb(self.red(), self.green(), self.blue());
if self.get_alpha().to_bits() == 1.0_f64.to_bits() {
color.encode()
} else {
let mut value = InlineTable::new();
value.insert("rgb", color.encode());
value.insert("alpha", self.get_alpha().encode());
value.into()
}
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
if let Some(color) = item.as_str() {
return Self::hex(color);
}
let fields = grammar::record_fields(item, COLOR_FIELDS)?;
let opaque: OpaqueColor = field(fields, "rgb", None)?;
Self::from(opaque).alpha(field(fields, "alpha", None)?)
}
}
fn exact_integer(value: &BigUint) -> Value {
i64::try_from(value).map_or_else(|_| Value::from(value.to_string()), Value::from)
}
fn nonnegative_integer(item: &Item) -> Result<BigUint> {
if let Some(value) = item.as_integer() {
return BigUint::try_from(value).map_err(|_| invalid("ratio integers must be nonnegative"));
}
let text = item
.as_str()
.ok_or_else(|| invalid("expected a nonnegative ratio integer"))?;
if text.is_empty() || !text.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(invalid(
"ratio integer string must contain only decimal digits",
));
}
text.parse()
.map_err(|_| invalid("invalid exact ratio integer"))
}
fn ratio_integer_schema(_: &mut Schema) -> serde_json::Value {
grammar::any_of([
serde_json::json!({"type":"integer","minimum":0}),
serde_json::json!({"type":"string","pattern":"^[0-9]+$"}),
])
}
const RATIO_FIELDS: &[grammar::Field] = &[
grammar::custom("numerator", true, ratio_integer_schema),
grammar::custom("denominator", true, ratio_integer_schema),
];
impl Codec for RelativeSpacing {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::any_of([
serde_json::json!({"type":"number","minimum":0}),
grammar::record(ctx, RATIO_FIELDS),
])
}
fn encode(&self) -> Value {
let approximate = self.as_f64();
if Self::new(approximate).is_ok_and(|value| &value == self) {
return approximate.encode();
}
let (numerator, denominator) = self.exact_parts();
let mut value = InlineTable::new();
value.insert("numerator", exact_integer(numerator));
value.insert("denominator", exact_integer(denominator));
value.into()
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
if item.as_table_like().is_none() {
return Self::new(f64::decode(item, None)?);
}
let fields = grammar::record_fields(item, RATIO_FIELDS)?;
let term = |name: &str| {
let value = fields
.get(name)
.ok_or_else(|| invalid(format!("missing ratio {name}")))?;
nonnegative_integer(value)
};
Self::from_exact_parts(term("numerator")?, term("denominator")?)
}
}
const LENGTH_FIELDS: &[grammar::Field] = &[
grammar::optional::<RelativeSpacing>("em"),
grammar::optional::<RelativeSpacing>("px"),
grammar::optional::<RelativeSpacing>("short_side"),
];
impl Codec for Length {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::with(
grammar::record(ctx, LENGTH_FIELDS),
grammar::exclusive(&["em", "px", "short_side"]),
)
}
fn encode(&self) -> Value {
let name = match self.unit() {
LengthUnit::Em => "em",
LengthUnit::Px => "px",
LengthUnit::ShortSide => "short_side",
};
let mut value = InlineTable::new();
value.insert(name, self.value().encode());
value.into()
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
let fields = grammar::record_fields(item, LENGTH_FIELDS)?;
if fields.len() != 1 {
return Err(invalid(
"length requires exactly one of em, px or short_side",
));
}
if let Some(value) = fields.get("em") {
Ok(Self::Em(RelativeSpacing::decode(value, None)?))
} else if let Some(value) = fields.get("px") {
Ok(Self::Px(RelativeSpacing::decode(value, None)?))
} else {
Ok(Self::ShortSide(field(fields, "short_side", None)?))
}
}
}
const INSET_FIELDS: &[grammar::Field] = &[
grammar::optional::<Length>("left"),
grammar::optional::<Length>("right"),
grammar::optional::<Length>("top"),
grammar::optional::<Length>("bottom"),
];
fn absolute_length_schema(ctx: &mut Schema) -> serde_json::Value {
let zero = grammar::any_of([
grammar::literal(0),
grammar::with(
grammar::record(ctx, RATIO_FIELDS),
serde_json::json!({
"properties":{"numerator":{"anyOf":[{"const":0},{"type":"string","pattern":"^0+$"}]}}
}),
),
]);
let mut length = grammar::record(ctx, LENGTH_FIELDS);
grammar::declare_property(&mut length, "em", zero.clone());
grammar::declare_property(&mut length, "short_side", zero);
grammar::with(length, grammar::exclusive(&grammar::names(LENGTH_FIELDS)))
}
pub(crate) fn absolute_insets_schema(ctx: &mut Schema) -> serde_json::Value {
ctx.named("AbsoluteInsets", |ctx| {
let length = ctx.named("AbsoluteLength", absolute_length_schema);
grammar::one_of([
length.clone(),
grammar::object(
INSET_FIELDS
.iter()
.map(|field| (field.name, length.clone())),
&[],
),
])
})
}
impl Codec for Insets {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::one_of([
ctx.reference::<Length>(),
grammar::record(ctx, INSET_FIELDS),
])
}
fn encode(&self) -> Value {
let mut value = InlineTable::new();
for (name, length) in [
("left", self.get_left()),
("right", self.get_right()),
("top", self.get_top()),
("bottom", self.get_bottom()),
] {
value.insert(name, length.encode());
}
value.into()
}
fn decode(item: &Item, base: Option<Self>) -> Result<Self> {
if item.as_table_like().is_some_and(|table| {
["em", "px", "short_side"]
.iter()
.any(|name| table.contains_key(name))
}) {
return Length::decode(item, None).map(Self::all);
}
let fields = grammar::record_fields(item, INSET_FIELDS)?;
let base = base.unwrap_or_else(Self::zero);
Ok(Self::zero()
.left(field(fields, "left", Some(base.get_left().clone()))?)
.right(field(fields, "right", Some(base.get_right().clone()))?)
.top(field(fields, "top", Some(base.get_top().clone()))?)
.bottom(field(fields, "bottom", Some(base.get_bottom().clone()))?))
}
}
const GAP_FIELDS: &[grammar::Field] = &[
grammar::optional::<Length>("row"),
grammar::optional::<Length>("column"),
];
impl Codec for GridGap {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::one_of([ctx.reference::<Length>(), grammar::record(ctx, GAP_FIELDS)])
}
fn encode(&self) -> Value {
let mut value = InlineTable::new();
value.insert("row", self.get_row().encode());
value.insert("column", self.get_column().encode());
value.into()
}
fn decode(item: &Item, base: Option<Self>) -> Result<Self> {
if item.as_table_like().is_some_and(|table| {
["em", "px", "short_side"]
.iter()
.any(|name| table.contains_key(name))
}) {
return Length::decode(item, None).map(Self::all);
}
let fields = grammar::record_fields(item, GAP_FIELDS)?;
let base = base.unwrap_or_else(Self::zero);
Ok(Self::zero()
.row(field(fields, "row", Some(base.get_row().clone()))?)
.column(field(fields, "column", Some(base.get_column().clone()))?))
}
}
impl Codec for FontStack {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::any_of([ctx.reference::<String>(), ctx.reference::<Vec<String>>()])
}
fn encode(&self) -> Value {
let selections: Vec<_> = self.families().iter().map(FontFamily::selection).collect();
selections.encode()
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
let selections = if let Some(selection) = item.as_str() {
vec![selection.to_owned()]
} else {
Vec::<String>::decode(item, None)?
};
let families = crate::data::source::collect_source(
selections
.iter()
.map(|selection| FontFamily::parse_selection(selection)),
)?;
Self::new(families)
}
}
choice!(TextWeight {Normal=>"normal",Semibold=>"semibold",Bold=>"bold"});
choice!(TextAlignment {Start=>"start",Center=>"center",End=>"end"});
choice!(LinePattern {Solid=>"solid",ShortDash=>"short_dash",MediumDash=>"medium_dash",Dashed=>"dashed"});
choice!(PointShape {Circle=>"circle",TriangleUp=>"triangle_up"});
record!(TextTheme {
family=>get_stack[borrow],
color=>get_color[copy],
font_size=>get_font_size[copy],
weight=>get_weight[copy],
line_height=>get_line_height[copy],
});
record!(RootTextRoles {title=>get_title[borrow],subtitle=>get_subtitle[borrow],caption=>get_caption[borrow]});
record!(AxisTextRoles {axis_title=>get_axis_title[borrow],tick_label=>get_tick_label[borrow]});
record!(GuideTextRoles {legend_title=>get_legend_title[borrow],legend_label=>get_legend_label[borrow]});
record!(CompositionTextRoles {
facet_header=>get_facet_header[borrow],composition_header=>get_composition_header[borrow],
text_panel_title=>get_text_panel_title[borrow],body=>get_body[borrow],
});
record!(ContrastTextRoles {light=>get_light[borrow],dark=>get_dark[borrow]});
record!(AnnotationTextRoles {
significance_label=>get_significance_label[borrow],estimate_detail=>get_estimate_detail[borrow],
waterfall_total=>get_waterfall_total[borrow],point_layer_label=>get_point_layer_label[borrow],
panel_text=>get_panel_text[borrow],contrast=>get_contrast[borrow],
});
record!(TypographyTheme {
root=>get_root[borrow],axes=>get_axes[borrow],guides=>get_guides[borrow],
composition=>get_composition[borrow],annotations=>get_annotations[borrow],
});
record!(SurfaceTheme {canvas_root=>get_canvas_root[copy],plot_panel=>get_plot_panel[copy]});
const OUTLINE_FIXED: &[grammar::Field] = &[
grammar::custom("kind", false, |_| grammar::literal("fixed")),
grammar::optional::<SolidStrokeTheme>("stroke"),
];
const OUTLINE_MAPPED: &[grammar::Field] = &[
grammar::custom("kind", false, |_| grammar::literal("mapped")),
grammar::optional::<f64>("width"),
grammar::optional::<f64>("alpha"),
];
impl Codec for DataOutlineTheme {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::one_of([
grammar::with(
grammar::record(ctx, OUTLINE_FIXED),
grammar::required(&["kind", "stroke"]),
),
grammar::with(
grammar::record(ctx, OUTLINE_MAPPED),
grammar::required(&["kind", "width", "alpha"]),
),
])
}
fn schema_with_default(ctx: &mut Schema) -> serde_json::Value {
grammar::any_of([
grammar::object(
[
("kind", grammar::literal("fixed")),
("stroke", SolidStrokeTheme::schema_with_default(ctx)),
],
&[],
),
grammar::record(ctx, OUTLINE_MAPPED),
])
}
fn encode(&self) -> Value {
let mut value = InlineTable::new();
if let Some(outline) = self.fixed_stroke() {
value.insert("kind", Value::from("fixed"));
value.insert("stroke", outline.encode());
} else {
value.insert("kind", Value::from("mapped"));
value.insert(
"width",
self.mapped_width().expect("mapped outline").encode(),
);
value.insert(
"alpha",
self.mapped_alpha().expect("mapped outline").encode(),
);
}
value.into()
}
fn decode(item: &Item, base: Option<Self>) -> Result<Self> {
let all = table(item, &["kind", "stroke", "width", "alpha"])?;
let kind = if let Some(kind) = all.get("kind") {
String::decode(kind, None)?
} else if let Some(base) = &base {
if base.fixed_stroke().is_some() {
"fixed"
} else {
"mapped"
}
.to_owned()
} else {
return Err(invalid("data outline needs a kind"));
};
match kind.as_str() {
"fixed" => {
let fields = grammar::record_fields(item, OUTLINE_FIXED)?;
Ok(Self::fixed(field(
fields,
"stroke",
base.as_ref().and_then(|base| base.fixed_stroke().cloned()),
)?))
}
"mapped" => {
let fields = grammar::record_fields(item, OUTLINE_MAPPED)?;
Self::mapped(
field(fields, "width", base.as_ref().and_then(Self::mapped_width))?,
field(fields, "alpha", base.as_ref().and_then(Self::mapped_alpha))?,
)
}
_ => Err(invalid("data outline kind must be fixed or mapped")),
}
}
}
choice!(PaletteCapacity {Fixed=>"fixed",Extendable=>"extendable"});
const PALETTE_FIELDS: &[grammar::Field] = &[
grammar::optional::<PaletteCapacity>("capacity"),
grammar::optional::<Vec<OpaqueColor>>("colors"),
];
impl Codec for QualitativePalette {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::with(
grammar::record(ctx, PALETTE_FIELDS),
grammar::required(&grammar::names(PALETTE_FIELDS)),
)
}
fn schema_with_default(ctx: &mut Schema) -> serde_json::Value {
grammar::record(ctx, PALETTE_FIELDS)
}
fn encode(&self) -> Value {
let mut value = InlineTable::new();
value.insert("capacity", self.capacity().encode());
value.insert("colors", array(self.colors()));
value.into()
}
fn decode(item: &Item, base: Option<Self>) -> Result<Self> {
let fields = grammar::record_fields(item, PALETTE_FIELDS)?;
let policy: PaletteCapacity = field(fields, "capacity", base.as_ref().map(Self::capacity))?;
let colors: Vec<OpaqueColor> = field(
fields,
"colors",
base.as_ref().map(|base| base.colors().to_vec()),
)?;
match policy {
PaletteCapacity::Fixed => Self::fixed(colors),
PaletteCapacity::Extendable => Self::extendable(colors),
}
}
}
impl Codec for AccentPalette {
fn schema(ctx: &mut Schema) -> serde_json::Value {
ctx.reference::<Vec<OpaqueColor>>()
}
fn encode(&self) -> Value {
array(self.seeds())
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
Self::new(Vec::<OpaqueColor>::decode(item, None)?)
}
}
record!(ColorStop {offset=>offset[copy],color=>color[copy]});
const GRADIENT_FIELDS: &[grammar::Field] = &[grammar::optional::<Vec<ColorStop>>("stops")];
macro_rules! gradient {
($type:ty) => {
impl Codec for $type {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::with(
grammar::record(ctx, GRADIENT_FIELDS),
grammar::required(&["stops"]),
)
}
fn schema_with_default(ctx: &mut Schema) -> serde_json::Value {
grammar::record(ctx, GRADIENT_FIELDS)
}
fn encode(&self) -> Value {
let mut value = InlineTable::new();
value.insert("stops", array(self.stops()));
value.into()
}
fn decode(item: &Item, base: Option<Self>) -> Result<Self> {
let fields = grammar::record_fields(item, GRADIENT_FIELDS)?;
let stops: Vec<ColorStop> = field(
fields,
"stops",
base.as_ref().map(|base| base.stops().to_vec()),
)?;
Self::new(stops)
}
}
};
}
gradient!(SequentialGradient);
gradient!(DivergingGradient);
record!(FrameSides {
top => get_top [copy],
right => get_right [copy],
bottom => get_bottom [copy],
left => get_left [copy],
});
record!(FrameTheme {
sides => get_sides [borrow],
stroke => get_stroke [borrow],
});
record!(TickTheme {
stroke => get_stroke [borrow],
length => get_length [copy],
});
record!(AxisSpacing {
x_tick_label_gap => get_x_tick_label_gap [borrow],
y_tick_label_gap => get_y_tick_label_gap [borrow],
x_title_tick_label_gap => get_x_title_tick_label_gap [borrow],
x_title_without_tick_labels_gap => get_x_title_without_tick_labels_gap [borrow],
y_title_tick_label_gap => get_y_title_tick_label_gap [borrow],
y_title_edge_padding => get_y_title_edge_padding [borrow],
});
record!(AxisTheme {
frame => get_frame [optional],
cell_frame => get_cell_frame [optional],
ticks => get_ticks [optional],
grid => get_grid [optional],
spacing => get_spacing [borrow],
});
record!(LegendSpacing {
padding => get_padding [borrow],
key_width => get_key_width [borrow],
key_label_gap => get_key_label_gap [borrow],
outside_gap => get_outside_gap [borrow],
shared_gap => get_shared_gap [borrow],
entry_gap => get_entry_gap [borrow],
title_gap => get_title_gap [borrow],
glyph_edge_padding => get_glyph_edge_padding [borrow],
inside_inset => get_inside_inset [borrow],
outside_inset => get_outside_inset [borrow],
});
record!(GradientLengths {
minimum => get_minimum [borrow],
preferred => get_preferred [borrow],
});
record!(LegendFrameTheme {
fill => get_fill [copy],
outline => get_outline [optional],
radius => get_radius [borrow],
});
record!(LegendTheme {
spacing => get_spacing [borrow],
gradient_lengths => get_gradient_lengths [borrow],
frame => get_frame [optional],
});
record!(RootTitleSpacing {
title_subtitle_gap => get_title_subtitle_gap [borrow],
title_block_to_content_clearance => get_title_block_to_content_clearance [borrow],
caption_to_content_clearance => get_caption_to_content_clearance [borrow],
});
record!(TextPanelSpacing {
padding => get_padding [borrow],
gap => get_gap [borrow],
});
record!(HeaderSpacing {
column_header_padding => get_column_header_padding [borrow],
row_header_padding => get_row_header_padding [borrow],
row_title_padding => get_row_title_padding [borrow],
});
record!(FacetStripSpacing {
padding => get_padding [borrow],
content_clearance => get_content_clearance [borrow],
});
record!(CompositionTheme {
root_title_alignment => get_root_title_alignment [copy],
root_subtitle_alignment => get_root_subtitle_alignment [optional_copy],
root_caption_alignment => get_root_caption_alignment [copy],
root_title_block => get_root_title_block [borrow],
root_padding => get_root_padding [borrow],
panel_edge_clearance => get_panel_edge_clearance [borrow],
text_panel => get_text_panel [borrow],
facet_gap => get_facet_gap [borrow],
canvas_grid_gap => get_canvas_grid_gap [borrow],
matrix_gap => get_matrix_gap [borrow],
marginal_gap => get_marginal_gap [borrow],
headers => get_headers [borrow],
facet_strip => get_facet_strip [borrow],
});
record!(SizedPointTheme {
appearance => get_appearance [borrow],
radius => get_radius [copy],
});
record!(SupplementalPointTheme {
radius => get_radius [copy],
fill_alpha => get_fill_alpha [copy],
});
record!(PointRadii {
scatter => get_scatter [copy],
path => get_path [copy],
trajectory => get_trajectory [copy],
regression => get_regression [copy],
qq => get_qq [copy],
marginal => get_marginal [copy],
matrix => get_matrix [copy],
interval_estimate => get_interval_estimate [copy],
dumbbell => get_dumbbell [copy],
interaction => get_interaction [copy],
beeswarm => get_beeswarm [copy],
box_flier => get_box_flier [copy],
});
record!(PointRoles {
primary => get_primary [borrow],
raw_overlay => get_raw_overlay [borrow],
mandatory_strip => get_mandatory_strip [borrow],
radii => get_radii [borrow],
supplemental => get_supplemental [borrow],
});
record!(BodyFillRoles {
bar_body => get_bar_body [borrow],
box_body => get_box_body [borrow],
violin_body => get_violin_body [borrow],
inner_summary => get_inner_summary [borrow],
histogram_bin => get_histogram_bin [borrow],
waterfall_bar => get_waterfall_bar [borrow],
});
record!(BandFillRoles {
line_band => get_line_band [borrow],
regression_band => get_regression_band [borrow],
});
record!(DensityFillRoles {
density_area => get_density_area [borrow],
marginal_density => get_marginal_density [borrow],
matrix_density => get_matrix_density [borrow],
});
record!(FillRoles {
bodies => get_bodies [borrow],
bands => get_bands [borrow],
densities => get_densities [borrow],
});
record!(DataLineRoles {
series_line => get_series_line [borrow],
path_line => get_path_line [borrow],
density_line => get_density_line [borrow],
interaction_interval => get_interaction_interval [borrow],
interaction_connector => get_interaction_connector [borrow],
});
record!(NeutralPaintRoles {
path => get_path [copy],
box_flier => get_box_flier [copy],
});
record!(ReferenceStrokeRoles {
bar_zero => get_bar_zero [borrow],
waterfall_reference => get_waterfall_reference [borrow],
beeswarm_reference => get_beeswarm_reference [borrow],
point_interval_reference => get_point_interval_reference [borrow],
estimate_reference => get_estimate_reference [borrow],
qq_reference => get_qq_reference [borrow],
});
record!(ConnectorStrokeRoles {
waterfall_connector => get_waterfall_connector [borrow],
dumbbell_connector => get_dumbbell_connector [borrow],
});
record!(SummaryStrokeRoles {
uncertainty => get_uncertainty [borrow],
summary => get_summary [borrow],
estimate_interval => get_estimate_interval [borrow],
median => get_median [borrow],
});
record!(CurveStrokeRoles {
histogram_curve => get_histogram_curve [borrow],
histogram_rug => get_histogram_rug [borrow],
regression_fit => get_regression_fit [borrow],
});
record!(StrokeRoles {
references => get_references [borrow],
connectors => get_connectors [borrow],
summaries => get_summaries [borrow],
curves => get_curves [borrow],
});
record!(CellMarkRoles {
fill_alpha => get_fill_alpha [copy],
cell_outline => get_cell_outline [optional],
missing_fill => get_missing_fill [copy],
missing_row_outline => get_missing_row_outline [optional],
missing_key_outline => get_missing_key_outline [optional],
missing_cross => get_missing_cross [borrow],
missing_cross_inset => get_missing_cross_inset [borrow],
});
record!(CategoryMarkGeometry {
vertical_body_breadth => get_vertical_body_breadth [borrow],
horizontal_body_breadth => get_horizontal_body_breadth [borrow],
vertical_group_span => get_vertical_group_span [borrow],
horizontal_group_span => get_horizontal_group_span [borrow],
uncertainty_cap_ratio => get_uncertainty_cap_ratio [borrow],
});
record!(MarkExtentTheme {
categories => get_categories [borrow],
waterfall_body_category_breadth => get_waterfall_body_category_breadth [borrow],
point_interval_cap_half_height => get_point_interval_cap_half_height [copy],
sampled_rug_height => get_sampled_rug_height [borrow],
marginal_density_fraction => get_marginal_density_fraction [borrow],
matrix_density_fraction => get_matrix_density_fraction [borrow],
});
record!(MarkTheme {
accents => get_accents [borrow],
points => get_points [borrow],
fills => get_fills [borrow],
data_lines => get_data_lines [borrow],
neutral_paints => get_neutral_paints [borrow],
strokes => get_strokes [borrow],
cells => get_cells [borrow],
extents => get_extents [borrow],
});
record!(SignificanceGeometry {
bracket_stroke => get_bracket_stroke [borrow],
label_gap => get_label_gap [borrow],
tick_height => get_tick_height [borrow],
data_gap => get_data_gap [borrow],
level_step => get_level_step [borrow],
panel_padding => get_panel_padding [borrow],
attached_extra_clearance => get_attached_extra_clearance [borrow],
});
record!(CellAnnotationGeometry {
highlight_outline => get_highlight_outline [borrow],
value_padding => get_value_padding [borrow],
null_row_padding => get_null_row_padding [borrow],
});
record!(EstimateAnnotationGeometry {
panel_inset => get_panel_inset [borrow],
guide_clearance => get_guide_clearance [borrow],
numeric_label_gap => get_numeric_label_gap [borrow],
});
record!(ValueShelfSpacing {
padding => get_padding [borrow],
gap => get_gap [borrow],
row_gap => get_row_gap [borrow],
});
record!(AnnotationTheme {
significance => get_significance [borrow],
cells => get_cells [borrow],
estimates => get_estimates [borrow],
point_label_gap => get_point_label_gap [borrow],
panel_text_padding => get_panel_text_padding [borrow],
waterfall_shelf => get_waterfall_shelf [borrow],
planning_backdrop => get_planning_backdrop [copy],
});
record!(StrokeTheme {
color => get_color [copy],
width => get_width [copy],
pattern => get_pattern [copy],
});
record!(SolidStrokeTheme {
color => get_color [copy],
width => get_width [copy],
});
record!(OutlineTheme {
color => get_color [copy],
width => get_width [copy],
});
record!(PointOutlineTheme {
color => get_color [copy],
width_ratio => get_width_ratio [borrow],
});
record!(DataFillTheme {
fill_alpha => get_fill_alpha [copy],
outline => get_outline [optional],
});
record!(FixedFillTheme {
color => get_color [copy],
outline => get_outline [optional],
});
record!(PointTheme {
fill_alpha => get_fill_alpha [copy],
shape => get_shape [copy],
outline => get_outline [optional],
});
record!(DataLineTheme {
width => get_width [copy],
alpha => get_alpha [copy],
pattern => get_pattern [copy],
});
record!(ColorScales {
qualitative => get_qualitative [borrow],
sequential => get_sequential [borrow],
diverging => get_diverging [borrow],
});
type Preset = (&'static str, fn() -> Theme);
const PRESETS: [Preset; 4] = [
("publication", Theme::publication),
("nature", Theme::nature),
("science", Theme::science),
("chi", Theme::chi),
];
fn same_theme(left: &Theme, right: &Theme) -> bool {
left == right
&& left
.typography()
.roles()
.into_iter()
.zip(right.typography().roles())
.all(|(left, right)| {
left.get_stack()
.families()
.iter()
.map(FontFamily::selection)
.eq(right
.get_stack()
.families()
.iter()
.map(FontFamily::selection))
})
}
const THEME_FIELDS: &[grammar::Field] = &[
grammar::custom("preset", false, |_| {
grammar::choices(&PRESETS.iter().map(|(name, _)| *name).collect::<Vec<_>>())
}),
grammar::custom("surfaces", false, SurfaceTheme::schema_with_default),
grammar::custom("typography", false, TypographyTheme::schema_with_default),
grammar::custom("axes", false, AxisTheme::schema_with_default),
grammar::custom("legend", false, LegendTheme::schema_with_default),
grammar::custom("composition", false, CompositionTheme::schema_with_default),
grammar::custom("marks", false, MarkTheme::schema_with_default),
grammar::custom("annotations", false, AnnotationTheme::schema_with_default),
grammar::custom("color_scales", false, ColorScales::schema_with_default),
];
impl Codec for Theme {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::record(ctx, THEME_FIELDS)
}
fn encode(&self) -> Value {
let mut value = InlineTable::new();
if let Some((name, _)) = PRESETS
.iter()
.find(|(_, preset)| same_theme(self, &preset()))
{
value.insert("preset", Value::from(*name));
} else {
value.insert("preset", Value::from("publication"));
value.insert("surfaces", self.surfaces().encode());
value.insert("typography", self.typography().encode());
value.insert("axes", self.axes().encode());
value.insert("legend", self.legend().encode());
value.insert("composition", self.composition().encode());
value.insert("marks", self.marks().encode());
value.insert("annotations", self.annotations().encode());
value.insert("color_scales", self.color_scales().encode());
}
value.into()
}
fn decode(item: &Item, base: Option<Self>) -> Result<Self> {
let fields = grammar::record_fields(item, THEME_FIELDS)?;
let initial = if let Some(preset) = fields.get("preset") {
let name = String::decode(preset, None)?;
let (_, constructor) = PRESETS
.iter()
.find(|(value, _)| *value == name)
.ok_or_else(|| invalid(format!("unknown theme preset {name:?}")))?;
constructor()
} else {
base.unwrap_or_else(Theme::publication)
};
Self::new(
field(fields, "surfaces", Some(initial.surfaces().clone()))?,
field(fields, "typography", Some(initial.typography().clone()))?,
field(fields, "axes", Some(initial.axes().clone()))?,
field(fields, "legend", Some(initial.legend().clone()))?,
field(fields, "composition", Some(initial.composition().clone()))?,
field(fields, "marks", Some(initial.marks().clone()))?,
field(fields, "annotations", Some(initial.annotations().clone()))?,
field(fields, "color_scales", Some(initial.color_scales().clone()))?,
)
}
}