vexy-vsvg-plugin-sdk 2.4.2

Plugin SDK for vexy-vsvg
Documentation
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
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
// this_file: crates/vexy-vsvg-plugin-sdk/src/plugins/remove_hidden_elems.rs

//! Remove hidden elements plugin implementation
//!
//! This plugin removes elements that are hidden through various means:
//! - display="none"
//! - visibility="hidden" or visibility="collapse"
//! - opacity="0" (optional)
//! - Zero width/height rectangles, ellipses, images
//! - Zero radius circles
//! - Empty paths
//!
//! SVGO parameters supported:
//! - `displayNone` (default: true) - Remove elements with display="none"
//! - `opacity0` (default: true) - Remove elements with opacity="0"
//! - `circleR0` (default: true) - Remove circles with r="0"
//! - `ellipseRX0` (default: true) - Remove ellipses with rx="0"
//! - `ellipseRY0` (default: true) - Remove ellipses with ry="0"
//! - `rectWidth0` (default: true) - Remove rects with width="0"
//! - `rectHeight0` (default: true) - Remove rects with height="0"
//! - `patternWidth0` (default: true) - Remove patterns with width="0"
//! - `patternHeight0` (default: true) - Remove patterns with height="0"
//! - `imageWidth0` (default: true) - Remove images with width="0"
//! - `imageHeight0` (default: true) - Remove images with height="0"
//! - `pathEmptyD` (default: true) - Remove paths with empty d attribute
//! - `polylineEmptyPoints` (default: true) - Remove polylines with empty points
//! - `polygonEmptyPoints` (default: true) - Remove polygons with empty points

use std::collections::{HashMap, HashSet};

use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use vexy_vsvg::ast::{Document, Element, Node};
use vexy_vsvg::error::VexyError;
use vexy_vsvg::visitor::Visitor;

use crate::Plugin;

/// Configuration parameters for remove hidden elems plugin
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RemoveHiddenElemsConfig {
    /// Remove elements with display="none"
    #[serde(default = "default_true")]
    pub display_none: bool,

    /// Remove elements with opacity="0"
    #[serde(default = "default_true")]
    pub opacity0: bool,

    /// Remove circles with r="0"
    #[serde(default = "default_true")]
    pub circle_r0: bool,

    /// Remove ellipses with rx="0"
    #[serde(default = "default_true")]
    pub ellipse_rx0: bool,

    /// Remove ellipses with ry="0"
    #[serde(default = "default_true")]
    pub ellipse_ry0: bool,

    /// Remove rects with width="0"
    #[serde(default = "default_true")]
    pub rect_width0: bool,

    /// Remove rects with height="0"
    #[serde(default = "default_true")]
    pub rect_height0: bool,

    /// Remove patterns with width="0"
    #[serde(default = "default_true")]
    pub pattern_width0: bool,

    /// Remove patterns with height="0"
    #[serde(default = "default_true")]
    pub pattern_height0: bool,

    /// Remove images with width="0"
    #[serde(default = "default_true")]
    pub image_width0: bool,

    /// Remove images with height="0"
    #[serde(default = "default_true")]
    pub image_height0: bool,

    /// Remove paths with empty d attribute
    #[serde(default = "default_true")]
    pub path_empty_d: bool,

    /// Remove polylines with empty points
    #[serde(default = "default_true")]
    pub polyline_empty_points: bool,

    /// Remove polygons with empty points
    #[serde(default = "default_true")]
    pub polygon_empty_points: bool,
}

impl Default for RemoveHiddenElemsConfig {
    fn default() -> Self {
        Self {
            display_none: default_true(),
            opacity0: default_true(),
            circle_r0: default_true(),
            ellipse_rx0: default_true(),
            ellipse_ry0: default_true(),
            rect_width0: default_true(),
            rect_height0: default_true(),
            pattern_width0: default_true(),
            pattern_height0: default_true(),
            image_width0: default_true(),
            image_height0: default_true(),
            path_empty_d: default_true(),
            polyline_empty_points: default_true(),
            polygon_empty_points: default_true(),
        }
    }
}

fn default_true() -> bool {
    true
}

/// Plugin that removes hidden elements
pub struct RemoveHiddenElemsPlugin {
    config: RemoveHiddenElemsConfig,
}

impl RemoveHiddenElemsPlugin {
    /// Create a new RemoveHiddenElemsPlugin
    pub fn new() -> Self {
        Self {
            config: RemoveHiddenElemsConfig::default(),
        }
    }

    /// Create a new RemoveHiddenElemsPlugin with config
    pub fn with_config(config: RemoveHiddenElemsConfig) -> Self {
        Self { config }
    }

    /// Parse configuration from JSON
    fn _parse_config(params: &Value) -> Result<RemoveHiddenElemsConfig> {
        if let Some(_obj) = params.as_object() {
            serde_json::from_value(params.clone())
                .map_err(|e| anyhow!("Invalid configuration: {}", e))
        } else {
            Ok(RemoveHiddenElemsConfig::default())
        }
    }
}

impl Default for RemoveHiddenElemsPlugin {
    fn default() -> Self {
        Self::new()
    }
}

impl Plugin for RemoveHiddenElemsPlugin {
    fn name(&self) -> &'static str {
        "removeHiddenElems"
    }

    fn description(&self) -> &'static str {
        "Remove hidden elements"
    }

    fn validate_params(&self, params: &Value) -> Result<()> {
        if let Some(obj) = params.as_object() {
            // Validate all boolean parameters
            for (key, value) in obj {
                match key.as_str() {
                    "displayNone"
                    | "opacity0"
                    | "circleR0"
                    | "ellipseRX0"
                    | "ellipseRY0"
                    | "rectWidth0"
                    | "rectHeight0"
                    | "patternWidth0"
                    | "patternHeight0"
                    | "imageWidth0"
                    | "imageHeight0"
                    | "pathEmptyD"
                    | "polylineEmptyPoints"
                    | "polygonEmptyPoints" => {
                        if !value.is_boolean() {
                            return Err(anyhow!("{} must be a boolean", key));
                        }
                    }
                    _ => return Err(anyhow!("Unknown parameter: {}", key)),
                }
            }
        }
        Ok(())
    }

    fn configure(&mut self, params: &Value) -> Result<()> {
        self.config = Self::_parse_config(params)?;
        Ok(())
    }

    fn apply(&self, document: &mut Document) -> Result<()> {
        // Phase 1: collect <use> references by target id.
        let mut use_references_by_id: HashMap<String, usize> = HashMap::new();
        collect_use_references(&document.root, &mut use_references_by_id);

        // Phase 2: collect existing <defs> count.
        let mut defs_count = 0usize;
        collect_defs_count(&document.root, &mut defs_count);

        let mut referenced_ids = HashSet::new();
        collect_referenced_ids(&document.root, &mut referenced_ids);

        let mut style_collector = HiddenElemsStyleCollector::new();
        vexy_vsvg::visitor::walk_document(&mut style_collector, document)?;

        let mut visitor = HiddenElemsRemovalVisitor::new(
            self.config.clone(),
            style_collector.class_overrides,
            referenced_ids,
        );
        // Phase 3: run hidden-element removal visitor.
        vexy_vsvg::visitor::walk_document(&mut visitor, document)?;

        // Phase 4: collect ids removed from inside <defs>.
        let removed_def_ids = visitor.take_removed_def_ids();

        // Phase 5: remove <use> elements that reference removed definitions.
        if !removed_def_ids.is_empty() {
            let mut removed_use_target_ids = HashSet::new();
            for id in &removed_def_ids {
                if use_references_by_id.contains_key(id) {
                    removed_use_target_ids.insert(id.clone());
                }
            }

            if !removed_use_target_ids.is_empty() {
                remove_use_elements_referencing_ids(&mut document.root, &removed_use_target_ids);
            }
        }

        // Phase 6: remove empty <defs> containers.
        if defs_count > 0 {
            remove_empty_defs(&mut document.root);
        }

        normalize_textpath_indentation(&mut document.root);
        cleanup_document_whitespace(document);

        Ok(())
    }
}

#[derive(Debug, Clone, Default)]
struct ClassStyleOverride {
    display: Option<String>,
    opacity: Option<f64>,
    visibility: Option<String>,
}

struct HiddenElemsStyleCollector {
    class_overrides: HashMap<String, ClassStyleOverride>,
}

impl HiddenElemsStyleCollector {
    fn new() -> Self {
        Self {
            class_overrides: HashMap::new(),
        }
    }

    fn parse_style_text(&mut self, css_text: &str) {
        for block in css_text.split('}') {
            if let Some((selectors, body)) = block.split_once('{') {
                for selector in selectors.split(',') {
                    let selector = selector.trim();
                    if !selector.starts_with('.') {
                        continue;
                    }

                    let class_name = selector
                        .trim_start_matches('.')
                        .split([':', ' ', '[', '>'])
                        .next()
                        .unwrap_or("")
                        .trim();

                    if class_name.is_empty() {
                        continue;
                    }

                    let entry = self
                        .class_overrides
                        .entry(class_name.to_string())
                        .or_default();

                    for declaration in body.split(';') {
                        if let Some((name, value)) = declaration.split_once(':') {
                            let name = name.trim();
                            let value = value.trim();
                            match name {
                                "display" => entry.display = Some(value.to_string()),
                                "visibility" => entry.visibility = Some(value.to_string()),
                                "opacity" => {
                                    if let Ok(v) = value.parse::<f64>() {
                                        entry.opacity = Some(v);
                                    }
                                }
                                _ => {}
                            }
                        }
                    }
                }
            }
        }
    }
}

impl Visitor<'_> for HiddenElemsStyleCollector {
    fn visit_element_enter(&mut self, element: &mut Element<'_>) -> Result<(), VexyError> {
        if element.name == "style" {
            for child in &element.children {
                match child {
                    Node::Text(text) | Node::CData(text) => self.parse_style_text(text),
                    _ => {}
                }
            }
        }
        Ok(())
    }
}

/// Visitor implementation that removes hidden elements
struct HiddenElemsRemovalVisitor {
    config: RemoveHiddenElemsConfig,
    class_overrides: HashMap<String, ClassStyleOverride>,
    referenced_ids: HashSet<String>,
    removed_def_ids: HashSet<String>,
}

impl HiddenElemsRemovalVisitor {
    fn new(
        config: RemoveHiddenElemsConfig,
        class_overrides: HashMap<String, ClassStyleOverride>,
        referenced_ids: HashSet<String>,
    ) -> Self {
        Self {
            config,
            class_overrides,
            referenced_ids,
            removed_def_ids: HashSet::new(),
        }
    }

    fn take_removed_def_ids(&mut self) -> HashSet<String> {
        std::mem::take(&mut self.removed_def_ids)
    }

    fn is_empty_container(&self, element: &Element) -> bool {
        !element
            .children
            .iter()
            .any(|child| matches!(child, Node::Element(_)))
    }

    fn is_empty_gradient(&self, element: &Element) -> bool {
        matches!(element.name.as_ref(), "linearGradient" | "radialGradient")
            && self.is_empty_container(element)
    }

    fn has_referenced_id(&self, element: &Element) -> bool {
        element
            .attributes
            .get("id")
            .map(|id| self.referenced_ids.contains(id.as_ref()))
            .unwrap_or(false)
    }

    fn has_class_override(&self, element: &Element, property: &str) -> bool {
        let Some(class_value) = element.attributes.get("class") else {
            return false;
        };

        for class_name in class_value.split_whitespace() {
            if let Some(overrides) = self.class_overrides.get(class_name) {
                match property {
                    "display" => {
                        if let Some(display) = &overrides.display {
                            if display != "none" {
                                return true;
                            }
                        }
                    }
                    "visibility" => {
                        if let Some(visibility) = &overrides.visibility {
                            if visibility != "hidden" && visibility != "collapse" {
                                return true;
                            }
                        }
                    }
                    "opacity" => {
                        if let Some(opacity) = overrides.opacity {
                            if opacity > 0.0 {
                                return true;
                            }
                        }
                    }
                    _ => {}
                }
            }
        }

        false
    }

    fn has_visible_descendant(&self, element: &Element) -> bool {
        for child in &element.children {
            if let Node::Element(child_element) = child {
                if child_element
                    .attributes
                    .get("visibility")
                    .map(|value| value == "visible")
                    .unwrap_or(false)
                    || self.has_class_override(child_element, "visibility")
                {
                    return true;
                }

                if self.has_visible_descendant(child_element) {
                    return true;
                }
            }
        }

        false
    }

    /// Check if an element is hidden and should be removed
    fn is_element_hidden(&self, element: &Element, parent_name: Option<&str>) -> bool {
        // Check display="none"
        if self.config.display_none {
            if let Some(display) = element.attributes.get("display") {
                if display == "none" && !self.has_class_override(element, "display") {
                    return true;
                }
            }
        }

        // Check visibility="hidden" or visibility="collapse"
        if let Some(visibility) = element.attributes.get("visibility") {
            if (visibility == "hidden" || visibility == "collapse")
                && !self.has_class_override(element, "visibility")
                && !self.has_visible_descendant(element)
            {
                return true;
            }
        }

        // Check opacity="0"
        if self.config.opacity0 {
            let inside_non_rendering_parent = parent_name
                .map(is_non_rendering_element_name)
                .unwrap_or(false);
            if !inside_non_rendering_parent {
                let has_opacity_zero_attr = element
                    .attributes
                    .get("opacity")
                    .and_then(|opacity| opacity.parse::<f64>().ok())
                    .map(|opacity_val| opacity_val == 0.0)
                    .unwrap_or(false);

                let has_opacity_zero =
                    has_opacity_zero_attr || self.has_inline_style_opacity_zero(element);
                if has_opacity_zero
                    && !self.has_class_override(element, "opacity")
                    && !self.has_referenced_id(element)
                {
                    return true;
                }
            }
        }

        // Check element-specific zero dimensions
        match element.name.as_ref() {
            "linearGradient" | "radialGradient" => {
                if self.is_empty_gradient(element) && !self.has_referenced_id(element) {
                    return true;
                }
            }
            "circle" if self.config.circle_r0 => {
                if element.children.is_empty() && self.is_zero_dimension(element, "r") {
                    return true;
                }
            }
            "ellipse" => {
                if element.children.is_empty()
                    && ((self.config.ellipse_rx0 && self.is_zero_dimension(element, "rx"))
                        || (self.config.ellipse_ry0 && self.is_zero_dimension(element, "ry")))
                {
                    return true;
                }
            }
            "rect" => {
                if element.children.is_empty()
                    && ((self.config.rect_width0 && self.is_zero_dimension(element, "width"))
                        || (self.config.rect_height0 && self.is_zero_dimension(element, "height")))
                {
                    return true;
                }
            }
            "pattern" => {
                if (self.config.pattern_width0 && self.is_zero_dimension(element, "width"))
                    || (self.config.pattern_height0 && self.is_zero_dimension(element, "height"))
                {
                    return true;
                }
            }
            "image" => {
                if (self.config.image_width0 && self.is_zero_dimension(element, "width"))
                    || (self.config.image_height0 && self.is_zero_dimension(element, "height"))
                {
                    return true;
                }
            }
            "path" if self.config.path_empty_d => {
                if let Some(d) = element.attributes.get("d") {
                    if d.trim().is_empty() {
                        return true;
                    }

                    if is_invalid_path_data(d) {
                        return true;
                    }

                    if is_single_point_path(d)
                        && !element.attributes.contains_key("marker-start")
                        && !element.attributes.contains_key("marker-end")
                    {
                        return true;
                    }
                } else {
                    return true;
                }
            }
            "polyline" if self.config.polyline_empty_points => {
                if let Some(points) = element.attributes.get("points") {
                    if points.trim().is_empty() {
                        return true;
                    }
                } else {
                    return true;
                }
            }
            "polygon" if self.config.polygon_empty_points => {
                if let Some(points) = element.attributes.get("points") {
                    if points.trim().is_empty() {
                        return true;
                    }
                } else {
                    return true;
                }
            }
            "line" => {
                // Line is hidden if start and end points are the same
                let x1 = self.get_numeric_attr(element, "x1").unwrap_or(0.0);
                let y1 = self.get_numeric_attr(element, "y1").unwrap_or(0.0);
                let x2 = self.get_numeric_attr(element, "x2").unwrap_or(0.0);
                let y2 = self.get_numeric_attr(element, "y2").unwrap_or(0.0);
                if x1 == x2 && y1 == y2 {
                    return true;
                }
            }
            _ => {}
        }

        false
    }

    fn is_zero_dimension(&self, element: &Element, attr_name: &str) -> bool {
        if let Some(value) = element.attributes.get(attr_name) {
            if let Ok(num_val) = value.parse::<f64>() {
                return num_val == 0.0;
            }
        }
        false
    }

    fn get_numeric_attr(&self, element: &Element, attr_name: &str) -> Option<f64> {
        element.attributes.get(attr_name)?.parse::<f64>().ok()
    }

    fn has_inline_style_opacity_zero(&self, element: &Element) -> bool {
        let Some(style_value) = element.attributes.get("style") else {
            return false;
        };

        for declaration in style_value.split(';') {
            if let Some((name, value)) = declaration.split_once(':') {
                if name.trim() == "opacity" {
                    if let Ok(opacity_val) = value.trim().parse::<f64>() {
                        if opacity_val == 0.0 {
                            return true;
                        }
                    }
                }
            }
        }

        false
    }
}

fn collect_referenced_ids(element: &Element<'_>, referenced_ids: &mut HashSet<String>) {
    for value in element.attributes.values() {
        collect_ids_from_attr_value(value, referenced_ids);
    }

    for child in &element.children {
        if let Node::Element(child_element) = child {
            collect_referenced_ids(child_element, referenced_ids);
        }
    }
}

fn collect_ids_from_attr_value(value: &str, referenced_ids: &mut HashSet<String>) {
    let bytes = value.as_bytes();
    let mut idx = 0;
    while idx < bytes.len() {
        if bytes[idx] == b'#' {
            let start = idx + 1;
            let mut end = start;
            while end < bytes.len() {
                let ch = bytes[end] as char;
                if ch.is_alphanumeric() || matches!(ch, '_' | '-' | ':' | '.') {
                    end += 1;
                } else {
                    break;
                }
            }

            if end > start {
                referenced_ids.insert(value[start..end].to_string());
                idx = end;
                continue;
            }
        }
        idx += 1;
    }
}

fn collect_use_references(element: &Element<'_>, references_by_id: &mut HashMap<String, usize>) {
    if element.name == "use" {
        for attr_name in ["href", "xlink:href"] {
            if let Some(value) = element.attributes.get(attr_name) {
                if let Some(id) = value.strip_prefix('#') {
                    if !id.is_empty() {
                        let counter = references_by_id.entry(id.to_string()).or_insert(0);
                        *counter += 1;
                    }
                }
            }
        }
    }

    for child in &element.children {
        if let Node::Element(child_element) = child {
            collect_use_references(child_element, references_by_id);
        }
    }
}

fn collect_defs_count(element: &Element<'_>, defs_count: &mut usize) {
    if element.name == "defs" {
        *defs_count += 1;
    }

    for child in &element.children {
        if let Node::Element(child_element) = child {
            collect_defs_count(child_element, defs_count);
        }
    }
}

fn remove_use_elements_referencing_ids(element: &mut Element<'_>, removed_ids: &HashSet<String>) {
    let mut idx = 0;
    while idx < element.children.len() {
        let should_remove = match &element.children[idx] {
            Node::Element(child_element) if child_element.name == "use" => {
                references_removed_id(child_element, removed_ids)
            }
            _ => false,
        };

        if should_remove {
            element.children.remove(idx);
            continue;
        }

        if let Node::Element(child_element) = &mut element.children[idx] {
            remove_use_elements_referencing_ids(child_element, removed_ids);
        }
        idx += 1;
    }
}

fn references_removed_id(element: &Element<'_>, removed_ids: &HashSet<String>) -> bool {
    for attr_name in ["href", "xlink:href"] {
        if let Some(value) = element.attributes.get(attr_name) {
            if let Some(id) = value.strip_prefix('#') {
                if removed_ids.contains(id) {
                    return true;
                }
            }
        }
    }

    false
}

fn remove_empty_defs(element: &mut Element<'_>) {
    let mut idx = 0;
    while idx < element.children.len() {
        if let Node::Element(child_element) = &mut element.children[idx] {
            remove_empty_defs(child_element);
        }

        let should_remove = match &element.children[idx] {
            Node::Element(child_element) => {
                child_element.name == "defs"
                    && !child_element
                        .children
                        .iter()
                        .any(|child| matches!(child, Node::Element(_)))
            }
            _ => false,
        };

        if should_remove {
            element.children.remove(idx);
            continue;
        }

        idx += 1;
    }
}

fn normalize_textpath_indentation(element: &mut Element<'_>) {
    if element.name == "textPath" {
        for child in &mut element.children {
            if let Node::Text(text) = child {
                *text = dedent_one_level(text).into();
            }
        }
    }

    for child in &mut element.children {
        if let Node::Element(child_element) = child {
            normalize_textpath_indentation(child_element);
        }
    }
}

fn dedent_one_level(text: &str) -> String {
    let mut lines = Vec::new();
    for line in text.split('\n') {
        if let Some(stripped) = line.strip_prefix("    ") {
            lines.push(stripped);
        } else {
            lines.push(line);
        }
    }
    lines.join("\n")
}

fn cleanup_document_whitespace(document: &mut Document<'_>) {
    document
        .prologue
        .retain(|node| !matches!(node, Node::Text(text) if text.trim().is_empty()));
    document.epilogue.clear();
}

fn is_single_point_path(path_data: &str) -> bool {
    use vexy_vsvg::utils::paths::PathUtils;

    let commands = PathUtils::parse_path_data(path_data);

    // Exactly one command, must be M/m with exactly 2 params (one coordinate pair)
    commands.len() == 1 && matches!(commands[0].command, 'M' | 'm') && commands[0].params.len() == 2
}

/// Check if path data is clearly invalid (empty, no commands, or no moveto).
///
/// This is intentionally lenient: it only rejects paths that are obviously broken.
/// Detailed param-count validation is not safe here because the path `d` attribute
/// may use compact SVGO-style formatting (adjacent decimals like `3.5.7`, negative
/// signs as separators like `5-3`). Uses `PathUtils::parse_path_data()` for robust
/// tokenization rather than manual counting, then validates param counts per SVG spec.
///
/// If the path contains scientific notation (e.g. `6.39e-11`), which our parser
/// cannot handle, we skip param-count validation and accept the path as valid
/// as long as it has basic structural integrity.
fn is_invalid_path_data(path_data: &str) -> bool {
    use vexy_vsvg::utils::paths::PathUtils;

    let trimmed = path_data.trim();
    if trimmed.is_empty() {
        return true;
    }

    // Check structural basics: must contain command letters and start with M/m
    let has_commands = trimmed
        .bytes()
        .any(|b| b"MLHVCSQTAZmlhvcsqtaz".contains(&b));
    if !has_commands {
        return true;
    }
    let first_cmd = trimmed
        .bytes()
        .find(|b| b.is_ascii_alphabetic())
        .unwrap_or(0);
    if first_cmd != b'M' && first_cmd != b'm' {
        return true;
    }

    // If path contains scientific notation, our parser can't tokenize it correctly.
    // Accept it as valid since it passes structural checks above.
    if trimmed.contains('e') || trimmed.contains('E') {
        return false;
    }

    let commands = PathUtils::parse_path_data(trimmed);
    if commands.is_empty() {
        return true;
    }

    for cmd in &commands {
        let n = cmd.params.len();
        let valid = match cmd.command.to_ascii_uppercase() {
            'M' | 'L' | 'T' => n >= 2 && n % 2 == 0,
            'H' | 'V' => n >= 1,
            'S' | 'Q' => n >= 4 && n % 4 == 0,
            'C' => n >= 6 && n % 6 == 0,
            'A' => n >= 7 && n % 7 == 0,
            'Z' => true,
            _ => false,
        };
        if !valid {
            return true;
        }
    }

    false
}

fn is_non_rendering_element_name(name: &str) -> bool {
    matches!(
        name,
        "defs"
            | "clipPath"
            | "mask"
            | "marker"
            | "pattern"
            | "linearGradient"
            | "radialGradient"
            | "symbol"
    )
}

impl Visitor<'_> for HiddenElemsRemovalVisitor {
    fn visit_element_exit(&mut self, element: &mut Element<'_>) -> Result<(), VexyError> {
        // Remove hidden child elements (process children first)
        element.children.retain(|child| {
            if let Node::Element(child_element) = child {
                let should_remove =
                    self.is_element_hidden(child_element, Some(element.name.as_ref()));
                if should_remove && element.name == "defs" {
                    if let Some(id) = child_element.attributes.get("id") {
                        self.removed_def_ids.insert(id.to_string());
                    }
                }
                !should_remove
            } else {
                true // Keep non-element nodes
            }
        });

        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 = RemoveHiddenElemsPlugin::new();
        assert_eq!(plugin.name(), "removeHiddenElems");
    }

    #[test]
    fn test_parameter_validation() {
        let plugin = RemoveHiddenElemsPlugin::new();

        // Valid parameters
        assert!(plugin.validate_params(&json!({})).is_ok());
        assert!(plugin
            .validate_params(&json!({
                "displayNone": true,
                "opacity0": false,
                "circleR0": true
            }))
            .is_ok());

        // Invalid parameters
        assert!(plugin
            .validate_params(&json!({"displayNone": "invalid"}))
            .is_err());
        assert!(plugin
            .validate_params(&json!({"unknownParam": true}))
            .is_err());
    }

    #[test]
    fn test_remove_display_none() {
        let plugin = RemoveHiddenElemsPlugin::new();
        let mut doc = Document::new();

        // Add elements with display attributes
        let mut rect1 = create_element("rect");
        rect1.attributes.insert("display".into(), "none".into());
        rect1.attributes.insert("width".into(), "100".into());

        let mut rect2 = create_element("rect");
        rect2.attributes.insert("display".into(), "block".into());
        rect2.attributes.insert("width".into(), "100".into());

        doc.root.children.push(Node::Element(rect1));
        doc.root.children.push(Node::Element(rect2));

        plugin.apply(&mut doc).unwrap();

        // Only the visible rect should remain
        assert_eq!(doc.root.children.len(), 1);
        if let Some(Node::Element(elem)) = doc.root.children.first() {
            assert_eq!(elem.attr("display"), Some("block"));
        }
    }

    #[test]
    fn test_remove_visibility_hidden() {
        let plugin = RemoveHiddenElemsPlugin::new();
        let mut doc = Document::new();

        // Add elements with visibility attributes
        let mut rect1 = create_element("rect");
        rect1.set_attr("visibility", "hidden");

        let mut rect2 = create_element("rect");
        rect2.set_attr("visibility", "collapse");

        let mut rect3 = create_element("rect");
        rect3.set_attr("visibility", "visible");

        doc.root.children.push(Node::Element(rect1));
        doc.root.children.push(Node::Element(rect2));
        doc.root.children.push(Node::Element(rect3));

        plugin.apply(&mut doc).unwrap();

        // Only the visible rect should remain
        assert_eq!(doc.root.children.len(), 1);
        if let Some(Node::Element(elem)) = doc.root.children.first() {
            assert_eq!(elem.attr("visibility"), Some("visible"));
        }
    }

    #[test]
    fn test_remove_opacity_zero() {
        let plugin = RemoveHiddenElemsPlugin::new();
        let mut doc = Document::new();

        // Add elements with opacity
        let mut rect1 = create_element("rect");
        rect1.set_attr("opacity", "0");

        let mut rect2 = create_element("rect");
        rect2.set_attr("opacity", "0.0");

        let mut rect3 = create_element("rect");
        rect3.set_attr("opacity", "0.5");

        doc.root.children.push(Node::Element(rect1));
        doc.root.children.push(Node::Element(rect2));
        doc.root.children.push(Node::Element(rect3));

        plugin.apply(&mut doc).unwrap();

        // Only the non-zero opacity rect should remain
        assert_eq!(doc.root.children.len(), 1);
        if let Some(Node::Element(elem)) = doc.root.children.first() {
            assert_eq!(elem.attr("opacity"), Some("0.5"));
        }
    }

    #[test]
    fn test_remove_zero_dimension_circle() {
        let plugin = RemoveHiddenElemsPlugin::new();
        let mut doc = Document::new();

        // Add circles with different radii
        let mut circle1 = create_element("circle");
        circle1.set_attr("r", "0");

        let mut circle2 = create_element("circle");
        circle2.set_attr("r", "10");

        doc.root.children.push(Node::Element(circle1));
        doc.root.children.push(Node::Element(circle2));

        plugin.apply(&mut doc).unwrap();

        // Only non-zero radius circle should remain
        assert_eq!(doc.root.children.len(), 1);
        if let Some(Node::Element(elem)) = doc.root.children.first() {
            assert_eq!(elem.attr("r"), Some("10"));
        }
    }

    #[test]
    fn test_remove_zero_dimension_rect() {
        let plugin = RemoveHiddenElemsPlugin::new();
        let mut doc = Document::new();

        // Add rects with zero dimensions
        let mut rect1 = create_element("rect");
        rect1.set_attr("width", "0");
        rect1.set_attr("height", "100");

        let mut rect2 = create_element("rect");
        rect2.set_attr("width", "100");
        rect2.set_attr("height", "0");

        let mut rect3 = create_element("rect");
        rect3.set_attr("width", "100");
        rect3.set_attr("height", "100");

        doc.root.children.push(Node::Element(rect1));
        doc.root.children.push(Node::Element(rect2));
        doc.root.children.push(Node::Element(rect3));

        plugin.apply(&mut doc).unwrap();

        // Only non-zero dimension rect should remain
        assert_eq!(doc.root.children.len(), 1);
        if let Some(Node::Element(elem)) = doc.root.children.first() {
            assert_eq!(elem.attr("width"), Some("100"));
            assert_eq!(elem.attr("height"), Some("100"));
        }
    }

    #[test]
    fn test_remove_empty_path() {
        let plugin = RemoveHiddenElemsPlugin::new();
        let mut doc = Document::new();

        // Add paths with different d attributes
        let mut path1 = create_element("path");
        path1.set_attr("d", "");

        let mut path2 = create_element("path");
        path2.set_attr("d", "   ");

        let mut path3 = create_element("path");
        path3.set_attr("d", "M10 10 L20 20");

        let path4 = create_element("path"); // No d attribute

        doc.root.children.push(Node::Element(path1));
        doc.root.children.push(Node::Element(path2));
        doc.root.children.push(Node::Element(path3));
        doc.root.children.push(Node::Element(path4));

        plugin.apply(&mut doc).unwrap();

        // Only path with valid d should remain
        assert_eq!(doc.root.children.len(), 1);
        if let Some(Node::Element(elem)) = doc.root.children.first() {
            assert_eq!(elem.attr("d"), Some("M10 10 L20 20"));
        }
    }

    #[test]
    fn test_config_parsing() {
        let config = RemoveHiddenElemsPlugin::_parse_config(&json!({
            "displayNone": false,
            "opacity0": true,
            "circleR0": false,
            "pathEmptyD": true
        }))
        .unwrap();

        assert!(!config.display_none);
        assert!(config.opacity0);
        assert!(!config.circle_r0);
        assert!(config.path_empty_d);
    }

    #[test]
    fn test_line_same_coordinates() {
        let plugin = RemoveHiddenElemsPlugin::new();
        let mut doc = Document::new();

        // Add lines with same start/end points
        let mut line1 = create_element("line");
        line1.attributes.insert("x1".into(), "10".into());
        line1.attributes.insert("y1".into(), "10".into());
        line1.attributes.insert("x2".into(), "10".into());
        line1.attributes.insert("y2".into(), "10".into());

        let mut line2 = create_element("line");
        line2.attributes.insert("x1".into(), "10".into());
        line2.attributes.insert("y1".into(), "10".into());
        line2.attributes.insert("x2".into(), "20".into());
        line2.attributes.insert("y2".into(), "20".into());

        doc.root.children.push(Node::Element(line1));
        doc.root.children.push(Node::Element(line2));

        plugin.apply(&mut doc).unwrap();

        // Only line with different coordinates should remain
        assert_eq!(doc.root.children.len(), 1);
        if let Some(Node::Element(elem)) = doc.root.children.first() {
            assert_eq!(elem.attr("x2"), Some("20"));
        }
    }

    #[test]
    fn test_selective_removal_config() {
        let config = RemoveHiddenElemsConfig {
            display_none: false,
            opacity0: true,
            ..Default::default()
        };
        let plugin = RemoveHiddenElemsPlugin::with_config(config);
        let mut doc = Document::new();

        // Add elements that would normally be removed
        let mut rect1 = create_element("rect");
        rect1.attributes.insert("display".into(), "none".into());

        let mut rect2 = create_element("rect");
        rect2.attributes.insert("opacity".into(), "0".into());

        doc.root.children.push(Node::Element(rect1));
        doc.root.children.push(Node::Element(rect2));

        plugin.apply(&mut doc).unwrap();

        // display="none" should be kept, opacity="0" should be removed
        assert_eq!(doc.root.children.len(), 1);
        if let Some(Node::Element(elem)) = doc.root.children.first() {
            assert_eq!(elem.attr("display"), Some("none"));
        }
    }
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use vexy_vsvg::Config;
    use vexy_vsvg_test_utils::load_fixtures;

    #[test]
    fn fixture_tests() -> Result<(), Box<dyn std::error::Error>> {
        let fixtures_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("..")
            .join("..")
            .join("testdata")
            .join("plugins")
            .join("removeHiddenElems");

        let fixtures = load_fixtures(&fixtures_path)?;
        for fixture in fixtures {
            let mut config = Config::new();
            config.plugins = vec![vexy_vsvg::PluginConfig::Name(
                "removeHiddenElems".to_string(),
            )];
            config.js2svg.pretty = true;
            config.js2svg.indent = "    ".to_string();
            config.js2svg.final_newline = false;

            let registry = crate::registry::create_migrated_plugin_registry();
            let options = vexy_vsvg::OptimizeOptions::new(config).with_registry(registry);
            let result = vexy_vsvg::optimize(&fixture.input, options)?;

            assert_eq!(result.data, fixture.expected, "Fixture: {}", fixture.name);
        }

        Ok(())
    }
}