CSS Discontinuity Detector: Planning Document
Overview
The CSS Discontinuity Detector is a static analysis tool that identifies inconsistencies ("discontinuities") in CSS codebases by flagging:
- Conflicting specificity: Overlapping selectors where higher-specificity rules unexpectedly override lower ones (e.g.,
div.foo overriding .foo).
- Unused tokens: CSS custom properties (
--var), at-rules, or declarations defined but never referenced/applied.
- Zombie classes: CSS classes/selectors defined but not used in linked HTML (dead code).
Goals:
- Improve maintainability, reduce bundle size, and prevent subtle bugs.
- CLI-first tool with extensible reporting (JSON, HTML report, IDE integration).
- Handle real-world complexity: Preprocessors (Sass/Less), frameworks (Tailwind), minified CSS.
Non-Goals:
- Runtime analysis (e.g., JS-generated classes).
- Full CSS-in-JS support (focus on vanilla CSS/SCSS).
- Automatic fixes (only flagging).
Key Assumptions:
- Input: Directory of CSS/SCSS files + HTML files (or build output).
- Ignores
@media/@supports for simplicity (configurable).
Architecture
Modular Node.js CLI tool using AST parsing for accuracy.
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Input CLI │───▶│ Parser Layer │───▶│ Analysis Core │
│ (files/directories)│ │ (CSS/HTML AST) │ │ (3 Detectors) │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│
▼
┌─────────────────┐
│ Reporter │
│ (JSON/HTML/CLI) │
└─────────────────┘
Tech Stack
- CSS Parsing:
postcss + postcss-scss (for Sass) + css-tree (low-level AST).
- HTML Parsing:
cheerio (fast, jQuery-like) or parse5 for full HTML5.
- Specificity Calc:
specificity npm package.
- Runtime: Node.js 18+,
commander for CLI, fs-extra for file globbing.
- Output:
table for CLI tables, ejs for HTML reports.
- Extensibility: Plugin system (e.g., for Tailwind purging).
Installation & Usage
npm init css-discontinuity-detector
npx css-discontinuity detect ./src/styles ./dist/html --report html --minify-tolerant
Workflow
-
Input Collection:
- Glob CSS/SCSS:
**/*.css{,.scss}.
- Glob HTML:
**/*.{html,htm} (exclude node_modules).
- Optional:
--critical-path for entry HTML/CSS.
-
Parsing Phase:
- CSS → PostCSS AST: Extract selectors, declarations, custom props (
--*), at-rules.
- HTML → DOM tree: Extract all
class attributes, IDs, tags (normalize to flat sets).
-
Analysis Phase (parallelizable):
- Run 3 detectors → Aggregate issues with file/line locations.
-
Reporting Phase:
- Filter by severity/threshold.
- Dedupe issues (e.g., same zombie class across files).
Detector Implementations
1. Conflicting Specificity Detector
Definition: Flags selector pairs where:
- Selectors overlap (share common elements).
- Specificities differ by >1 level (e.g., class vs. ID).
- Higher-spec rule declared after lower-spec (cascade override).
Algorithm:
for each CSS rule in AST:
selectors = rule.selector.split(',') // e.g., ['div.foo', '.foo']
specScore = specificity(selectors[0]) // Inline/block/attr/class/ID format [0,0,1,2,3]
for each possibleElement in simulatedTargets(selectors): // Expand to base elements
if existingRules[possibleElement] has lower spec:
flag({ type: 'conflict', selectors: [...], diff: specDelta, loc: rule.loc })
- Simulation: Use combinator expansion (e.g.,
.foo > div → targets div.foo-child).
- Threshold: Configurable
specDiff > 2 (e.g., class vs. ID).
- Edge Cases: Ignore universal
*, pseudo-elements.
- Output Example:
⚠️ Conflict: .foo [0,1,0,1,0] overrides div.foo [0,0,1,1,0] (diff=2)
CSS: styles/main.css:42
Suggestion: Refactor to single selector.
2. Unused Tokens Detector
Definition: Flags:
- Custom props (
--color-primary) declared but not var(--color-primary)-referenced.
- Unused
@keyframes, @font-face, unused properties in rules.
Algorithm:
tokens = new Set() // Collect all --var, @keyframes, etc.
traverse CSS AST:
if node.type === 'Declaration' && prop.startsWith('--'):
tokens.add(prop.value.slice(2)) // '--foo' → 'foo'
if node.type === 'Atrule' && name === 'keyframes':
tokens.add(params)
usages = new Set()
traverse CSS AST (values only):
if value contains 'var(--X)' → usages.add('X')
if value matches @keyframes → usages.add(keyframeName)
unused = tokens - usages
flag({ type: 'unused-token', tokens: unused, locs: [...] })
3. Zombie Classes Detector
Definition: .classname or [class*="classname"] in CSS but no class="...classname..." in HTML.
Algorithm:
cssClasses = new Set()
traverse CSS AST (selectors):
for each selector:
parseClassNames(selector) // e.g., '.foo.bar' → ['foo','bar']
cssClasses.addAll(...)
htmlClasses = new Set()
traverse HTML DOM:
for each el with class attr:
htmlClasses.addAll(el.className.split(/\s+/).filter(Boolean))
zombies = cssClasses - htmlClasses
flag({ type: 'zombie', classes: zombies, cssFiles: [...] })
Challenges & Mitigations
| Challenge | Mitigation |
|---|
| Dynamic Classes (JS-added) | --runtime mode with Puppeteer snapshot (opt-in, slow). |
| Preprocessors | PostCSS plugins for Sass/Nested. |
| Minified CSS | Sourcemaps + --minify-tolerant (group issues). |
| Vendor Prefixes | Normalize with clean-css parser. |
| Performance (large sites) | Worker threads, cache parsed ASTs. |
| False Positives | Config file (.css-discontinuityrc.json): { ignore: ['.no-use'] }. |
Configuration
.css-discontinuityrc.json:
{
"include": ["src/**/*.scss", "dist/**/*.html"],
"severity": { "zombie": "error", "unused": "warn" },
"tolerant": true,
"tailwind": true
}
Metrics & Extensibility
- Stats: Total issues, bundle size savings (est. zombie removal).
- Plugins:
api.registerDetector('custom', fn(ast, html)).
- CI Integration: Zero-exit on warnings, GitHub Action ready.
- Future: VSCode extension, webpack plugin.
Development Roadmap
- MVP: Core detectors (1 week).
- Tests: Jest snapshots on 100+ CSS samples (e.g., from CSS-Tricks).
- Beta: Tailwind/CSS Modules support.
- v1.0: Release to npm.
This plan provides a robust, scalable foundation. Prototype code snippets available on request!