excelerate 0.16.0

Read, write and recalculate spreadsheets: xlsx, xls, ods, csv, html, and a 518-function formula engine
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
//! Writing 2016 charts: an untouched one as the bytes it came in, a changed
//! one edited inside its part, a new one rendered with Excel's defaults.
//!
//! Runs after [`super::chart`], over the drawings it left. A `chartEx` part is
//! mostly formatting the model does not name - a colour per data point, label
//! styles, axis text - so a changed chart is not rendered but spliced: the
//! title's text, each series' layout, name, visibility and data, and nothing
//! else. See [`crate::model::chart::ChartEx`].

use super::chart::{
    DRAWING_NS, DRAWING_TYPE, MAIN_NS, REL_NS, XML_DECL, drawings, edit_relationships,
    max_object_id, part_text, relationships, render_anchor, set_part,
};
use super::image::{free_path, reanchor, set_attribute, splice};
use super::xmlesc::escape;
use crate::error::{Error, Result};
use crate::model::chart::{
    BinEdge, Binning, Bins, ChartEx, ChartText, Dimension, ExLabels, ExLegend, ExPoint, ExSeries,
    LegendPosition, SeriesLayout,
};
use crate::model::{Attachment, Spreadsheet, Worksheet};
use crate::reader::chart::{Node, children, read_chart_ex, rich_text, scan_drawing};
use core::ops::Range;
use std::borrow::Cow;
use std::fmt::Write as _;

const CHART_EX_NS: &str = "http://schemas.microsoft.com/office/drawing/2014/chartex";
const CHART_EX_TYPE: &str = "application/vnd.ms-office.chartex+xml";
const CHART_EX_REL: &str = "http://schemas.microsoft.com/office/2014/relationships/chartEx";

/// The workbook as the writer should see it, 2016 charts applied.
///
/// # Errors
/// [`Error::Xlsx`] for a series whose layout this crate cannot name.
pub(super) fn prepare(book: Cow<'_, Spreadsheet>) -> Result<Cow<'_, Spreadsheet>> {
    let dirty: Vec<usize> = book
        .sheets()
        .iter()
        .enumerate()
        .filter(|(_, sheet)| {
            sheet.extended_charts.iter().any(|c| !c.is_unchanged())
                || drawings(sheet).any(|d| lost_frames(&book, sheet, d))
        })
        .map(|(i, _)| i)
        .collect();
    if dirty.is_empty() {
        return Ok(book);
    }
    for sheet in dirty.iter().filter_map(|&i| book.sheet(i)) {
        for chart in &sheet.extended_charts {
            let changed = chart
                .origin
                .as_ref()
                .is_none_or(|o| o.read.series != chart.series);
            if let Some(series) = chart.series.iter().find(|s| s.layout.as_str().is_none())
                && changed
            {
                return Err(Error::Xlsx(format!(
                    "chart {:?}: a series layout of {:?} cannot be written",
                    chart.name, series.layout
                )));
            }
        }
    }
    let mut book = book.into_owned();
    for index in dirty {
        apply_sheet(&mut book, index);
    }
    Ok(Cow::Owned(book))
}

/// Whether a drawing shows a 2016 chart the sheet no longer has.
fn lost_frames(book: &Spreadsheet, sheet: &Worksheet, drawing: &str) -> bool {
    relationships(book, drawing)
        .iter()
        .filter(|r| r.kind == CHART_EX_REL)
        .any(|r| {
            claimant(&sheet.extended_charts, drawing, &r.target).is_none()
                && is_modelled(book, &r.target)
        })
}

fn claimant(charts: &[ChartEx], drawing: &str, part: &str) -> Option<usize> {
    charts
        .iter()
        .position(|c| c.part == part && c.origin.as_ref().is_some_and(|o| o.drawing == drawing))
}

/// Whether the reader turned the part into the model; one it could not read
/// never reached the sheet, so its absence there is no removal.
fn is_modelled(book: &Spreadsheet, part: &str) -> bool {
    part_text(book, part).is_some_and(|xml| read_chart_ex(xml).is_some())
}

fn apply_sheet(book: &mut Spreadsheet, index: usize) {
    let Some(sheet) = book.sheet(index) else {
        return;
    };
    let charts = sheet.extended_charts.clone();
    let mut paths: Vec<String> = drawings(sheet).map(str::to_owned).collect();
    if paths.is_empty() {
        if charts.iter().all(|c| c.origin.is_some()) {
            return;
        }
        let path = free_path(book, "xl/drawings/drawing", "xml");
        let empty = format!(
            r#"{XML_DECL}<xdr:wsDr xmlns:xdr="{DRAWING_NS}" xmlns:a="{MAIN_NS}"></xdr:wsDr>"#
        );
        set_part(book, &path, Some(DRAWING_TYPE), empty);
        if let Some(sheet) = book.sheet_mut(index) {
            sheet.attachments.push(Attachment {
                kind: format!("{REL_NS}/drawing"),
                target: path.clone(),
            });
        }
        paths.push(path);
    }
    // The first drawing takes the new charts.
    for (i, path) in paths.iter().enumerate() {
        rewrite_drawing(book, path, &charts, i == 0);
    }
}

fn rewrite_drawing(book: &mut Spreadsheet, path: &str, charts: &[ChartEx], takes_new: bool) {
    let Some(xml) = part_text(book, path).map(str::to_owned) else {
        return;
    };
    let rels = relationships(book, path);
    let mut splices: Vec<(Range<usize>, String)> = Vec::new();
    let mut removed: Vec<String> = Vec::new();

    for object in scan_drawing(&xml) {
        let alone = matches!(object.frames.as_slice(), [f] if !f.grouped);
        let original = &xml[object.span.clone()];
        let mut local: Vec<(Range<usize>, String)> = Vec::new();
        let mut moved_to = None;
        for frame in object.frames.iter().filter(|f| f.extended) {
            let Some(target) = rels
                .iter()
                .find(|r| r.id == frame.rel)
                .map(|r| r.target.clone())
            else {
                continue;
            };
            let Some(i) = claimant(charts, path, &target) else {
                // ponytail: a removed chart inside a group keeps its frame;
                // cutting it means finding the `mc:AlternateContent` around it.
                if alone && is_modelled(book, &target) {
                    splices.push((object.span.clone(), String::new()));
                    removed.push(frame.rel.clone());
                }
                continue;
            };
            let chart = &charts[i];
            let Some(origin) = &chart.origin else {
                continue;
            };
            if !chart.same_content(&origin.read)
                && let Some(part) = part_text(book, &target)
            {
                let text = rewrite_part(part, chart, &origin.read);
                set_part(book, &target, Some(CHART_EX_TYPE), text);
            }
            if chart.name != origin.read.name {
                let span = frame.span.start - object.span.start..frame.span.end - object.span.start;
                local.push((span.clone(), rename_frame(&original[span], &chart.name)));
            }
            // A frame inside a group is placed by the group.
            if alone && chart.anchor != origin.read.anchor {
                moved_to = Some(chart.anchor);
            }
        }
        if local.is_empty() && moved_to.is_none() {
            continue;
        }
        let text = splice(original, local);
        let text = match moved_to {
            Some(anchor) => reanchor(&text, anchor),
            None => text,
        };
        splices.push((object.span.clone(), text));
    }

    let mut added: Vec<(String, String)> = Vec::new();
    if takes_new {
        let mut next_id = max_object_id(&xml);
        let mut objects = String::new();
        for chart in charts.iter().filter(|c| c.origin.is_none()) {
            next_id = next_id.saturating_add(1);
            let part = free_path(book, "xl/charts/chartEx", "xml");
            set_part(book, &part, Some(CHART_EX_TYPE), render_part(chart));
            let rel = (1..=u32::MAX)
                .map(|n| format!("rId{n}"))
                .find(|id| !rels.iter().any(|r| r.id == *id) && !added.iter().any(|a| a.0 == *id))
                .unwrap_or_default();
            objects.push_str(&render_anchor(
                chart.anchor,
                &render_frame(chart, next_id, &rel),
            ));
            added.push((rel, part));
        }
        if !objects.is_empty() {
            let close = xml.rfind("</").unwrap_or(xml.len());
            splices.push((close..close, objects));
        }
    }
    if splices.is_empty() {
        return;
    }
    set_part(book, path, Some(DRAWING_TYPE), splice(&xml, splices));
    edit_relationships(book, path, &removed, &added, CHART_EX_REL);
}

/// A frame element with its `cNvPr` name replaced.
fn rename_frame(frame: &str, name: &str) -> String {
    let Some(start) = frame.find("cNvPr ") else {
        return frame.to_owned();
    };
    let Some(end) = frame[start..].find('>').map(|e| start + e) else {
        return frame.to_owned();
    };
    let tag = set_attribute(&frame[start..end], "name", name);
    format!("{}{tag}{}", &frame[..start], &frame[end..])
}

/// The frame of a new chart, behind the `mc:AlternateContent` switch a 2016
/// chart needs so older readers skip it.
fn render_frame(chart: &ChartEx, id: u32, rel: &str) -> String {
    let layout = chart.series.first().map(|s| s.layout);
    // Funnels and maps came after the first 2016 charts, and Excel asks for
    // the namespace that introduced them.
    let (prefix, requires) = match layout {
        Some(SeriesLayout::Funnel) => (
            "cx2",
            "http://schemas.microsoft.com/office/drawing/2015/10/21/chartex",
        ),
        Some(SeriesLayout::RegionMap) => (
            "cx4",
            "http://schemas.microsoft.com/office/drawing/2016/5/10/chartex",
        ),
        _ => (
            "cx1",
            "http://schemas.microsoft.com/office/drawing/2015/9/8/chartex",
        ),
    };
    let name = if chart.name.is_empty() {
        format!("Chart {id}")
    } else {
        chart.name.clone()
    };
    format!(
        concat!(
            r#"<mc:AlternateContent xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">"#,
            r#"<mc:Choice xmlns:{prefix}="{requires}" Requires="{prefix}">"#,
            r#"<xdr:graphicFrame macro=""><xdr:nvGraphicFramePr><xdr:cNvPr id="{id}" name="{name}"/>"#,
            r#"<xdr:cNvGraphicFramePr/></xdr:nvGraphicFramePr>"#,
            r#"<xdr:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/></xdr:xfrm>"#,
            r#"<a:graphic><a:graphicData uri="{ns}">"#,
            // Every namespace the element uses is declared on the element
            // itself, as Excel writes it: a reader that lifts the chosen
            // branch out of the switch has nothing to look up in.
            r#"<cx:chart xmlns:cx="{ns}" xmlns:r="{rel_ns}" r:id="{rel}"/>"#,
            r#"</a:graphicData></a:graphic></xdr:graphicFrame></mc:Choice>"#,
            // What a reader that does not know 2016 charts shows instead.
            r#"<mc:Fallback><xdr:sp macro="" textlink=""><xdr:nvSpPr>"#,
            r#"<xdr:cNvPr id="{id}" name="{name}"/><xdr:cNvSpPr><a:spLocks noTextEdit="1"/>"#,
            r#"</xdr:cNvSpPr></xdr:nvSpPr><xdr:spPr><a:xfrm><a:off x="0" y="0"/>"#,
            r#"<a:ext cx="0" cy="0"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom>"#,
            r#"<a:solidFill><a:prstClr val="white"/></a:solidFill></xdr:spPr><xdr:txBody>"#,
            r#"<a:bodyPr vertOverflow="clip" horzOverflow="clip"/><a:lstStyle/><a:p><a:r>"#,
            r#"<a:rPr lang="en-US"/><a:t>{name}</a:t></a:r></a:p></xdr:txBody></xdr:sp>"#,
            r#"</mc:Fallback></mc:AlternateContent><xdr:clientData/>"#
        ),
        prefix = prefix,
        requires = requires,
        id = id,
        name = escape(&name),
        ns = CHART_EX_NS,
        rel_ns = REL_NS,
        rel = escape(rel),
    )
}

/// A chart part for a chart made in code.
fn render_part(chart: &ChartEx) -> String {
    let p = "cx:";
    let mut s = format!(
        r#"{XML_DECL}<cx:chartSpace xmlns:a="{MAIN_NS}" xmlns:r="{REL_NS}" xmlns:cx="{CHART_EX_NS}"><cx:chartData>"#
    );
    for (i, series) in chart.series.iter().enumerate() {
        s.push_str(&render_data(i, &series.dimensions, p));
    }
    s.push_str("</cx:chartData><cx:chart>");
    if let Some(title) = &chart.title {
        s.push_str(&render_title(title, p));
    }
    s.push_str("<cx:plotArea><cx:plotAreaRegion>");
    for (i, series) in chart.series.iter().enumerate() {
        s.push_str(&render_series(i, series, p));
    }
    s.push_str("</cx:plotAreaRegion>");
    match chart.series.first().map(|s| s.layout) {
        Some(
            layout @ (SeriesLayout::Waterfall
            | SeriesLayout::ClusteredColumn
            | SeriesLayout::BoxWhisker
            | SeriesLayout::ParetoLine),
        ) => {
            let gap = if layout == SeriesLayout::ClusteredColumn {
                "0"
            } else {
                "0.5"
            };
            let _ = write!(
                s,
                concat!(
                    r#"<cx:axis id="0"><cx:catScaling gapWidth="{gap}"/><cx:tickLabels/></cx:axis>"#,
                    r#"<cx:axis id="1"><cx:valScaling/><cx:majorGridlines/><cx:tickLabels/></cx:axis>"#
                ),
                gap = gap
            );
        }
        Some(SeriesLayout::Funnel) => {
            s.push_str(
                r#"<cx:axis id="0"><cx:catScaling gapWidth="0.06"/><cx:tickLabels/></cx:axis>"#,
            );
        }
        _ => {}
    }
    s.push_str("</cx:plotArea>");
    if let Some(legend) = &chart.legend {
        s.push_str(&render_legend(*legend, p));
    }
    s.push_str("</cx:chart></cx:chartSpace>");
    s
}

/// The chart part with what the model changed spliced in.
fn rewrite_part(xml: &str, chart: &ChartEx, read: &ChartEx) -> String {
    let Some(root) = children(xml).into_iter().find(|n| n.name == "chartSpace") else {
        return xml.to_owned();
    };
    let p = prefix_of(&root);
    let mut edits: Vec<(Range<usize>, String)> = Vec::new();
    let base = root.inner_start;
    let kids = root.children();

    // The data sets are rewritten only when some series reads other data; the
    // series then point at them by position.
    let same_data = chart.series.len() == read.series.len()
        && chart
            .series
            .iter()
            .zip(&read.series)
            .all(|(a, b)| a.dimensions == b.dimensions);
    if !same_data && let Some(data) = kids.iter().find(|n| n.name == "chartData") {
        let inner = base + data.inner_start;
        let sets: Vec<Node<'_>> = data
            .children()
            .into_iter()
            .filter(|n| n.name == "data")
            .collect();
        let at = sets
            .first()
            .map_or(inner + data.inner.len(), |n| inner + n.span.start);
        let text: String = chart
            .series
            .iter()
            .enumerate()
            .map(|(i, s)| render_data(i, &s.dimensions, &p))
            .collect();
        // Before the cuts: a splice at the start of a cut stretch goes first.
        edits.push((at..at, text));
        for set in &sets {
            edits.push((inner + set.span.start..inner + set.span.end, String::new()));
        }
    }

    if let Some(body) = kids.iter().find(|n| n.name == "chart") {
        let inner = base + body.inner_start;
        let parts = body.children();
        if chart.title != read.title {
            let title = parts.iter().find(|n| n.name == "title");
            match (&chart.title, title) {
                (None, Some(node)) => edits.push((
                    inner + node.span.start..inner + node.span.end,
                    String::new(),
                )),
                (Some(text), Some(node)) => {
                    let at = inner + node.inner_start;
                    edits.extend(replace_tx(node, at, text, &p));
                }
                (Some(text), None) => edits.push((inner..inner, render_title(text, &p))),
                (None, None) => {}
            }
        }
        let (end, legend) = (inner + body.inner.len(), chart.legend);
        if legend != read.legend {
            edits.push(edit_legend(&parts, inner, end, legend, &p));
        }
        if let Some(area) = parts.iter().find(|n| n.name == "plotArea") {
            let area_inner = inner + area.inner_start;
            if let Some(region) = area
                .children()
                .into_iter()
                .find(|n| n.name == "plotAreaRegion")
            {
                let region_inner = area_inner + region.inner_start;
                let series: Vec<Node<'_>> = region
                    .children()
                    .into_iter()
                    .filter(|n| n.name == "series")
                    .collect();
                for (i, node) in series.iter().enumerate() {
                    let span = region_inner + node.span.start..region_inner + node.span.end;
                    match (chart.series.get(i), read.series.get(i)) {
                        (Some(now), Some(was)) if now != was || !same_data => {
                            edits.push((span, edit_series(node, i, now, was, !same_data, &p)));
                        }
                        (None, _) => edits.push((span, String::new())),
                        _ => {}
                    }
                }
                let at = series
                    .last()
                    .map_or(region_inner, |n| region_inner + n.span.end);
                let extra: String = chart
                    .series
                    .iter()
                    .enumerate()
                    .skip(series.len())
                    .map(|(i, s)| render_series(i, s, &p))
                    .collect();
                if !extra.is_empty() {
                    edits.push((at..at, extra));
                }
            }
        }
    }
    splice(xml, edits)
}

/// The prefix elements take in a part, `cx:` or empty.
fn prefix_of(node: &Node<'_>) -> String {
    if node.prefix.is_empty() {
        String::new()
    } else {
        format!("{}:", node.prefix)
    }
}

/// One series element with what the model changed in it.
fn edit_series(
    node: &Node<'_>,
    index: usize,
    now: &ExSeries,
    was: &ExSeries,
    repoint: bool,
    p: &str,
) -> String {
    let outer = node.outer;
    let head_len = node.tag.len();
    let mut tag = node.tag.trim_end_matches('>').to_owned();
    let empty = tag.ends_with('/');
    if empty {
        tag.pop();
    }
    if now.layout != was.layout
        && let Some(layout) = now.layout.as_str()
    {
        tag = set_attribute(&tag, "layoutId", layout);
    }
    if now.hidden != was.hidden {
        tag = set_attribute(&tag, "hidden", if now.hidden { "1" } else { "0" });
    }
    if empty {
        // A series with nothing in it: rendered whole.
        return render_series(index, now, p);
    }
    let mut edits: Vec<(Range<usize>, String)> = Vec::new();
    // Spans below are within `outer`.
    let inner = node.inner_start - node.span.start;
    let kids = node.children();
    if now.name != was.name {
        let tx = kids.iter().find(|n| n.name == "tx");
        let span = tx.map_or(inner..inner, |tx| {
            inner + tx.span.start..inner + tx.span.end
        });
        let text = now.name.as_ref().map_or(String::new(), |t| render_tx(t, p));
        edits.push((span, text));
    }
    // Before `dataId`: an insertion there goes ahead of its replacement.
    edits.extend(edit_drawn(node, &kids, inner, now, was, p));
    if repoint {
        let id = format!(r#"<{p}dataId val="{index}"/>"#);
        // `dataId` comes before the layout properties and the axis ids.
        let span = kids.iter().find(|n| n.name == "dataId").map_or_else(
            || {
                let at = kids
                    .iter()
                    .find(|n| matches!(n.name, "layoutPr" | "axisId" | "extLst"))
                    .map_or(inner + node.inner.len(), |n| inner + n.span.start);
                at..at
            },
            |d| inner + d.span.start..inner + d.span.end,
        );
        edits.push((span, id));
    }
    let body = splice(outer, edits);
    format!("{tag}>{}", &body[head_len..])
}

/// Edits replacing the `tx` child of a title, or adding one first.
fn replace_tx(
    node: &Node<'_>,
    inner: usize,
    text: &ChartText,
    p: &str,
) -> Vec<(Range<usize>, String)> {
    match node.children().into_iter().find(|n| n.name == "tx") {
        Some(tx) => vec![(
            inner + tx.span.start..inner + tx.span.end,
            render_tx(text, p),
        )],
        None => vec![(inner..inner, render_tx(text, p))],
    }
}

fn render_title(text: &ChartText, p: &str) -> String {
    format!(
        r#"<{p}title pos="t" align="ctr" overlay="0">{}</{p}title>"#,
        render_tx(text, p)
    )
}

/// `<cx:tx>`: a cell reference with its cached value, formatted text that
/// still says the same words, or plain text.
fn render_tx(text: &ChartText, p: &str) -> String {
    let body = match text {
        // `txData` is the form for text a cell holds: the formula, and what it
        // said. Typed text goes as `rich`, the way it does in a classic chart.
        ChartText::Reference { formula, cache } => {
            let value = cache
                .as_ref()
                .map_or(String::new(), |v| format!("<{p}v>{}</{p}v>", escape(v)));
            format!(
                "<{p}txData><{p}f>{}</{p}f>{value}</{p}txData>",
                escape(formula)
            )
        }
        ChartText::Text {
            text,
            rich: Some(rich),
        } if rich_text(rich) == *text => rich.clone(),
        ChartText::Text { text, .. } => render_rich(text, p),
    };
    format!("<{p}tx>{body}</{p}tx>")
}

/// Typed text as `DrawingML`, a paragraph per line.
fn render_rich(text: &str, p: &str) -> String {
    let mut s = format!("<{p}rich><a:bodyPr/><a:lstStyle/>");
    for line in text.split('\n') {
        let _ = write!(s, "<a:p><a:r><a:t>{}</a:t></a:r></a:p>", escape(line));
    }
    let _ = write!(s, "</{p}rich>");
    s
}

fn render_series(index: usize, series: &ExSeries, p: &str) -> String {
    let mut s = format!(
        r#"<{p}series layoutId="{}""#,
        series.layout.as_str().unwrap_or("clusteredColumn")
    );
    if series.hidden {
        s.push_str(r#" hidden="1""#);
    }
    s.push('>');
    if let Some(name) = &series.name {
        s.push_str(&render_tx(name, p));
    }
    s.push_str(&render_points(&series.points, p));
    if let Some(labels) = series.labels {
        s.push_str(&render_labels(labels, p));
    }
    let _ = write!(s, r#"<{p}dataId val="{index}"/>"#);
    let subtotals = render_subtotals(&series.subtotals, p);
    // What Excel writes for a new chart of each kind; the rest need nothing.
    match series.layout {
        // A histogram always has bins; Excel's are automatic.
        SeriesLayout::ClusteredColumn => {
            let binning = render_binning(series.binning.unwrap_or_default(), p);
            let _ = write!(s, "<{p}layoutPr>{binning}{subtotals}</{p}layoutPr>");
        }
        SeriesLayout::BoxWhisker => {
            let _ = write!(
                s,
                r#"<{p}layoutPr><{p}visibility meanLine="0" meanMarker="1" nonoutliers="0" outliers="1"/><{p}statistics quartileMethod="exclusive"/></{p}layoutPr>"#
            );
        }
        SeriesLayout::Treemap => {
            let _ = write!(
                s,
                r#"<{p}layoutPr><{p}parentLabelLayout val="overlapping"/></{p}layoutPr>"#
            );
        }
        _ if series.binning.is_some() || !subtotals.is_empty() => {
            let binning = series
                .binning
                .map_or(String::new(), |b| render_binning(b, p));
            let _ = write!(s, "<{p}layoutPr>{binning}{subtotals}</{p}layoutPr>");
        }
        _ => {}
    }
    let _ = write!(s, "</{p}series>");
    s
}

fn render_data(id: usize, dimensions: &[Dimension], p: &str) -> String {
    let mut s = format!(r#"<{p}data id="{id}">"#);
    for dim in dimensions {
        let kind = if dim.numeric { "numDim" } else { "strDim" };
        let _ = write!(s, r#"<{p}{kind} type="{}">"#, dim.role.as_str());
        if let Some(formula) = &dim.formula {
            let _ = write!(s, "<{p}f>{}</{p}f>", escape(formula));
        }
        for level in &dim.levels {
            let count = level.iter().map(|(i, _)| i + 1).max().unwrap_or(0);
            let _ = write!(s, r#"<{p}lvl ptCount="{count}">"#);
            for (idx, value) in level {
                let _ = write!(s, r#"<{p}pt idx="{idx}">{}</{p}pt>"#, escape(value));
            }
            let _ = write!(s, "</{p}lvl>");
        }
        let _ = write!(s, "</{p}{kind}>");
    }
    let _ = write!(s, "</{p}data>");
    s
}

const fn flag(on: bool) -> &'static str {
    if on { "1" } else { "0" }
}

/// The side a 2016 legend takes; it has no corner.
const fn legend_side(position: LegendPosition) -> &'static str {
    match position {
        LegendPosition::TopRight => "r",
        other => other.as_str(),
    }
}

fn render_legend(legend: ExLegend, p: &str) -> String {
    format!(
        r#"<{p}legend pos="{}" align="ctr" overlay="{}"/>"#,
        legend_side(legend.position),
        flag(legend.overlay)
    )
}

fn render_points(points: &[ExPoint], p: &str) -> String {
    let mut s = String::new();
    for point in points {
        let _ = write!(
            s,
            r#"<{p}dataPt idx="{}">{}</{p}dataPt>"#,
            point.index,
            super::chart::shape_format(p, &point.format)
        );
    }
    s
}

fn render_visibility(labels: ExLabels, p: &str) -> String {
    format!(
        r#"<{p}visibility seriesName="{}" categoryName="{}" value="{}"/>"#,
        flag(labels.series_name),
        flag(labels.category_name),
        flag(labels.value)
    )
}

fn render_labels(labels: ExLabels, p: &str) -> String {
    let pos = labels
        .position
        .map_or(String::new(), |at| format!(r#" pos="{}""#, at.as_str()));
    format!(
        "<{p}dataLabels{pos}>{}</{p}dataLabels>",
        render_visibility(labels, p)
    )
}

/// Edits bringing a `dataLabels` element with content in line with the
/// model: its position and its `visibility`, the rest kept. `inner` is where
/// the series' content starts within the series element.
fn edit_labels(
    node: &Node<'_>,
    inner: usize,
    labels: ExLabels,
    p: &str,
) -> Vec<(Range<usize>, String)> {
    let mut edits = Vec::new();
    let start = inner + node.span.start;
    // ponytail: a position taken away stays in the tag; Excel then keeps it.
    if let Some(at) = labels.position {
        let tag = set_attribute(node.tag.trim_end_matches('>'), "pos", at.as_str());
        edits.push((start..start + node.tag.len(), format!("{tag}>")));
    }
    let base = inner + node.inner_start;
    let kids = node.children();
    let text = render_visibility(labels, p);
    if let Some(old) = kids.iter().find(|c| c.name == "visibility") {
        edits.push((base + old.span.start..base + old.span.end, text));
    } else {
        let at = kids
            .iter()
            .find(|c| {
                matches!(
                    c.name,
                    "separator" | "dataLabel" | "dataLabelHidden" | "extLst"
                )
            })
            .map_or(base + node.inner.len(), |c| base + c.span.start);
        edits.push((at..at, text));
    }
    edits
}

fn render_binning(binning: Binning, p: &str) -> String {
    let edge = |name: &str, edge: Option<BinEdge>| match edge {
        None => String::new(),
        Some(BinEdge::Auto) => format!(r#" {name}="auto""#),
        Some(BinEdge::Value(v)) => format!(r#" {name}="{v}""#),
    };
    let mut s = format!(
        r#"<{p}binning intervalClosed="{}"{}{}"#,
        if binning.closed_left { "l" } else { "r" },
        edge("underflow", binning.underflow),
        edge("overflow", binning.overflow)
    );
    match binning.bins {
        None => s.push_str("/>"),
        Some(Bins::Width(w)) => {
            let _ = write!(s, r#"><{p}binSize val="{w}"/></{p}binning>"#);
        }
        Some(Bins::Count(n)) => {
            let _ = write!(s, r#"><{p}binCount val="{n}"/></{p}binning>"#);
        }
    }
    s
}

fn render_subtotals(subtotals: &[u32], p: &str) -> String {
    if subtotals.is_empty() {
        return String::new();
    }
    let mut s = format!("<{p}subtotals>");
    for index in subtotals {
        let _ = write!(s, r#"<{p}idx val="{index}"/>"#);
    }
    let _ = write!(s, "</{p}subtotals>");
    s
}

/// The edit bringing the chart's legend in line with the model; `inner` is
/// where the chart element's content starts and `end` where it ends.
fn edit_legend(
    parts: &[Node<'_>],
    inner: usize,
    end: usize,
    legend: Option<ExLegend>,
    p: &str,
) -> (Range<usize>, String) {
    let node = parts.iter().find(|n| n.name == "legend");
    match (legend, node) {
        (None, Some(node)) => (
            inner + node.span.start..inner + node.span.end,
            String::new(),
        ),
        (Some(legend), Some(node)) => {
            let tag = node.tag.trim_end_matches('>');
            let tag = set_attribute(tag, "pos", legend_side(legend.position));
            let tag = set_attribute(&tag, "overlay", flag(legend.overlay));
            let start = inner + node.span.start;
            (start..start + node.tag.len(), format!("{tag}>"))
        }
        (Some(legend), None) => {
            // After the plot area, before the extensions.
            let at = parts
                .iter()
                .find(|n| n.name == "extLst")
                .map_or(end, |n| inner + n.span.start);
            (at..at, render_legend(legend, p))
        }
        (None, None) => (end..end, String::new()),
    }
}

/// Edits bringing what a series draws beyond its data - point colours, data
/// labels, bins, totals - in line with the model. Spans are within the
/// series element; `inner` is where its content starts.
fn edit_drawn(
    node: &Node<'_>,
    kids: &[Node<'_>],
    inner: usize,
    now: &ExSeries,
    was: &ExSeries,
    p: &str,
) -> Vec<(Range<usize>, String)> {
    let mut edits: Vec<(Range<usize>, String)> = Vec::new();
    let before = |names: &[&str]| {
        kids.iter()
            .find(|n| names.contains(&n.name))
            .map_or(inner + node.inner.len(), |n| inner + n.span.start)
    };
    if now.points != was.points {
        let old: Vec<&Node<'_>> = kids.iter().filter(|n| n.name == "dataPt").collect();
        let at = old.first().map_or_else(
            || before(&["dataLabels", "dataId", "layoutPr", "axisId", "extLst"]),
            |n| inner + n.span.start,
        );
        edits.push((at..at, render_points(&now.points, p)));
        for n in old {
            edits.push((inner + n.span.start..inner + n.span.end, String::new()));
        }
    }
    if now.labels != was.labels {
        let node = kids.iter().find(|n| n.name == "dataLabels");
        match (now.labels, node) {
            (None, Some(n)) => {
                edits.push((inner + n.span.start..inner + n.span.end, String::new()));
            }
            (Some(labels), Some(n)) if !n.inner.is_empty() => {
                edits.extend(edit_labels(n, inner, labels, p));
            }
            (Some(labels), Some(n)) => edits.push((
                inner + n.span.start..inner + n.span.end,
                render_labels(labels, p),
            )),
            (Some(labels), None) => {
                let at = before(&["dataId", "layoutPr", "axisId", "extLst"]);
                edits.push((at..at, render_labels(labels, p)));
            }
            (None, None) => {}
        }
    }
    if now.binning != was.binning || now.subtotals != was.subtotals {
        let binning = now.binning.map_or(String::new(), |b| render_binning(b, p));
        let subtotals = render_subtotals(&now.subtotals, p);
        match kids.iter().find(|n| n.name == "layoutPr") {
            Some(n) if !n.inner.is_empty() => {
                let base = inner + n.inner_start;
                let parts = n.children();
                let mut child = |name: &str, text: String, follows: &[&str]| {
                    if let Some(old) = parts.iter().find(|c| c.name == name) {
                        edits.push((base + old.span.start..base + old.span.end, text));
                    } else {
                        let at = parts
                            .iter()
                            .find(|c| follows.contains(&c.name))
                            .map_or(base + n.inner.len(), |c| base + c.span.start);
                        edits.push((at..at, text));
                    }
                };
                if now.binning != was.binning {
                    child(
                        "binning",
                        binning,
                        &["geography", "statistics", "subtotals", "extLst"],
                    );
                }
                if now.subtotals != was.subtotals {
                    child("subtotals", subtotals, &["extLst"]);
                }
            }
            found => {
                let text = format!("<{p}layoutPr>{binning}{subtotals}</{p}layoutPr>");
                let span = found.map_or_else(
                    || {
                        let at = before(&["axisId", "extLst"]);
                        at..at
                    },
                    |n| inner + n.span.start..inner + n.span.end,
                );
                edits.push((span, text));
            }
        }
    }
    edits
}