1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
// this_file: crates/vexy-vsvg-plugin-sdk/src/plugins/remove_xml_proc_inst.rs
//! Remove XML Processing Instruction plugin implementation
//!
//! This plugin removes XML processing instructions (specifically `<?xml ... ?>` declarations)
//! from SVG documents. These declarations are unnecessary for modern SVG usage.
//!
//! ## What It Removes
//!
//! - XML declarations: `<?xml version="1.0" encoding="utf-8"?>`
//! - Only processing instructions with target `"xml"` (case-insensitive)
//! - Preserves other processing instructions (e.g., `<?xml-stylesheet ... ?>`)
//!
//! ## Why This Is Safe
//!
//! The XML declaration is optional in XML documents and provides no value for SVG:
//! - Browsers assume UTF-8 encoding by default (the standard for web content)
//! - The XML version is always 1.0 for SVG (1.1 never gained adoption)
//! - HTTP headers or HTML meta tags specify encoding when needed
//!
//! Removing it reduces file size without affecting parsing or rendering.
//!
//! ## What It Preserves
//!
//! - Other processing instructions like `<?xml-stylesheet type="text/css" href="style.css"?>`
//! - Only `target="xml"` processing instructions are removed
//!
//! ## Configuration
//!
//! This plugin accepts no configuration parameters.
//!
//! ## Example
//!
//! Before:
//! ```xml
//! <?xml version="1.0" encoding="utf-8"?>
//! <?xml-stylesheet href="style.css"?>
//! <svg>
//! <rect/>
//! </svg>
//! ```
//!
//! After:
//! ```xml
//! <?xml-stylesheet href="style.css"?>
//! <svg>
//! <rect/>
//! </svg>
//! ```
//!
//! ## SVGO Compatibility
//!
//! Ports SVGO's `removeXMLProcInst` plugin. Matches the same behavior.
//!
//! Reference: https://github.com/svg/svgo/blob/main/plugins/removeXMLProcInst.js
use anyhow::Result;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use vexy_vsvg::ast::{Document, Node};
use crate::Plugin;
/// Configuration parameters for remove XML processing instruction plugin
///
/// This plugin requires no configuration. The struct exists for API consistency.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[derive(Default)]
pub struct RemoveXMLProcInstConfig {
// No configuration options - matches SVGO behavior
}
/// Plugin that removes XML processing instructions from SVG documents
///
/// Specifically targets processing instructions with `target="xml"` (e.g., `<?xml version="1.0"?>`).
/// Preserves other processing instructions like `<?xml-stylesheet ... ?>`.
pub struct RemoveXMLProcInstPlugin {
#[allow(dead_code)]
config: RemoveXMLProcInstConfig,
}
impl RemoveXMLProcInstPlugin {
/// Check if a text node contains only formatting whitespace
///
/// Returns `true` if the text is empty after trimming AND contains newlines/tabs.
/// Used to identify text nodes added purely for source formatting.
fn is_formatting_whitespace(text: &str) -> bool {
text.trim().is_empty() && text.chars().any(|c| matches!(c, '\n' | '\r' | '\t'))
}
/// Remove formatting-only whitespace text nodes from a node list
///
/// After removing processing instructions, we may have leftover whitespace from source
/// formatting. This removes those text nodes ONLY if there's actual content nearby.
fn cleanup_formatting_whitespace(nodes: &mut Vec<Node>) {
// Check if there's any real content (not just formatting whitespace)
let has_non_whitespace_content = nodes.iter().any(|node| match node {
Node::Element(_) => true,
Node::Text(text) => !text.trim().is_empty(),
// Comments, processing instructions, DOCTYPE, and CDATA are real content
Node::Comment(_)
| Node::ProcessingInstruction { .. }
| Node::DocType(_)
| Node::CData(_) => true,
});
// Only clean up whitespace if there's actual content
if has_non_whitespace_content {
nodes.retain(
|node| !matches!(node, Node::Text(text) if Self::is_formatting_whitespace(text)),
);
}
}
/// Recursively clean up formatting whitespace in the document tree
///
/// After removing processing instructions, normalizes text children and removes formatting
/// whitespace throughout the tree. Preserves whitespace in text-rendering elements.
fn cleanup_formatting_whitespace_recursive(element: &mut vexy_vsvg::ast::Element<'_>) {
// Check if this is a text-rendering element where whitespace is semantic
let preserve = matches!(
element.name.as_ref(),
"text" | "tspan" | "tref" | "textPath" | "altGlyph"
);
// Trim text nodes (unless in text-rendering elements)
for child in &mut element.children {
if let Node::Text(text) = child {
if !preserve && (text.contains('\n') || text.contains('\r') || text.contains('\t'))
{
let trimmed = text.trim();
if !trimmed.is_empty() {
*text = trimmed.to_string().into();
}
}
}
}
// Remove formatting-only whitespace nodes
Self::cleanup_formatting_whitespace(&mut element.children);
// Recurse into child elements
for child in &mut element.children {
if let Node::Element(child_element) = child {
Self::cleanup_formatting_whitespace_recursive(child_element);
}
}
}
/// Create a new RemoveXMLProcInstPlugin with default configuration
pub fn new() -> Self {
Self {
#[allow(dead_code)]
config: RemoveXMLProcInstConfig::default(),
}
}
/// Create a new RemoveXMLProcInstPlugin with specific configuration
///
/// The config parameter exists for API consistency but has no effect.
pub fn with_config(config: RemoveXMLProcInstConfig) -> Self {
Self { config }
}
/// Parse configuration from JSON
///
/// The config parameter exists for API consistency but has no effect.
fn _parse_config(params: &Value) -> Result<RemoveXMLProcInstConfig> {
if params.is_object() {
serde_json::from_value(params.clone())
.map_err(|e| anyhow::anyhow!("Invalid configuration: {}", e))
} else {
Ok(RemoveXMLProcInstConfig::default())
}
}
}
impl Default for RemoveXMLProcInstPlugin {
fn default() -> Self {
Self::new()
}
}
impl Plugin for RemoveXMLProcInstPlugin {
fn name(&self) -> &'static str {
"removeXMLProcInst"
}
fn description(&self) -> &'static str {
"removes XML processing instructions"
}
fn validate_params(&self, params: &Value) -> Result<()> {
if let Some(obj) = params.as_object() {
if !obj.is_empty() {
return Err(anyhow::anyhow!(
"removeXMLProcInst plugin does not accept any parameters"
));
}
}
Ok(())
}
/// Apply XML processing instruction removal to the entire SVG document
///
/// This method processes the document in several steps:
///
/// 1. **Clear metadata** - Remove stored version/encoding info from document metadata
/// 2. **Prologue** - Remove `<?xml ...?>` declarations (standard location)
/// 3. **Root children** - Remove misplaced XML PIs (defensive)
/// 4. **Epilogue** - Clean up (completeness)
///
/// Only processing instructions with `target="xml"` (case-insensitive) are removed.
/// Other processing instructions like `<?xml-stylesheet ... ?>` are preserved.
///
/// After removing PIs, cleans up leftover formatting whitespace.
fn apply(&self, document: &mut Document) -> Result<()> {
// Clear version and encoding metadata stored in the document
document.metadata.version = None;
document.metadata.encoding = None;
// Remove all XML processing instruction nodes from the document prologue (standard location)
document.prologue.retain(|child| {
// Remove ProcessingInstruction nodes with target "xml" (case-insensitive)
if let Node::ProcessingInstruction { target, .. } = child {
// Check if it's an XML processing instruction
if target.eq_ignore_ascii_case("xml") {
return false; // Remove this node
}
}
true // Keep all other nodes
});
Self::cleanup_formatting_whitespace(&mut document.prologue);
// Also remove XML processing instructions from root children (defensive: handles misplaced PIs)
document.root.children.retain(|child| {
// Remove ProcessingInstruction nodes with target "xml"
if let Node::ProcessingInstruction { target, .. } = child {
// Check if it's an XML processing instruction
if target.eq_ignore_ascii_case("xml") {
return false; // Remove this node
}
}
true // Keep all other nodes
});
Self::cleanup_formatting_whitespace_recursive(&mut document.root);
// Clean up epilogue as well (completeness)
Self::cleanup_formatting_whitespace(&mut document.epilogue);
Ok(())
}
}
#[cfg(test)]
mod unit_tests {
use std::borrow::Cow;
use serde_json::json;
use vexy_vsvg::ast::{Document, Element, Node};
use super::*;
fn create_element(name: &'static str) -> Element<'static> {
let mut element = Element::new(name);
element.name = Cow::Borrowed(name);
element
}
#[test]
fn test_plugin_creation() {
let plugin = RemoveXMLProcInstPlugin::new();
assert_eq!(plugin.name(), "removeXMLProcInst");
assert_eq!(plugin.description(), "removes XML processing instructions");
}
#[test]
fn test_parameter_validation() {
let plugin = RemoveXMLProcInstPlugin::new();
// Valid parameters (empty object)
assert!(plugin.validate_params(&json!({})).is_ok());
// Invalid parameters (non-empty object)
assert!(plugin.validate_params(&json!({"param": "value"})).is_err());
}
#[test]
fn test_remove_xml_proc_inst() {
let plugin = RemoveXMLProcInstPlugin::new();
let mut doc = Document::new();
// Add an XML processing instruction
doc.root.children.push(Node::ProcessingInstruction {
target: "xml".into(),
data: "version=\"1.0\" encoding=\"UTF-8\"".to_string().into(),
});
// Add a regular element
let svg = create_element("svg");
doc.root.children.push(Node::Element(svg));
// Apply plugin
plugin.apply(&mut doc).unwrap();
// Should have removed the processing instruction
assert_eq!(doc.root.children.len(), 1);
assert!(matches!(doc.root.children[0], Node::Element(_)));
}
#[test]
fn test_remove_xml_proc_inst_simple() {
let plugin = RemoveXMLProcInstPlugin::new();
let mut doc = Document::new();
// Add a simple XML processing instruction
doc.root.children.push(Node::ProcessingInstruction {
target: "xml".into(),
data: "".to_string().into(),
});
// Add a regular element
let svg = create_element("svg");
doc.root.children.push(Node::Element(svg));
// Apply plugin
plugin.apply(&mut doc).unwrap();
// Should have removed the processing instruction
assert_eq!(doc.root.children.len(), 1);
assert!(matches!(doc.root.children[0], Node::Element(_)));
}
#[test]
fn test_keep_other_processing_instructions() {
let plugin = RemoveXMLProcInstPlugin::new();
let mut doc = Document::new();
// Add XML processing instruction (should be removed)
doc.root.children.push(Node::ProcessingInstruction {
target: "xml".into(),
data: "version=\"1.0\"".to_string().into(),
});
// Add other processing instruction (should be kept)
doc.root.children.push(Node::ProcessingInstruction {
target: "stylesheet".into(),
data: "type=\"text/css\"".to_string().into(),
});
// Add a regular element
let svg = create_element("svg");
doc.root.children.push(Node::Element(svg));
// Apply plugin
plugin.apply(&mut doc).unwrap();
// Should have removed only the XML processing instruction
assert_eq!(doc.root.children.len(), 2);
assert!(matches!(
doc.root.children[0],
Node::ProcessingInstruction { .. }
));
assert!(matches!(doc.root.children[1], Node::Element(_)));
// Check that the remaining processing instruction is not XML
if let Node::ProcessingInstruction { target, .. } = &doc.root.children[0] {
assert_eq!(target.as_ref(), "stylesheet");
}
}
#[test]
fn test_multiple_xml_proc_inst() {
let plugin = RemoveXMLProcInstPlugin::new();
let mut doc = Document::new();
// Add multiple XML processing instructions
doc.root.children.push(Node::ProcessingInstruction {
target: "xml".into(),
data: "version=\"1.0\"".to_string().into(),
});
doc.root.children.push(Node::ProcessingInstruction {
target: "xml".into(),
data: "encoding=\"UTF-8\"".to_string().into(),
});
// Add a regular element
let svg = create_element("svg");
doc.root.children.push(Node::Element(svg));
// Apply plugin
plugin.apply(&mut doc).unwrap();
// Should have removed all XML processing instructions
assert_eq!(doc.root.children.len(), 1);
assert!(matches!(doc.root.children[0], Node::Element(_)));
}
#[test]
fn test_no_processing_instructions() {
let plugin = RemoveXMLProcInstPlugin::new();
let mut doc = Document::new();
// Add only regular elements
let svg = create_element("svg");
doc.root.children.push(Node::Element(svg));
// Apply plugin
plugin.apply(&mut doc).unwrap();
// Should have no changes
assert_eq!(doc.root.children.len(), 1);
assert!(matches!(doc.root.children[0], Node::Element(_)));
}
#[test]
fn test_proc_inst_with_text() {
let plugin = RemoveXMLProcInstPlugin::new();
let mut doc = Document::new();
// Add XML processing instruction, text, and element
doc.root.children.push(Node::ProcessingInstruction {
target: "xml".into(),
data: "version=\"1.0\"".to_string().into(),
});
doc.root
.children
.push(Node::Text("Some text".to_string().into()));
let svg = create_element("svg");
doc.root.children.push(Node::Element(svg));
// Apply plugin
plugin.apply(&mut doc).unwrap();
// Should have removed only the XML processing instruction
assert_eq!(doc.root.children.len(), 2);
assert!(matches!(doc.root.children[0], Node::Text(_)));
assert!(matches!(doc.root.children[1], Node::Element(_)));
}
#[test]
fn test_config_parsing() {
let config = RemoveXMLProcInstPlugin::_parse_config(&json!({})).unwrap();
// No fields to check since config is empty
let _ = config;
}
}
// Use parameterized testing framework for SVGO fixture tests
#[cfg(test)]
#[cfg(test)]
vexy_vsvg_test_utils::plugin_fixture_tests!(RemoveXMLProcInstPlugin, "removeXMLProcInst");