1use super::backend::{
8 DrawBackend, FillPattern, FontFace, LineEnd, LineStyle, Linetype, PointShape, PointStyle,
9 RectStyle, TextAnchor, TextStyle,
10};
11use super::{Rect, RenderError};
12
13pub 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 mark_geom: Option<String>,
31 root_attrs: Vec<(String, String)>,
32 physical: Option<(String, String)>,
35 warnings: Vec<String>,
36 plot_attr: bool,
39 formatted_values: bool,
42 mark_fvalue: Option<String>,
45 mark_fx: Option<String>,
48 patterns: Vec<(FillPattern, String)>,
53 id_prefix: String,
58 mark_user_class: Option<String>,
61 mark_group: Option<(String, String)>,
64 layer_attrs: Vec<(String, String)>,
67 groups: Vec<(String, String, String)>,
70 group_slots: Vec<(usize, usize)>,
75 svg_title: Option<String>,
80 svg_desc: Option<String>,
85 corner_claims: Vec<Rect>,
88 viewport: Option<Rect>,
91 panels: Vec<(usize, String, Rect, Rect)>,
95 element_classes: bool,
97 element_class: Option<&'static str>,
98 clips: Vec<Rect>,
100}
101
102static 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 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 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 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 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 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 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 pub(crate) fn set_formatted_values(&mut self, on: bool) {
306 self.formatted_values = on;
307 }
308
309 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 pub fn extend_root_attrs(&mut self, attrs: Vec<(String, String)>) {
331 self.root_attrs.extend(attrs);
332 }
333
334 pub(crate) fn without_plot_attr(&mut self) {
336 self.plot_attr = false;
337 }
338
339 pub(crate) fn set_svg_title(&mut self, title: Option<String>) {
344 self.svg_title = title;
345 }
346
347 pub(crate) fn set_svg_desc(&mut self, desc: Option<String>) {
352 self.svg_desc = desc;
353 }
354
355 pub(crate) fn push_raw(&mut self, markup: &str) {
358 self.body.push_str(markup);
359 }
360
361 pub(crate) fn body(&mut self) -> &str {
364 self.flush_groups();
365 &self.body
366 }
367
368 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 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 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 pub fn take_warnings(&mut self) -> Vec<String> {
447 std::mem::take(&mut self.warnings)
448 }
449
450 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 None => match (self.element_classes, self.element_class) {
480 (true, Some(c)) => format!(" class=\"{c}\""),
481 _ => String::new(),
482 },
483 }
484 }
485
486 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 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 fn push_mark(&mut self, tag: &str, kind: &str, attrs: &str) {
541 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 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 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 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 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 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 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 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 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 fn draw_line_run(&mut self, pts: &[(f64, f64)], style: &LineStyle) {
739 let dash = dasharray_attr(&style.linetype);
740 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
760fn num(v: f64) -> String {
763 if v.is_finite() {
764 format!("{v:.2}")
765 } else {
766 "0".to_string()
767 }
768}
769
770fn 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
787fn 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
820fn 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
836fn 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
865fn 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
879fn 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
963fn g(v: f64) -> String {
966 format!("{v}")
967}
968
969fn 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
989fn 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
1005pub(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 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
1052pub(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
1060fn 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
1074const 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
1090pub(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
1140fn escape(s: &str) -> String {
1151 escape_impl(s, false)
1152}
1153
1154fn 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("&"),
1173 '<' => out.push_str("<"),
1174 '>' => out.push_str(">"),
1175 '"' => out.push_str("""),
1176 '\'' => out.push_str("'"),
1177 '\t' if in_attr => out.push_str("	"),
1178 '\n' if in_attr => out.push_str(" "),
1179 '\r' if in_attr => out.push_str(" "),
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
1202fn 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 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 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 for run in finite_runs(pts) {
1450 self.draw_line_run(&run, style);
1451 }
1452 Ok(())
1453 }
1454
1455 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 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 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 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 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 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 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 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 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
1843fn 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 #[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 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 #[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()), ("data-Upper".to_string(), "x".to_string()), ("data-ok".to_string(), "valid".to_string()), ]);
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 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 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 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 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 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 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}