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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
// this_file: crates/vexy-vsvg-plugin-sdk/src/plugins/remove_comments.rs
//! Remove comments plugin implementation
//!
//! This plugin removes XML comments (`<!-- ... -->`) from SVG documents while optionally
//! preserving "legal comments" that start with an exclamation mark (`<!-- ! ... -->`).
//!
//! ## What It Removes
//!
//! - Regular XML comments: `<!-- This is a comment -->`
//! - Nested comments within any element in the document tree
//! - Comments in the document prologue (before `<svg>`)
//! - Comments in the document epilogue (after `</svg>`)
//!
//! ## What It Preserves
//!
//! When `preservePatterns: true` (the default):
//! - Legal comments starting with `!`: `<!-- ! Copyright 2024 -->`
//! - These are typically used for copyright notices and license information
//!
//! ## Why This Is Safe
//!
//! Comments have no effect on SVG rendering. They're only useful for human readers
//! viewing the source. Removing them reduces file size with no visual impact.
//!
//! Legal comments (starting with `!`) follow a convention established by minifiers to
//! preserve important licensing information even in production builds.
//!
//! ## Configuration
//!
//! ```json
//! {
//! "preservePatterns": true // Default: true. Set to false to remove ALL comments.
//! }
//! ```
//!
//! ## Example
//!
//! Before:
//! ```xml
//! <!-- Author: Jane Doe -->
//! <svg>
//! <!-- ! Copyright 2024 Acme Corp -->
//! <rect/><!-- This is a rectangle -->
//! </svg>
//! ```
//!
//! After (with default config):
//! ```xml
//! <svg>
//! <!-- ! Copyright 2024 Acme Corp -->
//! <rect/>
//! </svg>
//! ```
//!
//! ## SVGO Compatibility
//!
//! Ports SVGO's `removeComments` plugin. Matches the same configuration schema and behavior.
//!
//! Reference: https://github.com/svg/svgo/blob/main/plugins/removeComments.js
use crate::Plugin;
use anyhow::Result;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use vexy_vsvg::ast::{Document, Element, Node};
/// Configuration for the remove comments plugin
///
/// Controls whether legal comments (starting with `!`) are preserved during optimization.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RemoveCommentsConfig {
/// Whether to preserve legal comments (those starting with '!')
///
/// When `true` (default), comments like `<!-- ! Copyright ... -->` are kept.
/// When `false`, all comments are removed regardless of content.
///
/// Legal comments follow a minification convention where important notices
/// (copyrights, licenses) are marked with `!` to survive optimization.
#[serde(default = "default_preserve_patterns")]
pub preserve_patterns: bool,
}
/// Default value for `preserve_patterns`: `true`
///
/// By default, legal comments are preserved to maintain licensing information.
fn default_preserve_patterns() -> bool {
true
}
impl Default for RemoveCommentsConfig {
fn default() -> Self {
Self {
preserve_patterns: default_preserve_patterns(),
}
}
}
/// Plugin that removes comments from SVG documents
///
/// Processes the entire document tree (prologue, root, epilogue) to remove comment nodes.
/// Optionally preserves legal comments starting with `!`.
#[derive(Clone)]
pub struct RemoveCommentsPlugin {
config: RemoveCommentsConfig,
}
impl RemoveCommentsPlugin {
/// Check if a text node contains only formatting whitespace
///
/// Returns `true` if the text is empty after trimming AND contains newlines/tabs/carriage returns.
/// This identifies text nodes that were added purely for source formatting (indentation, line breaks)
/// and have no semantic meaning.
///
/// Used during whitespace cleanup after removing comments to prevent leftover formatting artifacts.
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 comments, we often have leftover text nodes containing only newlines
/// and indentation. This function removes those ONLY if there's actual content nearby
/// (other elements or meaningful text).
///
/// We preserve empty documents (no elements/text) to avoid collapsing structure entirely.
fn cleanup_formatting_whitespace(nodes: &mut Vec<Node>) {
// Check if there's any real content (elements or non-whitespace text)
let has_non_whitespace_content = nodes.iter().any(|node| match node {
Node::Element(_) => true,
Node::Text(text) => !text.trim().is_empty(),
_ => false,
});
// Only clean up whitespace if there's actual content - otherwise we'd remove everything
if has_non_whitespace_content {
nodes.retain(
|node| !matches!(node, Node::Text(text) if Self::is_formatting_whitespace(text)),
);
}
}
/// Check if an element requires preserving whitespace in text children
///
/// SVG text elements (`<text>`, `<tspan>`, etc.) are whitespace-sensitive - spaces,
/// newlines, and indentation can affect rendering. We must NOT normalize whitespace
/// in these elements.
///
/// Returns `true` for text-rendering elements where whitespace is semantic.
fn should_preserve_text_whitespace(element_name: &str) -> bool {
matches!(
element_name,
"text" | "tspan" | "tref" | "textPath" | "altGlyph"
)
}
/// Normalize text children after comment removal
///
/// After removing comments, we may have text nodes with excessive whitespace from
/// source formatting. This trims text nodes (removing leading/trailing whitespace and
/// collapsing internal newlines/tabs) UNLESS the parent is a text-rendering element
/// where whitespace has semantic meaning.
///
/// Also calls `cleanup_formatting_whitespace` to remove entirely empty text nodes.
fn normalize_text_children(element: &mut Element<'_>) {
let preserve = Self::should_preserve_text_whitespace(element.name.as_ref());
for child in &mut element.children {
if let Node::Text(text) = child {
// Only trim if NOT in a text element AND contains formatting characters
if !preserve && (text.contains('\n') || text.contains('\r') || text.contains('\t'))
{
let trimmed = text.trim();
if !trimmed.is_empty() {
*text = trimmed.to_string().into();
}
}
}
}
Self::cleanup_formatting_whitespace(&mut element.children);
}
/// Create a new RemoveCommentsPlugin with default configuration
///
/// By default, `preservePatterns` is `true` (legal comments are preserved).
pub fn new() -> Self {
Self {
config: RemoveCommentsConfig::default(),
}
}
/// Create plugin with specific configuration
pub fn with_config(config: RemoveCommentsConfig) -> Self {
Self { config }
}
/// Create plugin with preserve_patterns setting (convenience constructor)
pub fn with_preserve_patterns(preserve_patterns: bool) -> Self {
Self {
config: RemoveCommentsConfig { preserve_patterns },
}
}
/// Parse configuration from JSON value
///
/// Accepts either `null` (uses defaults) or an object with `preservePatterns` field.
fn parse_config(params: &Value) -> Result<RemoveCommentsConfig> {
if params.is_null() {
Ok(RemoveCommentsConfig::default())
} else {
serde_json::from_value(params.clone())
.map_err(|e| anyhow::anyhow!("Invalid plugin configuration: {}", e))
}
}
/// Check if a comment should be preserved
///
/// Legal comments start with `!` after any leading whitespace: `<!-- ! Copyright ... -->`
/// These are preserved when `preservePatterns` is `true`.
///
/// Returns `true` if the comment should be kept, `false` if it should be removed.
fn should_keep_comment(&self, comment: &str) -> bool {
self.config.preserve_patterns && comment.trim_start().starts_with('!')
}
/// Remove comments from a list of nodes (prologue, epilogue, or element children)
///
/// Filters out comment nodes based on `should_keep_comment`. Preserves all non-comment
/// nodes. After removing comments, cleans up leftover formatting whitespace.
fn remove_comments_from_nodes(&self, nodes: &mut Vec<Node>) {
nodes.retain(|node| match node {
Node::Comment(comment) => self.should_keep_comment(comment),
_ => true,
});
Self::cleanup_formatting_whitespace(nodes);
}
/// Recursively remove comments from an element and its descendants
///
/// Processes the element's immediate children, normalizes text after comment removal,
/// then recurses into child elements. This depth-first traversal ensures all comments
/// at any nesting level are removed.
fn remove_comments_recursive(&self, element: &mut Element) {
// Remove comment nodes from children
self.remove_comments_from_nodes(&mut element.children);
Self::normalize_text_children(element);
// Recursively process child elements
for child in &mut element.children {
if let Node::Element(elem) = child {
self.remove_comments_recursive(elem);
}
}
}
}
impl Default for RemoveCommentsPlugin {
fn default() -> Self {
Self::new()
}
}
impl Plugin for RemoveCommentsPlugin {
fn name(&self) -> &'static str {
"removeComments"
}
fn description(&self) -> &'static str {
"removes comments"
}
fn validate_params(&self, params: &Value) -> Result<()> {
Self::parse_config(params)?;
Ok(())
}
fn configure(&mut self, params: &Value) -> Result<()> {
self.config = Self::parse_config(params)?;
Ok(())
}
/// Apply comment removal to the entire SVG document
///
/// Processes three sections in order:
/// 1. **Prologue** - Nodes before the root `<svg>` element (DOCTYPE, processing instructions, comments)
/// 2. **Root** - The main `<svg>` element and all descendants (recursively)
/// 3. **Epilogue** - Any nodes after the closing `</svg>` tag
///
/// Each section is cleaned independently. Comments are filtered based on `preservePatterns`
/// configuration, and formatting whitespace is cleaned up after removal.
fn apply(&self, document: &mut Document) -> Result<()> {
// Remove comments from prologue (before <svg>)
self.remove_comments_from_nodes(&mut document.prologue);
// Remove comments from the main document tree (recursively processes all descendants)
self.remove_comments_recursive(&mut document.root);
// Remove comments from epilogue (after </svg>)
self.remove_comments_from_nodes(&mut document.epilogue);
Ok(())
}
}
#[cfg(test)]
mod unit_tests {
use super::*;
use serde_json::json;
use std::borrow::Cow;
use vexy_vsvg::ast::{Document, Element, Node};
fn create_element(name: &'static str) -> Element<'static> {
let mut element = Element::new(name);
element.name = Cow::Borrowed(name);
element
}
#[test]
fn test_plugin_info() {
let plugin = RemoveCommentsPlugin::new();
assert_eq!(plugin.name(), "removeComments");
assert_eq!(plugin.description(), "removes comments");
}
#[test]
fn test_plugin_creation() {
let plugin = RemoveCommentsPlugin::new();
assert!(plugin.config.preserve_patterns);
let config = RemoveCommentsConfig {
preserve_patterns: false,
};
let plugin2 = RemoveCommentsPlugin::with_config(config);
assert!(!plugin2.config.preserve_patterns);
}
#[test]
fn test_parameter_validation() {
let plugin = RemoveCommentsPlugin::new();
// Valid parameters
assert!(plugin.validate_params(&json!(null)).is_ok());
assert!(plugin.validate_params(&json!({})).is_ok());
assert!(plugin
.validate_params(&json!({"preservePatterns": true}))
.is_ok());
assert!(plugin
.validate_params(&json!({"preservePatterns": false}))
.is_ok());
// Invalid parameters
assert!(plugin
.validate_params(&json!({"preservePatterns": "invalid"}))
.is_err());
assert!(plugin
.validate_params(&json!({"preservePatterns": 123}))
.is_err());
assert!(plugin
.validate_params(&json!({"unknownParam": true}))
.is_err());
}
#[test]
fn test_comment_preservation_logic() {
let plugin = RemoveCommentsPlugin::new();
// By default, legal comments are preserved
assert!(plugin.should_keep_comment("! Legal comment"));
assert!(plugin.should_keep_comment("!Important notice"));
assert!(!plugin.should_keep_comment(" Regular comment"));
assert!(!plugin.should_keep_comment("Just a comment"));
// Test with preserve_patterns disabled
let config = RemoveCommentsConfig {
preserve_patterns: false,
};
let plugin2 = RemoveCommentsPlugin::with_config(config);
assert!(!plugin2.should_keep_comment("! Legal comment"));
assert!(!plugin2.should_keep_comment("Regular comment"));
}
#[test]
fn test_removes_regular_comments() {
let config = RemoveCommentsConfig {
preserve_patterns: true,
};
let plugin = RemoveCommentsPlugin::with_config(config);
let mut doc = Document::new();
// Create SVG with comments
let mut svg = create_element("svg");
svg.children
.push(Node::Comment("Regular comment".to_string().into()));
svg.children.push(Node::Element(create_element("rect")));
svg.children
.push(Node::Comment("Another comment".to_string().into()));
doc.root = svg;
// Apply plugin
plugin.apply(&mut doc).unwrap();
// Check that regular comments were removed
assert_eq!(doc.root.children.len(), 1);
if let Node::Element(elem) = &doc.root.children[0] {
assert_eq!(elem.name, "rect");
}
}
#[test]
fn test_preserves_legal_comments() {
let config = RemoveCommentsConfig {
preserve_patterns: true,
};
let plugin = RemoveCommentsPlugin::with_config(config);
let mut doc = Document::new();
// Create SVG with legal and regular comments
let mut svg = create_element("svg");
svg.children
.push(Node::Comment("! Legal comment".to_string().into()));
svg.children
.push(Node::Comment("Regular comment".to_string().into()));
svg.children.push(Node::Element(create_element("rect")));
doc.root = svg;
// Apply plugin
plugin.apply(&mut doc).unwrap();
// Check that legal comment was preserved
assert_eq!(doc.root.children.len(), 2);
if let Node::Comment(comment) = &doc.root.children[0] {
assert_eq!(comment.as_ref(), "! Legal comment");
}
if let Node::Element(elem) = &doc.root.children[1] {
assert_eq!(elem.name, "rect");
}
}
#[test]
fn test_removes_all_comments_when_disabled() {
let config = RemoveCommentsConfig {
preserve_patterns: false,
};
let plugin = RemoveCommentsPlugin::with_config(config);
let mut doc = Document::new();
// Create SVG with legal and regular comments
let mut svg = create_element("svg");
svg.children
.push(Node::Comment("! Legal comment".to_string().into()));
svg.children
.push(Node::Comment("Regular comment".to_string().into()));
svg.children.push(Node::Element(create_element("rect")));
doc.root = svg;
// Apply plugin
plugin.apply(&mut doc).unwrap();
// Check that all comments were removed
assert_eq!(doc.root.children.len(), 1);
if let Node::Element(elem) = &doc.root.children[0] {
assert_eq!(elem.name, "rect");
}
}
#[test]
fn test_removes_nested_comments() {
let plugin = RemoveCommentsPlugin::new();
let mut doc = Document::new();
// Create SVG with nested comments
let mut svg = create_element("svg");
svg.children
.push(Node::Comment("Root comment".to_string().into()));
let mut group = create_element("g");
group
.children
.push(Node::Comment("Group comment".to_string().into()));
group.children.push(Node::Element(create_element("rect")));
svg.children.push(Node::Element(group));
doc.root = svg;
// Apply plugin
plugin.apply(&mut doc).unwrap();
// Check that nested comments were removed
assert_eq!(doc.root.children.len(), 1);
if let Node::Element(group_elem) = &doc.root.children[0] {
assert_eq!(group_elem.name, "g");
assert_eq!(group_elem.children.len(), 1);
if let Node::Element(rect_elem) = &group_elem.children[0] {
assert_eq!(rect_elem.name, "rect");
}
}
}
#[test]
fn test_removes_prologue_and_epilogue_comments() {
let plugin = RemoveCommentsPlugin::new();
let mut doc = Document::new();
// Add comments to prologue and epilogue
doc.prologue
.push(Node::Comment("Prologue comment".to_string().into()));
doc.prologue
.push(Node::Comment("! Legal prologue".to_string().into()));
doc.epilogue
.push(Node::Comment("Epilogue comment".to_string().into()));
doc.epilogue
.push(Node::Comment("! Legal epilogue".to_string().into()));
let svg = create_element("svg");
doc.root = svg;
// Apply plugin
plugin.apply(&mut doc).unwrap();
// Check that only legal comments remain
assert_eq!(doc.prologue.len(), 1);
if let Node::Comment(comment) = &doc.prologue[0] {
assert_eq!(comment.as_ref(), "! Legal prologue");
}
assert_eq!(doc.epilogue.len(), 1);
if let Node::Comment(comment) = &doc.epilogue[0] {
assert_eq!(comment.as_ref(), "! Legal epilogue");
}
}
#[test]
fn test_cleans_whitespace_only_text() {
let plugin = RemoveCommentsPlugin::new();
let mut doc = Document::new();
// Create SVG with comments and whitespace
let mut svg = create_element("svg");
svg.children.push(Node::Text("\n ".to_string().into()));
svg.children
.push(Node::Comment("Comment".to_string().into()));
svg.children.push(Node::Text("\n ".to_string().into()));
svg.children.push(Node::Element(create_element("rect")));
svg.children.push(Node::Text("\n".to_string().into()));
doc.root = svg;
// Apply plugin
plugin.apply(&mut doc).unwrap();
// Check that whitespace-only text nodes were cleaned up
assert_eq!(doc.root.children.len(), 1);
if let Node::Element(elem) = &doc.root.children[0] {
assert_eq!(elem.name, "rect");
}
}
#[test]
fn test_preserves_meaningful_text() {
let plugin = RemoveCommentsPlugin::new();
let mut doc = Document::new();
// Create SVG with meaningful text
let mut svg = create_element("svg");
let mut text_elem = create_element("text");
text_elem
.children
.push(Node::Text("Hello".to_string().into()));
text_elem
.children
.push(Node::Comment("Comment".to_string().into()));
text_elem
.children
.push(Node::Text(" World".to_string().into()));
svg.children.push(Node::Element(text_elem));
doc.root = svg;
// Apply plugin
plugin.apply(&mut doc).unwrap();
// Check that meaningful text was preserved
if let Node::Element(text_elem) = &doc.root.children[0] {
assert_eq!(text_elem.name, "text");
assert_eq!(text_elem.children.len(), 2);
if let Node::Text(text) = &text_elem.children[0] {
assert_eq!(text.as_ref(), "Hello");
}
if let Node::Text(text) = &text_elem.children[1] {
assert_eq!(text.as_ref(), " World");
}
}
}
#[test]
fn test_config_parsing() {
// Default config
let config = RemoveCommentsPlugin::parse_config(&json!(null)).unwrap();
assert!(config.preserve_patterns);
// Explicit config
let config =
RemoveCommentsPlugin::parse_config(&json!({"preservePatterns": false})).unwrap();
assert!(!config.preserve_patterns);
let config =
RemoveCommentsPlugin::parse_config(&json!({"preservePatterns": true})).unwrap();
assert!(config.preserve_patterns);
}
}
// Use parameterized testing framework for SVGO fixture tests
#[cfg(test)]
#[cfg(test)]
#[cfg(test)]
vexy_vsvg_test_utils::plugin_fixture_tests_with_params!(RemoveCommentsPlugin, "removeComments");