use toml_edit::{InlineTable, Item, Value};
use crate::{
alpha::{AlphaEncoding, AlphaMapping, AlphaTarget, AlphaValues},
data::{ColumnKeyLookup, KeyColumns, KeyValues, RawKey, RawKeyValues},
recipe::{
capture::Capture,
codec::{array_items, field, invalid, table, Codec},
declaration::{BindingRequirement, BindingValueType, Group},
resolve::Resolver,
},
spec::Bounds,
CategoryValues, Result,
};
use super::extras::Supply;
use crate::recipe::schema::{self as grammar, Schema};
pub(super) const TARGETS: [(&str, AlphaTarget); 3] = [
("point_alpha", AlphaTarget::Point),
("line_alpha", AlphaTarget::Line),
("fill_alpha", AlphaTarget::Fill),
];
fn pair(fields: &dyn toml_edit::TableLike, name: &str) -> Result<[f64; 2]> {
field::<Vec<f64>>(fields, name, None)?
.try_into()
.map_err(|_| invalid(format!("{name} requires two endpoints")))
}
const ALPHA_EVALUATED: &[grammar::Field] = &[
grammar::mandatory::<f64>("coordinate"),
grammar::mandatory::<f64>("alpha"),
];
const ALPHA_CAT_ENTRY: &[grammar::Field] = &[
grammar::mandatory::<RawKey>("key"),
grammar::mandatory::<f64>("alpha"),
];
const ALPHA_LINEAR: &[grammar::Field] = &[
grammar::custom("kind", true, |_| grammar::choices(&["linear", "log10"])),
grammar::custom("domain", true, |ctx| grammar::pair(ctx.reference::<f64>())),
grammar::custom("range", true, |ctx| grammar::pair(ctx.reference::<f64>())),
];
const ALPHA_THRESHOLD: &[grammar::Field] = &[
grammar::custom("kind", true, |_| grammar::literal("threshold")),
grammar::mandatory::<Vec<f64>>("boundaries"),
grammar::mandatory::<Vec<f64>>("alphas"),
];
const ALPHA_CONTINUOUS: &[grammar::Field] = &[
grammar::custom("kind", true, |_| grammar::literal("continuous")),
grammar::custom("domain", true, |ctx| grammar::pair(ctx.reference::<f64>())),
grammar::custom("evaluated", true, |ctx| {
grammar::array(grammar::record(ctx, ALPHA_EVALUATED))
}),
];
const ALPHA_CATEGORY: &[grammar::Field] = &[
grammar::custom("kind", true, |_| grammar::literal("categorical")),
grammar::custom("entries", true, |ctx| {
grammar::array(grammar::record(ctx, ALPHA_CAT_ENTRY))
}),
];
impl Codec for AlphaMapping {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::one_of([
grammar::literal("direct"),
grammar::record(ctx, ALPHA_LINEAR),
grammar::record(ctx, ALPHA_THRESHOLD),
grammar::record(ctx, ALPHA_CONTINUOUS),
grammar::record(ctx, ALPHA_CATEGORY),
])
}
fn encode(&self) -> Value {
let mut fields = InlineTable::new();
let kind = match self {
Self::Undeclared => return Value::from("direct"),
Self::Linear { domain, range } | Self::Log10 { domain, range } => {
fields.insert("domain", crate::recipe::codec::array(domain));
fields.insert("range", crate::recipe::codec::array(range));
if matches!(self, Self::Linear { .. }) {
"linear"
} else {
"log10"
}
}
Self::Threshold { boundaries, alphas } => {
fields.insert("boundaries", boundaries.encode());
fields.insert("alphas", alphas.encode());
"threshold"
}
Self::Continuous { domain, evaluated } => {
fields.insert("domain", crate::recipe::codec::array(domain));
let entries: toml_edit::Array = evaluated
.iter()
.map(|(coordinate, alpha)| {
let mut row = InlineTable::new();
row.insert("coordinate", coordinate.encode());
row.insert("alpha", alpha.encode());
Value::from(row)
})
.collect();
fields.insert("evaluated", entries.into());
"continuous"
}
Self::Categorical(entries) => {
let entries: toml_edit::Array = entries
.iter()
.map(|(key, alpha)| {
let mut row = InlineTable::new();
row.insert("key", key.encode());
row.insert("alpha", alpha.encode());
Value::from(row)
})
.collect();
fields.insert("entries", entries.into());
"categorical"
}
};
fields.insert("kind", kind.into());
fields.into()
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
if item.as_str() == Some("direct") {
return Ok(Self::Undeclared);
}
let fields = table(
item,
&[
"kind",
"domain",
"range",
"boundaries",
"alphas",
"entries",
"evaluated",
],
)?;
match field::<String>(fields, "kind", None)?.as_str() {
"linear" | "log10" => {
grammar::record_fields(item, ALPHA_LINEAR)?;
let domain = pair(fields, "domain")?;
let range = pair(fields, "range")?;
if fields.get("kind").and_then(Item::as_str) == Some("linear") {
Ok(Self::Linear { domain, range })
} else {
Ok(Self::Log10 { domain, range })
}
}
"threshold" => {
grammar::record_fields(item, ALPHA_THRESHOLD)?;
Ok(Self::Threshold {
boundaries: field(fields, "boundaries", None)?,
alphas: field(fields, "alphas", None)?,
})
}
"continuous" => {
grammar::record_fields(item, ALPHA_CONTINUOUS)?;
let evaluated = array_items(
fields
.get("evaluated")
.ok_or_else(|| invalid("missing evaluated alpha declarations"))?,
)?
.map(|item| {
let row = grammar::record_fields(item, ALPHA_EVALUATED)?;
Ok((field(row, "coordinate", None)?, field(row, "alpha", None)?))
})
.collect::<Result<_>>()?;
Ok(Self::Continuous {
domain: pair(fields, "domain")?,
evaluated,
})
}
"categorical" => {
grammar::record_fields(item, ALPHA_CATEGORY)?;
let entries = array_items(
fields
.get("entries")
.ok_or_else(|| invalid("missing categorical alpha map"))?,
)?
.map(|item| {
let row = grammar::record_fields(item, ALPHA_CAT_ENTRY)?;
Ok((field(row, "key", None)?, field(row, "alpha", None)?))
})
.collect::<Result<_>>()?;
Ok(Self::Categorical(entries))
}
_ => Err(invalid("unknown alpha mapping declaration")),
}
}
}
fn read_values(
group: &mut Group<'_, '_>,
mode: Option<crate::recipe::plot_input::CollectionMode>,
) -> Result<Supply<AlphaValues>> {
let mapping = field(group.fields, "mapping", Some(AlphaMapping::Undeclared))?;
mapping.validate_declaration()?;
if let AlphaMapping::Categorical(entries) = mapping {
let values = crate::recipe::collection::CategoryRequest::optional(group, "values")?
.ok_or_else(|| invalid("alpha requires categorical values"))?;
return Ok(Box::new(move |resolver| {
AlphaValues::from_declared_categories(&values.category(resolver)?, entries)
}));
}
let values = if let Some(item) = group
.fields
.get("values")
.filter(|item| item.get("generated").is_some())
{
let fields = table(item, &["generated"])?;
if mode != Some(crate::recipe::plot_input::CollectionMode::Indexed)
|| field::<String>(fields, "generated", None)? != "rows"
{
return Err(invalid(
"generated row opacity requires an indexed collection",
));
}
None
} else {
Some(group.required("values", BindingValueType::Numeric)?)
};
Ok(Box::new(move |resolver| {
let source = if let Some(values) = values {
values.numeric(resolver)?
} else {
resolver.row_positions()?
};
numeric_mapping(source, mapping)
}))
}
fn numeric_mapping(source: crate::NumericValues, mapping: AlphaMapping) -> Result<AlphaValues> {
match mapping {
AlphaMapping::Undeclared => AlphaValues::try_from(source),
AlphaMapping::Linear {
domain: [a, b],
range: [c, d],
} => AlphaValues::linear(source, (a, b), (c, d)),
AlphaMapping::Log10 {
domain: [a, b],
range: [c, d],
} => AlphaValues::log10(source, (a, b), (c, d)),
AlphaMapping::Threshold { boundaries, alphas } => {
AlphaValues::threshold(source, boundaries, alphas)
}
AlphaMapping::Continuous {
domain: [a, b],
evaluated,
} => AlphaValues::from_declared_continuous(&source, (a, b), &evaluated),
AlphaMapping::Categorical(_) => Err(invalid("categorical alpha requires category values")),
}
}
const COLUMN_KEY_FIELDS: &[grammar::Field] = &[
grammar::mandatory::<usize>("index"),
grammar::mandatory::<RawKey>("key"),
];
impl Codec for ColumnKeyLookup {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::one_of([
grammar::literal("position"),
grammar::array(grammar::record(ctx, COLUMN_KEY_FIELDS)),
])
}
fn encode(&self) -> Value {
match self {
Self::Selected => "position".into(),
Self::Named(keys) => {
let entries: toml_edit::Array = keys
.iter()
.map(|(index, key)| {
let mut fields = InlineTable::new();
fields.insert("index", index.encode());
fields.insert("key", key.encode());
Value::from(fields)
})
.collect();
entries.into()
}
}
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
if item.as_str() == Some("position") {
return Ok(Self::Selected);
}
let mut indices = std::collections::HashSet::new();
let keys = array_items(item)?
.map(|item| {
let fields = grammar::record_fields(item, COLUMN_KEY_FIELDS)?;
let index = field(fields, "index", None)?;
let key = field(fields, "key", None)?;
crate::recipe::capture::portable_key(&key)?;
if !indices.insert(index) {
return Err(invalid(
"duplicate logical column index in selector namespace",
));
}
Ok((index, key))
})
.collect::<Result<Vec<_>>>()?;
Ok(Self::Named(keys.into()))
}
}
const ALPHA_KEY_FIELDS: &[grammar::Field] = &[
grammar::mandatory::<RawKey>("field"),
grammar::role("values", true),
grammar::optional::<ColumnKeyLookup>("column_key"),
];
const ALPHA_ROLE_FIELDS: &[grammar::Field] = &[
grammar::optional::<String>("binding"),
grammar::custom("kind", true, |_| {
grammar::choices(&["observations", "single", "keyed", "bins"])
}),
grammar::custom("values", true, |ctx| {
grammar::any_of([
crate::recipe::collection::CategoryRequest::schema(ctx),
grammar::object([("generated", grammar::literal("rows"))], &["generated"]),
])
}),
grammar::optional::<AlphaMapping>("mapping"),
grammar::role("lower", false),
grammar::role("upper", false),
grammar::custom("keys", false, |ctx| {
grammar::array(grammar::group(ctx, ALPHA_KEY_FIELDS))
}),
];
const ALPHA_STYLE_FIELDS: &[grammar::Field] = &[
grammar::mandatory::<MappedKind>("kind"),
grammar::optional::<Vec<RawKey>>("fields"),
grammar::optional::<AlphaMapping>("mapping"),
];
pub(super) fn schema(ctx: &mut Schema) -> serde_json::Value {
ctx.named("AlphaDeclaration",|ctx|{
let shape = grammar::record(ctx, ALPHA_ROLE_FIELDS);
let shape = grammar::with(
shape,
serde_json::json!({"allOf":[
{"if":{"properties":{"kind":{"enum":["observations","single"]}}},"then":{"not":{"anyOf":[{"required":["keys"]},{"required":["lower"]},{"required":["upper"]}]}}},
{"if":{"properties":{"kind":{"const":"keyed"}}},"then":{"required":["keys"],"properties":{"keys":{"minItems":1}},"not":{"anyOf":[{"required":["lower"]},{"required":["upper"]}]}}},
{"if":{"properties":{"kind":{"const":"bins"}}},"then":{"required":["lower","upper"]}}
]}),
);
grammar::one_of([
grammar::literal("theme"),
serde_json::json!({"type":"number","minimum":0,"maximum":1}),
shape,
])
})
}
pub(super) fn style_schema(ctx: &mut Schema) -> serde_json::Value {
ctx.named("AlphaStyle",|ctx|{
let shape = grammar::with(
grammar::record(ctx, ALPHA_STYLE_FIELDS),
serde_json::json!({"allOf":[
{"if":{"properties":{"kind":{"const":"keyed"}}},"then":{"required":["fields"],"properties":{"fields":{"minItems":1}}}},
{"if":{"properties":{"kind":{"enum":["observations","single"]}}},"then":{"properties":{"fields":{"maxItems":0}}}}
]}),
);
grammar::one_of([
grammar::literal("theme"),
serde_json::json!({"type":"number","minimum":0,"maximum":1}),
shape,
])
})
}
struct AlphaKeyRequirement {
field: RawKey,
values: BindingRequirement,
lookup: Option<ColumnKeyLookup>,
}
fn read_keys(
item: Option<&Item>,
path: &str,
domain: &str,
fallback: Option<&str>,
requirements: &mut Vec<BindingRequirement>,
generated_columns: bool,
) -> Result<Vec<AlphaKeyRequirement>> {
let Some(item) = item else {
return Ok(Vec::new());
};
array_items(item)?
.enumerate()
.map(|(index, item)| {
let mut group = Group::new(
item,
&grammar::names(ALPHA_KEY_FIELDS),
format!("{path}.keys[{index}]"),
domain,
fallback,
requirements,
)?;
let lookup = group
.fields
.get("column_key")
.map(|item| ColumnKeyLookup::decode(item, None))
.transpose()?;
if lookup.is_some() && !generated_columns {
return Err(invalid(
"column selectors require a generated column dimension",
));
}
let dtype = if lookup.is_some() {
BindingValueType::ColumnIndex
} else {
BindingValueType::Key
};
Ok(AlphaKeyRequirement {
field: field(group.fields, "field", None)?,
values: group.required("values", dtype)?,
lookup,
})
})
.collect()
}
fn key_values(
keys: Vec<AlphaKeyRequirement>,
resolver: &mut Resolver<'_>,
) -> Result<Vec<CategoryValues>> {
keys.into_iter()
.map(|key| {
let values = if let Some(lookup) = key.lookup {
resolver
.supplied_column_keys(&key.values.reference, &key.field, lookup)
.map_err(|error| key.values.context(error))?
} else {
key.values.key_category(resolver)?
};
let name = values.original_name().to_owned();
Ok(values.with_field_key(key.field, name))
})
.collect()
}
pub(super) fn read(
item: &Item,
path: &str,
observation_domain: &str,
rectangle: Option<(&str, crate::recipe::plot_input::CollectionMode)>,
main_binding: Option<&str>,
fallback: Option<&str>,
requirements: &mut Vec<BindingRequirement>,
) -> Result<Supply<AlphaEncoding>> {
if item.as_str() == Some("theme") {
return Ok(Box::new(|_| Ok(AlphaEncoding::theme())));
}
if item.as_float().is_some() || item.as_integer().is_some() {
let value = AlphaEncoding::fixed(f64::decode(item, None)?)?;
return Ok(Box::new(move |_| Ok(value)));
}
let fields = grammar::record_fields(item, ALPHA_ROLE_FIELDS)?;
let kind = field::<String>(fields, "kind", None)?;
let independent = format!("{path}.rows");
let (domain, default, allowed) = match kind.as_str() {
"observations" => (
observation_domain,
main_binding,
&["binding", "kind", "values", "mapping"][..],
),
"single" => ("1", fallback, &["binding", "kind", "values", "mapping"][..]),
"keyed" => (
independent.as_str(),
fallback,
&["binding", "kind", "values", "mapping", "keys"][..],
),
"bins" => (
independent.as_str(),
fallback,
&[
"binding", "kind", "values", "mapping", "keys", "lower", "upper",
][..],
),
_ => return Err(invalid("unknown opacity-unit relationship")),
};
table(item, allowed)?;
let group = Group::new(item, allowed, path, domain, default, requirements)?;
let generated_columns =
rectangle.is_some_and(|(_, mode)| mode != crate::recipe::plot_input::CollectionMode::Grid);
let rectangle = rectangle.filter(|_| kind == "observations");
let mut group = match rectangle {
Some((owner, mode)) => group
.rectangular(owner)
.with_generated_columns(mode != crate::recipe::plot_input::CollectionMode::Grid),
None => group,
};
let values = read_values(&mut group, rectangle.map(|(_, mode)| mode))?;
match kind.as_str() {
"observations" => Ok(Box::new(move |r| {
Ok(AlphaEncoding::observations(values(r)?))
})),
"single" => Ok(Box::new(move |r| AlphaEncoding::single(values(r)?))),
"keyed" | "bins" => {
let lower = group.optional("lower", BindingValueType::Numeric)?;
let upper = group.optional("upper", BindingValueType::Numeric)?;
let key_binding = group.binding().map(str::to_owned);
let keys = read_keys(
fields.get("keys"),
path,
domain,
key_binding.as_deref(),
requirements,
generated_columns,
)?;
if kind == "keyed" {
if keys.is_empty() {
return Err(invalid("keyed alpha requires selector columns"));
}
return Ok(Box::new(move |r| {
AlphaEncoding::keyed(key_values(keys, r)?, values(r)?)
}));
}
let (Some(lower), Some(upper)) = (lower, upper) else {
return Err(invalid("bins alpha requires lower and upper"));
};
Ok(Box::new(move |r| {
AlphaEncoding::bins(
Bounds::new(lower.numeric(r)?, upper.numeric(r)?),
key_values(keys, r)?,
values(r)?,
)
}))
}
_ => unreachable!("validated alpha relationship"),
}
}
fn capture_values(
values: &AlphaValues,
capture: &mut Capture,
name: &str,
path: &str,
) -> Result<Value> {
if let Some(source) = values.get_numeric_source() {
capture.alpha_numeric(source, name, &format!("{path}.values"))
} else {
capture.keys(
values
.get_category_source()
.expect("actual categorical alpha source"),
name,
&format!("{path}.values"),
)
}
}
fn capture_keys(keys: &KeyColumns, capture: &mut Capture, name: &str, path: &str) -> Result<Value> {
let items = keys
.columns()
.iter()
.enumerate()
.map(|(index, column)| {
let mut fields = InlineTable::new();
fields.insert("field", crate::recipe::capture::portable_key(&column.key)?);
let source = match &column.values {
KeyValues::Strings(values) => values.get_source(),
KeyValues::Raw(values) => values.get_source(),
};
let original;
let values = if let Some(projected) = source.column_key_source() {
if let ColumnKeyLookup::Named(keys) = &projected.lookup {
for (_, key) in keys.iter() {
crate::recipe::capture::portable_key(key)?;
}
}
fields.insert("column_key", projected.lookup.encode());
original = KeyValues::Raw(
RawKeyValues::new(
"column indices",
projected.indices.iter().copied().map(RawKey::from),
)?
.with_source(source.clone())?,
);
&original
} else {
&column.values
};
fields.insert(
"values",
capture.keys(
values,
&format!("{name}_key"),
&format!("{path}.keys[{index}].values"),
)?,
);
Ok(Value::from(fields))
})
.collect::<Result<toml_edit::Array>>()?;
Ok(items.into())
}
pub(super) fn capture(
encoding: &AlphaEncoding,
capture: &mut Capture,
name: &str,
path: &str,
) -> Result<Value> {
if encoding.is_theme() {
return Ok("theme".into());
}
if let Some(fixed) = encoding.get_fixed() {
return Ok(fixed.encode());
}
capture.table_group(name, |capture| {
let mut fields = InlineTable::new();
let kind = if encoding.get_observations().is_some() {
"observations"
} else if encoding.get_single().is_some() {
"single"
} else if let Some((keys, _)) = encoding.get_keyed() {
fields.insert("keys", capture_keys(keys, capture, name, path)?);
"keyed"
} else {
let (bounds, keys, _) = encoding.get_bins().expect("actual bin alpha");
fields.insert(
"lower",
capture.numeric(
bounds.lower(),
&format!("{name}_lower"),
&format!("{path}.lower"),
)?,
);
fields.insert(
"upper",
capture.numeric(
bounds.upper(),
&format!("{name}_upper"),
&format!("{path}.upper"),
)?,
);
if !keys.is_empty() {
fields.insert("keys", capture_keys(keys, capture, name, path)?);
}
"bins"
};
fields.insert("kind", kind.into());
let values = encoding.values().expect("actual bound opacity");
fields.insert("values", capture_values(values, capture, name, path)?);
if !matches!(values.get_mapping(), AlphaMapping::Undeclared) {
fields.insert("mapping", values.get_mapping().encode());
}
Ok(fields.into())
})
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum MappedKind {
Observations,
Single,
Keyed,
Bins,
}
crate::recipe::codec::choice!(MappedKind {
Observations=>"observations",Single=>"single",Keyed=>"keyed",Bins=>"bins"
});
pub(super) enum AlphaStyle {
Scalar(AlphaEncoding),
Mapped {
kind: MappedKind,
fields: Vec<RawKey>,
mapping: AlphaMapping,
},
}
fn mapped_shape(encoding: &AlphaEncoding) -> Option<(MappedKind, Vec<RawKey>)> {
let collect = |keys: &KeyColumns| {
keys.columns()
.iter()
.map(|column| column.key.clone())
.collect()
};
if encoding.get_observations().is_some() {
Some((MappedKind::Observations, Vec::new()))
} else if encoding.get_single().is_some() {
Some((MappedKind::Single, Vec::new()))
} else if let Some((keys, _)) = encoding.get_keyed() {
Some((MappedKind::Keyed, collect(keys)))
} else {
encoding
.get_bins()
.map(|(_, keys, _)| (MappedKind::Bins, collect(keys)))
}
}
impl AlphaStyle {
pub(super) fn capture(encoding: &AlphaEncoding) -> Result<Value> {
if let Some((kind, keys)) = mapped_shape(encoding) {
let mut fields = InlineTable::new();
fields.insert("kind", kind.encode());
if !keys.is_empty() {
let keys = keys
.iter()
.map(crate::recipe::capture::portable_key)
.collect::<Result<toml_edit::Array>>()?;
fields.insert("fields", keys.into());
}
fields.insert(
"mapping",
encoding
.values()
.expect("bound opacity")
.get_mapping()
.encode(),
);
Ok(fields.into())
} else {
Ok(encoding
.get_fixed()
.map_or_else(|| "theme".into(), |value| value.encode()))
}
}
pub(super) fn read(item: Option<&Item>) -> Result<Self> {
let Some(item) = item else {
return Ok(Self::Scalar(AlphaEncoding::theme()));
};
if item.as_str() == Some("theme") {
return Ok(Self::Scalar(AlphaEncoding::theme()));
}
if item.as_integer().is_some() || item.as_float().is_some() {
return Ok(Self::Scalar(AlphaEncoding::fixed(f64::decode(
item, None,
)?)?));
}
let fields = grammar::record_fields(item, ALPHA_STYLE_FIELDS)?;
let kind = field(fields, "kind", None)?;
let keys: Vec<RawKey> = field(fields, "fields", Some(Vec::new()))?;
let mapping: AlphaMapping = field(fields, "mapping", Some(AlphaMapping::Undeclared))?;
if (kind == MappedKind::Keyed && keys.is_empty())
|| (matches!(kind, MappedKind::Observations | MappedKind::Single) && !keys.is_empty())
{
return Err(invalid("incompatible opacity style key roles"));
}
let mut seen = std::collections::HashSet::new();
for key in &keys {
crate::recipe::capture::portable_key(key)?;
if !seen.insert(key) {
return Err(invalid("duplicate opacity style key role"));
}
}
mapping.validate_declaration()?;
Ok(Self::Mapped {
kind,
fields: keys,
mapping,
})
}
pub(super) fn apply(self, target: &AlphaEncoding) -> Result<AlphaEncoding> {
match self {
Self::Scalar(style) => {
if target.values().is_some() {
return Err(invalid(
"scalar opacity style would replace a bound target domain",
));
}
Ok(style)
}
Self::Mapped {
kind,
fields,
mapping,
} => {
let Some((target_kind, target_fields)) = mapped_shape(target) else {
return Err(invalid(
"mapped opacity style requires a compatible bound target",
));
};
if kind != target_kind
|| fields.len() != target_fields.len()
|| fields.iter().any(|field| !target_fields.contains(field))
{
return Err(invalid(
"incompatible opacity style relationship or key roles",
));
}
let original = target.values().expect("validated target relationship");
let values = match mapping {
AlphaMapping::Categorical(entries) => {
let source = original
.get_category_source()
.and_then(crate::data::KeyValues::get_strings)
.ok_or_else(|| {
invalid("opacity style requires the target's categorical source")
})?;
AlphaValues::from_declared_categories(source, entries)?
}
mapping => {
let source = original.get_numeric_source().ok_or_else(|| {
invalid("opacity style requires the target's numeric source")
})?;
numeric_mapping(source.clone(), mapping)?
}
};
target.clone().replace_mapped_values(values)
}
}
}
}
pub(super) fn project_style(item: &Item) -> Result<Value> {
use crate::recipe::style::copy_fields;
if let Some(fields) = item.as_table_like() {
let mut style = InlineTable::new();
copy_fields(fields, &mut style, &["kind", "mapping"])?;
if let Some(keys) = fields.get("keys") {
let keys = array_items(keys)?
.map(|item| {
let key = item
.get("field")
.ok_or_else(|| invalid("missing opacity key field"))?;
crate::recipe::capture::portable_key(&RawKey::decode(key, None)?)
})
.collect::<Result<toml_edit::Array>>()?;
style.insert("fields", keys.into());
}
Ok(style.into())
} else {
item.clone()
.into_value()
.map_err(|_| invalid("invalid opacity style"))
}
}