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