Skip to main content

ggplot_rs/render/
svg_backend.rs

1//! A self-contained SVG `DrawBackend` — a *second* backend (no plotters),
2//! proving the `DrawBackend` abstraction: the same `PlotRenderer` drives it.
3//!
4//! It emits SVG elements directly, so SVG output needs no glyph rasterization
5//! (text is `<text>` with font attributes the viewer renders).
6
7use super::backend::{
8    DrawBackend, FillPattern, FontFace, LineEnd, LineStyle, Linetype, PointShape, PointStyle,
9    RectStyle, TextAnchor, TextStyle,
10};
11use super::{Rect, RenderError};
12
13/// Accumulates SVG markup for a plot rendered via [`DrawBackend`].
14///
15/// Every number written to an attribute is finite: marks whose geometry is
16/// `NaN`/`±inf` are dropped (a polyline keeps its finite vertices), and
17/// non-finite style values fall back to safe defaults. All data-derived
18/// attribute values and text go through [`escape`].
19pub struct SvgBackend {
20    plot_area: Rect,
21    total_area: Rect,
22    body: String,
23    tooltip: Option<String>,
24    axis_key: Option<String>,
25    series_key: Option<String>,
26    value_key: Option<String>,
27    mark_part: Option<String>,
28    mark_attrs: Vec<(String, String)>,
29    /// Geom of the layer being drawn (see [`DrawBackend::set_mark_geom`]).
30    mark_geom: Option<String>,
31    root_attrs: Vec<(String, String)>,
32    warnings: Vec<String>,
33    /// Emit the root `data-plot` panel rect (off for composite pages, whose
34    /// root is not a single panel).
35    plot_attr: bool,
36    /// B2-4: whether `GGPlot::svg_formatted_values` is on — see
37    /// [`DrawBackend::wants_formatted_values`].
38    formatted_values: bool,
39    /// `data-fvalue` for the next drawn mark(s) — see
40    /// [`DrawBackend::set_mark_fvalue`].
41    mark_fvalue: Option<String>,
42    /// `data-fx` for the next drawn mark(s) — see
43    /// [`DrawBackend::set_mark_fx`].
44    mark_fx: Option<String>,
45    /// Patterns registered so far via [`Self::pattern_url`] (#206),
46    /// deduped by equality: `(pattern, "<id_prefix>-pat-<n>")`. Drained
47    /// into a `<defs>` block by [`Self::pattern_defs`] on `finish`/
48    /// `finish_fragment`.
49    patterns: Vec<(FillPattern, String)>,
50    /// This backend instance's id prefix for `<defs>` — process-unique
51    /// (a monotonic counter), so inlining several rendered SVGs into one
52    /// HTML page never lets one's `url(#…)` resolve into another's
53    /// `<pattern>` (SVG ids share one DOM-wide namespace once inlined).
54    id_prefix: String,
55    /// #221: `Aes::class` tokens for the next drawn mark(s) — see
56    /// [`DrawBackend::set_mark_class`].
57    mark_user_class: Option<String>,
58    /// #221: the caller-named group `(attr, value)` the next drawn mark(s)
59    /// belong to — see [`DrawBackend::set_mark_group`].
60    mark_group: Option<(String, String)>,
61    /// #221: the current layer's `GGPlot::layer_svg_attr`s — see
62    /// [`DrawBackend::set_layer_attrs`].
63    layer_attrs: Vec<(String, String)>,
64    /// #221: each group's `(attr, value, accumulated markup)`, in order of
65    /// first appearance.
66    groups: Vec<(String, String, String)>,
67    /// #221: `(byte offset into body, index into groups)` — where each
68    /// group's `<g>` is spliced in by [`Self::flush_groups`]. Offsets are
69    /// non-decreasing (a group's slot is the body length when its first
70    /// mark arrives, and the body only ever grows at the end).
71    group_slots: Vec<(usize, usize)>,
72}
73
74/// Source for [`SvgBackend::id_prefix`] — process-wide, so every backend
75/// instance gets a distinct prefix regardless of thread.
76static NEXT_ID_PREFIX: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
77
78impl SvgBackend {
79    pub fn new(width: u32, height: u32, plot_area: Rect) -> Self {
80        SvgBackend {
81            plot_area,
82            total_area: Rect {
83                x: 0.0,
84                y: 0.0,
85                width: width as f64,
86                height: height as f64,
87            },
88            body: String::new(),
89            tooltip: None,
90            axis_key: None,
91            series_key: None,
92            value_key: None,
93            mark_part: None,
94            mark_attrs: Vec::new(),
95            mark_geom: None,
96            root_attrs: Vec::new(),
97            warnings: Vec::new(),
98            plot_attr: true,
99            formatted_values: false,
100            mark_fvalue: None,
101            mark_fx: None,
102            patterns: Vec::new(),
103            id_prefix: format!(
104                "gg{:x}",
105                NEXT_ID_PREFIX.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
106            ),
107            mark_user_class: None,
108            mark_group: None,
109            layer_attrs: Vec::new(),
110            groups: Vec::new(),
111            group_slots: Vec::new(),
112        }
113    }
114
115    /// The `url(#…)` fill value for `pattern`, registering its `<defs>
116    /// <pattern>` the first time this exact pattern is seen on this
117    /// backend (later calls with an equal pattern reuse the same id).
118    fn pattern_url(&mut self, pattern: &FillPattern) -> String {
119        if let Some((_, id)) = self.patterns.iter().find(|(p, _)| p == pattern) {
120            return format!("url(#{id})");
121        }
122        let id = format!("{}-pat-{}", self.id_prefix, self.patterns.len());
123        self.patterns.push((*pattern, id.clone()));
124        format!("url(#{id})")
125    }
126
127    /// Shared by [`DrawBackend::draw_rect`]/[`DrawBackend::draw_rect_pattern`]
128    /// — `fill` is already resolved (a hex colour or a pattern's `url(#…)`).
129    fn rect_markup(
130        &mut self,
131        (x0, y0): (f64, f64),
132        (x1, y1): (f64, f64),
133        fill: &str,
134        style: &RectStyle,
135    ) -> Result<(), RenderError> {
136        if !(x0.is_finite() && y0.is_finite() && x1.is_finite() && y1.is_finite()) {
137            return Ok(());
138        }
139        let (x, y) = (x0.min(x1), y0.min(y1));
140        let (w, h) = ((x1 - x0).abs(), (y1 - y0).abs());
141        let stroke = style.stroke.map(rgb).unwrap_or_else(|| "none".into());
142        // SVG `<rect>` takes rx/ry natively — clamp to half the shorter side
143        // so an oversized radius draws a "stadium" instead of a malformed box.
144        let r = style.corner_radius.max(0.0).min(w / 2.0).min(h / 2.0);
145        let radius = if r > 0.0 {
146            format!(" rx=\"{r:.2}\" ry=\"{r:.2}\"")
147        } else {
148            String::new()
149        };
150        let attrs = format!(
151            "x=\"{x:.2}\" y=\"{y:.2}\" width=\"{w:.2}\" height=\"{h:.2}\"{radius} fill=\"{fill}\"{} \
152             stroke=\"{stroke}\" stroke-width=\"{:.2}\"",
153            opacity_attr("fill", style.alpha),
154            finite_or(style.stroke_width, 0.0)
155        );
156        self.push_mark("rect", "bar", &attrs);
157        Ok(())
158    }
159
160    /// Shared by [`DrawBackend::draw_polygon`]/[`DrawBackend::draw_polygon_pattern`].
161    fn polygon_markup(
162        &mut self,
163        pts: &[(f64, f64)],
164        fill: &str,
165        style: &RectStyle,
166    ) -> Result<(), RenderError> {
167        let pts = finite_pts(pts);
168        if pts.len() < 3 {
169            return Ok(());
170        }
171        let stroke = style.stroke.map(rgb).unwrap_or_else(|| "none".into());
172        let attrs = format!(
173            "points=\"{}\" fill=\"{fill}\"{} stroke=\"{stroke}\" stroke-width=\"{:.2}\"",
174            points(&pts),
175            opacity_attr("fill", style.alpha),
176            finite_or(style.stroke_width, 0.0)
177        );
178        self.push_mark("polygon", "band", &attrs);
179        Ok(())
180    }
181
182    /// Shared by [`DrawBackend::draw_polygon_rings`]/
183    /// [`DrawBackend::draw_polygon_rings_pattern`].
184    fn polygon_rings_markup(
185        &mut self,
186        rings: &[Vec<(f64, f64)>],
187        fill: &str,
188        style: &RectStyle,
189    ) -> Result<(), RenderError> {
190        let mut d = String::new();
191        for ring in rings {
192            let pts = finite_pts(ring);
193            if pts.len() < 3 {
194                continue;
195            }
196            d.push('M');
197            d.push_str(&format!("{},{}", num(pts[0].0), num(pts[0].1)));
198            for p in &pts[1..] {
199                d.push('L');
200                d.push_str(&format!("{},{}", num(p.0), num(p.1)));
201            }
202            d.push('Z');
203        }
204        if d.is_empty() {
205            return Ok(());
206        }
207        let stroke = style.stroke.map(rgb).unwrap_or_else(|| "none".into());
208        let attrs = format!(
209            "d=\"{d}\" fill-rule=\"evenodd\" fill=\"{fill}\"{} stroke=\"{stroke}\" stroke-width=\"{:.2}\"",
210            opacity_attr("fill", style.alpha),
211            finite_or(style.stroke_width, 0.0)
212        );
213        self.push_mark("path", "band", &attrs);
214        Ok(())
215    }
216
217    /// The `<defs>` block for every pattern [`Self::pattern_url`]
218    /// registered (empty when none were) — a `<pattern>` tile per the
219    /// stripe's own cycle, rotated by `patternTransform`, a `bg`-filled
220    /// tile with a narrower `fg` stripe at its edge (#206).
221    fn pattern_defs(&self) -> String {
222        if self.patterns.is_empty() {
223            return String::new();
224        }
225        let mut defs = String::from("<defs>");
226        for (p, id) in &self.patterns {
227            let FillPattern::Stripe {
228                fg,
229                bg,
230                size_px,
231                angle_deg,
232            } = p;
233            let size = if *size_px > 0.0 { *size_px } else { 1.0 };
234            defs.push_str(&format!(
235                "<pattern id=\"{id}\" width=\"{size}\" height=\"{size}\" patternUnits=\"userSpaceOnUse\" patternTransform=\"rotate({angle_deg})\"><rect width=\"{size}\" height=\"{size}\" fill=\"{}\"/><rect width=\"{:.3}\" height=\"{size}\" fill=\"{}\"/></pattern>",
236                rgb(*bg),
237                size * 0.3,
238                rgb(*fg),
239            ));
240        }
241        defs.push_str("</defs>");
242        defs
243    }
244
245    /// Turn `data-fvalue`/`data-fx` on for the whole render
246    /// ([`GGPlot::svg_formatted_values`](crate::plot::GGPlot::svg_formatted_values)).
247    /// Default off (set once, before drawing).
248    pub(crate) fn set_formatted_values(&mut self, on: bool) {
249        self.formatted_values = on;
250    }
251
252    /// Add extra attributes to the root `<svg>` element (e.g. the
253    /// `data-domain` family from [`root_data_attrs`]). Names must be plain
254    /// attribute names; values are escaped on output.
255    pub fn set_root_attrs(&mut self, attrs: Vec<(String, String)>) {
256        self.root_attrs = attrs;
257    }
258
259    /// Append extra attributes to the root `<svg>` element, after any
260    /// already set by [`set_root_attrs`](Self::set_root_attrs) (e.g. the
261    /// `data-domain` family from [`root_data_attrs`]). Unlike
262    /// `set_root_attrs`, this does not replace what is already there.
263    /// Callers (`GGPlot::svg_attr`/`PlotGrid::svg_attr`, via
264    /// [`validate_root_attrs`]) are responsible for name validation and
265    /// collision checks; this just appends. Values are escaped on output.
266    pub fn extend_root_attrs(&mut self, attrs: Vec<(String, String)>) {
267        self.root_attrs.extend(attrs);
268    }
269
270    /// Omit the root `data-plot` attribute (composite pages).
271    pub(crate) fn without_plot_attr(&mut self) {
272        self.plot_attr = false;
273    }
274
275    /// Append pre-rendered, already-escaped SVG markup (e.g. a nested plot
276    /// fragment) to the body. Crate-internal: callers guarantee well-formedness.
277    pub(crate) fn push_raw(&mut self, markup: &str) {
278        self.body.push_str(markup);
279    }
280
281    /// The accumulated body markup (without the root element), with every
282    /// pending `group_wrap` group (#221) spliced in.
283    pub(crate) fn body(&mut self) -> &str {
284        self.flush_groups();
285        &self.body
286    }
287
288    /// Append one drawn mark: into its `group_wrap` group's buffer while a
289    /// layer's mark has one (#221), else straight onto the body.
290    fn emit(&mut self, markup: &str) {
291        let key = match (&self.mark_group, &self.mark_geom) {
292            (Some(k), Some(_)) => k,
293            _ => {
294                self.body.push_str(markup);
295                return;
296            }
297        };
298        match self
299            .groups
300            .iter_mut()
301            .find(|(n, v, _)| n == &key.0 && v == &key.1)
302        {
303            Some((_, _, content)) => content.push_str(markup),
304            None => {
305                self.group_slots.push((self.body.len(), self.groups.len()));
306                self.groups
307                    .push((key.0.clone(), key.1.clone(), markup.to_string()));
308            }
309        }
310    }
311
312    /// Splice every pending group (#221) into the body as
313    /// `<g data-<name>="<value>">…</g>` at its first mark's position. The
314    /// attribute name was validated by `Aes::group_wrap`/`resolve_mappings`
315    /// and is re-checked here (defence in depth, as for `mark_attrs`); a
316    /// group with an invalid name is spliced in unwrapped.
317    fn flush_groups(&mut self) {
318        if self.group_slots.is_empty() {
319            return;
320        }
321        let groups = std::mem::take(&mut self.groups);
322        let slots = std::mem::take(&mut self.group_slots);
323        let extra: usize = groups
324            .iter()
325            .map(|(n, v, c)| n.len() + v.len() + c.len() + 12)
326            .sum();
327        let mut out = String::with_capacity(self.body.len() + extra);
328        let mut last = 0;
329        for (off, gi) in slots {
330            out.push_str(&self.body[last..off]);
331            last = off;
332            let (name, value, content) = &groups[gi];
333            if is_valid_mark_attr_name(name) {
334                out.push_str(&format!("<g {name}=\"{}\">{content}</g>", escape(value)));
335            } else {
336                out.push_str(content);
337            }
338        }
339        out.push_str(&self.body[last..]);
340        self.body = out;
341    }
342
343    /// Wrap the accumulated body in a `<g>` carrying `attrs` (escaped) — a
344    /// `PlotGrid` cell's own `svg_attr`s (#208), which belong on that
345    /// cell's content, not the cell's own root `<svg>` (ggplot-rs's own
346    /// `root_data_attrs`/`data-panel`) or the grid's root (the grid's own
347    /// `svg_attr`s). A no-op for an empty `attrs` — unaffected output,
348    /// same as every other panel without a `svg_attr` call.
349    pub(crate) fn wrap_body_in_group(&mut self, attrs: &[(String, String)]) {
350        self.flush_groups();
351        if attrs.is_empty() {
352            return;
353        }
354        let mut open = String::from("<g");
355        for (k, v) in attrs {
356            open.push_str(&format!(" {k}=\"{}\"", escape(v)));
357        }
358        open.push('>');
359        self.body = format!("{open}{}</g>", self.body);
360    }
361
362    /// Take the warnings reported while drawing (see [`DrawBackend::warn`]).
363    pub fn take_warnings(&mut self) -> Vec<String> {
364        std::mem::take(&mut self.warnings)
365    }
366
367    /// ` class="gg-mark gg-<kind>" data-geom="<geom>"` while a layer's geom is
368    /// drawing; empty for axes, grid lines, legends and backgrounds.
369    ///
370    /// #221: the layer's `layer_svg_attr("class", …)` tokens, then the
371    /// row's `Aes::class` tokens, are appended (each re-validated, defence
372    /// in depth; duplicates written once) — still one `class` attribute.
373    fn mark_class(&self, kind: &str) -> String {
374        match &self.mark_geom {
375            Some(g) => {
376                let mut class = format!("gg-mark gg-{kind}");
377                let layer = self
378                    .layer_attrs
379                    .iter()
380                    .filter(|(n, _)| n == "class")
381                    .map(|(_, v)| v.as_str());
382                let mut seen: Vec<&str> = Vec::new();
383                for t in layer
384                    .chain(self.mark_user_class.as_deref())
385                    .flat_map(str::split_whitespace)
386                {
387                    if crate::aes::is_valid_class_token(t) && !seen.contains(&t) {
388                        seen.push(t);
389                        class.push(' ');
390                        class.push_str(t);
391                    }
392                }
393                format!(" class=\"{class}\" data-geom=\"{}\"", escape(g))
394            }
395            None => String::new(),
396        }
397    }
398
399    /// #221: ` aria-hidden="…" pointer-events="…"` from the current layer's
400    /// `layer_svg_attr`s (only while a layer draws). `aria_hidden_written`
401    /// skips the layer's `aria-hidden` when the mark already carries one
402    /// (a mark part — arrowhead/decorative — always writes `"true"`).
403    fn layer_flag_attrs(&self, aria_hidden_written: bool) -> String {
404        let mut out = String::new();
405        if self.mark_geom.is_none() {
406            return out;
407        }
408        for (name, value) in &self.layer_attrs {
409            let ok = match name.as_str() {
410                "aria-hidden" => !aria_hidden_written && matches!(value.as_str(), "true" | "false"),
411                "pointer-events" => POINTER_EVENTS_VALUES.contains(&value.as_str()),
412                _ => false,
413            };
414            if ok {
415                out.push_str(&format!(" {name}=\"{value}\""));
416            }
417        }
418        out
419    }
420
421    /// #221: the `data-*` attributes a layer's text mark carries — the
422    /// layer's `layer_svg_attr("data-…")`s, then the row's `Aes::data_attr`
423    /// ones (a row attr replaces a layer attr of the same name). Text marks
424    /// don't go through [`Self::push_mark`] (no `<title>`, no built-ins).
425    fn text_data_attrs(&self) -> String {
426        let mut pairs: Vec<(&str, &str)> = Vec::new();
427        if self.mark_geom.is_none() {
428            return String::new();
429        }
430        for (name, val) in self.layer_attrs.iter().chain(self.mark_attrs.iter()) {
431            if !is_valid_mark_attr_name(name) {
432                continue;
433            }
434            match pairs.iter_mut().find(|(n, _)| n == name) {
435                Some(existing) => existing.1 = val,
436                None => pairs.push((name, val)),
437            }
438        }
439        let mut out = String::new();
440        for (name, val) in pairs {
441            out.push_str(&format!(" {name}=\"{}\"", escape(val)));
442        }
443        out
444    }
445
446    /// Emit `<tag attrs/>`, or `<tag attrs data-…><title>tip</title></tag>`
447    /// when a tooltip / mark metadata is set (native SVG hover + host grouping).
448    ///
449    /// `kind` is the data-mark class suffix (see [`Self::mark_class`]) used
450    /// when no mark part is set. While a mark part *is* set (e.g. an
451    /// arrowhead), the part name is the effective kind instead — an
452    /// arrowhead gets `gg-mark gg-arrow`, not its parent's `gg-band`/`gg-line`.
453    fn push_mark(&mut self, tag: &str, kind: &str, attrs: &str) {
454        // Built-ins first, then user `data-*` attrs — re-validated here as
455        // defence in depth even though `geom::set_row_extras` already
456        // derives them only from validated `data_attr` mappings, because
457        // `set_mark_attrs` is a public `DrawBackend` method any caller could
458        // invoke directly. A later entry with the same name replaces an
459        // earlier one rather than duplicating it — including `mark_part`'s
460        // own `data-part`, added last, so it always wins over anything a
461        // caller supplied under that name (an element never carries the
462        // same attribute twice, which is an XML parse error).
463        let mut pairs: Vec<(String, String)> = Vec::new();
464        for (name, val) in [
465            ("data-x", &self.axis_key),
466            ("data-series", &self.series_key),
467            ("data-value", &self.value_key),
468        ] {
469            if let Some(v) = val {
470                pairs.push((name.to_string(), v.clone()));
471            }
472        }
473        // B2-4: `data-fx` only when it says something `data-x` doesn't —
474        // most marks have a plain numeric x, where the "formatted" value is
475        // the same string, and a redundant duplicate attribute is noise.
476        if let Some(fx) = &self.mark_fx {
477            if self.axis_key.as_deref() != Some(fx.as_str()) {
478                pairs.push(("data-fx".to_string(), fx.clone()));
479            }
480        }
481        if let Some(fvalue) = &self.mark_fvalue {
482            pairs.push(("data-fvalue".to_string(), fvalue.clone()));
483        }
484        // #221: the layer's own `data-*` (`layer_svg_attr`) first, so a
485        // row's `data_attr` of the same name replaces it.
486        let layer_data = self.layer_attrs.iter().filter(|_| self.mark_geom.is_some());
487        for (name, val) in layer_data.chain(self.mark_attrs.iter()) {
488            if !is_valid_mark_attr_name(name) {
489                continue;
490            }
491            match pairs.iter_mut().find(|(n, _)| n == name) {
492                Some(existing) => existing.1 = val.clone(),
493                None => pairs.push((name.clone(), val.clone())),
494            }
495        }
496        // A mark part (e.g. an arrowhead) is decorative: no `<title>`, but it
497        // still carries `data-part` plus `aria-hidden` so assistive tech
498        // skips it (the parent mark already carries the semantic tooltip).
499        // Routed through the same dedup as the other attrs.
500        if let Some(part) = &self.mark_part {
501            match pairs.iter_mut().find(|(n, _)| n == "data-part") {
502                Some(existing) => existing.1 = part.clone(),
503                None => pairs.push(("data-part".to_string(), part.clone())),
504            }
505        }
506        let mut data = String::new();
507        for (name, val) in &pairs {
508            data.push_str(&format!(" {name}=\"{}\"", escape(val)));
509        }
510        if self.mark_part.is_some() {
511            data.push_str(" aria-hidden=\"true\"");
512        }
513        data.push_str(&self.layer_flag_attrs(self.mark_part.is_some()));
514        // The class goes last so existing attribute sequences stay
515        // byte-identical. Exactly one `class` attribute is ever written here
516        // (no `data_attr` mapping can be named bare `class` — see
517        // `is_valid_mark_attr_name` — so nothing in `pairs` can collide with it).
518        let effective_kind: &str = self.mark_part.as_deref().unwrap_or(kind);
519        data.push_str(&self.mark_class(effective_kind));
520        let mark = if self.mark_part.is_some() {
521            format!("<{tag} {attrs}{data}/>")
522        } else {
523            match &self.tooltip {
524                Some(t) => format!("<{tag} {attrs}{data}><title>{}</title></{tag}>", escape(t)),
525                None => format!("<{tag} {attrs}{data}/>"),
526            }
527        };
528        self.emit(&mark);
529    }
530
531    fn root_open(&self, prefix: &str) -> String {
532        let p = &self.plot_area;
533        let (w, h) = (self.total_area.width as i64, self.total_area.height as i64);
534        let mut extra = String::new();
535        for (k, v) in &self.root_attrs {
536            extra.push_str(&format!(" {k}=\"{}\"", escape(v)));
537        }
538        let plot = if self.plot_attr {
539            format!(
540                " data-plot=\"{} {} {} {}\"",
541                num(p.x),
542                num(p.y),
543                num(p.width),
544                num(p.height),
545            )
546        } else {
547            String::new()
548        };
549        format!("<svg {prefix}width=\"{w}\" height=\"{h}\" viewBox=\"0 0 {w} {h}\"{plot}{extra}>")
550    }
551
552    /// Wrap the accumulated elements in a complete `<svg>` document. The
553    /// `data-plot` attribute records the panel (data) area in viewBox units so a
554    /// host can map screen coordinates back to data (e.g. for zoom/crosshair).
555    pub fn finish(mut self) -> String {
556        self.flush_groups();
557        let open = self.root_open("xmlns=\"http://www.w3.org/2000/svg\" ");
558        let defs = self.pattern_defs();
559        format!("{open}{defs}{}</svg>", self.body)
560    }
561
562    /// Wrap the accumulated elements in a *nested* `<svg>` positioned at
563    /// `(x, y)` in a parent SVG's user space — no `xmlns` (it inherits the
564    /// parent's namespace), so the result can be pasted into a larger SVG as-is.
565    /// `data-plot` stays in this fragment's own viewBox units.
566    pub fn finish_fragment(mut self, x: f64, y: f64) -> String {
567        self.flush_groups();
568        let open = self.root_open(&format!("x=\"{}\" y=\"{}\" ", num(x), num(y)));
569        let defs = self.pattern_defs();
570        format!("{open}{defs}{}</svg>", self.body)
571    }
572
573    /// Emit one `<polyline>` for an already-finite run of points — see
574    /// [`DrawBackend::draw_line`]'s splitting at non-finite vertices.
575    fn draw_line_run(&mut self, pts: &[(f64, f64)], style: &LineStyle) {
576        let dash = dasharray_attr(&style.linetype);
577        // `Butt` is SVG's own default: omitting the attribute keeps default
578        // output byte-identical.
579        let linecap = match style.lineend {
580            LineEnd::Butt => "",
581            LineEnd::Round => " stroke-linecap=\"round\"",
582            LineEnd::Square => " stroke-linecap=\"square\"",
583        };
584        let attrs = format!(
585            "points=\"{}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{:.2}\"{}{}{}",
586            points(pts),
587            rgb(style.color),
588            finite_or(style.width, 1.0),
589            opacity_attr("stroke", style.alpha),
590            dash,
591            linecap
592        );
593        self.push_mark("polyline", "line", &attrs);
594    }
595}
596
597/// Format a coordinate with two decimals; non-finite becomes `0` (callers
598/// drop marks with non-finite geometry before this, so this is a last resort).
599fn num(v: f64) -> String {
600    if v.is_finite() {
601        format!("{v:.2}")
602    } else {
603        "0".to_string()
604    }
605}
606
607/// ` stroke-dasharray="d,g,…"` for a linetype, or `""` for solid. Uses the
608/// sanitised [`Linetype::dash_pattern`], so a `Linetype::Custom` with NaN or
609/// negative lengths never reaches the attribute (#220).
610fn dasharray_attr(linetype: &Linetype) -> String {
611    let pattern = linetype.dash_pattern();
612    if pattern.is_empty() {
613        return String::new();
614    }
615    let s = pattern
616        .iter()
617        .flat_map(|(d, g)| [*d, *g])
618        .map(|v| format!("{v}"))
619        .collect::<Vec<_>>()
620        .join(",");
621    format!(" stroke-dasharray=\"{s}\"")
622}
623
624/// #214: `d` for [`SvgBackend::draw_polygon_rings_precise`] — one `M<x>,<y>`
625/// per ring (the first point, absolute) followed by one `l` command whose
626/// coordinate pairs are **deltas from the previous point**, SVG's implicit
627/// lineto-repeat (`l dx1,dy1 dx2,dy2 …`), each number rounded to
628/// `precision` decimals with trailing zeros trimmed. Deltas are typically
629/// far smaller than absolute screen coordinates, and the single `l` letter
630/// (vs. one `L` per point) is the other half of the size win; see
631/// [`push_num`] for the separator-omission this relies on. A ring under 3
632/// finite points is dropped, same as the absolute encoder.
633fn compact_rings_d(rings: &[Vec<(f64, f64)>], precision: u8) -> String {
634    let mut d = String::new();
635    for ring in rings {
636        let pts = finite_pts(ring);
637        if pts.len() < 3 {
638            continue;
639        }
640        d.push('M');
641        push_num(&mut d, &fmt_compact(pts[0].0, precision));
642        push_num(&mut d, &fmt_compact(pts[0].1, precision));
643        if pts.len() > 1 {
644            d.push('l');
645            let mut prev = pts[0];
646            for p in &pts[1..] {
647                push_num(&mut d, &fmt_compact(p.0 - prev.0, precision));
648                push_num(&mut d, &fmt_compact(p.1 - prev.1, precision));
649                prev = *p;
650            }
651        }
652        d.push('z');
653    }
654    d
655}
656
657/// Append `s` (a formatted number) to `d`, inserting a comma first only
658/// when one is actually needed to keep the path parseable: right after a
659/// digit, with the new number *not* itself starting with `-` (whose sign
660/// already disambiguates where the previous number ended, SVG's own
661/// "no separator needed before a negative number" rule — the "no
662/// redundant separators" #214 asks for). Right after a command letter
663/// (`M`/`l`/`z`) no separator is ever needed.
664fn push_num(d: &mut String, s: &str) {
665    let needs_sep =
666        matches!(d.chars().last(), Some(c) if c.is_ascii_digit()) && !s.starts_with('-');
667    if needs_sep {
668        d.push(',');
669    }
670    d.push_str(s);
671}
672
673/// Format `v` to `precision` decimals, then trim trailing zeros and a
674/// trailing `.` (`"5.0"` → `"5"`, `"1.20"` → `"1.2"`) — the SVG path
675/// grammar allows a bare integer anywhere a number is valid. Non-finite
676/// becomes `"0"`; `-0`-after-rounding (e.g. a tiny negative delta that
677/// rounds to zero) becomes `"0"` too, not `"-0"`.
678fn fmt_compact(v: f64, precision: u8) -> String {
679    if !v.is_finite() {
680        return "0".to_string();
681    }
682    let s = format!("{v:.*}", precision as usize);
683    let trimmed = if s.contains('.') {
684        s.trim_end_matches('0').trim_end_matches('.')
685    } else {
686        s.as_str()
687    };
688    match trimmed {
689        "" | "-" | "-0" => "0".to_string(),
690        other => other.to_string(),
691    }
692}
693
694fn finite_or(v: f64, fallback: f64) -> f64 {
695    if v.is_finite() {
696        v
697    } else {
698        fallback
699    }
700}
701
702/// ` {prefix}-opacity="{alpha:.3}"` (with its own leading space), or the
703/// empty string when `alpha` — after the usual non-finite fallback to fully
704/// opaque — formats to `"1.000"`. Full opacity is the SVG default, so
705/// omitting it keeps default output byte-identical; an explicit `alpha = 1`
706/// is indistinguishable from "not set" and also omits the no-op attribute.
707fn opacity_attr(prefix: &str, alpha: f64) -> String {
708    let a = finite_or(alpha, 1.0);
709    if format!("{a:.3}") == "1.000" {
710        String::new()
711    } else {
712        format!(" {prefix}-opacity=\"{a:.3}\"")
713    }
714}
715
716/// Root `<svg>` data attributes describing the trained position scales, for
717/// hosts that map screen coordinates back to data (zoom, crosshair, brushing):
718///
719/// - `data-xdomain="x0 x1"` / `data-ydomain="y0 y1"` — the data values at the
720///   panel's left/right (bottom/top) edges, i.e. the trained limits *after*
721///   expansion, for a continuous (numeric or date-time, epoch seconds) axis.
722///   Values are in the scale's transformed space (e.g. log10 units for
723///   `scale_x_log10`).
724/// - `data-domain="x0 x1 y0 y1"` — both of the above, emitted only when both
725///   axes are continuous.
726/// - `data-xlevels` / `data-ylevels` — a JSON array of the level labels for a
727///   discrete axis, in axis order.
728/// - `data-flip="true"` under `coord_flip` (x is then drawn vertically).
729///
730/// The `x`/`y` names refer to the x/y *aesthetics*. Omitted entirely for
731/// plots with free facet scales (each panel has its own domain).
732pub fn root_data_attrs(built: &crate::build::BuiltPlot) -> Vec<(String, String)> {
733    use crate::aes::Aesthetic;
734    let mut out = Vec::new();
735    if !built.panel_scales.is_empty() {
736        return out;
737    }
738    let axis = |aes: &Aesthetic| -> (Option<(f64, f64)>, Option<String>) {
739        match built.scales.get(aes) {
740            Some(s) if s.is_discrete() => {
741                let labels: Vec<String> = s
742                    .breaks()
743                    .into_iter()
744                    .map(|(_, l)| json_string(&l))
745                    .collect();
746                (None, Some(format!("[{}]", labels.join(","))))
747            }
748            Some(s) => (s.expanded_domain(), None),
749            None => (None, None),
750        }
751    };
752    let (xd, xl) = axis(&Aesthetic::X);
753    let (yd, yl) = axis(&Aesthetic::Y);
754    if let (Some((x0, x1)), Some((y0, y1))) = (xd, yd) {
755        out.push((
756            "data-domain".into(),
757            format!("{} {} {} {}", g(x0), g(x1), g(y0), g(y1)),
758        ));
759    }
760    if let Some((a, b)) = xd {
761        out.push(("data-xdomain".into(), format!("{} {}", g(a), g(b))));
762    }
763    if let Some((a, b)) = yd {
764        out.push(("data-ydomain".into(), format!("{} {}", g(a), g(b))));
765    }
766    if let Some(l) = xl {
767        out.push(("data-xlevels".into(), l));
768    }
769    if let Some(l) = yl {
770        out.push(("data-ylevels".into(), l));
771    }
772    if built.coord.is_flipped() {
773        out.push(("data-flip".into(), "true".into()));
774    }
775    out
776}
777
778/// Shortest round-trip formatting of a finite number (domains are filtered to
779/// finite values before this is called).
780fn g(v: f64) -> String {
781    format!("{v}")
782}
783
784/// Minimal JSON string literal (quotes, backslashes and control characters
785/// escaped); the result is attribute-escaped again on output.
786fn json_string(s: &str) -> String {
787    let mut out = String::with_capacity(s.len() + 2);
788    out.push('"');
789    for c in s.chars() {
790        match c {
791            '"' => out.push_str("\\\""),
792            '\\' => out.push_str("\\\\"),
793            '\n' => out.push_str("\\n"),
794            '\r' => out.push_str("\\r"),
795            '\t' => out.push_str("\\t"),
796            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
797            c => out.push(c),
798        }
799    }
800    out.push('"');
801    out
802}
803
804/// Allow-listed root-level attribute names for `GGPlot::svg_attr`/
805/// `PlotGrid::svg_attr`: the fixed names `role`, `id`, `class`, `lang`, or
806/// `data-*`/`aria-*` with the same charset-restricted suffix `data_attr`
807/// uses (`^[a-z0-9][a-z0-9-]*$`, excluding the reserved `part`/`geom`
808/// suffixes — irrelevant at the root, but no reason to special-case them
809/// out). Anything else is rejected.
810fn is_allowed_root_attr_name(name: &str) -> bool {
811    matches!(name, "role" | "id" | "class" | "lang")
812        || name
813            .strip_prefix("data-")
814            .is_some_and(crate::aes::is_valid_data_attr_name)
815        || name
816            .strip_prefix("aria-")
817            .is_some_and(crate::aes::is_valid_data_attr_name)
818}
819
820/// Validate and filter a caller's requested root `<svg>` attributes
821/// (`GGPlot::svg_attr`/`PlotGrid::svg_attr`), checked centrally here and
822/// used by both callers rather than re-implemented per type. A name outside
823/// [`is_allowed_root_attr_name`]'s allow-list, or one already present in
824/// `existing` (what ggplot-rs itself is about to write to the same root —
825/// e.g. `data-plot`/`data-domain`/`data-grid`, or `data-warnings` when
826/// `svg_warnings_attr` is also on), is dropped with a warning instead of
827/// silently overwriting or duplicating it. `label` names the caller
828/// (`"plot"`/`"grid"`) in the warning text.
829pub(crate) fn validate_root_attrs(
830    requested: &[(String, String)],
831    existing: &[(String, String)],
832    label: &str,
833    warnings: &mut Vec<String>,
834) -> Vec<(String, String)> {
835    let built_in: Vec<&str> = existing.iter().map(|(k, _)| k.as_str()).collect();
836    let mut used: Vec<&str> = built_in.clone();
837    let mut out = Vec::new();
838    for (name, value) in requested {
839        if !is_allowed_root_attr_name(name) {
840            warnings.push(format!(
841                "{label}: svg_attr(\"{name}\") is not on the allow-list (data-*, aria-*, role, id, class, lang) — ignored"
842            ));
843            continue;
844        }
845        if used.contains(&name.as_str()) {
846            // Review PR#141 nit #9: distinguish an actual collision with
847            // something ggplot-rs itself writes (`data-plot`, `data-grid`,
848            // …) from a *second* `svg_attr` call for the same name — the
849            // latter is the caller's own earlier value, not ggplot-rs's.
850            if built_in.contains(&name.as_str()) {
851                warnings.push(format!(
852                    "{label}: svg_attr(\"{name}\") collides with an attribute ggplot-rs already writes to the root — ignored"
853                ));
854            } else {
855                warnings.push(format!(
856                    "{label}: svg_attr(\"{name}\") was already set by an earlier svg_attr call — ignored"
857                ));
858            }
859            continue;
860        }
861        used.push(name.as_str());
862        out.push((name.clone(), value.clone()));
863    }
864    out
865}
866
867/// `["warning one", "warning two"]` — a minimal hand-rolled JSON array of
868/// strings for `svg_warnings_attr` (no serde dependency, kept out of the
869/// `sf`-feature dependency tree — see [`json_string`]).
870pub(crate) fn warnings_json(warnings: &[String]) -> String {
871    let items: Vec<String> = warnings.iter().map(|w| json_string(w)).collect();
872    format!("[{}]", items.join(","))
873}
874
875/// Defence-in-depth gate for `push_mark`'s `mark_attrs`: `^data-[a-z0-9][a-z0-9-]*$`.
876/// `geom::set_row_extras` only ever supplies already-validated names, but
877/// `set_mark_attrs` is a public `DrawBackend` method any caller (a custom
878/// `Geom` impl, or misuse from outside the crate) could invoke directly with
879/// an arbitrary string, so this is checked again right before it reaches
880/// the wire — never trust a single validation layer for attribute-name
881/// injection.
882fn is_valid_mark_attr_name(name: &str) -> bool {
883    match name.strip_prefix("data-") {
884        Some(suffix) => crate::aes::is_valid_data_attr_name(suffix),
885        None => false,
886    }
887}
888
889/// `pointer-events` keyword values accepted by
890/// [`validate_layer_svg_attr`] (#221) — SVG 1.1's full list.
891const POINTER_EVENTS_VALUES: &[&str] = &[
892    "auto",
893    "none",
894    "visiblePainted",
895    "visibleFill",
896    "visibleStroke",
897    "visible",
898    "painted",
899    "fill",
900    "stroke",
901    "all",
902    "bounding-box",
903];
904
905/// Validate one `GGPlot::layer_svg_attr(name, value)` (#221). The
906/// allow-list: `class` (space-separated tokens, each
907/// `[A-Za-z][A-Za-z0-9_-]*`; invalid tokens are dropped, the rest kept),
908/// `aria-hidden` (`"true"`/`"false"`), `pointer-events` (an SVG keyword,
909/// e.g. `"none"`), and `data-*` (same name rules as `Aes::data_attr`).
910/// Everything else — notably `style`, `on*` handlers, `id` — is rejected.
911/// Returns the attribute to keep (if any) and pushes a warning for anything
912/// dropped.
913pub(crate) fn validate_layer_svg_attr(
914    name: &str,
915    value: &str,
916    warnings: &mut Vec<String>,
917) -> Option<(String, String)> {
918    let keep = |v: &str| Some((name.to_string(), v.to_string()));
919    match name {
920        "class" => {
921            let (ok, bad) = crate::aes::split_class_tokens(value);
922            if !bad.is_empty() {
923                warnings.push(format!(
924                    "layer_svg_attr(\"class\"): invalid class token(s) {bad:?} (must match [A-Za-z][A-Za-z0-9_-]*) — dropped"
925                ));
926            }
927            if ok.is_empty() {
928                None
929            } else {
930                keep(&ok.join(" "))
931            }
932        }
933        "aria-hidden" if matches!(value, "true" | "false") => keep(value),
934        "pointer-events" if POINTER_EVENTS_VALUES.contains(&value) => keep(value),
935        "aria-hidden" | "pointer-events" => {
936            warnings.push(format!(
937                "layer_svg_attr(\"{name}\"): value {value:?} is not allowed — ignored"
938            ));
939            None
940        }
941        _ if is_valid_mark_attr_name(name) => keep(value),
942        _ => {
943            warnings.push(format!(
944                "layer_svg_attr(\"{name}\") is not on the allow-list (class, aria-hidden, pointer-events, data-*) — ignored"
945            ));
946            None
947        }
948    }
949}
950
951fn rgb((r, g, b): (u8, u8, u8)) -> String {
952    format!("#{r:02X}{g:02X}{b:02X}")
953}
954
955/// Escape text for use in SVG element content *and* quoted attribute values.
956/// Quotes must be escaped too: data values land in `data-x="…"`, and the SVG is
957/// routinely inlined into HTML, so an unescaped `"` would let data inject
958/// attributes (e.g. event handlers). Characters that are not legal in XML 1.0
959/// (C0 controls other than tab/LF/CR) are dropped so the document stays
960/// well-formed.
961fn escape(s: &str) -> String {
962    let mut out = String::with_capacity(s.len());
963    for c in s.chars() {
964        match c {
965            '&' => out.push_str("&amp;"),
966            '<' => out.push_str("&lt;"),
967            '>' => out.push_str("&gt;"),
968            '"' => out.push_str("&quot;"),
969            '\'' => out.push_str("&#39;"),
970            '\t' | '\n' | '\r' => out.push(c),
971            c if (c as u32) < 0x20 || c == '\u{FFFE}' || c == '\u{FFFF}' => {}
972            c => out.push(c),
973        }
974    }
975    out
976}
977
978fn points(pts: &[(f64, f64)]) -> String {
979    pts.iter()
980        .map(|(x, y)| format!("{x:.2},{y:.2}"))
981        .collect::<Vec<_>>()
982        .join(" ")
983}
984
985fn finite_pts(pts: &[(f64, f64)]) -> Vec<(f64, f64)> {
986    pts.iter()
987        .copied()
988        .filter(|(x, y)| x.is_finite() && y.is_finite())
989        .collect()
990}
991
992/// Split `pts` into maximal runs of consecutive finite vertices, dropping
993/// any run shorter than 2 points. Matches ggplot2's NA-break handling for
994/// lines: a non-finite vertex breaks the line instead of being silently
995/// skipped, which would otherwise visually bridge across the gap — but a
996/// single remaining observation isn't a line segment either (ggplot2 drops
997/// a one-point path piece the same way), so it draws nothing rather than
998/// an invisible 1-point `<polyline>` that would still carry a `<title>`
999/// and hover attributes.
1000fn finite_runs(pts: &[(f64, f64)]) -> Vec<Vec<(f64, f64)>> {
1001    let mut runs = Vec::new();
1002    let mut cur: Vec<(f64, f64)> = Vec::new();
1003    for &(x, y) in pts {
1004        if x.is_finite() && y.is_finite() {
1005            cur.push((x, y));
1006        } else if !cur.is_empty() {
1007            if cur.len() >= 2 {
1008                runs.push(std::mem::take(&mut cur));
1009            } else {
1010                cur.clear();
1011            }
1012        }
1013    }
1014    if cur.len() >= 2 {
1015        runs.push(cur);
1016    }
1017    runs
1018}
1019
1020impl DrawBackend for SvgBackend {
1021    fn plot_area(&self) -> Rect {
1022        self.plot_area.clone()
1023    }
1024    fn total_area(&self) -> Rect {
1025        self.total_area.clone()
1026    }
1027
1028    fn set_tooltip(&mut self, tooltip: Option<String>) {
1029        self.tooltip = tooltip;
1030    }
1031
1032    fn set_mark_axis(&mut self, key: Option<String>) {
1033        self.axis_key = key;
1034    }
1035
1036    fn set_mark_series(&mut self, series: Option<String>) {
1037        self.series_key = series;
1038    }
1039
1040    fn set_mark_value(&mut self, value: Option<String>) {
1041        self.value_key = value;
1042    }
1043
1044    fn set_mark_geom(&mut self, geom: Option<&str>) {
1045        self.mark_geom = geom.map(str::to_string);
1046    }
1047
1048    fn warn(&mut self, message: String) {
1049        self.warnings.push(message);
1050    }
1051
1052    fn set_mark_part(&mut self, part: Option<&str>) {
1053        self.mark_part = part.map(|s| s.to_string());
1054    }
1055
1056    fn set_mark_attrs(&mut self, attrs: Vec<(String, String)>) {
1057        self.mark_attrs = attrs;
1058    }
1059
1060    fn wants_formatted_values(&self) -> bool {
1061        self.formatted_values
1062    }
1063
1064    fn set_mark_fvalue(&mut self, value: Option<String>) {
1065        self.mark_fvalue = value;
1066    }
1067
1068    fn set_mark_fx(&mut self, value: Option<String>) {
1069        self.mark_fx = value;
1070    }
1071
1072    fn set_mark_class(&mut self, class: Option<String>) {
1073        self.mark_user_class = class;
1074    }
1075
1076    fn set_mark_group(&mut self, group: Option<(String, String)>) {
1077        self.mark_group = group;
1078    }
1079
1080    fn set_layer_attrs(&mut self, attrs: Vec<(String, String)>) {
1081        self.layer_attrs = attrs;
1082    }
1083
1084    fn draw_circle(
1085        &mut self,
1086        (cx, cy): (f64, f64),
1087        radius: f64,
1088        style: &PointStyle,
1089    ) -> Result<(), RenderError> {
1090        if !(cx.is_finite() && cy.is_finite() && radius.is_finite()) {
1091            return Ok(());
1092        }
1093        let attrs = format!(
1094            "cx=\"{cx:.2}\" cy=\"{cy:.2}\" r=\"{:.2}\" fill=\"{}\"{}",
1095            radius.max(0.0),
1096            rgb(style.color),
1097            opacity_attr("fill", style.alpha)
1098        );
1099        self.push_mark("circle", "point", &attrs);
1100        Ok(())
1101    }
1102
1103    /// Native shapes: filled polygons for square/triangle/diamond, a single
1104    /// stroked `<path>` for the `+` / `×` glyphs (so each point stays one
1105    /// hoverable mark carrying its `data-*` attributes).
1106    fn draw_shape(
1107        &mut self,
1108        (cx, cy): (f64, f64),
1109        radius: f64,
1110        style: &PointStyle,
1111    ) -> Result<(), RenderError> {
1112        if !(cx.is_finite() && cy.is_finite() && radius.is_finite()) {
1113            return Ok(());
1114        }
1115        let r = radius.max(0.0);
1116        let color = rgb(style.color);
1117        let fill_opacity = opacity_attr("fill", style.alpha);
1118        let stroke_opacity = opacity_attr("stroke", style.alpha);
1119        let poly = |pts: &[(f64, f64)]| {
1120            if style.filled {
1121                format!("points=\"{}\" fill=\"{color}\"{fill_opacity}", points(pts))
1122            } else {
1123                format!(
1124                    "points=\"{}\" fill=\"none\" stroke=\"{color}\"{stroke_opacity}",
1125                    points(pts)
1126                )
1127            }
1128        };
1129        match style.shape {
1130            PointShape::Circle => return self.draw_circle((cx, cy), radius, style),
1131            PointShape::Square => {
1132                let a = poly(&[
1133                    (cx - r, cy - r),
1134                    (cx + r, cy - r),
1135                    (cx + r, cy + r),
1136                    (cx - r, cy + r),
1137                ]);
1138                self.push_mark("polygon", "point", &a);
1139            }
1140            PointShape::Triangle => {
1141                let a = poly(&[(cx, cy - r), (cx + r, cy + r), (cx - r, cy + r)]);
1142                self.push_mark("polygon", "point", &a);
1143            }
1144            PointShape::Diamond => {
1145                let a = poly(&[(cx, cy - r), (cx + r, cy), (cx, cy + r), (cx - r, cy)]);
1146                self.push_mark("polygon", "point", &a);
1147            }
1148            PointShape::Plus | PointShape::Cross => {
1149                let d = if style.shape == PointShape::Plus {
1150                    format!(
1151                        "M{:.2} {cy:.2}H{:.2}M{cx:.2} {:.2}V{:.2}",
1152                        cx - r,
1153                        cx + r,
1154                        cy - r,
1155                        cy + r
1156                    )
1157                } else {
1158                    format!(
1159                        "M{:.2} {:.2}L{:.2} {:.2}M{:.2} {:.2}L{:.2} {:.2}",
1160                        cx - r,
1161                        cy - r,
1162                        cx + r,
1163                        cy + r,
1164                        cx - r,
1165                        cy + r,
1166                        cx + r,
1167                        cy - r
1168                    )
1169                };
1170                let a = format!(
1171                    "d=\"{d}\" fill=\"none\" stroke=\"{color}\" stroke-width=\"{:.2}\"{stroke_opacity}",
1172                    (r / 2.5).clamp(1.0, 3.0)
1173                );
1174                self.push_mark("path", "point", &a);
1175            }
1176        }
1177        Ok(())
1178    }
1179
1180    fn draw_line(&mut self, pts: &[(f64, f64)], style: &LineStyle) -> Result<(), RenderError> {
1181        // Split at non-finite vertices instead of silently dropping them:
1182        // dropping-and-joining would visually bridge the gap, but ggplot2
1183        // treats a non-finite (NA) vertex as a break in the line (see
1184        // `finite_runs`). Each run becomes its own `<polyline>` mark, with
1185        // the same style and the same data-x/series/value/part attrs.
1186        for run in finite_runs(pts) {
1187            self.draw_line_run(&run, style);
1188        }
1189        Ok(())
1190    }
1191
1192    /// Emit a native `<path d="M.. Q..">` quadratic Bézier (one real curve
1193    /// instead of a flattened polyline). Non-finite input draws nothing.
1194    fn draw_quadratic(
1195        &mut self,
1196        p0: (f64, f64),
1197        ctrl: (f64, f64),
1198        p1: (f64, f64),
1199        style: &LineStyle,
1200    ) -> Result<(), RenderError> {
1201        if !(p0.0.is_finite()
1202            && p0.1.is_finite()
1203            && ctrl.0.is_finite()
1204            && ctrl.1.is_finite()
1205            && p1.0.is_finite()
1206            && p1.1.is_finite())
1207        {
1208            return Ok(());
1209        }
1210        let dash = dasharray_attr(&style.linetype);
1211        let linecap = match style.lineend {
1212            LineEnd::Butt => "",
1213            LineEnd::Round => " stroke-linecap=\"round\"",
1214            LineEnd::Square => " stroke-linecap=\"square\"",
1215        };
1216        let d = format!(
1217            "M{:.2} {:.2} Q{:.2} {:.2} {:.2} {:.2}",
1218            p0.0, p0.1, ctrl.0, ctrl.1, p1.0, p1.1
1219        );
1220        let attrs = format!(
1221            "d=\"{d}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{:.2}\"{}{}{}",
1222            rgb(style.color),
1223            finite_or(style.width, 1.0),
1224            opacity_attr("stroke", style.alpha),
1225            dash,
1226            linecap
1227        );
1228        self.push_mark("path", "line", &attrs);
1229        Ok(())
1230    }
1231
1232    fn draw_rect(
1233        &mut self,
1234        top_left: (f64, f64),
1235        bottom_right: (f64, f64),
1236        style: &RectStyle,
1237    ) -> Result<(), RenderError> {
1238        let fill = style.fill.map(rgb).unwrap_or_else(|| "none".into());
1239        self.rect_markup(top_left, bottom_right, &fill, style)
1240    }
1241
1242    /// #206: same markup [`draw_rect`](Self::draw_rect) builds, filled
1243    /// with `pattern`'s registered `url(#…)` instead of `style.fill`.
1244    fn draw_rect_pattern(
1245        &mut self,
1246        top_left: (f64, f64),
1247        bottom_right: (f64, f64),
1248        pattern: &FillPattern,
1249        style: &RectStyle,
1250    ) -> Result<(), RenderError> {
1251        let fill = self.pattern_url(pattern);
1252        self.rect_markup(top_left, bottom_right, &fill, style)
1253    }
1254
1255    fn draw_polygon(&mut self, pts: &[(f64, f64)], style: &RectStyle) -> Result<(), RenderError> {
1256        let fill = style.fill.map(rgb).unwrap_or_else(|| "none".into());
1257        self.polygon_markup(pts, &fill, style)
1258    }
1259
1260    /// #206: same markup [`draw_polygon`](Self::draw_polygon) builds,
1261    /// filled with `pattern`'s registered `url(#…)` instead of `style.fill`.
1262    fn draw_polygon_pattern(
1263        &mut self,
1264        pts: &[(f64, f64)],
1265        pattern: &FillPattern,
1266        style: &RectStyle,
1267    ) -> Result<(), RenderError> {
1268        let fill = self.pattern_url(pattern);
1269        self.polygon_markup(pts, &fill, style)
1270    }
1271
1272    /// One `<path>`, every ring a subpath (`M…Z`), `fill-rule="evenodd"` so
1273    /// holes (rings after the first) are cut out of the fill — SVG's native
1274    /// equivalent of the even-odd rasteriser the pixel/plotters backends run
1275    /// (#178). A ring with fewer than 3 finite points is dropped; the whole
1276    /// shape draws nothing when every ring is.
1277    fn draw_polygon_rings(
1278        &mut self,
1279        rings: &[Vec<(f64, f64)>],
1280        style: &RectStyle,
1281    ) -> Result<(), RenderError> {
1282        let fill = style.fill.map(rgb).unwrap_or_else(|| "none".into());
1283        self.polygon_rings_markup(rings, &fill, style)
1284    }
1285
1286    /// #206: same markup [`draw_polygon_rings`](Self::draw_polygon_rings)
1287    /// builds (holes cut out under the same even-odd rule), filled with
1288    /// `pattern`'s registered `url(#…)` instead of `style.fill`.
1289    fn draw_polygon_rings_pattern(
1290        &mut self,
1291        rings: &[Vec<(f64, f64)>],
1292        pattern: &FillPattern,
1293        style: &RectStyle,
1294    ) -> Result<(), RenderError> {
1295        let fill = self.pattern_url(pattern);
1296        self.polygon_rings_markup(rings, &fill, style)
1297    }
1298
1299    /// #214: with `precision` set, writes a compact `d` (absolute `M` per
1300    /// ring, then one `l` with implicit-repeat relative coordinate pairs,
1301    /// rounded to `precision` decimals) instead of the one-`L`-per-point
1302    /// absolute encoding [`Self::polygon_rings_markup`] builds. `None`
1303    /// falls back to the trait default (today's encoding, unchanged).
1304    fn draw_polygon_rings_precise(
1305        &mut self,
1306        rings: &[Vec<(f64, f64)>],
1307        pattern: Option<&FillPattern>,
1308        precision: Option<u8>,
1309        style: &RectStyle,
1310    ) -> Result<(), RenderError> {
1311        let Some(precision) = precision else {
1312            return match pattern {
1313                Some(p) => self.draw_polygon_rings_pattern(rings, p, style),
1314                None => self.draw_polygon_rings(rings, style),
1315            };
1316        };
1317        let d = compact_rings_d(rings, precision);
1318        if d.is_empty() {
1319            return Ok(());
1320        }
1321        let fill = match pattern {
1322            Some(p) => self.pattern_url(p),
1323            None => style.fill.map(rgb).unwrap_or_else(|| "none".into()),
1324        };
1325        let stroke = style.stroke.map(rgb).unwrap_or_else(|| "none".into());
1326        let attrs = format!(
1327            "d=\"{d}\" fill-rule=\"evenodd\" fill=\"{fill}\"{} stroke=\"{stroke}\" stroke-width=\"{:.2}\"",
1328            opacity_attr("fill", style.alpha),
1329            finite_or(style.stroke_width, 0.0)
1330        );
1331        self.push_mark("path", "band", &attrs);
1332        Ok(())
1333    }
1334
1335    fn draw_text(
1336        &mut self,
1337        text: &str,
1338        pos: (f64, f64),
1339        style: &TextStyle,
1340    ) -> Result<(), RenderError> {
1341        self.draw_text_with_title(text, pos, style, None)
1342    }
1343
1344    /// #159: with `title`, wraps the `<text>` in a `<title>` child
1345    /// carrying the full (escaped) label — e.g. a legend key truncated
1346    /// with an ellipsis to fit a vertical multi-column grid.
1347    fn draw_text_with_title(
1348        &mut self,
1349        text: &str,
1350        (x, y): (f64, f64),
1351        style: &TextStyle,
1352        title: Option<&str>,
1353    ) -> Result<(), RenderError> {
1354        if !(x.is_finite() && y.is_finite()) {
1355            return Ok(());
1356        }
1357        let anchor = match style.anchor {
1358            TextAnchor::Start => "start",
1359            TextAnchor::Middle => "middle",
1360            TextAnchor::End => "end",
1361        };
1362        let family = escape(style.family.as_deref().unwrap_or("sans-serif"));
1363        let weight = if style.face == FontFace::Bold {
1364            " font-weight=\"bold\""
1365        } else {
1366            ""
1367        };
1368        let fstyle = if style.face == FontFace::Italic {
1369            " font-style=\"italic\""
1370        } else {
1371            ""
1372        };
1373        let angle = finite_or(style.angle, 0.0);
1374        let transform = if angle.abs() > 0.01 {
1375            format!(" transform=\"rotate({angle:.1} {x:.2} {y:.2})\"")
1376        } else {
1377            String::new()
1378        };
1379        let class = format!(
1380            "{}{}{}",
1381            self.text_data_attrs(),
1382            self.layer_flag_attrs(false),
1383            self.mark_class("text")
1384        );
1385        let title_tag = match title {
1386            Some(t) => format!("<title>{}</title>", escape(t)),
1387            None => String::new(),
1388        };
1389        let markup = format!(
1390            "<text x=\"{x:.2}\" y=\"{y:.2}\" font-size=\"{:.2}\" text-anchor=\"{anchor}\" \
1391             dominant-baseline=\"middle\" font-family=\"{family}\"{weight}{fstyle} fill=\"{}\"{transform}{class}>{title_tag}{}</text>",
1392            finite_or(style.size, 12.0),
1393            rgb(style.color),
1394            escape(text)
1395        );
1396        self.emit(&markup);
1397        Ok(())
1398    }
1399
1400    /// #196: each linked run becomes `<a href="…" target="_blank"
1401    /// rel="noopener"><tspan text-decoration="underline">…</tspan></a>`
1402    /// (`rel="noopener"` so the opened tab can't reach back via
1403    /// `window.opener`); a plain run is a bare `<tspan>`. All runs sit
1404    /// inside one `<text>`, so `style.anchor` aligns their combined width
1405    /// exactly as it would a single run's.
1406    fn draw_text_runs(
1407        &mut self,
1408        runs: &[(&str, Option<&str>)],
1409        (x, y): (f64, f64),
1410        style: &TextStyle,
1411    ) -> Result<(), RenderError> {
1412        if !(x.is_finite() && y.is_finite()) {
1413            return Ok(());
1414        }
1415        let anchor = match style.anchor {
1416            TextAnchor::Start => "start",
1417            TextAnchor::Middle => "middle",
1418            TextAnchor::End => "end",
1419        };
1420        let family = escape(style.family.as_deref().unwrap_or("sans-serif"));
1421        let weight = if style.face == FontFace::Bold {
1422            " font-weight=\"bold\""
1423        } else {
1424            ""
1425        };
1426        let fstyle = if style.face == FontFace::Italic {
1427            " font-style=\"italic\""
1428        } else {
1429            ""
1430        };
1431        let angle = finite_or(style.angle, 0.0);
1432        let transform = if angle.abs() > 0.01 {
1433            format!(" transform=\"rotate({angle:.1} {x:.2} {y:.2})\"")
1434        } else {
1435            String::new()
1436        };
1437        let class = format!(
1438            "{}{}{}",
1439            self.text_data_attrs(),
1440            self.layer_flag_attrs(false),
1441            self.mark_class("text")
1442        );
1443        let mut inner = String::new();
1444        for (text, href) in runs {
1445            match href {
1446                Some(u) => inner.push_str(&format!(
1447                    "<a href=\"{}\" target=\"_blank\" rel=\"noopener\"><tspan text-decoration=\"underline\">{}</tspan></a>",
1448                    escape(u),
1449                    escape(text)
1450                )),
1451                None => inner.push_str(&format!("<tspan>{}</tspan>", escape(text))),
1452            }
1453        }
1454        let markup = format!(
1455            "<text x=\"{x:.2}\" y=\"{y:.2}\" font-size=\"{:.2}\" text-anchor=\"{anchor}\" \
1456             dominant-baseline=\"middle\" font-family=\"{family}\"{weight}{fstyle} fill=\"{}\"{transform}{class}>{inner}</text>",
1457            finite_or(style.size, 12.0),
1458            rgb(style.color),
1459        );
1460        self.emit(&markup);
1461        Ok(())
1462    }
1463}
1464
1465#[cfg(test)]
1466mod tests {
1467    use super::*;
1468    use crate::render::Rect;
1469
1470    /// #221: the backend re-checks everything callers hand it directly
1471    /// through the public `DrawBackend` setters (defence in depth).
1472    #[test]
1473    fn issue221_backend_rechecks_class_group_and_layer_attrs() {
1474        let mut b = backend();
1475        b.set_mark_geom(Some("point"));
1476        b.set_mark_class(Some("ok \"bad 1x ok".into()));
1477        b.set_layer_attrs(vec![
1478            ("aria-hidden".into(), "maybe".into()),
1479            ("pointer-events".into(), "none\" onload=\"x".into()),
1480            ("style".into(), "fill:red".into()),
1481            ("class".into(), "lay".into()),
1482        ]);
1483        b.set_mark_group(Some(("onclick".into(), "x".into())));
1484        b.draw_circle((1.0, 1.0), 1.0, &PointStyle::default())
1485            .unwrap();
1486        b.set_mark_group(Some(("data-of".into(), "n".into())));
1487        let runs = [("a", None), ("b", Some("https://e.x"))];
1488        b.draw_text_runs(&runs, (5.0, 5.0), &TextStyle::default())
1489            .unwrap();
1490        b.set_mark_group(None);
1491        b.set_mark_geom(None);
1492        let body = b.body().to_string();
1493        assert!(
1494            body.contains(r#"class="gg-mark gg-point lay ok""#),
1495            "{body}"
1496        );
1497        assert!(!body.contains("bad") && !body.contains("1x"), "{body}");
1498        assert!(
1499            !body.contains("aria-hidden") && !body.contains("onload"),
1500            "{body}"
1501        );
1502        assert!(
1503            !body.contains("style=") && !body.contains("onclick"),
1504            "{body}"
1505        );
1506        assert!(body.contains(r#"<g data-of="n"><text"#), "{body}");
1507        assert!(body.contains("gg-text lay ok"), "{body}");
1508        // A later finish() has nothing left to splice.
1509        assert!(b.finish().contains(r#"<g data-of="n">"#));
1510    }
1511
1512    fn backend() -> SvgBackend {
1513        SvgBackend::new(
1514            100,
1515            100,
1516            Rect {
1517                x: 0.0,
1518                y: 0.0,
1519                width: 100.0,
1520                height: 100.0,
1521            },
1522        )
1523    }
1524
1525    #[test]
1526    fn draw_quadratic_emits_a_path_with_m_and_q() {
1527        let mut b = backend();
1528        b.draw_quadratic((0.0, 0.0), (10.0, 20.0), (20.0, 0.0), &LineStyle::default())
1529            .unwrap();
1530        let svg = b.finish();
1531        assert!(svg.contains("<path"));
1532        assert!(svg.contains("d=\"M0.00 0.00 Q10.00 20.00 20.00 0.00\""));
1533        assert!(!svg.contains("NaN"));
1534        assert!(!svg.contains("inf"));
1535    }
1536
1537    #[test]
1538    fn draw_quadratic_drops_non_finite_input() {
1539        let mut b = backend();
1540        b.draw_quadratic(
1541            (f64::NAN, 0.0),
1542            (10.0, 20.0),
1543            (20.0, 0.0),
1544            &LineStyle::default(),
1545        )
1546        .unwrap();
1547        b.draw_quadratic(
1548            (0.0, 0.0),
1549            (f64::INFINITY, 20.0),
1550            (20.0, 0.0),
1551            &LineStyle::default(),
1552        )
1553        .unwrap();
1554        let svg = b.finish();
1555        assert!(!svg.contains("<path"));
1556    }
1557
1558    #[test]
1559    fn draw_line_omits_linecap_by_default_but_writes_it_when_set() {
1560        let mut b = backend();
1561        b.draw_line(&[(0.0, 0.0), (10.0, 10.0)], &LineStyle::default())
1562            .unwrap();
1563        let svg = b.finish();
1564        assert!(!svg.contains("stroke-linecap"));
1565
1566        let mut b2 = backend();
1567        let style = LineStyle {
1568            lineend: LineEnd::Round,
1569            ..Default::default()
1570        };
1571        b2.draw_line(&[(0.0, 0.0), (10.0, 10.0)], &style).unwrap();
1572        let svg2 = b2.finish();
1573        assert!(svg2.contains("stroke-linecap=\"round\""));
1574    }
1575
1576    #[test]
1577    fn square_linecap_is_written_on_both_draw_line_and_draw_quadratic() {
1578        let style = LineStyle {
1579            lineend: LineEnd::Square,
1580            ..Default::default()
1581        };
1582        let mut b = backend();
1583        b.draw_line(&[(0.0, 0.0), (10.0, 10.0)], &style).unwrap();
1584        assert!(b.finish().contains("stroke-linecap=\"square\""));
1585
1586        let mut b2 = backend();
1587        b2.draw_quadratic((0.0, 0.0), (5.0, 10.0), (10.0, 0.0), &style)
1588            .unwrap();
1589        assert!(b2.finish().contains("stroke-linecap=\"square\""));
1590    }
1591
1592    /// `push_mark`'s defence-in-depth gate: even if an invalid name reaches
1593    /// `set_mark_attrs` directly (bypassing `Aes::data_attr`'s own
1594    /// validation — `set_mark_attrs` is a public `DrawBackend` method any
1595    /// caller could invoke), it's dropped before it reaches the wire.
1596    #[test]
1597    fn set_mark_attrs_defence_in_depth_drops_invalid_names() {
1598        let mut b = backend();
1599        b.set_mark_attrs(vec![
1600            ("not-data-prefixed".to_string(), "x".to_string()),
1601            ("data-".to_string(), "x".to_string()), // empty suffix
1602            ("data-Upper".to_string(), "x".to_string()), // uppercase
1603            ("data-ok".to_string(), "valid".to_string()), // the one legitimate entry
1604        ]);
1605        b.draw_circle((1.0, 1.0), 1.0, &PointStyle::default())
1606            .unwrap();
1607        let svg = b.finish();
1608        assert!(!svg.contains("not-data-prefixed"));
1609        assert!(!svg.contains("data-Upper"));
1610        assert!(!svg.contains("data-=\""));
1611        assert!(svg.contains("data-ok=\"valid\""));
1612    }
1613
1614    // #206: pattern fills.
1615
1616    fn stripe() -> FillPattern {
1617        FillPattern::Stripe {
1618            fg: (10, 20, 30),
1619            bg: (200, 210, 220),
1620            size_px: 4.0,
1621            angle_deg: 45.0,
1622        }
1623    }
1624
1625    fn pattern_id(svg: &str) -> String {
1626        let i = svg.find("<pattern id=\"").unwrap() + "<pattern id=\"".len();
1627        svg[i..i + svg[i..].find('"').unwrap()].to_string()
1628    }
1629
1630    #[test]
1631    fn a_pattern_fill_registers_one_defs_pattern_and_references_it() {
1632        let mut b = backend();
1633        b.draw_rect_pattern((0.0, 0.0), (10.0, 10.0), &stripe(), &RectStyle::default())
1634            .unwrap();
1635        let svg = b.finish();
1636        assert_eq!(svg.matches("<pattern ").count(), 1, "{svg}");
1637        let id = pattern_id(&svg);
1638        assert!(
1639            svg.contains(&format!("fill=\"url(#{id})\"")),
1640            "rect references the registered pattern id {id}: {svg}"
1641        );
1642    }
1643
1644    #[test]
1645    fn a_rounded_rect_pattern_still_rounds_its_corners() {
1646        let mut b = backend();
1647        b.draw_rect_pattern(
1648            (0.0, 0.0),
1649            (10.0, 10.0),
1650            &stripe(),
1651            &RectStyle {
1652                corner_radius: 3.0,
1653                ..Default::default()
1654            },
1655        )
1656        .unwrap();
1657        let svg = b.finish();
1658        assert!(svg.contains("rx=\"3.00\""), "{svg}");
1659        assert!(svg.contains("fill=\"url(#"), "{svg}");
1660    }
1661
1662    #[test]
1663    fn an_equal_pattern_reuses_the_same_defs_entry() {
1664        let mut b = backend();
1665        b.draw_rect_pattern((0.0, 0.0), (5.0, 5.0), &stripe(), &RectStyle::default())
1666            .unwrap();
1667        b.draw_polygon_pattern(
1668            &[(0.0, 0.0), (1.0, 0.0), (1.0, 1.0)],
1669            &stripe(),
1670            &RectStyle::default(),
1671        )
1672        .unwrap();
1673        let svg = b.finish();
1674        assert_eq!(
1675            svg.matches("<pattern ").count(),
1676            1,
1677            "two equal patterns share one <defs> entry: {svg}"
1678        );
1679    }
1680
1681    #[test]
1682    fn different_patterns_get_their_own_defs_entries() {
1683        let mut b = backend();
1684        b.draw_rect_pattern((0.0, 0.0), (5.0, 5.0), &stripe(), &RectStyle::default())
1685            .unwrap();
1686        let other = FillPattern::Stripe {
1687            fg: (1, 1, 1),
1688            bg: (2, 2, 2),
1689            size_px: 8.0,
1690            angle_deg: 0.0,
1691        };
1692        b.draw_rect_pattern((0.0, 0.0), (5.0, 5.0), &other, &RectStyle::default())
1693            .unwrap();
1694        let svg = b.finish();
1695        assert_eq!(svg.matches("<pattern ").count(), 2, "{svg}");
1696    }
1697
1698    #[test]
1699    fn no_pattern_used_means_no_defs_block_at_all() {
1700        let mut b = backend();
1701        b.draw_rect((0.0, 0.0), (5.0, 5.0), &RectStyle::default())
1702            .unwrap();
1703        let svg = b.finish();
1704        assert!(!svg.contains("<defs>"), "{svg}");
1705    }
1706
1707    #[test]
1708    fn pattern_fill_cuts_out_holes_like_a_flat_fill_does() {
1709        let mut b = backend();
1710        let outer = vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)];
1711        let hole = vec![(2.0, 2.0), (8.0, 2.0), (8.0, 8.0), (2.0, 8.0)];
1712        b.draw_polygon_rings_pattern(&[outer, hole], &stripe(), &RectStyle::default())
1713            .unwrap();
1714        let svg = b.finish();
1715        assert!(svg.contains("fill-rule=\"evenodd\""), "{svg}");
1716        assert_eq!(
1717            svg.matches("<path").count(),
1718            1,
1719            "one path, both rings: {svg}"
1720        );
1721    }
1722
1723    #[test]
1724    fn two_backends_on_one_page_never_collide_on_a_pattern_id() {
1725        let mut a = backend();
1726        a.draw_rect_pattern((0.0, 0.0), (5.0, 5.0), &stripe(), &RectStyle::default())
1727            .unwrap();
1728        let mut b = backend();
1729        b.draw_rect_pattern((0.0, 0.0), (5.0, 5.0), &stripe(), &RectStyle::default())
1730            .unwrap();
1731        let (sa, sb) = (a.finish(), b.finish());
1732        assert_ne!(pattern_id(&sa), pattern_id(&sb), "{sa}\n{sb}");
1733    }
1734
1735    /// #214: decode a [`compact_rings_d`]-style `d` back into absolute
1736    /// points, for the round-trip test below. Relies on the same
1737    /// separator rule [`push_num`] writes: a number starts right after a
1738    /// command letter, right after a comma, or right at a `-` sign (which
1739    /// needs no comma before it); every other digit boundary has an
1740    /// explicit comma.
1741    fn decode_compact_d(d: &str) -> Vec<Vec<(f64, f64)>> {
1742        let b = d.as_bytes();
1743        let mut i = 0;
1744        let read_num = |b: &[u8], i: &mut usize| -> f64 {
1745            let start = *i;
1746            if *i < b.len() && b[*i] == b'-' {
1747                *i += 1;
1748            }
1749            while *i < b.len() && b[*i].is_ascii_digit() {
1750                *i += 1;
1751            }
1752            if *i < b.len() && b[*i] == b'.' {
1753                *i += 1;
1754                while *i < b.len() && b[*i].is_ascii_digit() {
1755                    *i += 1;
1756                }
1757            }
1758            std::str::from_utf8(&b[start..*i]).unwrap().parse().unwrap()
1759        };
1760        let is_num_start = |c: u8| c.is_ascii_digit() || c == b'-' || c == b'.';
1761        let mut rings = Vec::new();
1762        let mut current = Vec::new();
1763        let mut cursor = (0.0, 0.0);
1764        while i < b.len() {
1765            match b[i] {
1766                b'M' => {
1767                    if !current.is_empty() {
1768                        rings.push(std::mem::take(&mut current));
1769                    }
1770                    i += 1;
1771                    let x = read_num(b, &mut i);
1772                    if i < b.len() && b[i] == b',' {
1773                        i += 1;
1774                    }
1775                    let y = read_num(b, &mut i);
1776                    cursor = (x, y);
1777                    current.push(cursor);
1778                }
1779                b'l' => {
1780                    i += 1;
1781                    while i < b.len() && is_num_start(b[i]) {
1782                        let dx = read_num(b, &mut i);
1783                        if i < b.len() && b[i] == b',' {
1784                            i += 1;
1785                        }
1786                        let dy = read_num(b, &mut i);
1787                        if i < b.len() && b[i] == b',' {
1788                            i += 1;
1789                        }
1790                        cursor = (cursor.0 + dx, cursor.1 + dy);
1791                        current.push(cursor);
1792                    }
1793                }
1794                b'z' => {
1795                    i += 1;
1796                    if !current.is_empty() {
1797                        rings.push(std::mem::take(&mut current));
1798                    }
1799                }
1800                _ => i += 1,
1801            }
1802        }
1803        if !current.is_empty() {
1804            rings.push(current);
1805        }
1806        rings
1807    }
1808
1809    /// A noisy, roughly-circular ring with `n` points, the shape of a
1810    /// simplified real boundary (not axis-aligned, no repeating deltas).
1811    fn noisy_ring(n: usize, cx: f64, cy: f64, r: f64) -> Vec<(f64, f64)> {
1812        (0..n)
1813            .map(|i| {
1814                let t = i as f64 / n as f64 * std::f64::consts::TAU;
1815                let wobble = 1.0 + 0.03 * ((i * 7) as f64).sin();
1816                (cx + r * wobble * t.cos(), cy + r * wobble * t.sin())
1817            })
1818            .collect()
1819    }
1820
1821    #[test]
1822    fn compact_encoding_is_well_under_the_absolute_encodings_size() {
1823        // Isolated from simplification entirely: the same 2,000-point
1824        // ring, encoded both ways directly (no GeomSf/simplify_px
1825        // involved) — the byte-size win is the encoding alone.
1826        let ring = noisy_ring(2000, 400.0, 300.0, 280.0);
1827        let mut b = backend();
1828        b.draw_polygon_rings(std::slice::from_ref(&ring), &RectStyle::default())
1829            .unwrap();
1830        let absolute_svg = b.finish();
1831        let absolute_d = absolute_svg
1832            .split("d=\"")
1833            .nth(1)
1834            .and_then(|s| s.split('"').next())
1835            .expect("absolute path d");
1836
1837        let compact_d = compact_rings_d(std::slice::from_ref(&ring), 1);
1838
1839        assert!(
1840            compact_d.len() * 3 < absolute_d.len() * 2,
1841            "compact {} bytes should be well under 2/3 of absolute {} bytes",
1842            compact_d.len(),
1843            absolute_d.len()
1844        );
1845    }
1846
1847    #[test]
1848    fn compact_encoding_round_trips_within_precision() {
1849        let ring = noisy_ring(40, 100.0, 80.0, 60.0);
1850        let precision: u8 = 1;
1851        let d = compact_rings_d(std::slice::from_ref(&ring), precision);
1852        let decoded = decode_compact_d(&d);
1853        assert_eq!(decoded.len(), 1, "{d}");
1854        assert_eq!(decoded[0].len(), ring.len(), "{d}");
1855        // Each step's rounding error is at most half a unit of precision;
1856        // reconstructed points accumulate it additively from M, so the
1857        // tolerance at point k scales with k (still a tight, provable
1858        // bound, not an arbitrary constant).
1859        let step_tol = 0.5 * 10f64.powi(-(precision as i32));
1860        for (k, (orig, got)) in ring.iter().zip(decoded[0].iter()).enumerate() {
1861            let tol = step_tol * (k as f64 + 1.0) + 1e-9;
1862            assert!(
1863                (orig.0 - got.0).abs() <= tol && (orig.1 - got.1).abs() <= tol,
1864                "point {k}: {orig:?} vs {got:?} (tol {tol}): {d}"
1865            );
1866        }
1867    }
1868
1869    #[test]
1870    fn compact_encoding_round_trips_a_hole_and_a_multipolygons_parts() {
1871        // Two parts (first a plain square, second a square with a hole) —
1872        // exactly the ring-set shape `GeomSf::draw_rings` now passes
1873        // through for a MultiPolygon row (#213) or a Polygon with holes.
1874        let part1 = vec![(0.0, 0.0), (20.0, 0.0), (20.0, 20.0), (0.0, 20.0)];
1875        let part2_outer = vec![(50.0, 0.0), (90.0, 0.0), (90.0, 40.0), (50.0, 40.0)];
1876        let part2_hole = vec![(60.0, 10.0), (80.0, 10.0), (80.0, 30.0), (60.0, 30.0)];
1877        let rings = vec![part1.clone(), part2_outer.clone(), part2_hole.clone()];
1878        let d = compact_rings_d(&rings, 1);
1879        let decoded = decode_compact_d(&d);
1880        assert_eq!(decoded.len(), 3, "{d}");
1881        for (orig, got) in [part1, part2_outer, part2_hole].iter().zip(decoded.iter()) {
1882            assert_eq!(orig.len(), got.len(), "{d}");
1883            for (o, g) in orig.iter().zip(got.iter()) {
1884                assert!((o.0 - g.0).abs() <= 0.1 && (o.1 - g.1).abs() <= 0.1, "{d}");
1885            }
1886        }
1887        assert!(d.contains("M0,0l20,0,0,20-20,0z"), "{d}");
1888    }
1889}