From 76b8839448dee862ea65c118dc5b587d2a36da9d Mon Sep 17 00:00:00 2001 From: Terra854 Date: Mon, 23 Nov 2026 06:13:39 +0800 Subject: [PATCH] SVG: share XML attribute escaping (#9030) Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- Cargo.lock | 1 + crates/svg/Cargo.toml | 1 + crates/svg/src/export/nodes.rs | 4 ++-- crates/svg/src/export/output.rs | 15 +++++---------- crates/svg/src/export/text.rs | 4 ++-- crates/svg/tests/it/data_attributes.rs | 6 ++++-- 6 files changed, 15 insertions(+), 16 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 01e7d2ebfc..1c00b127f1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7202,6 +7202,7 @@ dependencies = [ "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-mime", "craft-svg", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", "data-url", "flate2", "image", diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index c1a59d7022..310b9c8e6f 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -10,6 +10,7 @@ workspace = true [dependencies] craft-svg = { workspace = true } +craft-xml = { workspace = true } craft-mime = { workspace = true } # Which paths stored in documents may be opened. craft-docpath = { workspace = true } diff --git a/crates/svg/src/export/nodes.rs b/crates/svg/src/export/nodes.rs index b92e888b57..481db1f8a2 100644 --- a/crates/svg/src/export/nodes.rs +++ b/crates/svg/src/export/nodes.rs @@ -1,4 +1,4 @@ -use super::output::{sanitize_id, valid_xml_value, xml_attr_escape, xml_attr_valid}; +use super::output::{sanitize_id, valid_xml_value, xml_attr_escape}; use super::paint::{StrokePlan, has_raster, pixel_gradient}; use super::text::OUTLINE_TOLERANCE; use super::{ @@ -888,7 +888,7 @@ impl Writer<'_> { if !valid_xml_value(url) { self.warn("Link URLs containing invalid XML characters had those characters removed"); } - self.line(&format!("", xml_attr_valid(url))); + self.line(&format!("", xml_attr_escape(url))); self.depth += 1; self.node_body(n); self.depth -= 1; diff --git a/crates/svg/src/export/output.rs b/crates/svg/src/export/output.rs index 3ed101340a..00fb760c03 100644 --- a/crates/svg/src/export/output.rs +++ b/crates/svg/src/export/output.rs @@ -1,8 +1,9 @@ use super::*; -/// XML 1.0 literal attribute whitespace is normalized to spaces; references retain the value. +/// Escape a double-quoted attribute, retaining VectorCraft's apostrophe entity spelling. pub(super) fn xml_attr_escape(s: &str) -> String { - xml_escape(s).replace('\t', " ").replace('\n', " ").replace('\r', " ") + let escaped = craft_xml::esc_attr(s); + if escaped.contains('\'') { escaped.replace('\'', "'") } else { escaped } } /// Escape type for XML content. Characters XML 1.0 does not allow are dropped, except the line @@ -12,21 +13,15 @@ pub(super) fn xml_text(s: &str) -> String { .chars() .filter_map(|c| match c { '\u{b}' | '\u{c}' => Some(' '), - c if valid_xml_value(c.encode_utf8(&mut [0; 4])) => Some(c), + c if craft_xml::is_xml_char(c) => Some(c), _ => None, }) .collect(); xml_escape(&s) } -/// `s` without the characters XML 1.0 does not allow, ready for a double-quoted attribute. -pub(super) fn xml_attr_valid(s: &str) -> String { - let s: String = s.chars().filter(|c| valid_xml_value(c.encode_utf8(&mut [0; 4]))).collect(); - xml_attr_escape(&s) -} - pub(super) fn valid_xml_value(s: &str) -> bool { - s.chars().all(|c| matches!(c, '\t' | '\n' | '\r' | '\u{20}'..='\u{d7ff}' | '\u{e000}'..='\u{fffd}' | '\u{10000}'..='\u{10ffff}')) + s.chars().all(craft_xml::is_xml_char) } /// An XML name without a colon (an NCName): a letter or `_`, then [`xml_name_char`]s. diff --git a/crates/svg/src/export/text.rs b/crates/svg/src/export/text.rs index f8bc712117..289fcb81ba 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -1,4 +1,4 @@ -use super::output::{xml_attr_escape, xml_attr_valid, xml_text}; +use super::output::{xml_attr_escape, xml_text}; use super::{ Affine, AppearanceItem, Arc, BTreeSet, BezPath, BlendMode, CharStyle, FillRule, FontDb, FontFace, GradientKind, HashMap, Justify, Node, NodeId, NodeKind, Paint, PathData, Props, Rect, StrokeAlign, Styling, TextKind, TextObject, Writer, base64_encode, css, css_string, fmt_num, @@ -199,7 +199,7 @@ impl Writer<'_> { Some(named) if !id.is_empty() && !id.contains(" data-name=\"") => format!(" data-name=\"{}\"", xml_attr_escape(named)), _ => String::new(), }; - format!("{name} role=\"img\" aria-label=\"{}\"", xml_attr_valid(&text)) + format!("{name} role=\"img\" aria-label=\"{}\"", xml_attr_escape(&text)) } else { String::new() }; diff --git a/crates/svg/tests/it/data_attributes.rs b/crates/svg/tests/it/data_attributes.rs index 60edf3dd60..1d411143f0 100644 --- a/crates/svg/tests/it/data_attributes.rs +++ b/crates/svg/tests/it/data_attributes.rs @@ -32,10 +32,10 @@ fn native_data(raw: &str) -> Document { } #[test] fn imported_decimal_whitespace_references_survive_export() { - let doc = import(&svg(r#""#)).unwrap(); + let doc = import(&svg(r#""#)).unwrap(); assert_eq!( named(&doc, "shape").extras().attrs.as_deref().unwrap().data, - [("value".into(), "a\nb".into()), ("tab".into(), "a\tb".into()), ("cr".into(), "a\rb".into())] + [("value".into(), "a\nb".into()), ("tab".into(), "a\tb".into()), ("cr".into(), "a\rb".into()), ("mixed".into(), "a\t\"'<>&\r\n雲".into()),] ); for styling in styles() { for minify in [false, true] { @@ -45,6 +45,8 @@ fn imported_decimal_whitespace_references_survive_export() { for (key, value) in [("data-value", "a\nb"), ("data-tab", "a\tb"), ("data-cr", "a\rb")] { assert_eq!(n.attribute(key), Some(value)); } + assert_eq!(n.attribute("data-mixed"), Some("a\t\"'<>&\r\n雲")); + assert!(text.contains(r#"data-mixed="a "'<>& 雲""#)); let back = import(&text).unwrap(); assert_eq!(named(&back, "shape").extras().attrs.as_deref().unwrap().data, named(&doc, "shape").extras().attrs.as_deref().unwrap().data); }