CSS Code Quality

repository·main·Indexed 41 days ago

https://github.com/projectwallace/css-code-quality

A CSS Code Quality calculator (v3.1.4) that analyzes CSS files to provide high-level scores across Performance, Maintainability, and Complexity metrics. It uses the calculate() function to evaluate CSS strings and identify violations and passes based on a range of quality guards.

Tokens
3.8K
Snippets
13
Records
17
Agent score
99%

What's inside CSS Code Quality

  1. Understand the structure of pass and violation objects

    main

    The passes and violations arrays in the result object contain objects describing specific metrics. Each object includes an id, a score (representing points deducted), and a value (the actual measured value). Some metrics also include an actuals array showing the raw data points used for the calculation.

    // Example violation object
    {
      "id": "AverageSelectorsPerRule",
      "score": 0,
      "value": 1.5,
      "actuals": [
        2,
        1
      ]
    }
  2. Calculate CSS code quality score with calculate()

    main

    Use the calculate function to analyze a CSS string. The function returns a result object containing overall scores and detailed breakdowns for Performance, Maintainability, and Complexity. Each category includes lists of violations and passes.

    import { calculate } from '@projectwallace/css-code-quality'
    
    let css = `my_css { /* ... */ }`
    let result = calculate(css)
    
    /*
    Result shape:
    {
      "violations": [ ],
      "passes": [ ],
      "performance": {
        "score": 90,
        "violations": [ ],
        "passes": [ ]
      },
      "maintainability": {
        "score": 100,
        "violations": [ ],
        "passes": [ ]
      },
      "complexity": {
        "score": 97,
        "violations": [ ],
        "passes": [ ]
      }
    }
    */
  3. Configure tsdown for CSS Code Quality

    main

    The project uses tsdown for its build configuration. You can define entry points, output formats, and build-time checks like dts (declaration file generation) and publint (package publishing validation) within the defineConfig function.

    import { defineConfig } from 'tsdown'
    
    export default defineConfig({
    	entry: ['./src/index.ts', './src/core.ts'],
    	format: 'esm',
    	platform: 'neutral',
    	dts: true,
    	publint: true,
    })
  4. Configure Knip for CSS Code Quality

    main

    The project uses knip for dependency and unused file analysis. You can configure the analysis scope by defining the project paths and specifying dependencies to be ignored via ignoreDependencies. In the current setup, the project analyzes TypeScript files in the src directory and ignores @projectwallace/preset-oxlint to prevent false positives in dependency reporting.

    import type { KnipConfig } from 'knip'
    
    const config: KnipConfig = {
    	project: ['src/**/*.ts'],
    	ignoreDependencies: ['@projectwallace/preset-oxlint'],
    }
    
    export default config
  5. Performance metrics reference

    main

    The Performance score measures the likelihood of negative impact on performance. Metrics include:

    MetricWhat is testedPoints deducted
    ImportsNumber of @import rules10 per @import
    EmptyRulesNumber of empty rules1 per empty rule
    SelectorDuplicationsRatio of duplicate selectorsUp to 10 (when uniqueness ratio < 66%)
    DeclarationDuplicationsRatio of duplicate declarationsUp to 10 (when uniqueness ratio < 66%)
    CssSizeTotal CSS file size5 if size exceeds 200,000 bytes
    TooMuchCommentsTotal size of comments1 per 250 bytes of comments, max 10
    TooMuchEmbeddedContentTotal size of embedded content (e.g. base64)1 per 250 bytes of embedded content, max 20
  6. Maintainability metrics reference

    main

    The Maintainability score measures how difficult it is to locate specific code for bug fixes. Metrics include:

    MetricWhat is testedPoints deducted
    SourceLinesOfCodeTotal source lines of code1 per 1,000 lines over 10,000, max 15
    AverageSelectorsPerRuleAverage number of selectors per rule5 per selector over 2 (average), max 15
    AverageDeclarationsPerRuleAverage number of declarations per rule5 per declaration over 5 (average), max 15
    MaxSelectorsPerRuleMaximum number of selectors in a single rule0.5 per selector over 10, max 15
    MaxDeclarationsPerRuleMaximum number of declarations in a single rule0.5 per declaration over 10, max 15
    MoreThanMostCommonSelectorsPerRuleRules that have more selectors than the most common count0.01 per rule, max 15 (when > 10% of rules exceed the mode)
    MoreThanMostCommonDeclarationsPerRuleRules that have more declarations than the most common count0.01 per rule, max 15 (when > 10% of rules exceed the mode)
  7. Complexity metrics reference

    main

    The Complexity score measures the difficulty of making changes without side effects. Metrics include:

    MetricWhat is testedPoints deducted
    MoreThanMostCommonSelectorComplexitySelectors more complex than the most common complexity0.01 per selector, max 10 (when > 10% of selectors exceed the mode)
    MoreThanMostCommonSelectorSpecificitySelectors with higher specificity than the most common specificity0.01 per selector, max 10 (when > 10% of selectors exceed the mode)
    MaxSelectorComplexityMaximum complexity of a single selector0.5 per complexity unit over 5, max 5
    AverageSelectorComplexityAverage selector complexity2 per complexity unit over 2 (average), max 10
    IdSelectorRatioRatio of ID selectorsUp to 5 (when ID selector ratio exceeds 1%)
    ImportantRatioRatio of !important declarationsUp to 5 (when !important ratio exceeds 1%)
  8. Calculate CSS code quality with calculate()

    main

    The calculate function is the primary entrypoint for assessing the quality of a CSS string. It performs a full analysis of the provided CSS and returns quality metrics. Internally, it uses @projectwallace/css-analyzer to parse the CSS and then applies the calculation logic to the resulting analysis object.

    import { calculate } from '@projectwallace/css-code-quality';
    
    const css = '.my-class { color: red; font-size: 16px; }';
    const qualityMetrics = calculate(css);
    console.log(qualityMetrics);
  9. Calculate CSS code quality metrics with calculate()

    main

    The calculate function is the primary entry point for analyzing CSS code quality. It accepts an Analysis object and returns a comprehensive report containing scores and detailed results for three specific categories: performance, maintainability, and complexity.

    Each category in the returned object contains:

    • score: A numeric value (0-100) representing the quality for that specific category.
    • violations: An array of GuardResult objects representing failed quality checks.
    • passes: An array of GuardResult objects representing successful quality checks.

    The top-level return object also provides a flattened list of all violations and passes across all categories.

    import { calculate } from './core.js';
    
    // Assuming 'analysis' is a valid Analysis object obtained from a parser
    const report = calculate(analysis);
    
    console.log('Total Score:', report.performance.score);
    console.log('All Violations:', report.violations);
  10. Maintainability quality guards

    main

    The guards array contains a collection of Guard functions used to calculate the maintainability score of a CSS stylesheet. Each guard evaluates specific metrics from an Analysis object and returns an outcome containing a score (penalty points), an id, and the measured value.

    Note that in this scoring model, a higher score represents a higher penalty (deduction from the total maintainability score). Most scores are capped at 15 points.

    Guard IDs and Logic

    Guard IDMetric EvaluatedPenalty Logic
    SourceLinesOfCodeTotal lines in stylesheet1 point per 1,000 lines over 10,000
    AverageSelectorsPerRuleMean selectors per ruleset5 points per selector over 2
    AverageDeclarationsPerRuleMean declarations per ruleset5 points per declaration over 5
    MaxSelectorsPerRuleMaximum selectors in any single ruleset0.5 points per selector over 10
    MaxDeclarationsPerRuleMaximum declarations in any single ruleset0.5 points per declaration over 10
    MoreThanMostCommonSelectorsPerRuleVariance in selector countsIf >10% of rulesets exceed the mode, deduct 0.01 per applicable ruleset (max 15)
    MoreThanMostCommonDeclarationsPerRuleVariance in declaration countsIf >10% of rulesets exceed the mode, deduct 0.01 per applicable ruleset (max 15)
    import type { Analysis, Guard } from './types.js'
    
    export const guards: Guard[] = [
    	// ... implementation of various guards
    ]
  11. Complexity quality guards

    main

    The guards array contains functions used to calculate complexity scores for CSS analysis. Each guard takes an Analysis object and returns an outcome object containing an id, a score (typically 0-10), the value being measured, and the actuals (the raw data points used for the calculation). These guards monitor selector complexity, specificity, ID selector ratios, and the use of !important declarations.

    import { guards } from '@projectwallace/css-code-quality';
    
    // The guards array is used by the engine to evaluate the quality of a CSS Analysis result.
    // Each guard follows the signature: (result: Analysis) => Outcome