commandagi 0.6.10

The CommandAGI SDK for Rust: the platform client (agent threads, live sessions on a simulated world) and CommandAGI documents (a schematic, a 3D part …) declared as code. No dependencies.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
//! OFFICE DOCUMENTS IN RUST — a workbook (`.sheet.rs`), a page (`.page.rs`) and a deck (`.deck.rs`), declared as the
//! very document the CommandAGI sheets, docs and decks editors open. The same documents, part for part, as the
//! TypeScript SDK's office JSX (`office.ts`) and the Python SDK's `commandagi.design.office`:
//!
//! ```
//! use commandagi::design::office::*;
//!
//! fn document() -> El {
//!     workbook([sheet([
//!         column().at("A").width(160),
//!         cell().at("A1").value("Item").bold(true),
//!         cell().at("B1").value(1200).num_fmt("$#,##0"),
//!         cell().at("B2").formula("=B1*12"),
//!     ])
//!     .name("Q1")])
//!     .title("Budget")
//! }
//! # commandagi::design::declare(document()).unwrap();
//! ```
//!
//! ```
//! use commandagi::design::office::*;
//!
//! fn document() -> El {
//!     page([
//!         h1("Launch notes"),
//!         p(("The first sentence, with ", b("bold"), " and a ", a("link").href("https://commandagi.com"), ".")),
//!         bullet("a list item"),
//!     ])
//!     .title("Notes")
//! }
//! # commandagi::design::declare(document()).unwrap();
//! ```
//!
//! The elements (attributes are snake case of the TypeScript names: `.frozen_rows(1)`, `.num_fmt(…)`, `.font_size(…)`):
//!
//! ```text
//! workbook([sheets]).title(…)                                           the workbook
//! sheet([cells]).name .rows .cols .frozen_rows .frozen_cols .color     a grid sheet (200 rows, 26 columns unless it says)
//! sheet([]).name .source .query .format                                a data sheet: what it reads and the SQL over it
//!                                                                      (source: a file beside the workbook, an http(s)
//!                                                                      URL or "surface:<id>"; format "parquet", "sqlite" …)
//! cell().at("B4").value(…) | .formula("=…") .num_fmt .bold .italic .align .bg .color .wrap
//! column().at("A").width(…)   row().at(3).height(…)                    a column's width or a row's height, in pixels
//! page([blocks]).title .paper .font                                    the page; paper "letter" or "a4"; font "sans", "serif", "mono"
//! h1 h2 h3 p quote (text).align(…)                                     a text block: its text and marks; align "left", "center" …
//! bullet numbered (text)   todo(text).checked(true)                    a list item, a checklist item
//! pre("code").lang(…)   divider()   image().src(…).alt(…)              a code block, a rule, a picture
//! b i u s code (text)   a(text).href(…)   br()                          marks inside a text
//! span(text).color .size .font                                         a run's own colour, em size and family, in a text box
//! p(text)   li(text).bullet .level                                     one paragraph of a text box; li is a list item:
//!                                                                       bullet "disc", "number" or "none" (disc unless it says)
//! deck([slides]).name .width .height .dpi .style                        the deck (1280 × 720 slide units unless it says);
//!                                                                       style "plain", "ink", "editorial" or "signal"
//! slide([elements]).layout .name .notes .background .hidden
//! text(text).placeholder .x .y .w .h .rotation .font_size .color .bold .italic .underline .align .valign …
//! shape().shape .x .y .w .h .fill .stroke .stroke_width .corner_radius   image().src .x .y .w .h .fit .alt
//! every element also takes .opacity .label .locked; a text also takes .columns .gutter .inset
//! group([elements]).name                                               elements that select and move as one; nests
//! master([parts]).background                                           how the master differs from the stock one:
//! text_style().role .font_size .color .bold .italic .font_family .line_height .align   a role's text style
//! layout([placeholders]).name   placeholder().name .role .x .y .w .h .valign .prompt .font_size .color …
//!                                                                       its own elements, text styles and layouts
//! ```
//!
//! THE TEXT OF A BLOCK IS ITS TEXT PARAMETER, never an attribute: a string, or a tuple of texts and marks
//! (`p(("One ", b("two"), "."))`); a deck's text box takes a `p` per paragraph (`text([p("One"), p("Two")])`).
//!
//! A workbook and a page are documents of their own, with where each part was written in `sources` (`workbook`,
//! `sheet:<id>`, `cell:<id>!A1`, `column:<id>!B`, `row:<id>!3`, `page`, `block:<id>`). A deck is the deck's own op
//! graph (`deck.doc`, `deck.slide`, `deck.text` …), each node with `meta.source`. Anything else is refused by name.

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! {
    /// The workbook: its sheets.
    workbook: children;
    /// A grid sheet: its cells, columns and rows.
    sheet: children;
    /// One cell: `cell().at("B2").value(1800)` or `.formula("=B1*12")`.
    cell: leaf;
    /// A column's width in pixels: `column().at("A").width(160)`.
    column: leaf;
    /// A row's height in pixels: `row().at(3).height(40)`.
    row: leaf;
    /// A chart of a range of its sheet: `chart().name("Sales").range("A1:C5").kind("bar").category("Region").series(["Q1", "Q2"])`.
    chart: leaf;
    /// A pivot table of a range: `pivot().name("By region").range("A1:C9").rows("Region").value("Amount").aggregate("sum")`.
    pivot: leaf;
    /// The sheet's filter: `filter([criterion().column("B").test("greater").value(100)]).range("A1:C20")`.
    filter: children;
    /// One column's test in a filter.
    criterion: leaf;
    /// The page: its blocks.
    page: children;
    /// A heading.
    h1: text;
    /// A heading.
    h2: text;
    /// A heading.
    h3: text;
    /// A paragraph; in a deck's text box, one paragraph of it.
    p: text;
    /// A list item; in a deck's text box, one list paragraph of it: `li("First").bullet("number").level(2)`.
    li: text;
    /// A list item.
    bullet: text;
    /// A numbered list item.
    numbered: text;
    /// A checklist item: `todo("Write the report.").checked(true)`.
    todo: text;
    /// A quote.
    quote: text;
    /// A code block: its text as one string.
    pre: text;
    /// A rule.
    divider: leaf;
    /// A picture: a page's block, or a deck's element.
    image: leaf;
    /// Bold.
    b: text;
    /// Italic.
    i: text;
    /// Underline.
    u: text;
    /// Strike through.
    s: text;
    /// Code.
    code: text;
    /// A link: `a("link").href("https://commandagi.com")`.
    a: text;
    /// A run's own styling in a text box: `span("accent").color("#b91c1c").size(20).font("Georgia")`.
    span: text;
    /// A line break.
    br: leaf;
    /// The deck: its slides.
    deck: children;
    /// A slide on a layout, named by the layout's name: its elements.
    slide: children;
    /// A text box: its text, or a `p` per paragraph.
    text: text;
    /// A shape: `shape().shape("ellipse").x(…).y(…).w(…).h(…)`.
    shape: leaf;
    /// Elements (and groups) of a slide that select and move as one: `group([…]).name("Group 1")`.
    group: children;
    /// How the deck's master differs from the stock one: its own elements, its text styles and its layouts.
    master: children;
    /// The master's text style of a role: `text_style().role("title").color("#1d4ed8")`.
    text_style = "textStyle": leaf;
    /// A layout of the master, by its name: its placeholders.
    layout: children;
    /// A placeholder of a layout, by its name: what differs from the stock one.
    placeholder: leaf;
}

attributes! {
    /// The office documents' attributes, chained on their elements.
    pub trait OfficeAttrs {
        /// A workbook's or a page's title.
        title;
        /// A sheet's, a slide's or a deck's name.
        name;
        /// A sheet's rows.
        rows;
        /// A sheet's columns.
        cols;
        /// A sheet's frozen rows.
        frozen_rows;
        /// A sheet's frozen columns.
        frozen_cols;
        /// A data sheet's source: a file beside the workbook, an http(s) URL or `surface:<id>`.
        source;
        /// A data sheet's format: "parquet", "sqlite" …
        format;
        /// A data sheet's SQL over its source.
        query;
        /// A colour: a sheet's tab, a cell's text, a text box's text.
        color;
        /// Where a cell is ("B4"), a column's letters ("B"), a row's number (3).
        at;
        /// A cell's value: text, a number or true/false.
        value;
        /// The cells a chart, a pivot table or a filter reads: an A1 range ("A1:C20").
        range;
        /// A chart's kind: "bar", "line", "area", "scatter", "pie".
        kind;
        /// The field whose values label a chart's points.
        category;
        /// The fields a chart draws, one series each.
        series;
        /// The column a filter's criterion tests, by its letters ("B").
        column;
        /// A criterion's test: "equals", "notEquals", "contains", "greater", "less", "blank", "notBlank".
        test;
        /// How a pivot table's values become one number: "sum", "count", "avg", "min", "max", "first".
        aggregate;
        /// A cell's formula: it starts with "=".
        formula;
        /// A cell's number format: `"$#,##0"`.
        num_fmt;
        /// Bold.
        bold;
        /// Italic.
        italic;
        /// Underline.
        underline;
        /// A cell's or a text box's alignment.
        align;
        /// A cell's background.
        bg;
        /// A cell's text wraps.
        wrap;
        /// A column's width in pixels; a deck's width in slide units.
        width;
        /// A row's height in pixels; a deck's height in slide units.
        height;
        /// A todo is done.
        checked;
        /// A code block's language.
        lang;
        /// A picture's file, by its path relative to this file.
        src;
        /// A picture's alternative text.
        alt;
        /// A link's address.
        href;
        /// A deck's dots per inch.
        dpi;
        /// A slide's layout, by its name: "Title", "Title and body", "Section header", "Blank".
        layout;
        /// A slide's speaker notes.
        notes;
        /// A slide's background.
        background;
        /// A slide is hidden.
        hidden;
        /// The layout placeholder an element takes its box from: "title", "subtitle", "body".
        placeholder;
        /// Across, in slide units.
        x;
        /// Down, in slide units.
        y;
        /// Wide, in slide units.
        w;
        /// High, in slide units.
        h;
        /// Rotation, in degrees.
        rotation;
        /// Stacking order.
        z;
        /// Shown.
        visible;
        /// Opacity, 0 to 1.
        opacity;
        /// An element's label.
        label;
        /// A text box's font size, in slide units.
        font_size;
        /// A text box's vertical alignment: "top", "middle", "bottom".
        valign;
        /// A text box's font family.
        font_family;
        /// A text box's line height.
        line_height;
        /// What a text box does with text that does not fit: "visible", "clip", "ellipsis".
        overflow;
        /// A shape's shape: "rect", "ellipse", "triangle", "line".
        shape;
        /// A shape's fill.
        fill;
        /// A shape's stroke.
        stroke;
        /// A shape's stroke width.
        stroke_width;
        /// A shape's corner radius.
        corner_radius;
        /// How a deck's picture fits its box: "fill", "contain", "cover", "none".
        fit;
        /// A page's paper: "letter" or "a4".
        paper;
        /// A page's typeface: "sans", "serif" or "mono"; a run's family in a text box.
        font;
        /// A run's em size in a text box, in slide units.
        size;
        /// A list paragraph's bullet: "disc", "number" or "none".
        bullet;
        /// A list paragraph's indent depth, from 1.
        level;
        /// A deck's style: "plain", "ink", "editorial" or "signal".
        style;
        /// An element the editor does not move.
        locked;
        /// The role a placeholder plays, or a text style is for: "title", "subtitle", "body" …
        role;
        /// A placeholder's prompt ("Click to add a title"), shown only in the editor.
        prompt;
        /// A text box's columns.
        columns;
        /// The space between a text box's columns, in slide units.
        gutter;
        /// The space between a text box's edges and its text, in slide units.
        inset;
    }
}

pub(crate) const FAMILY: Family = Family { module: "office", roots: &["workbook", "page", "deck"], declare };

/// The deck's node types (the decks editor's own).
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)?)),
    }
}

/// How a message names an office element: its call, with its name or where it is.
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)
}

// ── Workbook ───────────────────────────────────────────────────────────────────────────────────────────────────

const ALIGN: &[&str] = &["left", "center", "right"];

/// An A1 reference's column letters and row number: `^([A-Z]{1,3})([1-9]\d{0,6})$`.
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()))
}

/// The schema of a workbook's elements besides its cells (`roots`: tag → definition, `$defs`), generated from the
/// sheets editor's types.
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"))
}

/// An A1 range: one reference, or two with a colon between (`A1:C20`), in either case.
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"];

/// A data sheet's source as its `source` text names it: a file beside the workbook, an http(s) URL, or `surface:<id>`.
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));
    }
    // The workbook's own file is its code, so a data sheet names another file.
    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()
}

/// The attributes of a chart, a pivot, a filter or a criterion, checked against the element's schema with the
/// sentences an op panel shows; a required attribute left out is at its declared default ([`with_defaults`]).
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)
}

/// A `workbook(…)` as the workbook JSON the sheets editor opens, with where each part was written.
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() })
}

// ── Page ───────────────────────────────────────────────────────────────────────────────────────────────────────

/// A text block's tag → its block type.
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('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
}

/// A text block's children as the block's inline HTML (the docs editor's subset: b, i, u, s, code, a, br).
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('&', "&amp;").replace('"', "&quot;")));
                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)
}

/// The plain text of a `pre`'s children.
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)
}

/// A `page(…)` as the page the docs editor opens, with where each block was written.
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() })
}

// ── Deck ───────────────────────────────────────────────────────────────────────────────────────────────────────

const BOX: &[&str] = &["x", "y", "w", "h", "rotation"];
const COMMON: &[&str] = &["x", "y", "w", "h", "rotation", "placeholder", "z", "visible", "opacity", "label", "locked"];
/// A text frame's columns, the gutter between them and the inset from its edges, in slide units.
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"];
/// The deck's styles: a few curated looks (the decks editor's own themes), not a theme editor.
pub const DECK_STYLES: &[&str] = &["plain", "ink", "editorial", "signal"];
/// The blocks that take an alignment, and the page's paper and typefaces (a few, not a font menu).
const ALIGNED: &[&str] = &["h1", "h2", "h3", "p", "quote"];
pub const PAPERS: &[&str] = &["letter", "a4"];
pub const PAGE_FONTS: &[&str] = &["sans", "serif", "mono"];

/// A run's style: its marks in the order they were written (`bold`, `link` …).
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
}

/// A text box's children as the deck's rich text: a `p` per paragraph, or text and marks for one paragraph.
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) => {
                // A run of the same style as the one before it is the same run.
                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
}

/// A text style's attributes as the deck's params (`fontSize` is `fontSizePx`).
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)?)),
    ])
}

/// One element of a slide or a master (a text, a shape, an image) as the node it declares.
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))
}

/// The elements of a slide or a master in paint order, each naming the groups around it (outermost first); where
/// each group was written goes in `sources` (`group:<name>`).
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)
}

/// A `master(…)`: its background, its text styles by role, its layouts' placeholders and its own elements.
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(())
}

/// A `deck(…)` as the deck's op graph: `doc`, then `slide-N`, then `slide-N.M` for its elements. A slide names its
/// layout by name (`layout`); the editor binds that name to its layouts. A `master(…)` says how the deck's master and
/// layouts differ from the stock ones.
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)))
}