SVG: share XML attribute escaping (#9030)

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
This commit is contained in:
Terra854andFredApps authored and GitHub committed 2026-11-23 05:13:39 +07:00
1 parent eb3a9ba335
commit 76b8839448
6 files changed
+15 -16

No files matched your search

Generated
+1
View File
@@ -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",
+1
View File
@@ -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 }
+2 -2
View File
@@ -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!("<a xlink:href=\"{}\">", xml_attr_valid(url)));
self.line(&format!("<a xlink:href=\"{}\">", xml_attr_escape(url)));
self.depth += 1;
self.node_body(n);
self.depth -= 1;
+5 -10
View File
@@ -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', "&#9;").replace('\n', "&#10;").replace('\r', "&#13;")
let escaped = craft_xml::esc_attr(s);
if escaped.contains('\'') { escaped.replace('\'', "&apos;") } 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.
+2 -2
View File
@@ -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()
};
+4 -2
View File
@@ -32,10 +32,10 @@ fn native_data(raw: &str) -> Document {
}
#[test]
fn imported_decimal_whitespace_references_survive_export() {
let doc = import(&svg(r#"<rect id="shape" width="20" height="20" data-value="a&#10;b" data-tab="a&#9;b" data-cr="a&#13;b"/>"#)).unwrap();
let doc = import(&svg(r#"<rect id="shape" width="20" height="20" data-value="a&#10;b" data-tab="a&#9;b" data-cr="a&#13;b" data-mixed="a&#9;&quot;&apos;&lt;&gt;&amp;&#13;&#10;雲"/>"#)).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&#9;&quot;&apos;&lt;&gt;&amp;&#13;&#10;雲""#));
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);
}