mirror of
https://github.com/storytold/deckcraft.git
synced 2026-12-02 02:36:14 -06:00
Columns spacing and Paragraph before, after and by were in inches, and Paragraph took align, special, spaceBefore and spaceAfter by their old names and values. The hosted dialogs keep points under other names, so these fields were refused or applied as points. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
222 lines
11 KiB
Rust
222 lines
11 KiB
Rust
//! The control protocol's dialog fields. A client may send any value as text (a number as its digits, a check box as
|
|
//! `1` or `0`), and some dialogs take the protocol's names for what their dialog calls otherwise: Find's `text`,
|
|
//! Hyperlink's `mode: slide`, Action Settings' `tab` and `kind`, Bullets' `tab`, Paragraph's `lineKind` and
|
|
//! `lineValue`, Tabs' `stops` as `position:align|…` with positions in inches, and Reuse Slides' `off{index}`, which
|
|
//! unticks a slide with `1`.
|
|
|
|
use serde_json::{Value, json};
|
|
|
|
/// The opener parameters of dialog `id`, with the fields that choose how it opens taken out of `fields`: the tab
|
|
/// Bullets and Action Settings open on. The opening fields the earlier dialogs took become the hosted dialogs' own.
|
|
pub(super) fn opener(id: &str, params: &Value, fields: &mut Vec<(String, Value)>) -> Value {
|
|
let mut params = if params.is_object() { params.clone() } else { json!({}) };
|
|
if matches!(id, "bullets" | "action")
|
|
&& let Some(at) = fields.iter().position(|(field, _)| field == "tab")
|
|
{
|
|
params["tab"] = fields.remove(at).1;
|
|
}
|
|
for (field, value) in fields.iter_mut() {
|
|
let (name, translated) = opening_field(id, field, value.take());
|
|
*field = name;
|
|
*value = translated;
|
|
}
|
|
params
|
|
}
|
|
|
|
/// An opening field as the earlier dialogs named it, in the hosted dialog's name and unit: Columns' `spacing` and
|
|
/// Paragraph's `before`, `after` and `by` in inches, Paragraph's `align`, `special`, `spaceBefore` and `spaceAfter`.
|
|
/// A value that cannot be read goes as it is, for the dialog to refuse.
|
|
fn opening_field(id: &str, field: &str, value: Value) -> (String, Value) {
|
|
let inches = |value: Value| number(&value).map_or(value, |inches| json!(inches * 72.0));
|
|
let named = |value: Value, names: &[(&str, &str)]| match names.iter().find(|(old, _)| value.as_str() == Some(*old)) {
|
|
Some((_, name)) => json!(name),
|
|
None => value,
|
|
};
|
|
let (name, value) = match (id, field) {
|
|
("columns", "spacing") => (field, inches(value)),
|
|
("paragraph", "before") => ("before_text", inches(value)),
|
|
("paragraph", "after") => ("after_text", inches(value)),
|
|
("paragraph", "by") => (field, inches(value)),
|
|
("paragraph", "spaceBefore") => ("space_before", value),
|
|
("paragraph", "spaceAfter") => ("space_after", value),
|
|
("paragraph", "align") => (
|
|
field,
|
|
named(
|
|
value,
|
|
&[
|
|
("left", "Left"),
|
|
("center", "Center"),
|
|
("right", "Right"),
|
|
("justify", "Justify"),
|
|
("justLow", "JustifyLow"),
|
|
("distributed", "Distributed"),
|
|
],
|
|
),
|
|
),
|
|
("paragraph", "special") => (field, named(value, &[("none", "None"), ("first", "FirstLine"), ("hanging", "Hanging")])),
|
|
_ => (field, value),
|
|
};
|
|
(name.to_owned(), value)
|
|
}
|
|
|
|
/// `fields` as dialog `key` takes them, read against its current fields `current`; `tab` is the Action Settings tab
|
|
/// a `kind` applies to.
|
|
pub(super) fn typed(key: &str, current: &Value, tab: &str, fields: Vec<(String, Value)>) -> Result<Vec<(String, Value)>, String> {
|
|
let mut out = Vec::new();
|
|
let mut line: Option<(Option<String>, Option<f64>)> = None;
|
|
let mut unticked: Vec<(u64, bool)> = Vec::new();
|
|
for (field, value) in fields {
|
|
let slide = field.strip_prefix("off").and_then(|index| index.parse::<u64>().ok());
|
|
match (key, field.as_str()) {
|
|
("reuseSlides", _) if slide.is_some() => {
|
|
let off = as_typed(Some(&json!(false)), value.clone());
|
|
unticked.push((slide.unwrap_or_default(), off.as_bool().ok_or_else(|| format!("`{field}` must be 1 or 0"))?));
|
|
}
|
|
("find", "text") => out.push(("find".to_owned(), value)),
|
|
("hyperlink", "mode") if value == "slide" => out.push((field, json!("place"))),
|
|
("action", "kind") => {
|
|
let kind = value.as_str().ok_or("`kind` must be text")?;
|
|
if matches!(kind, "none" | "program" | "playMedia") {
|
|
out.push((format!("{tab}.kind"), value));
|
|
} else {
|
|
out.push((format!("{tab}.kind"), json!("link")));
|
|
out.push((format!("{tab}.target"), value));
|
|
}
|
|
}
|
|
("paragraph", "lineKind") => line.get_or_insert_default().0 = Some(value.as_str().ok_or("`lineKind` must be text")?.to_owned()),
|
|
("paragraph", "lineValue") => line.get_or_insert_default().1 = Some(number(&value).ok_or("`lineValue` must be a number")?),
|
|
("tabs", "stops") if value.is_string() => out.push((field, stops(&value)?)),
|
|
_ => out.push((field, value)),
|
|
}
|
|
}
|
|
if let Some((kind, value)) = line {
|
|
out.push(("line_spacing".to_owned(), line_spacing(current, kind.as_deref(), value)?));
|
|
}
|
|
if !unticked.is_empty() {
|
|
let mut ticked: Vec<u64> = current["ticked"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect();
|
|
for (slide, off) in unticked {
|
|
ticked.retain(|at| *at != slide);
|
|
if !off {
|
|
ticked.push(slide);
|
|
}
|
|
}
|
|
ticked.sort_unstable();
|
|
out.push(("ticked".to_owned(), json!(ticked)));
|
|
}
|
|
Ok(out
|
|
.into_iter()
|
|
.map(|(field, value)| {
|
|
let value = as_typed(current.get(&field), value);
|
|
(field, value)
|
|
})
|
|
.collect())
|
|
}
|
|
|
|
fn number(value: &Value) -> Option<f64> {
|
|
value.as_f64().or_else(|| value.as_str()?.trim().parse().ok()).filter(|n: &f64| n.is_finite())
|
|
}
|
|
|
|
/// A text value as the type the field holds now: a number field takes its digits, a check box `1`, `0`, `true` or
|
|
/// `false`. Other values, and text the type cannot read, go as they are for the dialog to accept or refuse.
|
|
fn as_typed(now: Option<&Value>, value: Value) -> Value {
|
|
let Some(text) = value.as_str().map(str::trim) else { return value };
|
|
let read = match now {
|
|
Some(Value::Number(_)) => text.parse::<i64>().map(Value::from).ok().or_else(|| number(&value).map(Value::from)),
|
|
Some(Value::Bool(_)) => match text {
|
|
"1" | "true" => Some(Value::Bool(true)),
|
|
"0" | "false" => Some(Value::Bool(false)),
|
|
_ => None,
|
|
},
|
|
_ => None,
|
|
};
|
|
read.unwrap_or(value)
|
|
}
|
|
|
|
/// Paragraph's line spacing set to `kind` (`multiple` or `exactly`, the current kind when absent) and `value` (a
|
|
/// multiple, or points). Without a value a kind keeps its current one, and a change of kind starts at single spacing
|
|
/// or 18 pt.
|
|
fn line_spacing(current: &Value, kind: Option<&str>, value: Option<f64>) -> Result<Value, String> {
|
|
let (now, now_value) = match ¤t["line_spacing"] {
|
|
Value::Object(spacing) => spacing.iter().next().map(|(kind, value)| (kind.clone(), value.as_f64())).unwrap_or_default(),
|
|
_ => (String::new(), None),
|
|
};
|
|
let kind = match kind {
|
|
Some("exactly") => "Exactly",
|
|
Some("multiple") => "Multiple",
|
|
None if now == "Exactly" => "Exactly",
|
|
None => "Multiple",
|
|
Some(other) => return Err(format!("`lineKind` can't take {other:?} (multiple or exactly)")),
|
|
};
|
|
let value = value.or(now_value.filter(|_| now == kind)).unwrap_or(if kind == "Exactly" { 18.0 } else { 1.0 });
|
|
Ok(json!({ kind: value }))
|
|
}
|
|
|
|
/// Tabs' stops in the protocol's text form, `position:align|…`: positions in inches, aligns `l`, `ctr`, `r` or `dec`.
|
|
fn stops(value: &Value) -> Result<Value, String> {
|
|
let refused = |stop: &str| format!("`stops` can't take {stop:?} (position:align in inches, align l, ctr, r or dec)");
|
|
value
|
|
.as_str()
|
|
.unwrap_or_default()
|
|
.split('|')
|
|
.filter(|stop| !stop.trim().is_empty())
|
|
.map(|stop| {
|
|
let (at, align) = stop.split_once(':').ok_or_else(|| refused(stop))?;
|
|
let inches = number(&json!(at)).ok_or_else(|| refused(stop))?;
|
|
let align = match align.trim() {
|
|
"l" => "left",
|
|
"ctr" => "center",
|
|
"r" => "right",
|
|
"dec" => "decimal",
|
|
_ => return Err(refused(stop)),
|
|
};
|
|
Ok(json!({"position": inches * 72.0, "align": align, "leader": "none"}))
|
|
})
|
|
.collect::<Result<Vec<_>, _>>()
|
|
.map(Value::from)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
/// Text values take the type of the field they set; a value the type cannot read is left for the dialog to refuse.
|
|
#[test]
|
|
fn text_values_take_their_field_s_type() {
|
|
let current = json!({"size": 18.0, "count": 1, "bold": false, "family": "Inter"});
|
|
let fields = vec![
|
|
("size".to_owned(), json!("28")),
|
|
("count".to_owned(), json!("40")),
|
|
("bold".to_owned(), json!("1")),
|
|
("family".to_owned(), json!("12")),
|
|
("size".to_owned(), json!("big")),
|
|
];
|
|
let typed = typed("font", ¤t, "click", fields).unwrap_or_default();
|
|
let values: Vec<&Value> = typed.iter().map(|(_, value)| value).collect();
|
|
assert!(values[0].is_number() && values[1].is_i64() && values[2] == &json!(true), "{typed:?}");
|
|
assert!(values[3].is_string() && values[4].is_string(), "text fields and unreadable text stay text: {typed:?}");
|
|
}
|
|
|
|
/// The protocol's names reach the fields the dialogs have: an action kind becomes a hyperlink target on the tab it
|
|
/// is for, Exactly line spacing a paragraph format, text tab stops the dialog's stops in points.
|
|
#[test]
|
|
fn protocol_names_reach_the_dialogs_fields() {
|
|
let action = typed("action", &json!({}), "hover", vec![("kind".to_owned(), json!("url"))]).unwrap_or_default();
|
|
assert!(action.contains(&("hover.kind".to_owned(), json!("link"))) && action.contains(&("hover.target".to_owned(), json!("url"))));
|
|
|
|
let current = json!({"line_spacing": {"Multiple": 1.0}, "tab": "indents"});
|
|
let paragraph = typed("paragraph", ¤t, "click", vec![("lineKind".to_owned(), json!("exactly"))]).unwrap_or_default();
|
|
assert_eq!(paragraph.first().map(|(field, _)| field.as_str()), Some("line_spacing"));
|
|
let spacing = ¶graph[0].1["Exactly"];
|
|
assert!(spacing.as_f64().is_some_and(|pt| pt > 1.0), "exactly starts at a distance in points: {paragraph:?}");
|
|
|
|
let tabs = typed("tabs", &json!({}), "click", vec![("stops".to_owned(), json!("0.5:l|2.25:r"))]).unwrap_or_default();
|
|
let stops = tabs[0].1.as_array().cloned().unwrap_or_default();
|
|
assert_eq!(stops.len(), 2);
|
|
assert!(stops[1]["position"].as_f64() > stops[0]["position"].as_f64() && stops[1]["align"] == "right", "{stops:?}");
|
|
assert!(typed("tabs", &json!({}), "click", vec![("stops".to_owned(), json!("0.5:sideways"))]).is_err());
|
|
|
|
let reuse = typed("reuseSlides", &json!({"ticked": [0, 1, 2]}), "click", vec![("off1".to_owned(), json!("1"))]).unwrap_or_default();
|
|
assert_eq!(reuse, vec![("ticked".to_owned(), json!([0, 2]))], "off1 unticks the second slide only");
|
|
}
|
|
}
|