dioxus-iconify 0.4.1

CLI tool for importing/vendoring icons from [Iconify](https://icon-sets.iconify.design/) (material, lucid, heroicons,....) or from local SVG files in Dioxus projects
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
use anyhow::{Context, Result};
use indoc::{formatdoc, indoc};
use std::collections::{BTreeMap, HashMap};
use std::fs;
use std::path::{Path, PathBuf};

use crate::api::{IconifyCollectionInfo, IconifyIcon};
use crate::naming::IconIdentifier;

const MOD_RS_TEMPLATE: &str = indoc! {r#"// Auto-generated by dioxus-iconify - DO NOT EDIT
    use dioxus::prelude::*;

    #[derive(Clone, Copy, PartialEq)]
    pub struct IconData {
        pub name: &'static str,
        pub body: &'static str,
        pub view_box: &'static str,
        pub width: &'static str,
        pub height: &'static str,
    }

    #[component]
    pub fn Icon(
        data: IconData,
        /// Optional size to set both width and height
        #[props(default, into)]
        size: String,
        /// Additional attributes to extend the svg element
        #[props(extends = SvgAttributes)]
        attributes: Vec<Attribute>,
    ) -> Element {
        let (width, height) = if size.is_empty() {
            (data.width, data.height)
        } else {
            (size.as_str(), size.as_str())
        };

        rsx! {
            svg {
                view_box: "{data.view_box}",
                width: "{width}",
                height: "{height}",
                dangerous_inner_html: "{data.body}",
                ..attributes,
            }
        }
    }
    "#};

/// Represents a generated icon constant
#[derive(Debug, Clone)]
struct IconConst {
    name: String,
    full_icon_name: String,
    body: String,
    view_box: String,
    width: String,
    height: String,
}

impl IconConst {
    fn from_api_icon(identifier: &IconIdentifier, icon: &IconifyIcon) -> Self {
        Self {
            name: identifier.to_const_name(),
            full_icon_name: identifier.full_name.clone(),
            body: icon.body.clone(),
            view_box: icon
                .view_box
                .clone()
                .unwrap_or_else(|| "0 0 24 24".to_string()),
            width: icon.width.unwrap_or(24).to_string(),
            height: icon.height.unwrap_or(24).to_string(),
        }
    }

    fn to_rust_code(&self) -> String {
        // we use non upper case to be able to switch/wrap to struct or enum i the future
        formatdoc! { "

            #[allow(non_upper_case_globals)]
            pub const {}: IconData = IconData {{
                name: \"{}\",
                body: r#\"{}\"#,
                view_box: \"{}\",
                width: \"{}\",
                height: \"{}\",
            }};
            ",
            self.name,
            self.full_icon_name,
            self.body,
            self.view_box,
            self.width,
            self.height
        }
    }
}

/// Icon code generator
pub struct Generator {
    icons_dir: PathBuf,
}

impl Generator {
    /// Create a new generator with the specified icons directory
    pub fn new(icons_dir: PathBuf) -> Self {
        Self { icons_dir }
    }

    /// List all generated icons grouped by collection
    pub fn list_icons(&self) -> Result<BTreeMap<String, Vec<String>>> {
        let mut icons_by_collection: BTreeMap<String, Vec<String>> = BTreeMap::new();

        // Check if icons directory exists
        if !self.icons_dir.exists() {
            return Ok(icons_by_collection);
        }

        // Read all .rs files in the icons directory (except mod.rs)
        let entries = fs::read_dir(&self.icons_dir).context("Failed to read icons directory")?;

        for entry in entries {
            let entry = entry.context("Failed to read directory entry")?;
            let path = entry.path();

            // Skip if not a file or if it's mod.rs
            if !path.is_file() || path.file_name() == Some("mod.rs".as_ref()) {
                continue;
            }

            // Skip if not a .rs file
            if path.extension() != Some("rs".as_ref()) {
                continue;
            }

            // Parse the collection file
            let icons = self.parse_collection_file(&path)?;

            // Get collection name from file name
            if let Some(collection_name) = path.file_stem().and_then(|s| s.to_str()) {
                let icon_names: Vec<String> = icons
                    .values()
                    .map(|icon| icon.full_icon_name.clone())
                    .collect();

                if !icon_names.is_empty() {
                    icons_by_collection.insert(collection_name.to_string(), icon_names);
                }
            }
        }

        Ok(icons_by_collection)
    }

    /// Get all icon identifiers from generated files
    pub fn get_all_icon_identifiers(&self) -> Result<Vec<String>> {
        let icons_by_collection = self.list_icons()?;
        let mut all_icons = Vec::new();

        for icon_names in icons_by_collection.values() {
            all_icons.extend(icon_names.clone());
        }

        Ok(all_icons)
    }

    /// Initialize the icons directory with mod.rs if it doesn't exist
    pub fn init(&self) -> Result<()> {
        // Create icons directory if it doesn't exist
        if !self.icons_dir.exists() {
            fs::create_dir_all(&self.icons_dir).context("Failed to create icons directory")?;
        }

        // Create mod.rs if it doesn't exist
        let mod_rs_path = self.icons_dir.join("mod.rs");
        if !mod_rs_path.exists() {
            fs::write(&mod_rs_path, MOD_RS_TEMPLATE).context("Failed to create mod.rs")?;
        }

        Ok(())
    }

    /// Add icons to the generated code
    pub fn add_icons(
        &self,
        icons: &[(IconIdentifier, IconifyIcon)],
        collection_info: &HashMap<String, IconifyCollectionInfo>,
    ) -> Result<()> {
        // Ensure icons directory and mod.rs exist
        self.init()?;

        // Group icons by collection
        let mut icons_by_collection: HashMap<String, Vec<(IconIdentifier, IconifyIcon)>> =
            HashMap::new();

        for (identifier, icon) in icons {
            icons_by_collection
                .entry(identifier.collection.clone())
                .or_default()
                .push((identifier.clone(), icon.clone()));
        }

        // Generate/update each collection file
        for (collection, collection_icons) in &icons_by_collection {
            let info = collection_info.get(collection);
            self.update_collection_file(collection, collection_icons, info)?;
        }

        // Update mod.rs with module declarations
        self.update_mod_rs(&icons_by_collection.keys().cloned().collect::<Vec<_>>())?;

        Ok(())
    }

    /// Regenerate mod.rs with the latest template
    /// This is useful for updating the Icon component definition after CLI updates
    pub fn regenerate_mod_rs(&self) -> Result<()> {
        let mod_rs_path = self.icons_dir.join("mod.rs");

        // If mod.rs doesn't exist, just use init
        if !mod_rs_path.exists() {
            return self.init();
        }

        // Read existing mod.rs to extract module declarations
        let content = fs::read_to_string(&mod_rs_path).context("Failed to read mod.rs")?;

        // Extract existing module declarations with their visibility
        let existing_modules = extract_module_declarations(&content);

        // Regenerate mod.rs with latest template
        let mut new_content = MOD_RS_TEMPLATE.to_string();
        new_content.push('\n');

        // Add module declarations in alphabetical order
        let mut sorted_modules: Vec<_> = existing_modules.iter().collect();
        sorted_modules.sort_by_key(|(name, _)| *name);

        for (module, visibility) in sorted_modules {
            new_content.push_str(&format!("{}mod {};\n", visibility, module));
        }

        fs::write(&mod_rs_path, new_content).context("Failed to update mod.rs")?;

        Ok(())
    }

    /// Update a collection file (e.g., mdi.rs) with new icons
    fn update_collection_file(
        &self,
        collection: &str,
        new_icons: &[(IconIdentifier, IconifyIcon)],
        collection_info: Option<&IconifyCollectionInfo>,
    ) -> Result<()> {
        let module_name = collection.replace('-', "_");
        let file_path = self.icons_dir.join(format!("{}.rs", module_name));

        // Read existing icons if file exists
        let mut existing_icons: BTreeMap<String, IconConst> = BTreeMap::new();
        if file_path.exists() {
            existing_icons = self.parse_collection_file(&file_path)?;
        }

        // Add/update new icons
        for (identifier, icon) in new_icons {
            let icon_const = IconConst::from_api_icon(identifier, icon);
            existing_icons.insert(icon_const.name.clone(), icon_const);
        }

        // Generate file content
        let content =
            self.generate_collection_file(collection, &existing_icons, collection_info)?;

        // Write to file
        fs::write(&file_path, content)
            .context(format!("Failed to write collection file {:?}", file_path))?;

        println!(
            "✓ Updated {}.rs with {} icon(s)",
            module_name,
            new_icons.len()
        );

        Ok(())
    }

    /// Parse existing icons from a collection file
    fn parse_collection_file(&self, path: &Path) -> Result<BTreeMap<String, IconConst>> {
        let content =
            fs::read_to_string(path).context(format!("Failed to read file {:?}", path))?;

        let mut icons = BTreeMap::new();

        // Simple regex-free parsing: look for "pub const NAME: IconData = IconData {"
        // and extract the data between braces
        let lines: Vec<&str> = content.lines().collect();
        let mut i = 0;

        while i < lines.len() {
            let line = lines[i].trim();

            // Look for "pub const NAME: IconData"
            if line.starts_with("pub const ")
                && line.contains(": IconData")
                && let Some(name_end) = line.find(':')
            {
                let name = line[10..name_end].trim().to_string();

                // Parse the IconData struct (next several lines)
                if let Some(icon_const) = self.parse_icon_data(&lines, &mut i, &name) {
                    icons.insert(name, icon_const);
                }
            }

            i += 1;
        }

        Ok(icons)
    }

    /// Parse IconData struct from lines
    fn parse_icon_data(
        &self,
        lines: &[&str],
        index: &mut usize,
        const_name: &str,
    ) -> Option<IconConst> {
        let mut full_icon_name = String::new();
        let mut body = String::new();
        let mut view_box = String::new();
        let mut width = String::new();
        let mut height = String::new();

        // Look ahead to find all fields
        let mut j = *index;
        while j < lines.len() {
            let line = lines[j].trim();

            if line.contains("name:") {
                full_icon_name = extract_string_value(line);
            } else if line.contains("body:") {
                // Body might span multiple lines in raw string
                body = extract_raw_string_value(lines, &mut j);
            } else if line.contains("view_box:") {
                view_box = extract_string_value(line);
            } else if line.contains("width:") {
                width = extract_string_value(line);
            } else if line.contains("height:") {
                height = extract_string_value(line);
            }

            // End of struct
            if line.contains("};") {
                break;
            }

            j += 1;
        }

        *index = j;

        if !full_icon_name.is_empty() && !body.is_empty() {
            Some(IconConst {
                name: const_name.to_string(),
                full_icon_name,
                body,
                view_box,
                width,
                height,
            })
        } else {
            None
        }
    }

    /// Generate content for a collection file
    fn generate_collection_file(
        &self,
        collection: &str,
        icons: &BTreeMap<String, IconConst>,
        collection_info: Option<&IconifyCollectionInfo>,
    ) -> Result<String> {
        let mut content = String::from("/// Auto-generated by dioxus-iconify - DO NOT EDIT\n");

        // Add generation timestamp
        let now = chrono::Utc::now();
        content.push_str(&format!("/// Generated: {}\n", now.to_rfc3339()));

        content.push_str(&format!("/// Collection: {}\n", collection));
        content.push_str("/// This is a partial import from Iconify\n");
        content.push_str(&format!(
            "/// Browse icons: https://icon-sets.iconify.design/{}/\n",
            collection
        ));

        // Add collection info if available
        if let Some(info) = collection_info {
            content.push_str("///\n");
            content.push_str(&format_collection_info_comment(info));
        }

        content.push_str("use super::IconData;\n");

        // Add each icon const in alphabetical order (BTreeMap maintains order)
        for icon_const in icons.values() {
            content.push_str(&icon_const.to_rust_code());
        }

        Ok(content)
    }

    /// Update mod.rs with module declarations
    fn update_mod_rs(&self, collections: &[String]) -> Result<()> {
        let mod_rs_path = self.icons_dir.join("mod.rs");

        // Read existing mod.rs
        let content = fs::read_to_string(&mod_rs_path).context("Failed to read mod.rs")?;

        // Extract existing module declarations with their visibility
        let mut existing_modules = extract_module_declarations(&content);

        // Add new modules (with pub visibility by default)
        let mut needs_update = false;
        for collection in collections {
            let module_name = collection.replace('-', "_");
            if let std::collections::hash_map::Entry::Vacant(e) =
                existing_modules.entry(module_name)
            {
                e.insert("pub ".to_string());
                needs_update = true;
            }
        }

        // Regenerate mod.rs if we have new modules
        if needs_update {
            let mut new_content = MOD_RS_TEMPLATE.to_string();
            new_content.push('\n');

            // Add module declarations in alphabetical order
            let mut sorted_modules: Vec<_> = existing_modules.iter().collect();
            sorted_modules.sort_by_key(|(name, _)| *name);

            for (module, visibility) in sorted_modules {
                new_content.push_str(&format!("{}mod {};\n", visibility, module));
            }

            fs::write(&mod_rs_path, new_content).context("Failed to update mod.rs")?;
        }

        Ok(())
    }
}

/// Extract module declarations from mod.rs content, preserving their visibility modifiers
/// Returns a HashMap where keys are module names and values are visibility prefixes
/// (e.g., "pub ", "pub(crate) ", "" for private modules)
fn extract_module_declarations(content: &str) -> HashMap<String, String> {
    let mut modules = HashMap::new();

    for line in content.lines() {
        let trimmed = line.trim();

        // Skip lines that don't end with semicolon
        if !trimmed.ends_with(';') {
            continue;
        }

        // Remove the trailing semicolon
        let without_semi = &trimmed[..trimmed.len() - 1];

        // Look for "mod " pattern
        if let Some(mod_idx) = without_semi.find("mod ") {
            // Everything before "mod " is the visibility (if any)
            let visibility = if mod_idx == 0 {
                // Line starts with "mod " - no visibility modifier
                String::new()
            } else {
                // There's something before "mod " - that's the visibility
                // The space before "mod" is already there, so just take everything before mod_idx
                let vis = without_semi[..mod_idx].trim();
                if vis.is_empty() {
                    String::new()
                } else {
                    vis.to_string() + " "
                }
            };

            // Everything after "mod " is the module name
            let module_name = without_semi[mod_idx + 4..].trim();

            // Only add if we have a valid module name
            if !module_name.is_empty() {
                modules.insert(module_name.to_string(), visibility);
            }
        }
    }

    modules
}

/// Format collection info as a YAML comment block
fn format_collection_info_comment(info: &IconifyCollectionInfo) -> String {
    use crate::api::{IconifyAuthor, IconifyLicense};

    let mut lines = Vec::new();
    lines.push("/// ```yaml".to_string());

    if let Some(name) = &info.name {
        lines.push(format!("/// name: {}", name));
    }

    if let Some(author) = &info.author {
        match author {
            IconifyAuthor::Simple(s) => {
                lines.push(format!("/// author: {}", s));
            }
            IconifyAuthor::Detailed { name, url } => {
                lines.push("/// author:".to_string());
                if let Some(n) = name {
                    lines.push(format!("///   name: {}", n));
                }
                if let Some(u) = url {
                    lines.push(format!("///   url: {}", u));
                }
            }
        }
    }

    if let Some(license) = &info.license {
        match license {
            IconifyLicense::Simple(s) => {
                lines.push(format!("/// license: {}", s));
            }
            IconifyLicense::Detailed { title, spdx, url } => {
                lines.push("/// license:".to_string());
                if let Some(t) = title {
                    lines.push(format!("///   title: {}", t));
                }
                if let Some(s) = spdx {
                    lines.push(format!("///   spdx: {}", s));
                }
                if let Some(u) = url {
                    lines.push(format!("///   url: {}", u));
                }
            }
        }
    }

    if let Some(total) = info.total {
        lines.push(format!("/// total: {}", total));
    }

    if let Some(category) = &info.category {
        lines.push(format!("/// category: {}", category));
    }

    if let Some(palette) = info.palette {
        lines.push(format!("/// palette: {}", palette));
    }

    if let Some(height) = info.height {
        lines.push(format!("/// height: {}", height));
    }

    lines.push("/// ```".to_string());

    lines.join("\n") + "\n"
}

/// Extract a string value from a line like `name: "value",`
fn extract_string_value(line: &str) -> String {
    if let Some(start) = line.find('"')
        && let Some(end) = line.rfind('"')
        && end > start
    {
        return line[start + 1..end].to_string();
    }
    String::new()
}

/// Extract a raw string value that might span multiple lines
fn extract_raw_string_value(lines: &[&str], index: &mut usize) -> String {
    let line = lines[*index];

    // Look for r#"..."#
    if let Some(start) = line.find("r#\"") {
        let start_pos = start + 3;

        // Check if it ends on the same line
        if let Some(end) = line[start_pos..].find("\"#") {
            return line[start_pos..start_pos + end].to_string();
        }

        // Multi-line: collect until we find "#
        let mut result = line[start_pos..].to_string();
        *index += 1;

        while *index < lines.len() {
            let next_line = lines[*index];
            if let Some(end) = next_line.find("\"#") {
                result.push_str(&next_line[..end]);
                break;
            }
            result.push_str(next_line);
            result.push('\n');
            *index += 1;
        }

        result
    } else {
        String::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::api::IconifyIcon;
    use tempfile::TempDir;

    #[test]
    fn test_list_icons_empty_directory() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let generator = Generator::new(temp_dir.path().join("icons"));

        let icons = generator.list_icons()?;
        assert!(
            icons.is_empty(),
            "Should return empty map for non-existent directory"
        );

        Ok(())
    }

    #[test]
    fn test_list_icons_with_generated_icons() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let icons_dir = temp_dir.path().join("icons");
        let generator = Generator::new(icons_dir.clone());

        // Add some test icons
        let test_icon1 = IconifyIcon {
            body: r#"<path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/>"#.to_string(),
            width: Some(24),
            height: Some(24),
            view_box: Some("0 0 24 24".to_string()),
        };

        let test_icon2 = IconifyIcon {
            body: r#"<circle cx="12" cy="12" r="10"/>"#.to_string(),
            width: Some(24),
            height: Some(24),
            view_box: Some("0 0 24 24".to_string()),
        };

        let identifier1 = IconIdentifier::parse("mdi:home")?;
        let identifier2 = IconIdentifier::parse("mdi:settings")?;
        let identifier3 = IconIdentifier::parse("heroicons:arrow-left")?;

        generator.add_icons(
            &[
                (identifier1, test_icon1.clone()),
                (identifier2, test_icon2.clone()),
                (identifier3, test_icon1.clone()),
            ],
            &HashMap::new(),
        )?;

        // List the icons
        let icons = generator.list_icons()?;

        // Should have 2 collections
        assert_eq!(icons.len(), 2, "Should have 2 collections");
        assert!(icons.contains_key("mdi"), "Should have mdi collection");
        assert!(
            icons.contains_key("heroicons"),
            "Should have heroicons collection"
        );

        // Check mdi collection has 2 icons
        let mdi_icons = icons.get("mdi").unwrap();
        assert_eq!(mdi_icons.len(), 2, "mdi should have 2 icons");
        assert!(mdi_icons.contains(&"mdi:home".to_string()));
        assert!(mdi_icons.contains(&"mdi:settings".to_string()));

        // Check heroicons collection has 1 icon
        let heroicons_icons = icons.get("heroicons").unwrap();
        assert_eq!(heroicons_icons.len(), 1, "heroicons should have 1 icon");
        assert!(heroicons_icons.contains(&"heroicons:arrow-left".to_string()));

        Ok(())
    }

    #[test]
    fn test_get_all_icon_identifiers() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let icons_dir = temp_dir.path().join("icons");
        let generator = Generator::new(icons_dir.clone());

        // Test with no icons
        let empty_icons = generator.get_all_icon_identifiers()?;
        assert!(
            empty_icons.is_empty(),
            "Should return empty vec for no icons"
        );

        // Add some test icons
        let test_icon = IconifyIcon {
            body: r#"<path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/>"#.to_string(),
            width: Some(24),
            height: Some(24),
            view_box: Some("0 0 24 24".to_string()),
        };

        let identifier1 = IconIdentifier::parse("mdi:home")?;
        let identifier2 = IconIdentifier::parse("mdi:settings")?;
        let identifier3 = IconIdentifier::parse("heroicons:arrow-left")?;

        generator.add_icons(
            &[
                (identifier1, test_icon.clone()),
                (identifier2, test_icon.clone()),
                (identifier3, test_icon.clone()),
            ],
            &HashMap::new(),
        )?;

        // Get all identifiers
        let all_icons = generator.get_all_icon_identifiers()?;

        // Should have 3 icons
        assert_eq!(all_icons.len(), 3, "Should have 3 icons");
        assert!(
            all_icons.contains(&"mdi:home".to_string()),
            "Should contain mdi:home"
        );
        assert!(
            all_icons.contains(&"mdi:settings".to_string()),
            "Should contain mdi:settings"
        );
        assert!(
            all_icons.contains(&"heroicons:arrow-left".to_string()),
            "Should contain heroicons:arrow-left"
        );

        Ok(())
    }

    #[test]
    fn test_regenerate_mod_rs_updates_template() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let icons_dir = temp_dir.path().join("icons");
        let generator = Generator::new(icons_dir.clone());

        // Add some test icons
        let test_icon = IconifyIcon {
            body: r#"<path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/>"#.to_string(),
            width: Some(24),
            height: Some(24),
            view_box: Some("0 0 24 24".to_string()),
        };

        let identifier1 = IconIdentifier::parse("mdi:home")?;
        let identifier2 = IconIdentifier::parse("heroicons:arrow-left")?;

        generator.add_icons(
            &[
                (identifier1, test_icon.clone()),
                (identifier2, test_icon.clone()),
            ],
            &HashMap::new(),
        )?;

        let mod_rs_path = icons_dir.join("mod.rs");
        assert!(mod_rs_path.exists(), "mod.rs should exist");

        // Simulate an old version by writing outdated content
        let old_content = r#"// Auto-generated by dioxus-iconify - DO NOT EDIT
use dioxus::prelude::*;

// OLD VERSION WITHOUT SIZE PARAMETER
#[component]
pub fn Icon(data: IconData) -> Element {
    rsx! { svg {} }
}

pub mod heroicons;
pub mod mdi;
"#;
        fs::write(&mod_rs_path, old_content)?;

        // Verify the old content is there
        let content_before = fs::read_to_string(&mod_rs_path)?;
        assert!(
            content_before.contains("OLD VERSION"),
            "Should have old version marker"
        );
        assert!(
            !content_before.contains("size: Option<String>"),
            "Should not have size parameter yet"
        );

        // Regenerate mod.rs
        generator.regenerate_mod_rs()?;

        // Verify the new content has the latest template
        let content_after = fs::read_to_string(&mod_rs_path)?;
        assert!(
            !content_after.contains("OLD VERSION"),
            "Should not have old version marker"
        );
        assert!(
            content_after.contains("size: String"),
            "Should have size parameter from latest template"
        );
        assert!(
            content_after.contains("pub mod heroicons;"),
            "Should preserve heroicons module"
        );
        assert!(
            content_after.contains("pub mod mdi;"),
            "Should preserve mdi module"
        );

        Ok(())
    }

    #[test]
    fn test_collection_info_in_generated_file() -> Result<()> {
        use crate::api::{IconifyAuthor, IconifyCollectionInfo, IconifyLicense};

        let temp_dir = TempDir::new()?;
        let icons_dir = temp_dir.path().join("icons");
        let generator = Generator::new(icons_dir.clone());

        // Create test icon
        let test_icon = IconifyIcon {
            body: r#"<path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/>"#.to_string(),
            width: Some(24),
            height: Some(24),
            view_box: Some("0 0 24 24".to_string()),
        };

        let identifier = IconIdentifier::parse("mdi:home")?;

        // Create collection info
        let mut collection_info = HashMap::new();
        collection_info.insert(
            "mdi".to_string(),
            IconifyCollectionInfo {
                name: Some("Material Design Icons".to_string()),
                author: Some(IconifyAuthor::Detailed {
                    name: Some("Pictogrammers".to_string()),
                    url: Some("https://pictogrammers.com".to_string()),
                }),
                license: Some(IconifyLicense::Detailed {
                    title: Some("Apache 2.0".to_string()),
                    spdx: Some("Apache-2.0".to_string()),
                    url: Some("https://www.apache.org/licenses/LICENSE-2.0".to_string()),
                }),
                total: Some(7000),
                category: Some("General".to_string()),
                palette: Some(false),
                height: Some(24),
            },
        );

        // Generate the icon with collection info
        generator.add_icons(&[(identifier, test_icon)], &collection_info)?;

        // Read the generated file
        let generated_file = icons_dir.join("mdi.rs");
        let content = fs::read_to_string(&generated_file)?;

        // Verify generation metadata
        assert!(
            content.contains("/// Generated:"),
            "Should include generation timestamp"
        );
        assert!(
            content.contains("/// Collection: mdi"),
            "Should include collection name"
        );
        assert!(
            content.contains("/// This is a partial import from Iconify"),
            "Should indicate partial import"
        );
        assert!(
            content.contains("/// Browse icons: https://icon-sets.iconify.design/mdi/"),
            "Should include browse URL"
        );

        // Verify collection info is included
        assert!(
            content.contains("/// ```yaml"),
            "Should include YAML code block"
        );
        assert!(
            content.contains("name: Material Design Icons"),
            "Should include collection name"
        );
        assert!(content.contains("author:"), "Should include author section");
        assert!(
            content.contains("name: Pictogrammers"),
            "Should include author name"
        );
        assert!(
            content.contains("url: https://pictogrammers.com"),
            "Should include author URL"
        );
        assert!(
            content.contains("license:"),
            "Should include license section"
        );
        assert!(
            content.contains("title: Apache 2.0"),
            "Should include license title"
        );
        assert!(
            content.contains("spdx: Apache-2.0"),
            "Should include SPDX identifier"
        );
        assert!(
            content.contains("total: 7000"),
            "Should include total count"
        );
        assert!(
            content.contains("category: General"),
            "Should include category"
        );
        assert!(content.contains("palette: false"), "Should include palette");
        assert!(content.contains("height: 24"), "Should include height");

        Ok(())
    }

    #[test]
    fn test_module_visibility_preservation() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let icons_dir = temp_dir.path().join("icons");
        let generator = Generator::new(icons_dir.clone());

        // Add initial icons
        let test_icon = IconifyIcon {
            body: r#"<path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/>"#.to_string(),
            width: Some(24),
            height: Some(24),
            view_box: Some("0 0 24 24".to_string()),
        };

        let identifier1 = IconIdentifier::parse("mdi:home")?;
        let identifier2 = IconIdentifier::parse("heroicons:arrow-left")?;

        generator.add_icons(
            &[
                (identifier1, test_icon.clone()),
                (identifier2, test_icon.clone()),
            ],
            &HashMap::new(),
        )?;

        let mod_rs_path = icons_dir.join("mod.rs");

        // Modify mod.rs to have different visibility modifiers
        let modified_content = r#"// Auto-generated by dioxus-iconify - DO NOT EDIT
use dioxus::prelude::*;

#[derive(Clone, Copy, PartialEq)]
pub struct IconData {
    pub name: &'static str,
    pub body: &'static str,
    pub view_box: &'static str,
    pub width: &'static str,
    pub height: &'static str,
}

#[component]
pub fn Icon(
    data: IconData,
    /// Optional size to set both width and height
    #[props(default, into)]
    size: String,
    /// Additional attributes to extend the svg element
    #[props(extends = GlobalAttributes)]
    attributes: Vec<Attribute>,
) -> Element {
    let (width, height) = if size.is_empty() {
        (data.width, data.height)
    } else {
        (size.as_str(), size.as_str())
    };

    rsx! {
        svg {
            view_box: "{data.view_box}",
            width: "{width}",
            height: "{height}",
            dangerous_inner_html: "{data.body}",
            ..attributes,
        }
    }
}

mod heroicons;
pub mod mdi;
"#;
        fs::write(&mod_rs_path, modified_content)?;

        // Add another icon from a new collection
        let identifier3 = IconIdentifier::parse("lucide:star")?;
        generator.add_icons(&[(identifier3, test_icon.clone())], &HashMap::new())?;

        // Read the updated mod.rs
        let content_after = fs::read_to_string(&mod_rs_path)?;

        // Verify that visibility is preserved
        assert!(
            content_after.contains("mod heroicons;"),
            "Should preserve 'mod heroicons;' without pub"
        );
        assert!(
            content_after.contains("pub mod mdi;"),
            "Should preserve 'pub mod mdi;'"
        );
        assert!(
            content_after.contains("pub mod lucide;"),
            "New modules should be added with 'pub mod'"
        );

        // Verify that all three modules are present
        let has_heroicons = content_after.lines().any(|l| l.trim() == "mod heroicons;");
        let has_mdi = content_after.lines().any(|l| l.trim() == "pub mod mdi;");
        let has_lucide = content_after.lines().any(|l| l.trim() == "pub mod lucide;");

        assert!(has_heroicons, "Should have mod heroicons;");
        assert!(has_mdi, "Should have pub mod mdi;");
        assert!(has_lucide, "Should have pub mod lucide;");

        Ok(())
    }

    #[test]
    fn test_extract_module_declarations() {
        let content = r#"
// Some comment
pub mod mdi;
mod heroicons;
pub(crate) mod feather;
pub mod simple_icons;
"#;

        let modules = extract_module_declarations(content);

        assert_eq!(modules.len(), 4);
        assert_eq!(modules.get("mdi"), Some(&"pub ".to_string()));
        assert_eq!(modules.get("heroicons"), Some(&"".to_string()));
        assert_eq!(modules.get("feather"), Some(&"pub(crate) ".to_string()));
        assert_eq!(modules.get("simple_icons"), Some(&"pub ".to_string()));
    }

    #[test]
    fn test_custom_user_module_preservation() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let icons_dir = temp_dir.path().join("icons");
        let generator = Generator::new(icons_dir.clone());

        // Create custom user module with custom IconData
        fs::create_dir_all(&icons_dir)?;
        let app_rs_path = icons_dir.join("app.rs");
        let custom_icon_content = r##"/// Custom user-defined icons
use super::IconData;

#[allow(non_upper_case_globals)]
pub const CustomLogo: IconData = IconData {
    name: "app:custom-logo",
    body: r#"<rect width="100" height="100" fill="blue"/>"#,
    view_box: "0 0 100 100",
    width: "100",
    height: "100",
};

#[allow(non_upper_case_globals)]
pub const CustomBrand: IconData = IconData {
    name: "app:custom-brand",
    body: r#"<circle cx="50" cy="50" r="40" fill="red"/>"#,
    view_box: "0 0 100 100",
    width: "100",
    height: "100",
};
"##;
        fs::write(&app_rs_path, custom_icon_content)?;

        // Initialize with mod.rs and add the custom module with pub(crate) visibility
        generator.init()?;
        let mod_rs_path = icons_dir.join("mod.rs");
        let initial_mod_content = format!(
            "{}
pub(crate) mod app;
",
            MOD_RS_TEMPLATE
        );
        fs::write(&mod_rs_path, initial_mod_content)?;

        // Verify custom module file exists
        assert!(app_rs_path.exists(), "Custom app.rs should exist");
        let custom_content_before = fs::read_to_string(&app_rs_path)?;
        assert!(
            custom_content_before.contains("CustomLogo"),
            "Custom icon should be defined"
        );

        // Now add some generated icons
        let test_icon = IconifyIcon {
            body: r#"<path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/>"#.to_string(),
            width: Some(24),
            height: Some(24),
            view_box: Some("0 0 24 24".to_string()),
        };

        let identifier1 = IconIdentifier::parse("mdi:home")?;
        let identifier2 = IconIdentifier::parse("heroicons:star")?;

        generator.add_icons(
            &[
                (identifier1, test_icon.clone()),
                (identifier2, test_icon.clone()),
            ],
            &HashMap::new(),
        )?;

        // Verify custom module file still exists and is unchanged
        assert!(
            app_rs_path.exists(),
            "Custom app.rs should still exist after adding generated icons"
        );
        let custom_content_after = fs::read_to_string(&app_rs_path)?;
        assert_eq!(
            custom_content_before, custom_content_after,
            "Custom module content should not be modified"
        );

        // Read updated mod.rs
        let mod_rs_content = fs::read_to_string(&mod_rs_path)?;

        // Verify that custom module is still present with original visibility
        assert!(
            mod_rs_content.contains("pub(crate) mod app;"),
            "Custom module should be preserved with pub(crate) visibility"
        );

        // Verify that generated modules were added
        assert!(
            mod_rs_content.contains("pub mod mdi;"),
            "Generated mdi module should be added"
        );
        assert!(
            mod_rs_content.contains("pub mod heroicons;"),
            "Generated heroicons module should be added"
        );

        // Count module declarations to ensure nothing was removed
        let module_count = mod_rs_content
            .lines()
            .filter(|line| line.trim().contains("mod ") && line.trim().ends_with(';'))
            .count();
        assert_eq!(
            module_count, 3,
            "Should have exactly 3 modules: app, heroicons, and mdi"
        );

        // Verify modules are in alphabetical order
        let mod_lines: Vec<&str> = mod_rs_content
            .lines()
            .filter(|line| line.trim().contains("mod ") && line.trim().ends_with(';'))
            .collect();
        assert_eq!(mod_lines.len(), 3, "Should have 3 module lines");

        // Check that they appear in alphabetical order
        let mut module_names: Vec<String> = Vec::new();
        for line in &mod_lines {
            if let Some(name_start) = line.find("mod ") {
                let name_part = &line[name_start + 4..];
                if let Some(name_end) = name_part.find(';') {
                    module_names.push(name_part[..name_end].trim().to_string());
                }
            }
        }
        assert_eq!(module_names, vec!["app", "heroicons", "mdi"]);

        Ok(())
    }
}