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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
// this_file: crates/vexy-vsvg-plugin-sdk/src/plugins/convert_colors.rs
//! Shrink colors by converting between formats.
//!
//! This plugin ports SVGO's `convertColors` plugin. It converts colors to their smallest
//! representation by trying multiple transformations:
//! - `rgb(255, 0, 0)` → `#ff0000` → `#f00` → `red` (saves 12 bytes)
//! - `rgb(100%, 50%, 25%)` → `#ff8040` (saves 10 bytes)
//! - `#aabbcc` → `#abc` (saves 3 bytes)
//! - `#000000` → `black` (saves 3 bytes)
//!
//! The plugin respects SVG masking contexts where color names behave differently than hex colors,
//! so `fill="red"` inside a `<mask>` stays as `#f00` instead of becoming `red`.
//!
//! # Before
//! ```xml
//! <rect fill="rgb(255, 0, 0)" stroke="#aabbcc"/>
//! ```
//!
//! # After
//! ```xml
//! <rect fill="red" stroke="#abc"/>
//! ```
//!
//! # Savings
//! - `rgb(255, 0, 0)` (14 chars) → `red` (3 chars) = 11 bytes saved
//! - `#aabbcc` (7 chars) → `#abc` (4 chars) = 3 bytes saved
use crate::Plugin;
use anyhow::Result;
use once_cell::sync::Lazy;
use regex::Regex;
use std::collections::HashMap;
use vexy_vsvg::ast::{Document, Element};
use vexy_vsvg::error::VexyError;
use vexy_vsvg::visitor::Visitor;
use serde::{Deserialize, Serialize};
static RGB_REGEX: Lazy<Regex> = Lazy::new(|| {
Regex::new(r"^rgb\(\s*([+-]?(?:\d*\.\d+|\d+\.?)%?)\s*[,\s]+\s*([+-]?(?:\d*\.\d+|\d+\.?)%?)\s*[,\s]+\s*([+-]?(?:\d*\.\d+|\d+\.?)%?)\s*\)$").unwrap()
});
/// Configuration parameters for ConvertColors plugin.
///
/// Each field enables a specific color conversion. The plugin applies conversions
/// in a pipeline, so `rgb2hex` feeds into `shorthex` which feeds into `shortname`.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ConvertColorsConfig {
/// Convert colors to `currentColor` keyword (inherits from parent element's color).
/// - `false`: no conversion
/// - `true`: convert all colors to `currentColor`
/// - `"#ff0000"`: convert this specific color to `currentColor`
/// - `"/^#ff/"`: regex pattern matching colors to convert
#[serde(rename = "currentColor")]
pub current_color: ConvertCurrentColor,
/// Convert color names to hex (`red` → `#ff0000`).
pub names2hex: bool,
/// Convert `rgb()` functions to hex (`rgb(255,0,0)` → `#ff0000`).
pub rgb2hex: bool,
/// Force hex color case (`lower`, `upper`, or `none`).
#[serde(rename = "convertCase")]
pub convert_case: ConvertCase,
/// Shorten hex when possible (`#aabbcc` → `#abc`).
pub shorthex: bool,
/// Convert hex to short color names when shorter (`#f00` → `red`).
pub shortname: bool,
}
/// How to convert colors to the `currentColor` keyword.
///
/// `currentColor` makes an element inherit the color from its parent's `color` attribute,
/// useful for reducing duplication when child elements match their parent's color.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum ConvertCurrentColor {
/// Disabled (default).
False,
/// When `true`, convert all colors to `currentColor`. When `false`, no conversion.
Bool(bool),
/// Match a specific color or regex pattern. Examples: `"#ff0000"` or `"/^#ff/"`.
String(String),
// Regex(String), // Regex not directly serializable/deserializable easily, assume string for config
}
/// Hex color case normalization.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ConvertCase {
/// Don't change case (keep original).
None,
/// Force lowercase (`#FF0000` → `#ff0000`).
Lower,
/// Force uppercase (`#ff0000` → `#FF0000`).
Upper,
}
impl Default for ConvertColorsConfig {
fn default() -> Self {
Self {
current_color: ConvertCurrentColor::False,
names2hex: true,
rgb2hex: true,
convert_case: ConvertCase::Lower,
shorthex: true,
shortname: true,
}
}
}
/// Plugin that converts colors between different formats
pub struct ConvertColorsPlugin {
config: ConvertColorsConfig,
}
impl ConvertColorsPlugin {
/// Create a new ConvertColorsPlugin with default configuration
pub fn new() -> Self {
Self {
config: ConvertColorsConfig::default(),
}
}
/// Create a new ConvertColorsPlugin with custom configuration
pub fn with_config(config: ConvertColorsConfig) -> Self {
Self { config }
}
/// Parse configuration from JSON parameters
pub fn parse_config(params: &serde_json::Value) -> anyhow::Result<ConvertColorsConfig> {
if params.is_null() {
return Ok(ConvertColorsConfig::default());
}
let mut config = ConvertColorsConfig::default();
if let Some(obj) = params.as_object() {
for (key, value) in obj {
match key.as_str() {
"currentColor" => {
if let Some(bool_val) = value.as_bool() {
config.current_color = if bool_val {
ConvertCurrentColor::Bool(true)
} else {
ConvertCurrentColor::Bool(false)
};
} else if let Some(str_val) = value.as_str() {
config.current_color = ConvertCurrentColor::String(str_val.to_string());
}
}
"names2hex" => {
if let Some(bool_val) = value.as_bool() {
config.names2hex = bool_val;
}
}
"rgb2hex" => {
if let Some(bool_val) = value.as_bool() {
config.rgb2hex = bool_val;
}
}
"shorthex" => {
if let Some(bool_val) = value.as_bool() {
config.shorthex = bool_val;
}
}
"shortname" => {
if let Some(bool_val) = value.as_bool() {
config.shortname = bool_val;
}
}
"convertCase" => {
if let Some(str_val) = value.as_str() {
match str_val {
"lower" => config.convert_case = ConvertCase::Lower,
"upper" => config.convert_case = ConvertCase::Upper,
_ => {
return Err(anyhow::anyhow!(
"Invalid convertCase value: {}",
str_val
))
}
}
} else if value.as_bool() == Some(false) {
config.convert_case = ConvertCase::None;
}
}
_ => return Err(anyhow::anyhow!("Unknown parameter: {}", key)),
}
}
}
Ok(config)
}
/// Color name keywords to hex values.
///
/// Maps SVG color names to their canonical hex representation.
/// Used in the `names2hex` conversion step to normalize color keywords into hex.
fn color_names() -> &'static HashMap<&'static str, &'static str> {
static COLOR_NAMES: std::sync::OnceLock<HashMap<&'static str, &'static str>> =
std::sync::OnceLock::new();
COLOR_NAMES.get_or_init(|| {
[
("black", "#000000"),
("silver", "#c0c0c0"),
("gray", "#808080"),
("white", "#ffffff"),
("maroon", "#800000"),
("red", "#ff0000"),
("purple", "#800080"),
("fuchsia", "#ff00ff"),
("green", "#008000"),
("lime", "#00ff00"),
("olive", "#808000"),
("yellow", "#ffff00"),
("navy", "#000080"),
("blue", "#0000ff"),
("teal", "#008080"),
("aqua", "#00ffff"),
// Extended color names
("aliceblue", "#f0f8ff"),
("antiquewhite", "#faebd7"),
("aquamarine", "#7fffd4"),
("azure", "#f0ffff"),
("beige", "#f5f5dc"),
("bisque", "#ffe4c4"),
("blanchedalmond", "#ffebcd"),
("blueviolet", "#8a2be2"),
("brown", "#a52a2a"),
("burlywood", "#deb887"),
("cadetblue", "#5f9ea0"),
("chartreuse", "#7fff00"),
("chocolate", "#d2691e"),
("coral", "#ff7f50"),
("cornflowerblue", "#6495ed"),
("cornsilk", "#fff8dc"),
("crimson", "#dc143c"),
("cyan", "#00ffff"),
("darkblue", "#00008b"),
("darkcyan", "#008b8b"),
("darkgoldenrod", "#b8860b"),
("darkgray", "#a9a9a9"),
("darkgreen", "#006400"),
("darkkhaki", "#bdb76b"),
("darkmagenta", "#8b008b"),
("darkolivegreen", "#556b2f"),
("darkorange", "#ff8c00"),
("darkorchid", "#9932cc"),
("darkred", "#8b0000"),
("darksalmon", "#e9967a"),
("darkseagreen", "#8fbc8f"),
("darkslateblue", "#483d8b"),
("darkslategray", "#2f4f4f"),
("darkturquoise", "#00ced1"),
("darkviolet", "#9400d3"),
("deeppink", "#ff1493"),
("deepskyblue", "#00bfff"),
("dimgray", "#696969"),
("dodgerblue", "#1e90ff"),
("firebrick", "#b22222"),
("floralwhite", "#fffaf0"),
("forestgreen", "#228b22"),
("gainsboro", "#dcdcdc"),
("ghostwhite", "#f8f8ff"),
("gold", "#ffd700"),
("goldenrod", "#daa520"),
("greenyellow", "#adff2f"),
("honeydew", "#f0fff0"),
("hotpink", "#ff69b4"),
("indianred", "#cd5c5c"),
("indigo", "#4b0082"),
("ivory", "#fffff0"),
("khaki", "#f0e68c"),
("lavender", "#e6e6fa"),
("lavenderblush", "#fff0f5"),
("lawngreen", "#7cfc00"),
("lemonchiffon", "#fffacd"),
("lightblue", "#add8e6"),
("lightcoral", "#f08080"),
("lightcyan", "#e0ffff"),
("lightgoldenrodyellow", "#fafad2"),
("lightgray", "#d3d3d3"),
("lightgreen", "#90ee90"),
("lightpink", "#ffb6c1"),
("lightsalmon", "#ffa07a"),
("lightseagreen", "#20b2aa"),
("lightskyblue", "#87cefa"),
("lightslategray", "#778899"),
("lightsteelblue", "#b0c4de"),
("lightyellow", "#ffffe0"),
("limegreen", "#32cd32"),
("linen", "#faf0e6"),
("magenta", "#ff00ff"),
("mediumaquamarine", "#66cdaa"),
("mediumblue", "#0000cd"),
("mediumorchid", "#ba55d3"),
("mediumpurple", "#9370db"),
("mediumseagreen", "#3cb371"),
("mediumslateblue", "#7b68ee"),
("mediumspringgreen", "#00fa9a"),
("mediumturquoise", "#48d1cc"),
("mediumvioletred", "#c71585"),
("midnightblue", "#191970"),
("mintcream", "#f5fffa"),
("mistyrose", "#ffe4e1"),
("moccasin", "#ffe4b5"),
("navajowhite", "#ffdead"),
("oldlace", "#fdf5e6"),
("olivedrab", "#6b8e23"),
("orange", "#ffa500"),
("orangered", "#ff4500"),
("orchid", "#da70d6"),
("palegoldenrod", "#eee8aa"),
("palegreen", "#98fb98"),
("paleturquoise", "#afeeee"),
("palevioletred", "#db7093"),
("papayawhip", "#ffefd5"),
("peachpuff", "#ffdab9"),
("peru", "#cd853f"),
("pink", "#ffc0cb"),
("plum", "#dda0dd"),
("powderblue", "#b0e0e6"),
("rosybrown", "#bc8f8f"),
("royalblue", "#4169e1"),
("saddlebrown", "#8b4513"),
("salmon", "#fa8072"),
("sandybrown", "#f4a460"),
("seagreen", "#2e8b57"),
("seashell", "#fff5ee"),
("sienna", "#a0522d"),
("skyblue", "#87ceeb"),
("slateblue", "#6a5acd"),
("slategray", "#708090"),
("snow", "#fffafa"),
("springgreen", "#00ff7f"),
("steelblue", "#4682b4"),
("tan", "#d2b48c"),
("thistle", "#d8bfd8"),
("tomato", "#ff6347"),
("turquoise", "#40e0d0"),
("violet", "#ee82ee"),
("wheat", "#f5deb3"),
("whitesmoke", "#f5f5f5"),
("yellowgreen", "#9acd32"),
]
.into_iter()
.collect()
})
}
/// Short color names for hex values.
///
/// Maps hex colors (both long and short form) to their shortest keyword representation.
/// Only includes colors where the keyword is shorter than the hex form.
/// Example: `#f00` → `red` saves 1 byte, `#000000` → `black` saves 3 bytes.
fn color_short_names() -> &'static HashMap<&'static str, &'static str> {
static COLOR_SHORT_NAMES: std::sync::OnceLock<HashMap<&'static str, &'static str>> =
std::sync::OnceLock::new();
COLOR_SHORT_NAMES.get_or_init(|| {
[
("#000000", "black"),
("#000", "black"),
("#000080", "navy"),
("#008", "navy"),
("#008000", "green"),
("#080", "green"),
("#008080", "teal"),
("#088", "teal"),
("#4b0082", "indigo"),
("#800000", "maroon"),
("#800", "maroon"),
("#800080", "purple"),
("#808", "purple"),
("#808000", "olive"),
("#880", "olive"),
("#808080", "gray"),
("#888", "gray"),
("#a0522d", "sienna"),
("#a52a2a", "brown"),
("#c0c0c0", "silver"),
("#ccc", "silver"),
("#cd853f", "peru"),
("#d2b48c", "tan"),
("#da70d6", "orchid"),
("#dda0dd", "plum"),
("#ee82ee", "violet"),
("#f0e68c", "khaki"),
("#f0ffff", "azure"),
("#f5deb3", "wheat"),
("#f5f5dc", "beige"),
("#fa8072", "salmon"),
("#faf0e6", "linen"),
("#ff0000", "red"),
("#f00", "red"),
("#ff6347", "tomato"),
("#ff7f50", "coral"),
("#ffa500", "orange"),
("#ffc0cb", "pink"),
("#ffd700", "gold"),
("#ffe4c4", "bisque"),
("#fffafa", "snow"),
("#fffff0", "ivory"),
("#ffffff", "white"),
("#fff", "white"),
]
.into_iter()
.collect()
})
}
/// SVG attributes that accept color values.
///
/// These are the presentation attributes that can contain color values.
/// We only convert colors in these specific attributes to avoid touching
/// non-color data that happens to look like a color (e.g., `id="red"`).
fn color_props() -> &'static std::collections::HashSet<&'static str> {
static COLOR_PROPS: std::sync::OnceLock<std::collections::HashSet<&'static str>> =
std::sync::OnceLock::new();
COLOR_PROPS.get_or_init(|| {
[
"color",
"fill",
"stroke",
"stop-color",
"flood-color",
"lighting-color",
]
.into_iter()
.collect()
})
}
/// Parse `rgb()` function notation into RGB components.
///
/// Handles both numeric and percentage values:
/// - `rgb(255, 128, 0)` → `(255, 128, 0)`
/// - `rgb(100%, 50%, 0%)` → `(255, 128, 0)` (percentage × 2.55 = byte value)
/// - `rgb(255 128 0)` → `(255, 128, 0)` (modern space-separated syntax)
///
/// Clamps out-of-range values to 0-255. Returns `None` if parsing fails.
fn parse_rgb(value: &str) -> Option<(u8, u8, u8)> {
if let Some(captures) = RGB_REGEX.captures(value) {
let mut components = Vec::new();
for i in 1..=3 {
let component_str = captures.get(i)?.as_str();
let component = if component_str.contains('%') {
// Percentage: 0% → 0, 100% → 255
let percentage = component_str.trim_end_matches('%').parse::<f64>().ok()?;
// Multiply by 2.55 to convert from 0-100 range to 0-255 range
(percentage * 2.55).round() as i32
} else {
// Absolute value: parse directly as integer
component_str.parse::<i32>().ok()?
};
// Clamp to valid u8 range (SVG spec allows out-of-range values)
components.push(component.clamp(0, 255) as u8);
}
if components.len() == 3 {
return Some((components[0], components[1], components[2]));
}
}
None
}
/// Convert RGB components to hex notation.
///
/// Formats three 8-bit color channels into CSS hex notation `#RRGGBB`.
/// Always produces uppercase hex digits with zero-padding.
fn rgb_to_hex(r: u8, g: u8, b: u8) -> String {
format!("#{:02X}{:02X}{:02X}", r, g, b)
}
/// Convert 6-digit hex to 3-digit hex if possible.
///
/// When all three color channels have duplicate hex digits (`#RRGGBB` where R, G, and B
/// are the same digit repeated), we can shorten to `#RGB`.
/// Example: `#aabbcc` → `#abc` (saves 3 bytes).
///
/// Returns `None` if the hex can't be shortened (e.g., `#123456` or already short `#abc`).
fn hex_to_short_hex(hex: &str) -> Option<String> {
// Only works on 7-character strings like "#aabbcc"
if hex.len() == 7 && hex.starts_with('#') {
let chars: Vec<char> = hex.chars().collect();
// Check if each channel has duplicate digits: chars[1]==chars[2], etc.
if chars[1] == chars[2] && chars[3] == chars[4] && chars[5] == chars[6] {
return Some(format!("#{}{}{}", chars[1], chars[3], chars[5]));
}
}
None
}
/// Check if value contains a URL reference.
///
/// Paint servers like gradients and patterns use `url(#id)` syntax.
/// We don't convert case for these since the fragment identifier is case-sensitive.
fn includes_url_reference(value: &str) -> bool {
value.contains("url(")
}
/// Convert a color value through the configured transformation pipeline.
///
/// Applies conversions in order:
/// 1. `currentColor` replacement (if configured)
/// 2. Color name → hex (`red` → `#ff0000`)
/// 3. `rgb()` → hex (`rgb(255,0,0)` → `#FF0000`)
/// 4. Case normalization (`#FF0000` → `#ff0000`)
/// 5. Hex shortening (`#ff0000` → `#f00`)
/// 6. Hex → short name (`#f00` → `red`)
///
/// The `in_mask` parameter prevents converting to color names inside `<mask>` elements,
/// since mask colors use luminance values where `red` and `#ff0000` can differ slightly
/// in how browsers interpret them.
fn convert_color_value(&self, value: &str, in_mask: bool) -> String {
let mut val = value.to_string();
// SVG keywords that should never be converted to currentColor
let special_values = ["none", "inherit", "transparent", "currentColor"];
let is_special = special_values
.iter()
.any(|&special| val.eq_ignore_ascii_case(special));
// Step 1: Convert to currentColor if configured
match &self.config.current_color {
ConvertCurrentColor::Bool(true) => {
// Convert all non-special colors to currentColor (outside masks)
if !in_mask && !is_special {
val = "currentColor".to_string();
}
}
ConvertCurrentColor::String(ref target) => {
if !in_mask && !is_special {
// Exact match or regex match
if val == *target {
val = "currentColor".to_string();
} else if let Ok(regex) = Regex::new(target) {
if regex.is_match(&val) {
val = "currentColor".to_string();
}
}
}
}
_ => {}
}
// Step 2: Convert color names to hex (enables further optimizations)
if self.config.names2hex {
let color_name = val.to_lowercase();
if let Some(hex_value) = Self::color_names().get(color_name.as_str()) {
val = hex_value.to_string();
}
}
// Step 3: Convert rgb() function notation to hex
if self.config.rgb2hex {
if let Some((r, g, b)) = Self::parse_rgb(&val) {
val = Self::rgb_to_hex(r, g, b);
}
}
// Step 4: Normalize case (preserve special keywords and URL references)
let is_special_for_case = ["none", "inherit", "transparent", "currentColor"]
.iter()
.any(|&special| val.eq_ignore_ascii_case(special));
if !Self::includes_url_reference(&val) && !is_special_for_case {
match self.config.convert_case {
ConvertCase::Lower => val = val.to_lowercase(),
ConvertCase::Upper => val = val.to_uppercase(),
ConvertCase::None => {}
}
}
// Step 5: Shorten hex when possible (#aabbcc → #abc)
if self.config.shorthex {
if let Some(short_hex) = Self::hex_to_short_hex(&val) {
val = short_hex;
}
}
// Step 6: Convert to short color name if shorter (not in masks)
if self.config.shortname && !in_mask {
let color_name = val.to_lowercase();
if let Some(short_name) = Self::color_short_names().get(color_name.as_str()) {
if short_name.len() < val.len() {
val = short_name.to_string();
}
}
}
val
}
}
impl Default for ConvertColorsPlugin {
fn default() -> Self {
Self::new()
}
}
impl crate::PluginWithParams for ConvertColorsPlugin {
type Config = ConvertColorsConfig;
fn with_config(config: Self::Config) -> Self {
Self::with_config(config)
}
fn parse_config(params: &serde_json::Value) -> anyhow::Result<Self::Config> {
Self::parse_config(params)
}
}
impl Plugin for ConvertColorsPlugin {
fn name(&self) -> &'static str {
"convertColors"
}
fn description(&self) -> &'static str {
"Convert colors: rgb() to #rrggbb and #rrggbb to #rgb"
}
fn validate_params(&self, params: &serde_json::Value) -> anyhow::Result<()> {
if let Some(obj) = params.as_object() {
for (key, value) in obj {
match key.as_str() {
"currentColor" => {
if !value.is_boolean() && !value.is_string() {
return Err(anyhow::anyhow!(
"currentColor must be a boolean or string"
));
}
}
"names2hex" | "rgb2hex" | "shorthex" | "shortname" => {
if !value.is_boolean() {
return Err(anyhow::anyhow!("{} must be a boolean", key));
}
}
"convertCase" => {
if let Some(case_str) = value.as_str() {
match case_str {
"lower" | "upper" => {}
_ => {
return Err(anyhow::anyhow!(
"convertCase must be 'lower' or 'upper'"
))
}
}
} else if value.as_bool() == Some(false) {
// false is allowed
} else {
return Err(anyhow::anyhow!(
"convertCase must be false, 'lower', or 'upper'"
));
}
}
_ => {
return Err(anyhow::anyhow!("Unknown parameter: {}", key));
}
}
}
}
Ok(())
}
fn apply(&self, document: &mut Document) -> anyhow::Result<()> {
let mut visitor = ColorConversionVisitor::new(self.config.clone());
vexy_vsvg::visitor::walk_document(&mut visitor, document)?;
Ok(())
}
}
/// Visitor that walks the document tree and converts color attributes.
///
/// Tracks mask element nesting depth to prevent converting colors to names inside masks,
/// where color names and hex colors can have subtly different luminance interpretations.
struct ColorConversionVisitor {
config: ConvertColorsConfig,
/// Counts how many `<mask>` elements deep we are (0 = not in a mask).
mask_counter: usize,
}
impl ColorConversionVisitor {
fn new(config: ConvertColorsConfig) -> Self {
Self {
config,
mask_counter: 0,
}
}
}
impl Visitor<'_> for ColorConversionVisitor {
fn visit_element_enter(&mut self, element: &mut Element<'_>) -> Result<(), VexyError> {
// Track when we enter a mask element (increment nesting counter)
if element.name == "mask" {
self.mask_counter += 1;
}
// Find and convert color attributes on this element
let plugin = ConvertColorsPlugin::with_config(self.config.clone());
let mut attrs_to_update = Vec::new();
for (attr_name, attr_value) in &element.attributes {
// Only process known color attributes (skip id, class, etc.)
if ConvertColorsPlugin::color_props().contains(attr_name.as_ref()) {
let converted_value = plugin.convert_color_value(attr_value, self.mask_counter > 0);
if converted_value != *attr_value {
attrs_to_update.push((attr_name.clone(), converted_value));
}
}
}
// Apply the conversions (done in separate loop to avoid borrowing conflicts)
for (attr_name, new_value) in attrs_to_update {
element.attributes.insert(attr_name, new_value.into());
}
Ok(())
}
fn visit_element_exit(&mut self, element: &mut Element<'_>) -> Result<(), VexyError> {
// Track when we exit a mask element (decrement nesting counter)
if element.name == "mask" {
self.mask_counter = self.mask_counter.saturating_sub(1);
}
Ok(())
}
}
#[cfg(test)]
mod 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
}
fn create_element_with_attrs(name: &'static str, attrs: &[(&str, &str)]) -> Element<'static> {
let mut element = create_element(name);
for (key, value) in attrs {
element.set_attr(*key, *value);
}
element
}
#[test]
fn test_plugin_creation() {
let plugin = ConvertColorsPlugin::new();
assert_eq!(plugin.name(), "convertColors");
assert!(plugin.config.names2hex);
assert!(plugin.config.rgb2hex);
}
#[test]
fn test_parameter_validation() {
let plugin = ConvertColorsPlugin::new();
// Valid parameters
assert!(plugin.validate_params(&json!({})).is_ok());
assert!(plugin.validate_params(&json!({"names2hex": true})).is_ok());
assert!(plugin
.validate_params(&json!({"convertCase": "lower"}))
.is_ok());
assert!(plugin
.validate_params(&json!({"convertCase": false}))
.is_ok());
// Invalid parameters
assert!(plugin
.validate_params(&json!({"names2hex": "invalid"}))
.is_err());
assert!(plugin
.validate_params(&json!({"convertCase": "invalid"}))
.is_err());
assert!(plugin
.validate_params(&json!({"invalidParam": true}))
.is_err());
}
#[test]
fn test_color_names() {
let names = ConvertColorsPlugin::color_names();
assert_eq!(names.get("black"), Some(&"#000000"));
assert_eq!(names.get("white"), Some(&"#ffffff"));
assert_eq!(names.get("red"), Some(&"#ff0000"));
}
#[test]
fn test_rgb_to_hex() {
assert_eq!(ConvertColorsPlugin::rgb_to_hex(255, 0, 0), "#FF0000");
assert_eq!(ConvertColorsPlugin::rgb_to_hex(0, 255, 0), "#00FF00");
assert_eq!(ConvertColorsPlugin::rgb_to_hex(0, 0, 255), "#0000FF");
assert_eq!(ConvertColorsPlugin::rgb_to_hex(64, 64, 64), "#404040");
}
#[test]
fn test_hex_to_short_hex() {
assert_eq!(
ConvertColorsPlugin::hex_to_short_hex("#aabbcc"),
Some("#abc".to_string())
);
assert_eq!(
ConvertColorsPlugin::hex_to_short_hex("#000000"),
Some("#000".to_string())
);
assert_eq!(ConvertColorsPlugin::hex_to_short_hex("#123456"), None);
assert_eq!(ConvertColorsPlugin::hex_to_short_hex("#abc"), None);
}
#[test]
fn test_parse_rgb() {
assert_eq!(
ConvertColorsPlugin::parse_rgb("rgb(255, 0, 0)"),
Some((255, 0, 0))
);
assert_eq!(
ConvertColorsPlugin::parse_rgb("rgb(64, 64, 64)"),
Some((64, 64, 64))
);
assert_eq!(
ConvertColorsPlugin::parse_rgb("rgb(64 64 64)"),
Some((64, 64, 64))
);
assert_eq!(
ConvertColorsPlugin::parse_rgb("rgb(100%, 0%, 0%)"),
Some((255, 0, 0))
);
assert_eq!(
ConvertColorsPlugin::parse_rgb("rgb(-255, 100, 500)"),
Some((0, 100, 255))
);
assert_eq!(ConvertColorsPlugin::parse_rgb("invalid"), None);
}
#[test]
fn test_convert_color_value() {
let plugin = ConvertColorsPlugin::new();
assert_eq!(plugin.convert_color_value("black", false), "#000");
assert_eq!(plugin.convert_color_value("RED", false), "red");
assert_eq!(plugin.convert_color_value("rgb(255, 0, 0)", false), "red");
assert_eq!(
plugin.convert_color_value("rgb(64, 64, 64)", false),
"#404040"
);
assert_eq!(plugin.convert_color_value("#aabbcc", false), "#abc");
assert_eq!(plugin.convert_color_value("#000000", false), "#000");
assert_eq!(plugin.convert_color_value("invalid", false), "invalid");
}
#[test]
fn test_convert_color_value_with_current_color() {
let config = ConvertColorsConfig {
current_color: ConvertCurrentColor::Bool(true),
names2hex: false,
rgb2hex: false,
shorthex: false,
shortname: false,
..ConvertColorsConfig::default()
};
let plugin = ConvertColorsPlugin::with_config(config);
// Regular colors should be converted to currentColor
assert_eq!(plugin.convert_color_value("black", false), "currentColor");
assert_eq!(plugin.convert_color_value("RED", false), "currentColor");
assert_eq!(
plugin.convert_color_value("rgb(255, 0, 0)", false),
"currentColor"
);
assert_eq!(plugin.convert_color_value("#ff0000", false), "currentColor");
// Special values should NOT be converted to currentColor and should preserve their case
assert_eq!(plugin.convert_color_value("none", false), "none");
assert_eq!(plugin.convert_color_value("NONE", false), "NONE"); // case preserved for special values
assert_eq!(plugin.convert_color_value("inherit", false), "inherit");
assert_eq!(
plugin.convert_color_value("transparent", false),
"transparent"
);
assert_eq!(
plugin.convert_color_value("currentColor", false),
"currentColor"
);
}
#[test]
fn test_convert_color_value_in_mask() {
let config = ConvertColorsConfig {
current_color: ConvertCurrentColor::Bool(true),
..ConvertColorsConfig::default()
};
let plugin = ConvertColorsPlugin::with_config(config);
// Inside mask (in_mask=true): Should NOT convert to currentColor but should do other conversions
assert_eq!(plugin.convert_color_value("white", true), "#fff"); // names2hex -> shorthex (shortname disabled in masks)
assert_eq!(plugin.convert_color_value("black", true), "#000"); // names2hex -> shorthex (shortname disabled in masks)
assert_eq!(plugin.convert_color_value("red", true), "#f00"); // names2hex -> shorthex (shortname disabled in masks)
// Outside mask (in_mask=false): Should convert to currentColor
assert_eq!(plugin.convert_color_value("white", false), "currentColor");
assert_eq!(plugin.convert_color_value("black", false), "currentColor");
assert_eq!(plugin.convert_color_value("red", false), "currentColor");
}
#[test]
fn test_plugin_apply() {
let plugin = ConvertColorsPlugin::new();
let mut doc = Document::new();
// Create element with color attributes
let element = create_element_with_attrs(
"rect",
&[
("fill", "red"),
("stroke", "rgb(0, 255, 0)"),
("color", "#aabbcc"),
],
);
doc.root.children.push(Node::Element(element));
plugin.apply(&mut doc).unwrap();
if let Some(Node::Element(rect)) = doc.root.children.first() {
assert_eq!(rect.attr("fill"), Some("red"));
assert_eq!(rect.attr("stroke"), Some("#0f0"));
assert_eq!(rect.attr("color"), Some("#abc"));
}
}
#[test]
fn test_mask_counter() {
let plugin = ConvertColorsPlugin::new();
let mut doc = Document::new();
// Create mask element with nested colored element
let mut mask = create_element("mask");
let colored_element = create_element_with_attrs("rect", &[("fill", "red")]);
mask.children.push(Node::Element(colored_element));
doc.root.children.push(Node::Element(mask));
plugin.apply(&mut doc).unwrap();
// Should still convert colors inside mask but not to color names
if let Some(Node::Element(mask_elem)) = doc.root.children.first() {
if let Some(Node::Element(rect)) = mask_elem.children.first() {
assert_eq!(rect.attr("fill"), Some("#f00")); // red -> #ff0000 -> #f00 (shortname disabled in masks)
}
}
}
}
// Custom fixture tests for ConvertColorsPlugin with parameter support
#[cfg(test)]
mod fixture_tests {
// TODO: Re-enable this test when test utilities are properly imported
// #[test]
// fn test_plugin_with_fixtures() {
// let fixtures = load_plugin_fixtures("convertColors").unwrap();
//
// if fixtures.is_empty() {
// println!("No fixtures found for plugin: convertColors");
// return;
// }
//
// for fixture in fixtures {
// println!("Testing fixture: {}", fixture.name);
//
// // Create plugin instance with parameters
// let mut plugin = if let Some(ref params) = fixture.params {
// let config = ConvertColorsPlugin::parse_config(params).unwrap_or_else(|e| {
// panic!("Failed to parse config for fixture {}: {}", fixture.name, e)
// });
// ConvertColorsPlugin::with_config(config)
// } else {
// ConvertColorsPlugin::default()
// };
//
// // Apply plugin to input
// let result = apply_plugin_to_svg(&mut plugin, &fixture.input, fixture.params.as_ref()).unwrap_or_else(|e| {
// panic!("Failed to apply plugin to fixture {}: {}", fixture.name, e)
// });
//
// // Compare result with expected output
// if !compare_svg(&result, &fixture.expected) {
// panic!(
// "Fixture {} failed\nInput:\n{}\nExpected:\n{}\nActual:\n{}",
// fixture.name, fixture.input, fixture.expected, result
// );
// }
// }
// }
}