use super::element::{attributes, elements, rust_name, Child};
use super::ir::{channels, wire};
use super::read::{boolean, call, defined, len, names, number, tag, text as text_of};
use super::schema::{describe_issue, validate, with_defaults};
use super::source::{meta, Sources};
use super::{Declared, Family};
pub use super::{fragment, json, El, Json, Value};
use std::collections::BTreeMap;
use std::sync::OnceLock;
elements! {
workbook: children;
sheet: children;
cell: leaf;
column: leaf;
row: leaf;
chart: leaf;
pivot: leaf;
filter: children;
criterion: leaf;
page: children;
h1: text;
h2: text;
h3: text;
p: text;
li: text;
bullet: text;
numbered: text;
todo: text;
quote: text;
pre: text;
divider: leaf;
image: leaf;
b: text;
i: text;
u: text;
s: text;
code: text;
a: text;
span: text;
br: leaf;
deck: children;
slide: children;
text: text;
shape: leaf;
group: children;
master: children;
text_style = "textStyle": leaf;
layout: children;
placeholder: leaf;
}
attributes! {
pub trait OfficeAttrs {
title;
name;
rows;
cols;
frozen_rows;
frozen_cols;
source;
format;
query;
color;
at;
value;
range;
kind;
category;
series;
column;
test;
aggregate;
formula;
num_fmt;
bold;
italic;
underline;
align;
bg;
wrap;
width;
height;
checked;
lang;
src;
alt;
href;
dpi;
layout;
notes;
background;
hidden;
placeholder;
x;
y;
w;
h;
rotation;
z;
visible;
opacity;
label;
font_size;
valign;
font_family;
line_height;
overflow;
shape;
fill;
stroke;
stroke_width;
corner_radius;
fit;
paper;
font;
size;
bullet;
level;
style;
locked;
role;
prompt;
columns;
gutter;
inset;
}
}
pub(crate) const FAMILY: Family = Family { module: "office", roots: &["workbook", "page", "deck"], declare };
pub const DECK_DOC: &str = "deck.doc";
pub const DECK_SLIDE: &str = "deck.slide";
pub const DECK_TEXT: &str = "deck.text";
pub const DECK_IMAGE: &str = "deck.image";
pub const DECK_SHAPE: &str = "deck.shape";
fn declare(root: El) -> Result<Declared, String> {
match root.tag {
"workbook" => read_workbook(&root),
"page" => read_page(&root),
_ => Ok(Declared::Graph(read_deck(&root)?)),
}
}
fn place(el: &El) -> String {
call(el, &["name", "at"])
}
fn only(el: &El, allowed: &[&str]) -> Result<(), String> {
match el.attrs.iter().find(|(k, _)| !allowed.contains(&k.as_str())) {
Some((k, _)) => {
let takes = if allowed.is_empty() { "nothing".to_string() } else { names(allowed) };
Err(format!("{}: {} is not read on a {} (it takes {takes})", place(el), rust_name(k), tag(el.tag)))
}
None => Ok(()),
}
}
fn txt(el: &El, prop: &str) -> Result<Option<String>, String> {
text_of(el, prop, &place(el))
}
fn num(el: &El, prop: &str) -> Result<Option<f64>, String> {
number(el, prop, &place(el))
}
fn flag(el: &El, prop: &str) -> Result<Option<bool>, String> {
boolean(el, prop, &place(el))
}
fn one_of(el: &El, prop: &str, values: &[&str]) -> Result<Option<String>, String> {
let v = txt(el, prop)?;
match v {
Some(s) if !values.contains(&s.as_str()) => Err(format!("{}: {} is one of {}", place(el), rust_name(prop), values.join(", "))),
v => Ok(v),
}
}
fn js(v: Option<String>) -> Option<Json> {
v.map(Json::from)
}
fn jn(v: Option<f64>) -> Option<Json> {
v.map(Json::Num)
}
fn jb(v: Option<bool>) -> Option<Json> {
v.map(Json::Bool)
}
const ALIGN: &[&str] = &["left", "center", "right"];
fn a1(at: &str) -> Option<(&str, u64)> {
let split = at.find(|c: char| !c.is_ascii_uppercase()).unwrap_or(at.len());
let (letters, digits) = at.split_at(split);
let ok = (1..=3).contains(&letters.len())
&& (1..=7).contains(&digits.len())
&& digits.bytes().all(|c| c.is_ascii_digit())
&& !digits.starts_with('0');
if ok {
digits.parse().ok().map(|r| (letters, r))
} else {
None
}
}
fn col_index(letters: &str) -> u64 {
letters.bytes().fold(0u64, |n, c| n * 26 + (c - 64) as u64) - 1
}
fn sizes(map: &BTreeMap<u64, f64>) -> Option<Json> {
if map.is_empty() {
return None;
}
Some(Json::Obj(map.iter().map(|(k, v)| (k.to_string(), Json::Num(*v))).collect()))
}
pub fn workbook_schema() -> &'static Json {
static SCHEMA: OnceLock<Json> = OnceLock::new();
SCHEMA.get_or_init(|| Json::parse(include_str!("workbook_schema.json")).expect("workbook_schema.json is JSON"))
}
const DATA_FORMATS: &[&str] = &[
"parquet", "arrow", "feather", "csv", "tsv", "json", "ndjson", "avro", "orc", "sqlite", "duckdb", "xlsx", "auto",
];
const SURFACES: &[&str] = &["threads", "devices", "snapshots", "drive", "notifications", "marketplace", "credits"];
fn data_source_of(el: &El, text: &str, format: Option<&str>) -> Result<Json, String> {
if text.starts_with("http://") || text.starts_with("https://") {
return Ok(defined(vec![("kind", Some("remote".into())), ("engine", Some("http".into())), ("url", Some(text.into())), ("format", js(format.map(str::to_string)))]));
}
if let Some(id) = text.strip_prefix("surface:") {
if !SURFACES.contains(&id) {
return Err(format!("{}: source is surface:<id>, a platform surface ({}), not {}", place(el), SURFACES.join(", "), Json::from(text).text()));
}
if format.is_some() {
return Err(format!("{}: a surface source has no format", place(el)));
}
return Ok(Json::obj().with("kind", "surface").with("surface", id));
}
let scheme = text.find("://").is_some_and(|at| {
let head = &text[..at];
!head.is_empty() && head.chars().next().is_some_and(|c| c.is_ascii_lowercase()) && head.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '+' | '.' | '-'))
});
if text == "self" || scheme {
return Err(format!("{}: source is a file beside the workbook, an http(s) URL or surface:<id>, not {}", place(el), Json::from(text).text()));
}
Ok(defined(vec![("kind", Some("file".into())), ("ref", Some(text.into())), ("format", js(format.map(str::to_string)))]))
}
fn is_range(text: &str) -> bool {
let upper = text.to_uppercase();
let mut ends = upper.split(':');
let ok = ends.next().is_some_and(|e| a1(e).is_some()) && ends.next().map_or(true, |e| a1(e).is_some());
ok && ends.next().is_none()
}
fn workbook_element(el: &El) -> Result<Json, String> {
let schema = workbook_schema();
let def = schema.get("roots").and_then(|r| r.get(el.tag)).and_then(Json::as_str).unwrap_or_default();
let defs = schema.get("$defs").cloned().unwrap_or_else(Json::obj);
let root = Json::obj().with("$ref", format!("#/$defs/{def}"));
let props = with_defaults(&root, &Json::Obj(el.attrs.clone()), &defs)?;
let issues = validate(&root, &props, &defs, "")?;
if !issues.is_empty() {
return Err(format!("{}: {}", place(el), issues.iter().map(describe_issue).collect::<Vec<_>>().join("; ")));
}
if let Some(range) = props.get("range").and_then(Json::as_str) {
if !is_range(range) {
return Err(format!("{}: range is an A1 range (\"A1:C20\"), not {}", place(el), Json::from(range).text()));
}
}
Ok(props)
}
fn read_workbook(root: &El) -> Result<Declared, String> {
only(root, &["title"])?;
let mut sources = Sources::new();
sources.put("workbook", root);
let mut seen: Vec<String> = Vec::new();
let mut named: [Vec<String>; 2] = [Vec::new(), Vec::new()];
let mut sheets = Vec::new();
for (i, el) in root.child_elements().enumerate() {
if el.tag != "sheet" {
return Err(format!("{} is not read in a workbook() (it holds sheet()s)", tag(el.tag)));
}
only(el, &["name", "rows", "cols", "frozenRows", "frozenCols", "color", "source", "format", "query"])?;
let id = format!("sheet-{}", i + 1);
let name = txt(el, "name")?.unwrap_or_else(|| format!("Sheet {}", i + 1));
if seen.contains(&name.to_lowercase()) {
return Err(format!("two sheets are called {name}"));
}
seen.push(name.to_lowercase());
sources.put(format!("sheet:{id}"), el);
if let Some(source) = txt(el, "source")? {
let format = one_of(el, "format", DATA_FORMATS)?;
let query = txt(el, "query")?;
if !el.children.is_empty() {
return Err(format!("{}: a data sheet holds nothing: its source and query say what it reads", place(el)));
}
for k in ["rows", "cols", "frozenRows", "frozenCols"] {
if el.attr_of(k).is_some() {
return Err(format!("{}: a data sheet reads a table, so it has no {k}", place(el)));
}
}
sheets.push(defined(vec![
("id", Some(id.into())),
("name", Some(name.into())),
("color", js(txt(el, "color")?)),
("kind", Some("data".into())),
("source", Some(data_source_of(el, &source, format.as_deref())?)),
("query", js(query)),
]));
continue;
}
if el.attr_of("query").is_some() || el.attr_of("format").is_some() {
return Err(format!("{}: a grid sheet reads no source (a sheet() with a source is a data sheet)", place(el)));
}
let mut cells: Vec<(String, Json)> = Vec::new();
let mut col_widths: BTreeMap<u64, f64> = BTreeMap::new();
let mut row_heights: BTreeMap<u64, f64> = BTreeMap::new();
let mut rows = num(el, "rows")?.unwrap_or(200.0);
let mut cols = num(el, "cols")?.unwrap_or(26.0);
let mut charts: Vec<Json> = Vec::new();
let mut pivots: Vec<Json> = Vec::new();
let mut filter: Option<(Json, Vec<Json>)> = None;
for c in el.child_elements() {
if c.tag == "chart" || c.tag == "pivot" {
let is_chart = c.tag == "chart";
let props = workbook_element(c)?;
let called = props.get("name").and_then(Json::as_str).unwrap_or_default().to_string();
let taken = &mut named[if is_chart { 0 } else { 1 }];
if taken.contains(&called.to_lowercase()) {
return Err(format!("two {} are called {called}", if is_chart { "charts" } else { "pivot tables" }));
}
taken.push(called.to_lowercase());
let list = if is_chart { &mut charts } else { &mut pivots };
let eid = format!("{}-{}", c.tag, list.len() + 1);
let mut entries = vec![("id".to_string(), Json::from(eid.as_str()))];
if let Json::Obj(fields) = props {
entries.extend(fields);
}
list.push(Json::Obj(entries));
sources.put(format!("{}:{id}!{eid}", c.tag), c);
continue;
}
if c.tag == "filter" {
if filter.is_some() {
return Err(format!("{name} has two filters (a sheet has one)"));
}
let range = workbook_element(c)?.get("range").cloned().unwrap_or(Json::Null);
sources.put(format!("filter:{id}"), c);
let mut criteria: Vec<Json> = Vec::new();
for k in c.child_elements() {
if k.tag != "criterion" {
return Err(format!("{} is not read in a filter() (it holds criterion()s)", tag(k.tag)));
}
let mut props = workbook_element(k)?;
let given = props.get("column").and_then(Json::as_str).unwrap_or_default().to_string();
let column = given.to_uppercase();
if !(1..=3).contains(&column.len()) || !column.bytes().all(|b| b.is_ascii_uppercase()) {
return Err(format!("criterion(): column is a column's letters (\"B\"), not {}", Json::from(given.as_str()).text()));
}
if criteria.iter().any(|x| x.get("column").and_then(Json::as_str) == Some(column.as_str())) {
return Err(format!("the filter of {name} has two criteria for column {column}"));
}
props.set("column", column.as_str());
criteria.push(props);
sources.put(format!("criterion:{id}!{column}"), k);
}
filter = Some((range, criteria));
continue;
}
if c.tag == "column" || c.tag == "row" {
let is_column = c.tag == "column";
let size_prop = if is_column { "width" } else { "height" };
only(c, &["at", size_prop])?;
let index = match (is_column, c.attr_of("at")) {
(true, Some(Json::Str(s))) if (1..=3).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_uppercase()) => Some(col_index(s)),
(false, Some(Json::Num(r))) if r.fract() == 0.0 && *r >= 1.0 => Some(*r as u64 - 1),
_ => None,
};
let Some(index) = index else {
let what = if is_column { "a column's letters (\"B\")" } else { "a row's number (1 is the first)" };
return Err(format!("{}: at is {what}", place(c)));
};
let size = match num(c, size_prop)? {
Some(v) if v > 0.0 => v,
_ => return Err(format!("{}: {size_prop} is a number of pixels", place(c))),
};
let key = match c.attr_of("at") {
Some(Json::Str(s)) if is_column => s.clone(),
_ => (index + 1).to_string(),
};
if is_column { &mut col_widths } else { &mut row_heights }.insert(index, size);
sources.put(format!("{}:{id}!{key}", c.tag), c);
continue;
}
if c.tag != "cell" {
return Err(format!("{} is not read in a sheet() (it holds cell(), column(), row(), chart(), pivot() and filter())", tag(c.tag)));
}
only(c, &["at", "value", "formula", "numFmt", "bold", "italic", "align", "bg", "color", "wrap"])?;
let at = txt(c, "at")?.map(|a| a.to_uppercase());
let Some((at, (letters, row))) = at.as_deref().and_then(|a| a1(a).map(|m| (a.to_string(), m))) else {
let given = c.attr_of("at").map(Json::text).unwrap_or_else(|| "nothing".into());
return Err(format!("cell(): at is an A1 reference (\"B4\"), not {given}"));
};
if cells.iter().any(|(k, _)| *k == at) {
return Err(format!("two cells of {name} are at {at}"));
}
let v = c.attr_of("value");
if matches!(v, Some(Json::Arr(_) | Json::Obj(_))) {
return Err(format!("{}: value is text, a number or true/false", place(c)));
}
let f = txt(c, "formula")?;
if f.as_deref().is_some_and(|f| !f.starts_with('=')) {
return Err(format!("{}: a formula starts with = (\"=SUM(B2:B4)\")", place(c)));
}
if f.is_some() && v.is_some() {
return Err(format!("{}: a cell has a value or a formula, not both", place(c)));
}
let fmt = defined(vec![
("numFmt", js(txt(c, "numFmt")?)),
("bold", jb(flag(c, "bold")?)),
("italic", jb(flag(c, "italic")?)),
("align", js(one_of(c, "align", ALIGN)?)),
("bg", js(txt(c, "bg")?)),
("color", js(txt(c, "color")?)),
("wrap", jb(flag(c, "wrap")?)),
]);
let has_fmt = len(&fmt) > 0;
let value = if f.is_none() { v.cloned() } else { None };
cells.push((at.clone(), defined(vec![("v", value), ("f", js(f)), ("fmt", has_fmt.then_some(fmt))])));
rows = rows.max(row as f64);
cols = cols.max((col_index(letters) + 1) as f64);
sources.put(format!("cell:{id}!{at}"), c);
}
let (fr, fc) = (num(el, "frozenRows")?, num(el, "frozenCols")?);
let frozen = (fr.is_some() || fc.is_some()).then(|| Json::obj().with("rows", fr.unwrap_or(0.0)).with("cols", fc.unwrap_or(0.0)));
sheets.push(defined(vec![
("id", Some(id.into())),
("name", Some(name.into())),
("color", js(txt(el, "color")?)),
("kind", Some("grid".into())),
("rows", Some(rows.into())),
("cols", Some(cols.into())),
("cells", Some(Json::Obj(cells))),
("colWidths", sizes(&col_widths)),
("rowHeights", sizes(&row_heights)),
("frozen", frozen),
("charts", (!charts.is_empty()).then_some(Json::Arr(charts))),
("pivots", (!pivots.is_empty()).then_some(Json::Arr(pivots))),
("filter", filter.map(|(range, criteria)| Json::obj().with("range", range).with("criteria", Json::Arr(criteria)))),
]));
}
if sheets.is_empty() {
return Err("a workbook() holds at least one sheet()".into());
}
let mut document = Json::obj().with("format", "workbook").with("version", 1i64).with("sheets", Json::Arr(sheets));
if let Some(title) = txt(root, "title")? {
document.set("meta", Json::obj().with("title", title));
}
Ok(Declared::Document { format: "workbook".into(), document, sources: sources.json() })
}
fn text_block(t: &str) -> Option<&'static str> {
Some(match t {
"h1" => "h1",
"h2" => "h2",
"h3" => "h3",
"p" => "p",
"bullet" => "ul",
"numbered" => "ol",
"todo" => "todo",
"quote" => "quote",
_ => return None,
})
}
const MARKS: &[&str] = &["b", "i", "u", "s", "code"];
fn escape(s: &str) -> String {
s.replace('&', "&").replace('<', "<").replace('>', ">")
}
pub fn inline_html(children: &[Child], at: &str) -> Result<String, String> {
fn walk(children: &[Child], at: &str, out: &mut String) -> Result<(), String> {
for c in children {
let el = match c {
Child::Text(t) => {
out.push_str(&escape(t));
continue;
}
Child::El(el) => el,
};
if el.tag == "br" {
only(el, &[])?;
out.push_str("<br>");
} else if el.tag == "a" {
only(el, &["href"])?;
let href = txt(el, "href")?.unwrap_or_default();
out.push_str(&format!("<a href=\"{}\">", href.replace('&', "&").replace('"', """)));
walk(&el.children, at, out)?;
out.push_str("</a>");
} else if MARKS.contains(&el.tag) {
only(el, &[])?;
out.push_str(&format!("<{}>", el.tag));
walk(&el.children, at, out)?;
out.push_str(&format!("</{}>", el.tag));
} else {
return Err(format!("{at}: {} is not a mark (the marks are b, i, u, s, code, a and br)", tag(el.tag)));
}
}
Ok(())
}
let mut out = String::new();
walk(children, at, &mut out)?;
Ok(out)
}
fn plain_text(children: &[Child], at: &str) -> Result<String, String> {
let mut out = String::new();
for c in children {
match c {
Child::Text(t) => out.push_str(t),
Child::El(_) => return Err(format!("{at}: a code block holds text, not elements")),
}
}
Ok(out)
}
fn read_page(root: &El) -> Result<Declared, String> {
only(root, &["title", "paper", "font"])?;
let mut sources = Sources::new();
sources.put("page", root);
let mut blocks = Vec::new();
for (i, el) in root.child_elements().enumerate() {
let id = format!("block-{}", i + 1);
sources.put(format!("block:{id}"), el);
let block = if let Some(kind) = text_block(el.tag) {
let aligned = ALIGNED.contains(&el.tag);
only(el, if kind == "todo" { &["checked"] } else if aligned { &["align"] } else { &[] })?;
let html = inline_html(&el.children, &tag(el.tag))?;
let checked = if kind == "todo" { Some(Json::Bool(flag(el, "checked")?.unwrap_or(false))) } else { None };
let align = if aligned { js(one_of(el, "align", &["left", "center", "right", "justify"])?) } else { None };
defined(vec![("id", Some(id.into())), ("type", Some(kind.into())), ("html", Some(html.into())), ("checked", checked), ("align", align)])
} else {
match el.tag {
"pre" => {
only(el, &["lang"])?;
let html = escape(&plain_text(&el.children, "pre()")?);
defined(vec![("id", Some(id.into())), ("type", Some("code".into())), ("html", Some(html.into())), ("lang", js(txt(el, "lang")?))])
}
"divider" => {
only(el, &[])?;
Json::obj().with("id", id).with("type", "divider").with("html", "")
}
"image" => {
only(el, &["src", "alt"])?;
defined(vec![
("id", Some(id.into())),
("type", Some("image".into())),
("html", Some("".into())),
("src", Some(txt(el, "src")?.unwrap_or_default().into())),
("alt", js(txt(el, "alt")?)),
])
}
_ => {
return Err(format!(
"{} is not a block of a page() (the blocks are h1, h2, h3, p, bullet, numbered, todo, quote, pre, divider and image)",
tag(el.tag)
))
}
}
};
blocks.push(block);
}
let mut document = Json::obj().with("format", "page").with("version", 1i64).with("blocks", Json::Arr(blocks));
if let Some(title) = txt(root, "title")? {
document.set("meta", Json::obj().with("title", title));
}
let setup = defined(vec![("paper", js(one_of(root, "paper", PAPERS)?)), ("font", js(one_of(root, "font", PAGE_FONTS)?))]);
if len(&setup) > 0 {
document.set("page", setup);
}
Ok(Declared::Document { format: "page".into(), document, sources: sources.json() })
}
const BOX: &[&str] = &["x", "y", "w", "h", "rotation"];
const COMMON: &[&str] = &["x", "y", "w", "h", "rotation", "placeholder", "z", "visible", "opacity", "label", "locked"];
const TEXT_FRAME: &[&str] = &["columns", "gutter", "inset"];
const ROLES: &[&str] = &["title", "subtitle", "body", "image", "caption", "footer", "slideNumber"];
const TEXT_STYLE: &[&str] = &["fontSize", "color", "bold", "italic", "fontFamily", "lineHeight", "align"];
const TEXT_ALIGN: &[&str] = &["left", "center", "right", "justify"];
pub const DECK_STYLES: &[&str] = &["plain", "ink", "editorial", "signal"];
const ALIGNED: &[&str] = &["h1", "h2", "h3", "p", "quote"];
pub const PAPERS: &[&str] = &["letter", "a4"];
pub const PAGE_FONTS: &[&str] = &["sans", "serif", "mono"];
type Style = Vec<(String, Json)>;
fn styled(style: &Style, key: &str, value: Json) -> Style {
let mut out = style.clone();
match out.iter_mut().find(|(k, _)| k == key) {
Some(entry) => entry.1 = value,
None => out.push((key.to_string(), value)),
}
out
}
pub fn rich_text(children: &[Child], at: &str) -> Result<Json, String> {
fn runs_of(c: &Child, style: &Style, at: &str, out: &mut Vec<(String, Style)>) -> Result<(), String> {
let el = match c {
Child::Text(t) => {
match out.last_mut() {
Some(prev) if prev.1 == *style => prev.0.push_str(t),
_ => out.push((t.clone(), style.clone())),
}
return Ok(());
}
Child::El(el) => el,
};
if el.tag == "a" {
only(el, &["href"])?;
let link = styled(style, "link", txt(el, "href")?.unwrap_or_default().into());
return el.children.iter().try_for_each(|x| runs_of(x, &link, at, out));
}
if el.tag == "span" {
only(el, &["color", "size", "font"])?;
let mut own = style.clone();
for (key, value) in [("color", js(txt(el, "color")?)), ("sizePx", jn(num(el, "size")?)), ("fontFamily", js(txt(el, "font")?))] {
if let Some(v) = value {
own = styled(&own, key, v);
}
}
return el.children.iter().try_for_each(|x| runs_of(x, &own, at, out));
}
let mark = match el.tag {
"b" => "bold",
"i" => "italic",
"u" => "underline",
"s" => "strike",
_ => return Err(format!("{at}: {} is not a mark of a text box (b, i, u, s, a, span; a p() or an li() per paragraph)", tag(el.tag))),
};
only(el, &[])?;
let marked = styled(style, mark, Json::Bool(true));
el.children.iter().try_for_each(|x| runs_of(x, &marked, at, out))
}
fn runs(children: &[Child], at: &str) -> Result<Json, String> {
let mut out = Vec::new();
children.iter().try_for_each(|c| runs_of(c, &Vec::new(), at, &mut out))?;
let runs = out.into_iter().map(|(text, style)| {
let mut run = vec![("text".to_string(), Json::from(text))];
run.extend(style);
Json::Obj(run)
});
Ok(Json::obj().with("runs", Json::Arr(runs.collect())))
}
fn paragraph(el: &El, at: &str) -> Result<Json, String> {
if el.tag == "p" {
only(el, &[])?;
return runs(&el.children, at);
}
only(el, &["bullet", "level"])?;
let level = num(el, "level")?.unwrap_or(1.0);
if level.fract() != 0.0 || level < 1.0 {
return Err(format!("{}: level is a whole number from 1", place(el)));
}
let bullet = one_of(el, "bullet", &["disc", "number", "none"])?.unwrap_or_else(|| "disc".to_string());
Ok(runs(&el.children, at)?.with("listLevel", Json::Num(level)).with("bullet", Json::from(bullet)))
}
let paragraphs = if children.iter().any(|c| matches!(c, Child::El(el) if el.tag == "p" || el.tag == "li")) {
children
.iter()
.map(|c| match c {
Child::El(el) if el.tag == "p" || el.tag == "li" => paragraph(el, at),
_ => Err(format!("{at}: a text with paragraphs holds only p()s and li()s")),
})
.collect::<Result<Vec<_>, _>>()?
} else {
vec![runs(children, at)?]
};
Ok(Json::obj().with("paragraphs", Json::Arr(paragraphs)))
}
fn node(id: &str, kind: &str, inputs: Json, el: &El) -> Json {
let mut n = Json::obj().with("id", id).with("type", kind).with("inputs", inputs);
if let Some(m) = meta(el) {
n.set("meta", m);
}
n
}
fn with_channels(mut inputs: Json, set: &str, wires: Vec<Json>) -> Json {
for (k, v) in channels(set, wires) {
inputs.set(&k, v);
}
inputs
}
fn node_with(id: &str, kind: &str, inputs: Json, el: &El, sources: Sources) -> Json {
let mut n = Json::obj().with("id", id).with("type", kind).with("inputs", inputs);
if let Some(mut m) = meta(el) {
if !sources.is_empty() {
m.set("sources", sources.json());
}
n.set("meta", m);
}
n
}
fn text_style_of(el: &El) -> Result<Vec<(&'static str, Option<Json>)>, String> {
Ok(vec![
("fontSizePx", jn(num(el, "fontSize")?)),
("color", js(txt(el, "color")?)),
("bold", jb(flag(el, "bold")?)),
("italic", jb(flag(el, "italic")?)),
("fontFamily", js(txt(el, "fontFamily")?)),
("lineHeight", jn(num(el, "lineHeight")?)),
("align", js(one_of(el, "align", TEXT_ALIGN)?)),
])
}
fn read_element(c: &El, eid: &str, k: usize, at: &str, groups: &[String]) -> Result<Json, String> {
let mut b = Vec::new();
for p in BOX {
b.push((*p, jn(num(c, p)?)));
}
let b = defined(b);
let placeholder = txt(c, "placeholder")?;
let mut common = vec![
("box", (len(&b) > 0).then(|| b.clone())),
("placeholder", js(placeholder.clone())),
("z", jn(num(c, "z")?)),
("visible", jb(flag(c, "visible")?)),
("opacity", jn(num(c, "opacity")?)),
("label", js(txt(c, "label")?)),
("locked", jb(flag(c, "locked")?)),
("groups", (!groups.is_empty()).then(|| Json::Arr(groups.iter().map(|g| Json::from(g.as_str())).collect()))),
];
let kind = match c.tag {
"text" => {
only(c, &[COMMON, &["fontSize", "color", "bold", "italic", "underline", "align", "valign", "fontFamily", "lineHeight", "overflow"], TEXT_FRAME].concat())?;
let columns = num(c, "columns")?;
if columns.is_some_and(|n| n.fract() != 0.0 || n < 1.0) {
return Err(format!("{}: columns is a whole number from 1", place(c)));
}
common.extend([
("text", Some(rich_text(&c.children, &format!("text() of {at}"))?)),
("fontSizePx", jn(num(c, "fontSize")?)),
("color", js(txt(c, "color")?)),
("bold", jb(flag(c, "bold")?)),
("italic", jb(flag(c, "italic")?)),
("underline", jb(flag(c, "underline")?)),
("align", js(one_of(c, "align", TEXT_ALIGN)?)),
("valign", js(one_of(c, "valign", &["top", "middle", "bottom"])?)),
("fontFamily", js(txt(c, "fontFamily")?)),
("lineHeight", jn(num(c, "lineHeight")?)),
("overflow", js(one_of(c, "overflow", &["visible", "clip", "ellipsis"])?)),
("columns", jn(columns)),
("gutter", jn(num(c, "gutter")?)),
("inset", jn(num(c, "inset")?)),
]);
DECK_TEXT
}
"shape" => {
only(c, &[COMMON, &["shape", "fill", "stroke", "strokeWidth", "cornerRadius"]].concat())?;
common.extend([
("shape", Some(one_of(c, "shape", &["rect", "ellipse", "triangle", "line"])?.unwrap_or_else(|| "rect".into()).into())),
("fill", js(txt(c, "fill")?)),
("stroke", js(txt(c, "stroke")?)),
("strokeWidth", jn(num(c, "strokeWidth")?)),
("cornerRadius", jn(num(c, "cornerRadius")?)),
]);
DECK_SHAPE
}
"image" => {
only(c, &[COMMON, &["src", "fit", "alt"]].concat())?;
common.extend([
("src", Some(txt(c, "src")?.unwrap_or_default().into())),
("fit", js(one_of(c, "fit", &["fill", "contain", "cover", "none"])?)),
("alt", js(txt(c, "alt")?)),
]);
DECK_IMAGE
}
_ => return Err(format!("{} is not an element of {at} (text, shape, image, group)", tag(c.tag))),
};
let placed = placeholder.is_some_and(|p| !p.is_empty());
if !placed && ["x", "y", "w", "h"].iter().any(|p| b.get(p).is_none()) {
return Err(format!("the {} {k} of {at} needs x, y, w and h (or a placeholder to take them from)", tag(c.tag)));
}
Ok(node(eid, kind, defined(common), c))
}
fn read_elements<'a>(children: impl Iterator<Item = &'a El>, owner: &str, at: &str, nodes: &mut Vec<(String, Json)>, sources: &mut Sources) -> Result<Vec<Json>, String> {
fn walk<'a>(kids: Vec<&'a El>, groups: &mut Vec<String>, owner: &str, at: &str, names: &mut Vec<String>, nodes: &mut Vec<(String, Json)>, sources: &mut Sources, wires: &mut Vec<Json>) -> Result<(), String> {
for c in kids {
if c.tag == "group" {
only(c, &["name"])?;
let name = txt(c, "name")?.filter(|n| !n.is_empty()).ok_or_else(|| format!("a group() of {at} needs a name"))?;
if names.contains(&name) {
return Err(format!("two groups of {at} are called {name}"));
}
names.push(name.clone());
if c.child_elements().next().is_none() {
return Err(format!("the group \"{name}\" of {at} holds no element"));
}
sources.put(format!("group:{name}"), c);
groups.push(name);
walk(c.child_elements().collect(), groups, owner, at, names, nodes, sources, wires)?;
groups.pop();
continue;
}
let eid = format!("{owner}.{}", wires.len() + 1);
nodes.push((eid.clone(), read_element(c, &eid, wires.len() + 1, at, groups)?));
wires.push(wire(&eid, "out"));
}
Ok(())
}
let mut wires = Vec::new();
walk(children.collect(), &mut Vec::new(), owner, at, &mut Vec::new(), nodes, sources, &mut wires)?;
Ok(wires)
}
fn read_master(el: &El, nodes: &mut Vec<(String, Json)>) -> Result<(), String> {
only(el, &["background"])?;
let mut sources = Sources::new();
let mut styles: Vec<(String, Json)> = Vec::new();
let mut layouts: Vec<String> = Vec::new();
let mut decoration = Vec::new();
for c in el.child_elements() {
match c.tag {
"textStyle" => {
only(c, &[&["role"][..], TEXT_STYLE].concat())?;
let role = one_of(c, "role", ROLES)?.ok_or_else(|| format!("a text_style() needs a role ({})", ROLES.join(", ")))?;
if styles.iter().any(|(r, _)| *r == role) {
return Err(format!("two text styles of the master are for {role}"));
}
sources.put(format!("textStyle:{role}"), c);
styles.push((role, defined(text_style_of(c)?)));
}
"layout" => {
only(c, &["name"])?;
let name = txt(c, "name")?.filter(|n| !n.is_empty()).ok_or("a layout() needs a name")?;
if layouts.contains(&name) {
return Err(format!("two layouts are called {name}"));
}
layouts.push(name.clone());
let id = format!("master.layout-{}", layouts.len());
let mut own = Sources::new();
let mut seen: Vec<String> = Vec::new();
let mut placeholders = Vec::new();
for p in c.child_elements() {
if p.tag != "placeholder" {
return Err(format!("{} is not read in a layout() (it holds placeholder()s)", tag(p.tag)));
}
only(p, &[&["name", "role", "x", "y", "w", "h", "valign", "prompt"][..], TEXT_STYLE].concat())?;
let pname = txt(p, "name")?.filter(|n| !n.is_empty()).ok_or_else(|| format!("a placeholder() of the layout {name} needs a name"))?;
if seen.contains(&pname) {
return Err(format!("two placeholders of the layout {name} are called {pname}"));
}
seen.push(pname.clone());
own.put(format!("placeholder:{pname}"), p);
let bx = defined(vec![("x", jn(num(p, "x")?)), ("y", jn(num(p, "y")?)), ("w", jn(num(p, "w")?)), ("h", jn(num(p, "h")?))]);
let mut fields = vec![("name", Some(Json::from(pname.as_str()))), ("role", js(one_of(p, "role", ROLES)?)), ("box", (len(&bx) > 0).then(|| bx.clone()))];
fields.extend(text_style_of(p)?);
fields.extend([("valign", js(one_of(p, "valign", &["top", "middle", "bottom"])?)), ("prompt", js(txt(p, "prompt")?))]);
placeholders.push(defined(fields));
}
let inputs = Json::obj().with("name", name.as_str()).with("placeholders", Json::Arr(placeholders));
nodes.push((id.clone(), node_with(&id, "deck.layout", inputs, c, own)));
}
_ => decoration.push(c),
}
}
let wires = read_elements(decoration.into_iter(), "master", "the master", nodes, &mut sources)?;
let inputs = defined(vec![("background", js(txt(el, "background")?)), ("textStyles", (!styles.is_empty()).then(|| Json::Obj(styles)))]);
let mut n = Json::obj().with("id", "master").with("type", "deck.master").with("inputs", with_channels(inputs, "elements", wires));
if let Some(mut m) = meta(el) {
m.set("sources", sources.json());
n.set("meta", m);
}
nodes.push(("master".into(), n));
Ok(())
}
fn read_deck(root: &El) -> Result<Json, String> {
only(root, &["name", "width", "height", "dpi", "style"])?;
let mut nodes: Vec<(String, Json)> = Vec::new();
let mut slides = Vec::new();
let mut mastered = false;
for el in root.child_elements() {
if el.tag == "master" {
if mastered {
return Err("a deck() has one master()".into());
}
mastered = true;
read_master(el, &mut nodes)?;
continue;
}
if el.tag != "slide" {
return Err(format!("{} is not read in a deck() (it holds a master() and slide()s)", tag(el.tag)));
}
only(el, &["layout", "name", "notes", "background", "hidden"])?;
let id = format!("slide-{}", slides.len() + 1);
let mut sources = Sources::new();
let elements = read_elements(el.child_elements(), &id, &id, &mut nodes, &mut sources)?;
let inputs = defined(vec![
("layout", Some(txt(el, "layout")?.unwrap_or_else(|| "Title and body".into()).into())),
("name", js(txt(el, "name")?)),
("notes", js(txt(el, "notes")?)),
("background", js(txt(el, "background")?)),
("hidden", jb(flag(el, "hidden")?)),
]);
nodes.push((id.clone(), node_with(&id, DECK_SLIDE, with_channels(inputs, "elements", elements), el, sources)));
slides.push(wire(&id, "out"));
}
let name = txt(root, "name")?.unwrap_or_else(|| "Deck".into());
let inputs = defined(vec![
("name", Some(name.as_str().into())),
("width", Some(num(root, "width")?.unwrap_or(1280.0).into())),
("height", Some(num(root, "height")?.unwrap_or(720.0).into())),
("dpi", jn(num(root, "dpi")?)),
("style", js(one_of(root, "style", DECK_STYLES)?)),
]);
nodes.push(("doc".into(), node("doc", DECK_DOC, with_channels(inputs, "slides", slides), root)));
Ok(Json::obj()
.with("id", format!("deck:{name}"))
.with("nodes", Json::Obj(nodes))
.with("outputs", Json::Arr(vec!["doc".into()]))
.with("meta", Json::obj().with("domain", "deck").with("name", name)))
}