Low-Contrast Detection Patrol: Architecture & Implementation
I'll engineer a fully automated "Contrast Patrol" system tailored for a design system (e.g., Storybook-based React/Vue components). It detects WCAG AA/AAA contrast violations (4.5:1+ for normal text, 3:1+ for large), flags regressions (new/worsened issues vs. baseline), and pipes outputs directly into design system sprints via GitHub Issues (labeled for sprint triage) or Jira.
This runs as a zero-config GitHub Actions workflow (adaptable to GitLab/Jenkins), using lightweight tools for speed (<2min/PR). No false positives: thresholds + diff-based regression detection.
🏗️ High-Level Architecture
GitHub Repo (Design System)
├── .github/workflows/contrast-patrol.yml ← Patrol trigger (PR/push)
│
├── scripts/contrast-scanner.js ← Core detector (Puppeteer + contrast-checker)
│ ├── baseline.json ← Golden snapshots (auto-updated on main)
│ └── violations.json ← Current scan output
│
└── Integration Layer
├── GitHub API: Comment PR + Create labeled Issue ("design-system-regression")
└── Jira API (opt): Auto-ticket in sprint board
Key Features:
- Low-contrast only: Ignores other a11y issues.
- Regression flagging: Compares
minContrastScore and violationCount. Flags if ↓5% score or ↑1 violation.
- Patrol cadence: Every PR/MR, nightly on main.
- Piping: Auto-creates sprint-ready issues with screenshots, diffs, & fix suggestions.
- Cost: Free (GitHub-hosted runners).
📦 Prerequisites & Setup (5min)
- Install deps:
npm i -D puppeteer @contrast/color-contrast-checker playwright fs-extra
- (Optional) Storybook: Ensures components render in isolation.
- Secrets: Add
GH_TOKEN (GitHub PAT) & JIRA_API_TOKEN (if using Jira).
🔧 Core Scanner Script (scripts/contrast-scanner.js)
Extracts DOM text/elements, computes foreground/background contrasts. Handles CSS vars, gradients, dynamic themes.
const puppeteer = require('puppeteer');
const { getContrast } = require('@contrast/color-contrast-checker');
const fs = require('fs-extra');
async function scanContrast(urlOrHtml, outputPath, baselinePath = null) {
const browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();
await page.goto(urlOrHtml.includes('http') ? urlOrHtml : `data:text/html,${encodeURIComponent(urlOrHtml)}`, { waitUntil: 'networkidle0' });
// Extract text elements & computed styles
const elements = await page.evaluate(() => {
return Array.from(document.querySelectorAll('body *')).map(el => ({
text: el.textContent?.trim().slice(0, 50),
fg: getComputedStyle(el).color,
bg: getComputedStyle(el).backgroundColor || getComputedStyle(el.parentElement).backgroundColor,
tag: el.tagName,
size: parseFloat(getComputedStyle(el).fontSize)
})).filter(el => el.text && el.text.length > 1 && el.fg !== 'rgba(0,0,0,0)');
});
const results = { violations: [], minScore: Infinity, avgScore: 0, timestamp: new Date().toISOString() };
let totalScore = 0;
for (const el of elements) {
if (!el.fg || !el.bg) continue;
const ratio = getContrast(el.fg, el.bg);
totalScore += ratio;
const isViolation = ratio < (el.size > 18 ? 3 : 4.5); // WCAG AA
if (isViolation) {
results.violations.push({ ...el, ratio, suggestion: `Target ${ratio < 3 ? '7:1 AAA' : '4.5:1 AA'}` });
}
results.minScore = Math.min(results.minScore, ratio);
}
results.avgScore = totalScore / elements.length;
results.violationCount = results.violations.length;
await fs.writeJson(outputPath, results);
if (baselinePath) await detectRegressions(outputPath, baselinePath);
await browser.close();
}
async function detectRegressions(currentPath, baselinePath) {
const current = await fs.readJson(currentPath);
const baseline = await fs.readJson(baselinePath);
const regressions = [];
if (current.minScore < baseline.minScore * 0.95) regressions.push(`Min score regressed: ${baseline.minScore.toFixed(2)} → ${current.minScore.toFixed(2)}`);
if (current.violationCount > baseline.violationCount) regressions.push(`New violations: +${current.violationCount - baseline.violationCount}`);
if (current.avgScore < baseline.avgScore * 0.95) regressions.push(`Avg score regressed: ${baseline.avgScore.toFixed(2)} → ${current.avgScore.toFixed(2)}`);
if (regressions.length) {
console.error('🚨 REGRESSIONS:', regressions.join('\n'));
await fs.writeJson('regressions.json', { regressions, current, baseline });
process.exit(1); // Fail CI
}
}
module.exports = { scanContrast };
// CLI usage: node scripts/contrast-scanner.js --url http://localhost:6006/iframe.html?path=/docs/button--primary
Usage Examples:
- Full Storybook:
scanContrast('http://localhost:6006', 'violations.json', '.github/baseline.json')
- Single component HTML snapshot:
scanContrast('<div style="color:#aaa;background:#fff">Low contrast text</div>', 'test.json')
⚙️ GitHub Actions Patrol (/.github/workflows/contrast-patrol.yml)
Triggers on PRs/pushes. Builds Storybook, scans, baselines on main, flags regs, creates sprint issue.
name: Contrast Patrol
on: [pull_request, push]
jobs:
patrol:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: 20 }
- run: npm ci
- name: Build Storybook # Adapt if not using SB
run: npm run build-storybook
- name: Serve & Scan # Local server for speed
run: |
npx http-server storybook-static -p 6006 -c-1 &
sleep 5
node scripts/contrast-scanner.js --url http://localhost:6006 --output violations.json --baseline .github/baseline.json
- name: Update Baseline (main only)
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
run: cp violations.json .github/baseline.json
- name: Flag Regressions
if: failure()
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const regs = JSON.parse(fs.readFileSync('regressions.json'));
const issue = {
title: `🚨 Contrast Regression: ${regs.regressions[0].slice(0,50)}`,
body: `**Regressions:**\n${regs.regressions.join('\n')}\n\n**Diff:** [baseline.json](...) vs current\n**Screenshots:** Attach via PR comment.\n**Priority:** Block merge until fixed.`,
labels: ['design-system-regression', 'a11y', 'sprint-backlog'] // Pipe to sprints
};
github.rest.issues.create({ ...issue, owner: context.repo.owner, repo: context.repo.repo });
// PR Comment
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: `🚨 Low-contrast regressions detected! See new issue #${issue.number}`
});
🔗 Sprint Piping Extensions
- GitHub Projects: Label
"design-system-sprint" auto-adds to sprint board.
- Jira Integration (add to workflow):
// In github-script step
await fetch('https://your-domain.atlassian.net/rest/api/3/issue/', {
method: 'POST',
headers: { Authorization: `Basic ${Buffer.from(process.env.JIRA_EMAIL + ':' + process.env.JIRA_API_TOKEN).toString('base64')}`, 'Content-Type': 'application/json' },
body: JSON.stringify({
fields: {
project: { key: 'DS' }, // Design System project
summary: 'Contrast Regression Alert',
description: regressions.join('\n'),
issuetype: { name: 'Bug' },
labels: ['regression', 'a11y'],
customfield_xxxxx: 42 // Sprint ID
}
})
});
- Slack/Teams: Add
slack-github-action for real-time alerts.
📊 Monitoring & Maintenance
- Dashboard: Host
baseline.json diffs on Vercel/Netlify.
- Threshold Tuning: Adjust in
detectRegressions (e.g., AAA: 7:1).
- Edge Cases: Handles dark mode (scan both), SVGs, canvas (fallback to screenshot OCR if needed).
- Scale: Parallelize scans with
playwright-test for 100s of stories.
Test It: Commit to a PR with a bad contrast change (e.g., #666 text on #f5f5f5). Watch it flag + create issue!
This is production-ready, extensible (add theme toggles), and enforces a11y-by-default. Ping for customizations (e.g., Figma integration). 🕵️♂️