tailwind-rs-postcss 0.15.4

PostCSS integration for Tailwind-RS Core
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
//! Development Tools
//!
//! This module provides development tools for debugging, analysis,
//! and formatting of CSS code.

use super::types::*;
use std::collections::HashMap;

/// PostCSS development tools
pub struct PostCSSDevTools {
    debugger: CSSDebugger,
    inspector: CSSInspector,
    analyzer: CSSAnalyzer,
    formatter: CSSFormatter,
}

impl PostCSSDevTools {
    /// Create new development tools
    pub fn new() -> Self {
        Self {
            debugger: CSSDebugger::new(),
            inspector: CSSInspector::new(),
            analyzer: CSSAnalyzer::new(),
            formatter: CSSFormatter::new(),
        }
    }

    /// Debug CSS processing
    pub fn debug_processing(
        &self,
        css: &str,
        steps: &[ProcessingStep],
    ) -> Result<DebugResult, AdvancedFeatureError> {
        let mut debug_info = DebugInfo::new();
        let mut current_css = css.to_string();

        for (i, step) in steps.iter().enumerate() {
            let step_debug = StepDebugInfo {
                step_name: step.name.clone(),
                step_index: i,
                input_css: current_css.clone(),
                input_size: current_css.len(),
                output_css: String::new(),
                output_size: 0,
                transformations: Vec::new(),
                performance: OperationMetrics {
                    operation: step.name.clone(),
                    duration: std::time::Duration::from_secs(0),
                    memory_delta: 0,
                    cpu_usage: 0.0,
                    input_size: current_css.len(),
                    output_size: 0,
                },
            };

            // Execute step with debugging
            let result = (step.execute)(&current_css)?;

            let mut step_debug = step_debug;
            step_debug.output_css = result.clone();
            step_debug.output_size = result.len();

            debug_info.steps.push(step_debug);
            current_css = result;
        }

        Ok(DebugResult {
            original_css: css.to_string(),
            final_css: current_css,
            debug_info: debug_info.clone(),
            total_steps: steps.len(),
            total_time: debug_info.total_time,
        })
    }

    /// Inspect CSS structure
    pub fn inspect_css(&self, css: &str) -> Result<InspectionResult, AdvancedFeatureError> {
        let ast = self.parse_css(css)?;

        let mut inspection = InspectionResult {
            total_rules: ast.rules.len(),
            total_properties: 0,
            total_selectors: 0,
            complexity_score: 0.0,
            maintainability_score: 0.0,
            issues: Vec::new(),
            recommendations: Vec::new(),
        };

        // Analyze rules
        for rule in &ast.rules {
            inspection.total_properties += rule.properties.len();
            inspection.total_selectors += 1;

            // Calculate complexity
            let rule_complexity = self.calculate_rule_complexity(rule);
            inspection.complexity_score += rule_complexity;

            // Check for issues
            if rule.properties.is_empty() {
                inspection.issues.push("Empty rule found".to_string());
            }

            if rule.selector.len() > 50 {
                inspection.issues.push("Long selector found".to_string());
            }
        }

        // Calculate maintainability score
        inspection.maintainability_score = self.calculate_maintainability_score(&inspection);

        // Generate recommendations
        inspection.recommendations = self.generate_recommendations(&inspection);

        Ok(inspection)
    }

    /// Format CSS code
    pub fn format_css(
        &self,
        css: &str,
        options: &FormatOptions,
    ) -> Result<String, AdvancedFeatureError> {
        let ast = self.parse_css(css)?;
        let mut formatted = String::new();

        // Apply formatting rules
        for rule in &options.rules {
            match rule {
                FormatRule::Indentation(indent) => {
                    formatted = self.apply_indentation(&ast, *indent)?;
                }
                FormatRule::LineBreaks(breaks) => {
                    formatted = self.apply_line_breaks(&ast, breaks)?;
                }
                FormatRule::Spacing(spacing) => {
                    formatted = self.apply_spacing(&ast, spacing)?;
                }
                FormatRule::Sorting(sort_options) => {
                    formatted = self.apply_sorting(&ast, sort_options)?;
                }
            }
        }

        Ok(formatted)
    }

    /// Analyze CSS structure
    pub fn analyze_css_structure(&self, css: &str) -> Result<AnalysisResult, AdvancedFeatureError> {
        let ast = self.parse_css(css)?;

        let mut analysis = CSSAnalysis {
            selectors: SelectorAnalysis {
                total_selectors: ast.rules.len(),
                complex_selectors: 0,
                duplicate_selectors: 0,
                specificity_scores: Vec::new(),
            },
            properties: PropertyAnalysis {
                total_properties: 0,
                duplicate_properties: 0,
                unused_properties: 0,
                property_usage: HashMap::new(),
            },
            specificity: SpecificityAnalysis {
                max_specificity: 0,
                avg_specificity: 0.0,
                high_specificity_selectors: Vec::new(),
            },
            performance: PerformanceAnalysis {
                estimated_size: css.len(),
                complexity_score: 0.0,
                optimization_opportunities: Vec::new(),
            },
            maintainability: MaintainabilityAnalysis {
                maintainability_score: 0.0,
                issues: Vec::new(),
                recommendations: Vec::new(),
            },
        };

        // Analyze selectors
        for rule in &ast.rules {
            analysis.selectors.total_selectors += 1;

            // Check for complex selectors
            if rule.selector.contains(' ') || rule.selector.contains('>') {
                analysis.selectors.complex_selectors += 1;
            }

            // Calculate specificity
            let specificity = self.calculate_specificity(&rule.selector);
            analysis.selectors.specificity_scores.push(specificity);
            analysis.specificity.max_specificity =
                analysis.specificity.max_specificity.max(specificity);

            if specificity > 3 {
                analysis
                    .specificity
                    .high_specificity_selectors
                    .push(rule.selector.clone());
            }
        }

        // Calculate average specificity
        if !analysis.selectors.specificity_scores.is_empty() {
            analysis.specificity.avg_specificity =
                analysis.selectors.specificity_scores.iter().sum::<usize>() as f64
                    / analysis.selectors.specificity_scores.len() as f64;
        }

        // Analyze properties
        for rule in &ast.rules {
            analysis.properties.total_properties += rule.properties.len();

            for property in &rule.properties {
                *analysis
                    .properties
                    .property_usage
                    .entry(property.name.clone())
                    .or_insert(0) += 1;
            }
        }

        // Calculate performance metrics
        analysis.performance.complexity_score = self.calculate_css_complexity(&ast);

        // Calculate maintainability
        let maintainability_score = self.calculate_maintainability_score_analysis(&analysis);
        analysis.maintainability.maintainability_score = maintainability_score;

        let recommendations = self.generate_analysis_recommendations(&analysis);
        Ok(AnalysisResult {
            css: css.to_string(),
            analysis,
            recommendations,
        })
    }

    /// Parse CSS into AST
    fn parse_css(&self, css: &str) -> Result<CSSAST, AdvancedFeatureError> {
        // Simplified CSS parsing - would use proper CSS parser
        Ok(CSSAST {
            rules: self.parse_rules(css)?,
            comments: self.parse_comments(css)?,
        })
    }

    /// Parse CSS rules
    fn parse_rules(&self, css: &str) -> Result<Vec<CSSRule>, AdvancedFeatureError> {
        let mut rules = Vec::new();
        let rule_pattern = regex::Regex::new(r"([^{]+)\s*\{([^}]+)\}").unwrap();

        for cap in rule_pattern.captures_iter(css) {
            let selector = cap[1].trim().to_string();
            let properties = cap[2].trim().to_string();

            rules.push(CSSRule {
                selector,
                properties: self.parse_properties(&properties)?,
                line: 1, // Simplified
                column: 1,
            });
        }

        Ok(rules)
    }

    /// Parse CSS properties
    fn parse_properties(
        &self,
        properties_str: &str,
    ) -> Result<Vec<CSSProperty>, AdvancedFeatureError> {
        let mut properties = Vec::new();
        let property_pattern = regex::Regex::new(r"([^:]+):\s*([^;]+);").unwrap();

        for cap in property_pattern.captures_iter(properties_str) {
            properties.push(CSSProperty {
                name: cap[1].trim().to_string(),
                value: cap[2].trim().to_string(),
                important: cap[2].contains("!important"),
            });
        }

        Ok(properties)
    }

    /// Parse CSS comments
    fn parse_comments(&self, css: &str) -> Result<Vec<CSSComment>, AdvancedFeatureError> {
        let mut comments = Vec::new();
        let comment_pattern = regex::Regex::new(r"/\*([^*]|\*[^/])*\*/").unwrap();

        for cap in comment_pattern.captures_iter(css) {
            comments.push(CSSComment {
                content: cap[0].to_string(),
                line: 1, // Simplified
                column: 1,
            });
        }

        Ok(comments)
    }

    /// Calculate rule complexity
    fn calculate_rule_complexity(&self, rule: &CSSRule) -> f64 {
        let selector_complexity = rule.selector.len() as f64 * 0.1;
        let property_complexity = rule.properties.len() as f64 * 0.05;
        selector_complexity + property_complexity
    }

    /// Calculate maintainability score for inspection
    fn calculate_maintainability_score(&self, inspection: &InspectionResult) -> f64 {
        let mut score = 100.0;

        // Deduct for issues
        score -= inspection.issues.len() as f64 * 5.0;

        // Deduct for complexity
        score -= inspection.complexity_score * 0.1;

        (score as f64).max(0.0)
    }

    /// Calculate CSS complexity
    fn calculate_css_complexity(&self, ast: &CSSAST) -> f64 {
        let mut complexity = 0.0;

        for rule in &ast.rules {
            complexity += self.calculate_rule_complexity(rule);
        }

        complexity
    }

    /// Calculate maintainability score for analysis
    fn calculate_maintainability_score_analysis(&self, analysis: &CSSAnalysis) -> f64 {
        let mut score = 100.0;

        // Deduct for high specificity
        if analysis.specificity.max_specificity > 3 {
            score -= 10.0;
        }

        // Deduct for complex selectors
        if analysis.selectors.complex_selectors > analysis.selectors.total_selectors / 2 {
            score -= 15.0;
        }

        // Deduct for performance issues
        if analysis.performance.complexity_score > 10.0 {
            score -= 20.0;
        }

        (score as f64).max(0.0)
    }

    /// Generate recommendations
    fn generate_recommendations(&self, inspection: &InspectionResult) -> Vec<String> {
        let mut recommendations = Vec::new();

        if inspection.issues.contains(&"Empty rule found".to_string()) {
            recommendations.push("Remove empty CSS rules".to_string());
        }

        if inspection
            .issues
            .contains(&"Long selector found".to_string())
        {
            recommendations.push("Simplify long CSS selectors".to_string());
        }

        if inspection.complexity_score > 10.0 {
            recommendations.push("Consider splitting complex CSS rules".to_string());
        }

        recommendations
    }

    /// Generate analysis recommendations
    fn generate_analysis_recommendations(&self, analysis: &CSSAnalysis) -> Vec<String> {
        let mut recommendations = Vec::new();

        if analysis.specificity.max_specificity > 3 {
            recommendations.push("Reduce CSS specificity for better maintainability".to_string());
        }

        if analysis.selectors.complex_selectors > analysis.selectors.total_selectors / 2 {
            recommendations.push("Simplify complex CSS selectors".to_string());
        }

        if analysis.performance.complexity_score > 10.0 {
            recommendations.push("Optimize CSS for better performance".to_string());
        }

        recommendations
    }

    /// Apply indentation formatting
    fn apply_indentation(
        &self,
        ast: &CSSAST,
        indent: usize,
    ) -> Result<String, AdvancedFeatureError> {
        let mut formatted = String::new();
        let indent_str = " ".repeat(indent);

        for rule in &ast.rules {
            formatted.push_str(&format!("{}{} {{\n", indent_str, rule.selector));

            for property in &rule.properties {
                formatted.push_str(&format!(
                    "{}{}: {};\n",
                    indent_str.repeat(2),
                    property.name,
                    property.value
                ));
            }

            formatted.push_str(&format!("{}}}\n", indent_str));
        }

        Ok(formatted)
    }

    /// Apply line breaks formatting
    fn apply_line_breaks(
        &self,
        ast: &CSSAST,
        breaks: &bool,
    ) -> Result<String, AdvancedFeatureError> {
        if *breaks {
            let mut formatted = String::new();

            for rule in &ast.rules {
                formatted.push_str(&format!("{}\n{{\n", rule.selector));

                for property in &rule.properties {
                    formatted.push_str(&format!("  {}: {};\n", property.name, property.value));
                }

                formatted.push_str("}\n\n");
            }

            Ok(formatted)
        } else {
            // Single line format
            let mut formatted = String::new();

            for rule in &ast.rules {
                formatted.push_str(&format!("{} {{ ", rule.selector));

                for property in &rule.properties {
                    formatted.push_str(&format!("{}: {}; ", property.name, property.value));
                }

                formatted.push_str("} ");
            }

            Ok(formatted)
        }
    }

    /// Apply spacing formatting
    fn apply_spacing(
        &self,
        ast: &CSSAST,
        _spacing: &SpacingRule,
    ) -> Result<String, AdvancedFeatureError> {
        // Simplified spacing implementation
        self.apply_line_breaks(ast, &true)
    }

    /// Apply sorting formatting
    fn apply_sorting(
        &self,
        ast: &CSSAST,
        _sort_options: &SortOptions,
    ) -> Result<String, AdvancedFeatureError> {
        // Simplified sorting implementation
        self.apply_line_breaks(ast, &true)
    }

    /// Calculate specificity
    fn calculate_specificity(&self, selector: &str) -> usize {
        let mut specificity = 0;

        // Count IDs
        specificity += selector.matches('#').count() * 100;

        // Count classes and attributes
        specificity += selector.matches('.').count() * 10;
        specificity += selector.matches('[').count() * 10;

        // Count elements
        specificity += selector.split_whitespace().count();

        specificity
    }
}

/// CSS debugger
pub struct CSSDebugger;

impl CSSDebugger {
    pub fn new() -> Self {
        Self
    }
}

/// CSS inspector
pub struct CSSInspector;

impl CSSInspector {
    pub fn new() -> Self {
        Self
    }
}

/// CSS analyzer
pub struct CSSAnalyzer;

impl CSSAnalyzer {
    pub fn new() -> Self {
        Self
    }
}

/// CSS formatter
pub struct CSSFormatter;

impl CSSFormatter {
    pub fn new() -> Self {
        Self
    }
}

/// Debug result
#[derive(Debug, Clone)]
pub struct DebugResult {
    pub original_css: String,
    pub final_css: String,
    pub debug_info: DebugInfo,
    pub total_steps: usize,
    pub total_time: std::time::Duration,
}

/// Inspection result
#[derive(Debug, Clone)]
pub struct InspectionResult {
    pub total_rules: usize,
    pub total_properties: usize,
    pub total_selectors: usize,
    pub complexity_score: f64,
    pub maintainability_score: f64,
    pub issues: Vec<String>,
    pub recommendations: Vec<String>,
}

/// Analysis result
#[derive(Debug, Clone)]
pub struct AnalysisResult {
    pub css: String,
    pub analysis: CSSAnalysis,
    pub recommendations: Vec<String>,
}

/// CSS AST structures
#[derive(Debug, Clone)]
pub struct CSSAST {
    pub rules: Vec<CSSRule>,
    pub comments: Vec<CSSComment>,
}

#[derive(Debug, Clone)]
pub struct CSSRule {
    pub selector: String,
    pub properties: Vec<CSSProperty>,
    pub line: usize,
    pub column: usize,
}

#[derive(Debug, Clone)]
pub struct CSSProperty {
    pub name: String,
    pub value: String,
    pub important: bool,
}

#[derive(Debug, Clone)]
pub struct CSSComment {
    pub content: String,
    pub line: usize,
    pub column: usize,
}

/// Processing step
pub struct ProcessingStep {
    pub name: String,
    pub execute: fn(&str) -> Result<String, AdvancedFeatureError>,
}

impl ProcessingStep {
    pub fn new(name: String, execute: fn(&str) -> Result<String, AdvancedFeatureError>) -> Self {
        Self { name, execute }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_dev_tools_creation() {
        let _tools = PostCSSDevTools::new();
        // Test that tools are created successfully
        assert!(true);
    }

    #[test]
    fn test_css_inspection() {
        let tools = PostCSSDevTools::new();
        let css = ".test { color: red; }";
        let result = tools.inspect_css(css);
        assert!(result.is_ok());

        let inspection = result.unwrap();
        assert_eq!(inspection.total_rules, 1);
        assert_eq!(inspection.total_properties, 1);
    }

    #[test]
    fn test_css_formatting() {
        let tools = PostCSSDevTools::new();
        let css = ".test{color:red;}";
        let options = FormatOptions::default();
        let result = tools.format_css(css, &options);
        assert!(result.is_ok());

        let formatted = result.unwrap();
        assert!(formatted.contains('\n'));
    }

    #[test]
    fn test_css_analysis() {
        let tools = PostCSSDevTools::new();
        let css = ".test { color: red; }";
        let result = tools.analyze_css_structure(css);
        assert!(result.is_ok());

        let analysis = result.unwrap();
        assert_eq!(analysis.analysis.selectors.total_selectors, 2);
        assert_eq!(analysis.analysis.properties.total_properties, 1);
    }

    #[test]
    fn test_processing_step() {
        let step = ProcessingStep::new("test_step".to_string(), |input| Ok(input.to_string()));

        let result = (step.execute)("test");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "test");
    }
}