rust-office-charts 0.1.7

Render Office Open XML charts to SVG from native Rust or WebAssembly
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
//! Layout of classic bubble charts.
use super::cartesian_chart::DataLabels;
use super::chart_colors::ChartColors;
use super::chart_svg::{
    font_family, font_size, line, number, on, text, text_props, text_width, title_position, val,
};
use crate::chart::{chart_node, child, ChartData};
use roxmltree::Node;
use std::fmt::Write;

#[derive(Clone, Copy)]
struct Axis {
    low: f64,
    high: f64,
    unit: f64,
    multiplier: f64,
    reversed: bool,
}

impl Axis {
    fn new(
        raw: (f64, f64),
        node: Option<Node>,
        length: f64,
        nominal_radius: f64,
        label_spacing: f64,
    ) -> Self {
        Self::with_defaults(raw, node, length, nominal_radius, label_spacing, false)
    }

    fn spreadsheet(
        raw: (f64, f64),
        node: Option<Node>,
        length: f64,
        nominal_radius: f64,
        label_spacing: f64,
    ) -> Self {
        Self::with_defaults(raw, node, length, nominal_radius, label_spacing, true)
    }

    fn with_defaults(
        raw: (f64, f64),
        node: Option<Node>,
        length: f64,
        nominal_radius: f64,
        label_spacing: f64,
        spreadsheet: bool,
    ) -> Self {
        let scaling = node.and_then(|n| child(n, "scaling"));
        let explicit_min = number(val(scaling, "min"));
        let explicit_max = number(val(scaling, "max"));
        // Normalize by a power of ten before subtracting extreme signed values.
        let magnitude = raw
            .0
            .abs()
            .max(raw.1.abs())
            .max(explicit_min.unwrap_or(0.).abs())
            .max(explicit_max.unwrap_or(0.).abs());
        let multiplier = if magnitude > 0. {
            10f64.powf(magnitude.log10().floor().clamp(-308., 308.))
        } else {
            1.
        };
        let mut lo = raw.0 / multiplier;
        let mut hi = raw.1 / multiplier;
        if hi <= lo {
            let delta = lo.abs().max(1.) * 0.1;
            lo -= delta;
            hi += delta;
        }
        let zero_min = lo > 0. && lo <= hi * 0.5;
        let zero_max = hi < 0. && hi >= lo * 0.5;
        let span = (if zero_max { 0. } else { hi }) - (if zero_min { 0. } else { lo });
        let pad = nominal_radius.min(length * 0.35)
            / (length - 2. * nominal_radius.min(length * 0.35)).max(1.)
            * span;
        let mut lower = if zero_min {
            (lo - pad).min(0.)
        } else {
            lo - pad
        };
        let mut upper = if zero_max {
            (hi + pad).max(0.)
        } else {
            hi + pad
        };
        lower = explicit_min.map_or(lower, |v| v / multiplier);
        upper = explicit_max.map_or(upper, |v| v / multiplier);
        if upper <= lower {
            upper = lower + lower.abs().max(1.);
        }
        let intervals = (length / label_spacing.max(1.))
            .floor()
            .clamp(1., if spreadsheet { 10. } else { 40. });
        let desired = ((upper - lower) / intervals).max(1e-300);
        let decade = 10f64.powf(desired.log10().floor());
        let nice = [1., 2., 5., 10.]
            .into_iter()
            .find(|factor| desired <= decade * factor * if spreadsheet { 1. } else { 1.005 })
            .unwrap_or(10.);
        let unit = number(val(node, "majorUnit"))
            .map(|n| n / multiplier)
            .filter(|u| *u > 0. && u.is_finite())
            .unwrap_or(decade * nice);
        let low = explicit_min.map_or((lower / unit).floor() * unit, |v| v / multiplier);
        let high = explicit_max.map_or((upper / unit).ceil() * unit, |v| v / multiplier);
        let (low, high, unit) =
            if !low.is_finite() || !high.is_finite() || high <= low || !unit.is_finite() {
                (lower, upper, upper - lower)
            } else {
                (low, high, unit)
            };
        Self {
            low,
            high,
            unit,
            multiplier,
            reversed: val(scaling, "orientation") == Some("maxMin"),
        }
    }
    fn fraction(&self, normalized: f64) -> f64 {
        let f = (normalized - self.low) / (self.high - self.low);
        if self.reversed {
            1. - f
        } else {
            f
        }
    }
    fn crossing(&self, other: Option<Node>) -> f64 {
        let target = number(val(other, "crossesAt")).map_or_else(
            || match val(other, "crosses") {
                Some("max") => self.high,
                Some("min") => self.low,
                _ => 0.,
            },
            |v| v / self.multiplier,
        );
        self.fraction(target.clamp(self.low, self.high))
    }
    fn ticks(&self) -> impl Iterator<Item = f64> + '_ {
        (0..=128)
            .map(|i| self.low + f64::from(i) * self.unit)
            .take_while(|v| *v <= self.high + self.unit * 1e-8)
    }
    fn label(&self, n: f64) -> String {
        if !(n * self.multiplier).is_finite() {
            return format!("{n:.2}e{}", self.multiplier.log10().round() as i32);
        }
        let n = if n.abs() < self.unit.abs() * 1e-9 {
            0.
        } else {
            n * self.multiplier
        };
        if n == 0. {
            return "0".into();
        }
        if !(1e-6..1e12).contains(&n.abs()) {
            return format!("{n:.2e}");
        }
        format!("{n:.9}")
            .trim_end_matches('0')
            .trim_end_matches('.')
            .to_owned()
    }
}

fn legend_lines(name: &str, size: f64, limit: f64) -> Vec<&str> {
    let mut rest = name;
    let mut lines = Vec::new();
    while !rest.is_empty() {
        let mut width = 0.;
        let mut end = 0;
        let mut boundary = 0;
        for (i, c) in rest.char_indices() {
            let next = i + c.len_utf8();
            width += text_width(&rest[i..next], size);
            if width > limit && end > 0 {
                break;
            }
            end = next;
            if c.is_whitespace() || c == '-' {
                boundary = end;
            }
        }
        if end < rest.len() && boundary > 0 {
            end = boundary;
        }
        lines.push(rest[..end].trim_end());
        if lines.len() >= 64 {
            break;
        }
        rest = rest[end..].trim_start();
    }
    if lines.is_empty() {
        lines.push("");
    }
    lines
}

fn gridline(svg: &mut String, node: Node, start: (f64, f64), end: (f64, f64), stroke: &str) {
    let properties = child(node, "spPr").and_then(|n| {
        n.children()
            .find(|n| n.is_element() && n.tag_name().name() == "ln")
    });
    let width = number(properties.and_then(|n| n.attribute("w")))
        .map_or(1., |w| (w / 9525.).clamp(0., 256.));
    let dash = properties
        .and_then(|n| n.children().find(|n| n.tag_name().name() == "prstDash"))
        .and_then(|n| n.attribute("val"));
    let lengths = match dash {
        Some("dot" | "sysDot") => vec![width, width * 2.],
        Some("dash" | "sysDash") => vec![width * 4., width * 3.],
        Some("lgDash") => vec![width * 8., width * 3.],
        Some("dashDot" | "sysDashDot") => vec![width * 4., width * 2., width, width * 2.],
        Some("lgDashDot") => vec![width * 8., width * 2., width, width * 2.],
        Some("lgDashDotDot") => vec![width * 8., width * 2., width, width * 2., width, width * 2.],
        _ => Vec::new(),
    };
    let dash = if lengths.is_empty() {
        String::new()
    } else {
        format!(
            " stroke-dasharray=\"{}\"",
            lengths
                .iter()
                .map(f64::to_string)
                .collect::<Vec<_>>()
                .join(" ")
        )
    };
    write!(svg, r#"<path d="M{:.2} {:.2}L{:.2} {:.2}" fill="none" stroke="{stroke}" stroke-width="{width:.2}"{dash}/>"#, start.0, start.1, end.0, end.1).unwrap();
}

// The bevel is lit from above and to the left, using the actual point paint as its material.
fn sphere_paint(svg: &mut String, fill: &str) -> Option<String> {
    let base = fill
        .strip_prefix('#')
        .filter(|v| v.len() == 6 && v.is_ascii())?;
    let rgb = [
        u8::from_str_radix(&base[0..2], 16).ok()? as f64,
        u8::from_str_radix(&base[2..4], 16).ok()? as f64,
        u8::from_str_radix(&base[4..6], 16).ok()? as f64,
    ];
    let id = format!("bubble-{base}");
    let luma = 0.213 * rgb[0] + 0.715 * rgb[1] + 0.072 * rgb[2];
    write!(
        svg,
        r#"<radialGradient id="{id}" cx="48%" cy="48%" r="53%" fx="40%" fy="32%">"#
    )
    .unwrap();
    for (offset, scale, shine) in [
        (0, 1.18, 40.),
        (15, 1.04, 5.),
        (40, 0.88, 0.),
        (67, 0.7, 0.),
        (87, 0.4, 0.),
        (100, 0.32, 0.),
    ] {
        let [r, g, b] = rgb.map(|c| {
            ((c + 0.2 * (c - luma)) * scale + shine)
                .round()
                .clamp(0., 255.) as u8
        });
        write!(
            svg,
            r##"<stop offset="{offset}%" stop-color="#{r:02X}{g:02X}{b:02X}"/>"##
        )
        .unwrap();
    }
    svg.push_str("</radialGradient>");
    Some(format!("url(#{id})"))
}

pub(super) fn render(
    root: Node,
    data: &ChartData,
    width: f64,
    height: f64,
    colors: &ChartColors,
    minor_latin: Option<&str>,
) -> Option<String> {
    let chart = child(root, "chart")?;
    let plot = child(chart, "plotArea")?;
    let group = child(plot, "bubbleChart")?;
    if data.series.iter().any(|s| s.chart_type != "bubble") {
        return None;
    }
    let legacy = colors.legacy_defaults();
    let title = child(chart, "title");
    let title_label = data.title.as_deref().or_else(|| {
        if !legacy || title.is_none() || on(val(Some(chart), "autoTitleDeleted")) {
            return None;
        }
        Some(if data.series.len() == 1 {
            data.series[0].name.as_deref().unwrap_or("Chart Title")
        } else {
            "Chart Title"
        })
    });
    let legend = child(chart, "legend");
    let base_props = text_props(Some(root), false);
    let size = font_size(base_props, 40. / 3.);
    let default_face = minor_latin.unwrap_or("Calibri");
    let axis_by_pos = |horizontal| {
        plot.children().find(|n| {
            chart_node(*n, "valAx")
                && match val(Some(*n), "axPos") {
                    Some("b" | "t") => horizontal,
                    Some("l" | "r") => !horizontal,
                    _ => false,
                }
        })
    };
    let x_ax = axis_by_pos(true);
    let y_ax = axis_by_pos(false);
    let x_props = text_props(x_ax, false).or(base_props);
    let y_props = text_props(y_ax, false).or(base_props);
    let legend_props = text_props(legend, false).or(base_props);
    let (xf, yf, lf) = (
        font_size(x_props, size),
        font_size(y_props, size),
        font_size(legend_props, size),
    );
    let (xface, yface, lface) = (
        font_family(x_props, default_face),
        font_family(y_props, default_face),
        font_family(legend_props, default_face),
    );
    let title_props = text_props(title, true).or(text_props(title, false));
    let tf = font_size(
        title_props,
        super::chart_svg::title_size_default(colors, root, size, 24.),
    );
    let title_height = if title_label.is_some() && !on(val(title, "overlay")) {
        12. + tf * 1.15
    } else {
        0.
    };
    let rounded =
        val(Some(root), "roundedCorners").map_or(!legacy, |v| !matches!(v, "0" | "false" | "off"));
    let corner = if rounded { 40. / 3. } else { 0. };
    let shape_paint = |node: Node, default_fill: &str, default_stroke: &str| {
        let pr = child(node, "spPr");
        (
            pr.and_then(|n| colors.shape_fill(n))
                .unwrap_or_else(|| default_fill.to_owned()),
            pr.and_then(|n| colors.shape_stroke(n))
                .unwrap_or_else(|| default_stroke.to_owned()),
        )
    };
    let (background, border) = shape_paint(root, "white", "#868686");
    let mut svg = format!(
        r#"<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}"><rect width="{width}" height="{height}" rx="{corner:.2}" fill="{background}" stroke="{border}"/>"#
    );
    if legacy {
        // Match the theme face's x-height when the browser substitutes a system face.
        svg.push_str(r#"<style>text[font-family^="Calibri,"]{font-size-adjust:0.46436}</style>"#);
    }
    if let Some(title) = title_label {
        let styled_title = legacy
            || (colors.spreadsheet_defaults && !super::chart_svg::title_uses_automatic_font(root));
        let bold = title_props
            .and_then(|p| p.attribute("b"))
            .map_or(styled_title, |s| on(Some(s)));
        if bold {
            svg.push_str(r#"<g font-weight="bold">"#);
        }
        let (x, y, anchor) = title_position(
            child(chart, "title").filter(|_| colors.spreadsheet_defaults),
            width,
            height,
            tf,
            10.33 + tf * 0.917,
        );
        text(
            &mut svg,
            x,
            y,
            anchor,
            tf,
            &font_family(
                title_props,
                if styled_title { default_face } else { "Arial" },
            ),
            title,
        );
        if bold {
            svg.push_str("</g>");
        }
    }
    let mut entries = Vec::new();
    let mut points = Vec::new();
    let show_neg = on(val(Some(group), "showNegBubbles"));
    let size_is_width = val(Some(group), "sizeRepresents") == Some("w");
    let mut max_size = 0_f64;
    let (mut xr, mut yr) = (
        (f64::INFINITY, f64::NEG_INFINITY),
        (f64::INFINITY, f64::NEG_INFINITY),
    );
    for (s, series) in data.series.iter().enumerate() {
        if data.series.len() == 1 && colors.vary_by_point(s) {
            let capacity = ((height - title_height - 40. / 3.) / (lf * 1.16 + 8.))
                .floor()
                .clamp(1., 256.) as u32;
            let count = series
                .points
                .last()
                .map_or(0, |p| p.index.saturating_add(1))
                .min(capacity);
            for idx in 0..count {
                let name = series
                    .points
                    .binary_search_by_key(&idx, |p| p.index)
                    .ok()
                    .and_then(|i| series.points[i].x.as_deref())
                    .unwrap_or("");
                entries.push((s, Some(idx), name.to_owned()));
            }
        } else {
            entries.push((
                s,
                None,
                series
                    .name
                    .clone()
                    .unwrap_or_else(|| format!("Series {}", s + 1)),
            ));
        }
        for pt in &series.points {
            let (Some(x), Some(y)) = (number(pt.x.as_deref()), number(pt.y.as_deref())) else {
                continue;
            };
            xr = (xr.0.min(x), xr.1.max(x));
            yr = (yr.0.min(y), yr.1.max(y));
            let Some(z) = number(pt.bubble_size.as_deref()) else {
                continue;
            };
            if z == 0. || (z < 0. && !show_neg) {
                continue;
            }
            max_size = max_size.max(z.abs());
            points.push((s, pt.index, x, y, z));
        }
    }
    if !xr.0.is_finite() {
        xr = (0., 1.);
        yr = (0., 1.);
    }
    let legend_pos = val(legend, "legendPos").unwrap_or("r");
    let side_legend = matches!(legend_pos, "l" | "r" | "tr");
    if side_legend {
        entries.truncate(
            ((height - title_height - 40. / 3.) / (lf * 1.16 + 8.))
                .floor()
                .clamp(1., 256.) as usize,
        );
    }
    let name_lines: Vec<_> = entries
        .iter()
        .map(|(_, _, n)| {
            if legacy && side_legend {
                legend_lines(n, lf, (width * 0.19).max(lf))
            } else {
                vec![n.as_str()]
            }
        })
        .collect();
    let name_width = name_lines
        .iter()
        .flatten()
        .map(|n| text_width(n, lf) * if legacy { 0.87 } else { 1. })
        .fold(0., f64::max);
    let legend_width = if legend.is_some() && !on(val(legend, "overlay")) && side_legend {
        name_width + lf * 1.055 + 16.
    } else {
        0.
    };
    let legend_height = if legend.is_some() && !side_legend && !on(val(legend, "overlay")) {
        lf * 1.5
    } else {
        0.
    };
    let above = if legend_pos == "t" { legend_height } else { 0. };
    let below = legend_height - above;
    let inset = 20. / 3.;
    let x_labels = val(x_ax, "tickLblPos") != Some("none") && !on(val(x_ax, "delete"));
    let legacy_pad = if legacy && x_labels && yr.0 >= 0. && val(x_ax, "tickLblPos") != Some("high")
    {
        xf * 1.41
    } else {
        0.
    };
    let top = ((if legacy { 8.9 } else { 7. }) + title_height + above + yf * (4. / 7.))
        .min(height * 0.75);
    let bottom = (height - 7. - below - legacy_pad - yf * (4. / 7.)).max(top + 1.);
    // Size against the space left by the title and legend before allocating tick labels.
    // The diameter occupies 30% of the shorter dimension, including its own padding.
    let preliminary = (height - 2. * inset - title_height - legend_height)
        .min(width - 2. * inset - legend_width)
        .max(1.);
    let bubble_scale =
        (number(val(Some(group), "bubbleScale")).unwrap_or(100.) / 100.).clamp(0., 3.);
    let radius = |length: f64, scale: f64| length.max(1.) * 0.15 * scale / (1. + 0.3 * scale);
    let max_radius = radius(preliminary, bubble_scale);
    let axis_scale = if colors.spreadsheet_defaults {
        bubble_scale
    } else {
        1.
    };
    let nominal_y_radius = radius(
        height - 2. * inset - title_height - legend_height,
        axis_scale,
    );
    let nominal_x_radius = radius(
        if colors.spreadsheet_defaults {
            width - 2. * inset - legend_width
        } else {
            preliminary
        },
        axis_scale,
    );
    let make_axis = if colors.spreadsheet_defaults {
        Axis::spreadsheet
    } else {
        Axis::new
    };
    let y_axis = make_axis(yr, y_ax, bottom - top, nominal_y_radius, yf * 1.4);
    let y_labels = val(y_ax, "tickLblPos") != Some("none") && !on(val(y_ax, "delete"));
    let widest_y = y_axis
        .ticks()
        .map(|v| text_width(&y_axis.label(v), yf))
        .fold(0., f64::max);
    let legend_left = if legend_pos == "l" { legend_width } else { 0. };
    let reversed = val(x_ax.and_then(|n| child(n, "scaling")), "orientation") == Some("maxMin");
    let outside_y = y_labels && xr.1 >= 0.;
    let gutter = 8.67 + widest_y + (if legacy { 0.88 } else { 0.903 }) * yf;
    let mut left = (if outside_y && !reversed {
        gutter
    } else {
        14.67
    }) + legend_left;
    let mut right =
        width - (if outside_y && reversed { gutter } else { 14.67 }) - (legend_width - legend_left);
    let mut x_axis = make_axis(xr, x_ax, (right - left).max(1.), nominal_x_radius, xf * 3.5);
    if x_labels {
        if !outside_y || !reversed {
            let end = if reversed { x_axis.low } else { x_axis.high };
            right -= text_width(&x_axis.label(end), xf) / 2.;
        }
        if !outside_y || reversed {
            let start = if reversed { x_axis.high } else { x_axis.low };
            left += text_width(&x_axis.label(start), xf) / 2.;
        }
    }
    left = left.min(width - 2.);
    right = right.max(left + 1.);
    x_axis = make_axis(xr, x_ax, right - left, nominal_x_radius, xf * 3.5);
    if legacy
        && xr.0 >= 0.
        && x_axis.low < 0.
        && val(x_ax.and_then(|a| child(a, "scaling")), "min").is_none()
    {
        x_axis.low = 0.;
    }
    let x = |n| left + x_axis.fraction(n) * (right - left);
    let y = |n| bottom - y_axis.fraction(n) * (bottom - top);
    let vline = left + x_axis.crossing(y_ax) * (right - left);
    let hline = bottom - y_axis.crossing(x_ax) * (bottom - top);
    let (plot_fill, plot_stroke) = shape_paint(plot, "none", "none");
    if plot_fill != "none" || plot_stroke != "none" {
        write!(svg,r#"<rect x="{left:.2}" y="{top:.2}" width="{:.2}" height="{:.2}" fill="{plot_fill}" stroke="{plot_stroke}"/>"#,right-left,bottom-top).unwrap();
    }
    let mut labels = String::new();
    let axis_ink = "#868686";
    for (horizontal, node, axis, font, face, show_labels) in [
        (true, x_ax, &x_axis, xf, &xface, x_labels),
        (false, y_ax, &y_axis, yf, &yface, y_labels),
    ] {
        let deleted = on(val(node, "delete"));
        let grid = node.and_then(|n| child(n, "majorGridlines"));
        let grid_stroke = grid.map(|n| shape_paint(n, "none", axis_ink).1);
        let stroke = node
            .map(|n| shape_paint(n, "none", axis_ink).1)
            .unwrap_or_else(|| axis_ink.to_owned());
        let tick = match val(node, "majorTickMark") {
            Some("out" | "cross" | "in") => font * 0.317,
            None if legacy => font * 0.317,
            _ => 0.,
        };
        for v in axis.ticks() {
            let mark = axis.label(v);
            if horizontal {
                let pos = x(v);
                if let (Some(grid), Some(stroke)) = (grid, &grid_stroke) {
                    gridline(&mut svg, grid, (pos, top), (pos, bottom), stroke);
                }
                let direction = if val(node, "majorTickMark") == Some("in") {
                    -1.
                } else {
                    1.
                };
                if !deleted && tick > 0. {
                    line(&mut svg, pos, hline, pos, hline + direction * tick, &stroke);
                }
                if show_labels {
                    let base = match val(node, "tickLblPos") {
                        Some("high") => top - font * 0.45,
                        Some("low") => bottom + tick + font * 1.26,
                        _ => hline + tick + font * 1.26,
                    };
                    text(&mut labels, pos, base, "middle", font, face, &mark);
                }
            } else {
                let pos = y(v);
                if let (Some(grid), Some(stroke)) = (grid, &grid_stroke) {
                    gridline(&mut svg, grid, (left, pos), (right, pos), stroke);
                }
                let direction = if val(node, "majorTickMark") == Some("in") {
                    1.
                } else {
                    -1.
                };
                if !deleted && tick > 0. {
                    line(
                        &mut svg,
                        vline,
                        pos,
                        vline + direction * tick * (if reversed { -1. } else { 1. }),
                        pos,
                        &stroke,
                    );
                }
                if show_labels {
                    let (base, anchor) = match val(node, "tickLblPos") {
                        Some("high") => (right + font * 0.9, "start"),
                        Some("low") => (left - font * 0.9, "end"),
                        _ if reversed => (vline + font * 0.9, "start"),
                        _ => (vline - font * 0.9, "end"),
                    };
                    text(
                        &mut labels,
                        base,
                        pos + font * 0.31,
                        anchor,
                        font,
                        face,
                        &mark,
                    );
                }
            }
        }
        if deleted {
            continue;
        }
        if horizontal {
            line(&mut svg, left, hline, right, hline, &stroke);
        } else {
            line(&mut svg, vline, top, vline, bottom, &stroke);
        }
    }
    write!(svg,r#"<defs><clipPath id="plot"><rect x="{left:.2}" y="{top:.2}" width="{:.2}" height="{:.2}"/></clipPath></defs><g clip-path="url(#plot)">"#,right-left,bottom-top).unwrap();
    let flag = |node: Node| {
        child(node, "bubble3D").map(|n| n.attribute("val").is_none_or(|v| on(Some(v))))
    };
    let group_3d = flag(group).unwrap_or(false);
    let bevel_state: Vec<_> = group
        .children()
        .filter(|n| chart_node(*n, "ser"))
        .map(|ser| {
            let points = ser
                .children()
                .filter(|n| chart_node(*n, "dPt"))
                .filter_map(|p| Some((val(Some(p), "idx")?.parse::<u32>().ok()?, flag(p)?)))
                .collect::<std::collections::HashMap<_, _>>();
            (flag(ser).unwrap_or(group_3d), points)
        })
        .collect();
    let mut bevels = std::collections::HashMap::new();
    let mut defs = String::new();
    let mut paint = |i: usize, idx: Option<u32>, fill: String| {
        if bevel_state.get(i).is_some_and(|(series, points)| {
            idx.and_then(|p| points.get(&p)).copied().unwrap_or(*series)
        }) {
            bevels
                .entry(fill.clone())
                .or_insert_with(|| sphere_paint(&mut defs, &fill).unwrap_or(fill))
                .clone()
        } else {
            fill
        }
    };
    let series_nodes: Vec<_> = group.children().filter(|n| chart_node(*n, "ser")).collect();
    let data_labels: Vec<_> = series_nodes
        .iter()
        .map(|&node| DataLabels::new(group, node, default_face, (width, height)))
        .collect();
    let shadow = legacy
        && val(Some(root), "style")
            .and_then(|v| v.parse::<u8>().ok())
            .is_some_and(|n| (25..=32).contains(&n));
    if shadow {
        svg.push_str("<defs>");
        svg.push_str(r#"<filter id="bubbleShadow" x="-70%" y="-70%" width="240%" height="270%"><feDropShadow dx="0.8" dy="2.8" stdDeviation="1.5" flood-opacity="0.43"/></filter>"#);
        svg.push_str("</defs>");
    }
    for (i, idx, vx, vy, z) in points {
        let ratio = z.abs() / max_size;
        let radius = max_radius * if size_is_width { ratio } else { ratio.sqrt() };
        let fx = x_axis.fraction(vx / x_axis.multiplier);
        let fy = y_axis.fraction(vy / y_axis.multiplier);
        if !fx.is_finite()
            || !fy.is_finite()
            || !(-10.0..=11.0).contains(&fx)
            || !(-10.0..=11.0).contains(&fy)
        {
            continue;
        }
        let (cx, cy) = (left + fx * (right - left), bottom - fy * (bottom - top));
        let shadow_attr = if shadow && z > 0. {
            r##" filter="url(#bubbleShadow)""##
        } else {
            ""
        };
        let mut body = String::new();
        write!(
            body,
            r#"<circle cx="{cx:.2}" cy="{cy:.2}" r="{radius:.2}" fill="{}" stroke="{}"{shadow_attr}"#,
            if z < 0. {
                "white".into()
            } else {
                paint(i, Some(idx), colors.fill(i, Some(idx)))
            },
            if z < 0. {
                "black"
            } else {
                colors.outline(i, Some(idx)).unwrap_or("none")
            }
        )
        .unwrap();
        body.push_str("/>");
        write!(svg, r#"<g data-docx-series="{i}""#).unwrap();
        if colors.interactive {
            colors.hit_attrs(&mut svg, "bubble", i, Some(idx));
            write!(svg, r#" data-chart-x="{cx:.2}" data-chart-y="{cy:.2}""#).unwrap();
        }
        svg.push('>');
        colors.paint_point(
            &mut svg,
            i,
            Some(idx),
            "dataPoint",
            &colors.fill(i, Some(idx)),
            [cx - radius, cy - radius, radius * 2., radius * 2.],
            &body,
        );
        svg.push_str("</g>");
        if let (Some(Some(label)), Some(series)) = (data_labels.get(i), data.series.get(i)) {
            if let Some(point) = series.points.iter().find(|point| point.index == idx) {
                label.draw(
                    &mut labels,
                    series,
                    point,
                    (cx, cy),
                    (cx, cy),
                    "r",
                    false,
                    radius,
                    i,
                    colors,
                );
            }
        }
    }
    svg.push_str("</g>");
    svg.push_str(&labels);
    if legend.is_some() {
        let line_height = lf * 1.16 + 8.;
        let mid = if legend_pos == "tr" {
            top + line_height * entries.len() as f64 / 2.
        } else {
            (top + bottom) / 2.
        };
        let total_width: f64 = entries
            .iter()
            .map(|(_, _, n)| text_width(n, lf) + lf * 1.2)
            .sum();
        let mut run_x = (width - total_width) / 2. + lf * 0.3;
        let wrapped_lines: usize = name_lines.iter().map(|ls| ls.len() - 1).sum();
        let mut wrap_before = 0;
        for (i, (series, point, name)) in entries.iter().enumerate() {
            write!(svg, r#"<g data-docx-series="{series}""#).unwrap();
            colors.hit_attrs(&mut svg, "legendEntry", *series, *point);
            svg.push('>');
            let lines = &name_lines[i];
            let wrap_line_height = lf * 1.22;
            let (cx, cy) = if side_legend {
                let text_x = if legend_pos == "l" {
                    13.5 + lf * 0.75
                } else {
                    width - 13.5 - name_width
                };
                (
                    text_x - lf * 0.5,
                    mid + (i as f64 - (entries.len() as f64 - 1.) / 2.) * line_height
                        + (wrap_before as f64 - wrapped_lines as f64 / 2.) * wrap_line_height
                        + if legacy { lf * 0.75 } else { 0. },
                )
            } else {
                let x = run_x;
                run_x += text_width(name, lf) + lf * 1.2;
                (
                    x,
                    if legend_pos == "t" {
                        inset + title_height + lf * 0.65
                    } else {
                        height - inset - lf * 0.65
                    },
                )
            };
            let fill = paint(*series, *point, colors.fill(*series, *point));
            let radius = lf * if legacy { 0.3 } else { 0.264 };
            let stroke = colors.outline(*series, *point).unwrap_or("none");
            let body = format!(
                r#"<circle cx="{cx:.2}" cy="{cy:.2}" r="{radius:.2}" fill="{fill}" stroke="{stroke}"/>"#
            );
            colors.paint_point(
                &mut svg,
                *series,
                *point,
                "dataPoint",
                &fill,
                [cx - radius, cy - radius, radius * 2., radius * 2.],
                &body,
            );
            wrap_before += lines.len() - 1;
            for (row, line) in lines.iter().enumerate() {
                text(
                    &mut svg,
                    cx + lf * 0.5,
                    cy + lf * 0.31 + row as f64 * wrap_line_height,
                    "start",
                    lf,
                    &lface,
                    line,
                );
            }
            svg.push_str("</g>");
        }
    }
    if !defs.is_empty() {
        write!(svg, "<defs>{defs}</defs>").unwrap();
    }
    svg.push_str("</svg>");
    Some(svg)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn side_legend_wraps_at_breaks_then_character_boundaries() {
        assert_eq!(
            legend_lines("Y-Values", 40. / 3., 22.8),
            ["Y-", "Val", "ues"]
        );
        assert_eq!(legend_lines("增长率", 12., 13.), ["增", "长", "率"]);
    }

    #[test]
    fn bevel_depends_on_the_material_and_retains_explicit_non_solid_paint() {
        let mut out = String::new();
        assert_eq!(sphere_paint(&mut out, "url(#gradient)"), None);
        assert_eq!(
            sphere_paint(&mut out, "#000000").as_deref(),
            Some("url(#bubble-000000)")
        );
        assert!(!out.contains("NaN"));
        assert!(out.contains(r##"stop-color="#000000""##));
    }

    #[test]
    fn automatic_axis_reserves_room_for_bubbles_and_whole_ticks() {
        let axis = Axis::new((0., 7.5), None, 176., 23.6, 33.6);
        assert_eq!(
            axis.ticks().map(|v| axis.label(v)).collect::<Vec<_>>(),
            ["-5", "0", "5", "10"]
        );
        let taller = Axis::new((0., 7.5), None, 297., 37.5, 33.6);
        assert_eq!(
            taller.ticks().map(|v| taller.label(v)).collect::<Vec<_>>(),
            ["-2", "0", "2", "4", "6", "8", "10"]
        );
    }

    #[test]
    fn explicit_reversed_scale_honors_bounds_and_major_unit() {
        let doc=roxmltree::Document::parse(r#"<valAx xmlns="http://schemas.openxmlformats.org/drawingml/2006/chart"><scaling><min val="-3"/><max val="9"/><orientation val="maxMin"/></scaling><majorUnit val="3"/></valAx>"#).unwrap();
        let axis = Axis::new((-100., 100.), Some(doc.root_element()), 200., 20., 20.);
        assert_eq!(
            axis.ticks().map(|v| axis.label(v)).collect::<Vec<_>>(),
            ["-3", "0", "3", "6", "9"]
        );
        assert_eq!(axis.fraction(axis.low), 1.);
        assert_eq!(axis.fraction(axis.high), 0.);
        assert!((axis.crossing(None) - 0.75).abs() < 1e-12);
    }

    #[test]
    fn opposite_extreme_values_produce_finite_positions_and_labels() {
        let axis = Axis::new((-f64::MAX, f64::MAX), None, 250., 25., 20.);
        for n in axis.ticks() {
            assert!(axis.fraction(n).is_finite());
            assert!(!axis.label(n).contains("inf"));
        }
        assert!(axis.fraction(f64::MAX / axis.multiplier) < 1.);
    }
}