We are to design an automated accessibility regression pipeline that uses computer vision for screenshot diffing, heuristic validation, and includes human review loops and backlog integration.
Key Components:
- Automated Screenshot Capture: Capture screenshots of web pages (or app screens) in a consistent manner (same viewport, same state). Possibly using tools like Puppeteer, Selenium, or Playwright.
- Computer Vision-based Visual Diffing: Compare screenshots to detect visual changes that might indicate accessibility regressions (e.g., missing alt text causing layout shifts, color contrast changes). But note: visual diffing can be noisy. We need to focus on accessibility-related changes. We could use perceptual diffing (e.g., pixelmatch, Resemble.js) but also consider layout analysis, text recognition, etc.
- Heuristic Validation: Run automated accessibility testing tools (e.g., axe-core, Lighthouse, WAVE) on the pages to catch violations. These tools can be run headlessly.
- Human Review Loop: When the automated steps detect potential issues, they are queued for human review. Possibly with a UI that shows before/after screenshots, diff highlights, and accessibility violation details. Human reviewers can confirm, reject, or mark as false positive.
- Backlog Integration: Issues confirmed by humans (or automatically if high confidence) are automatically created in a project management tool (e.g., Jira, GitHub Issues, Trello). The issue should include context: page URL, step to reproduce, screenshots, diff, accessibility violation details, and maybe severity.
Pipeline Flow:
- Trigger: On code change (CI/CD pipeline) or periodically.
- Setup: Deploy the new version to a test environment. Also have a baseline (previous version) to compare against.
- Capture:
a. For each page (or a set of critical pages) in the test environment, capture a screenshot of the new version.
b. Also capture screenshots of the baseline version (or compare with stored baseline from previous run).
- Visual Diff:
a. Compare new and baseline screenshots. Highlight differences (e.g., using pixelmatch and generating diff image).
b. Optionally, use computer vision to analyze layout: detect elements (like buttons, images, text blocks) and compare positions, sizes, and content? Could be complex. Maybe start with simple pixel diff and then filter diffs that are likely accessibility related (e.g., changes in areas that are known to be interactive or contain text). Alternatively, we can run the accessibility tools on both versions and then visually highlight the elements that changed and have accessibility issues.
- Heuristic Validation: Run accessibility scanner on the new version (and possibly baseline) and collect violations.
- Combine Results: Identify changes that are both visually significant and have accessibility violations. Or simply collect all accessibility violations and also note any visual changes that might indicate a regression (like a missing image alt might change layout? Actually missing alt might not change layout if alt text is not displayed, but maybe the image is missing entirely). So we might need to correlate: if an element with an accessibility violation has changed in appearance (size, position, color) compared to baseline, that's a regression.
- Human Review:
a. Create a report that lists potential regressions: for each, show the page, the diff, the violation, and maybe a description.
b. Send to a review queue (could be a simple web app or integrate with a review tool). Human reviewers go through and decide.
- Backlog Integration: For issues confirmed by human, create a ticket. For issues that are new (no baseline) but have accessibility violations, we might also create tickets? That's more for new issues, but regression pipeline is about changes. So we focus on changes from baseline.
- Baseline Update: After human review, update the baseline for the next run (only for issues that are not regressions? Actually baseline should be updated with the new version's screenshots for pages that have changed but are acceptable? Typically, after a release, the new version becomes the baseline. So we might update baseline after successful human review? Or we update baseline periodically. But for regression, we want to compare with the version that was accepted as baseline. So we need to manage baselines: maybe store baselines per version or per release. Simpler: after each successful build, we update the baseline to that build's screenshots. Then next build compares against that. But if we want to catch regressions relative to a fixed baseline (like production), then we keep production baseline. So we need to decide.
Let's design a pipeline that:
- Compares current build (staging) against production baseline (or last approved build).
- When we deploy a new version to production, we update the baseline to that version.
Implementation Outline:
Step 1: Capture Baselines
- We have a command
capture-baseline that takes a list of URLs and captures screenshots (full page or viewport). It stores them in a baseline directory with a version tag (e.g., production-latest). Also store metadata (URL, timestamp, viewport size, user agent, etc.)
Step 2: Run Regression Check
- For a given build (e.g., pull request, staging), we run
check-regression which:
a. Captures screenshots for the same set of URLs (or a subset) from the build environment.
b. For each URL, compare new screenshot with baseline screenshot (from the baseline directory, selected by config, e.g., production).
c. Compute visual diff (pixel diff) and generate a diff image with highlighted changes.
d. Run accessibility scanner on the new page (and optionally baseline) and collect violations.
e. Correlate: For each accessibility violation, check if the element's bounding box (if available from the scanner) overlaps with the visual diff region. Or simply note that the page has visual changes and accessibility violations. Maybe we want to flag any page that has both visual changes and new accessibility violations? Or we can do: if a violation is on an element that has changed (visually) compared to baseline, that's a regression. But we need to know which element changed. That's more complex: we could use a visual element detection (like using a DOM-based approach: get computed styles and positions for elements from both versions? That's not computer vision but DOM comparison). Actually, we have the page source from both? Could use a tool like Puppeteer to extract accessibility tree and computed styles. But if we want pure computer vision, we could use object detection to find UI elements and compare. That's heavy. Alternatively, we can use the accessibility scanner's output to get the element's position (if the scanner provides bounding boxes). Many scanners (axe) can provide the node info including CSS selector and sometimes location. But location might be from the DOM at the time of scan. We could compare the location of the element in the new page vs baseline by running the scanner on both and comparing? That would be easier than pure CV. So we could do:
- Run accessibility scanner on new page, get list of violations with element selectors and bounding boxes.
- Run scanner on baseline page as well? But the baseline may have different violations. We want to detect new violations or changes in existing ones. So we need to compare baseline violations? That's more complex. Maybe we just run scanner on new page and then check if the element corresponding to the violation has changed visually compared to baseline. How to know if it changed? We can get the element's computed style (like size, position, color) from the new page and from baseline page (by running the same script on baseline). Then compare. That's not computer vision but DOM-based. But the requirement says "using computer vision: screenshot diffing". So we must incorporate computer vision. So we could use the visual diff to see if the region of the element has changed. We can get the element's bounding box from the new page (from scanner) and then look at the diff image: if the diff in that region is above a threshold, then it changed. That's a way to combine.
Steps for each URL:
- New screenshot:
new.png
- Baseline screenshot:
baseline.png
- Diff image:
diff.png (highlighting pixel differences)
- Run accessibility scanner on new page, get violations: each violation has:
element (selector), bbox (x, y, width, height), description, help, impact, etc.
- For each violation, extract the region from the diff image corresponding to the bbox. Compute the percentage of diff pixels in that region. If above threshold, then the element's visual appearance changed. Then flag as potential regression.
- Also, we might consider violations that are in areas with no visual change but are new? That might still be a regression (e.g., a new alt text missing on an image that looks the same). But visually it might not change. So we might also flag new violations regardless of visual change? But then it's not a regression in terms of visual change, but still an accessibility issue. The pipeline is for regression, so we want changes that introduced new issues or made existing ones worse. So we need to compare with baseline violations. So we need to store baseline violations as well. That means we need to run scanner on baseline and store results. Then for each URL, we have baseline violations and new violations. Then we can compute:
- New violations (not present in baseline)
- Fixed violations (present in baseline but not in new)
- Changed violations: same element (by selector?) but with different impact or description? Or maybe the same rule but different element? That's tricky.
But we could also use the visual change as a signal: if an element that had a violation in baseline has changed visually, that might be a regression even if the violation is still there? Actually, if the violation persists, it's not a regression (it was already there). Regression means a previously accessible thing became inaccessible. So we care about new violations. But also, if a violation was previously fixed and now reappears, that's a regression. So we need to track violations over time. So we need a way to identify the same violation across builds. Possibly using the element's selector and the rule ID. However, selectors can change. Maybe we can use a fingerprint: hash of the element's text content? Not reliable. Better: we store baseline violations with their element's CSS path and maybe some attributes. Then for new violations, we try to match with baseline by comparing the element's position and size? That could be done with visual diff: if the element's location is similar, it might be the same element. But that's complex.
Simpler approach: For regression, we focus on visual changes and new accessibility violations. We can define: a regression is either:
- A new accessibility violation (not present in baseline) that appears on a page that has visual changes (or even if page didn't change, but new violation is still a regression? Actually, if the page didn't change visually, how could a new violation appear? Unless the accessibility scanner updated or the DOM changed but visuals same? Possibly if we added an image without alt but the image is hidden? That might not be a regression because it wasn't accessible before? Actually, if we added an element that violates accessibility, that's a new issue. But visually it might not change if it's hidden or identical. So we might want to catch that too. So we should not rely solely on visual change.
Therefore, we need a comprehensive approach:
- Run accessibility scanner on baseline and new.
- Compute the set of violations for each URL. Compare to find new violations (present in new but not in baseline). Also, if a violation existed in baseline but is fixed in new, that's improvement.
- For new violations, we want to flag them for review if they are likely regressions. But we also want to reduce noise: if the page didn't change at all (visually identical) and we get a new violation, maybe it's a false positive from the scanner update. So we can check if the page had any visual change. If the page is visually identical, we might still get new violations due to scanner updates. So we need to consider that.
Alternatively, we can use the visual diff to identify changed elements (regions with differences). Then we can focus on accessibility violations that are in changed regions. But we also need to consider that a change might cause a violation elsewhere (e.g., a layout shift that affects an element's contrast). So it's not trivial.
Given complexity, we might start with a simpler pipeline:
- Visual diff: detect any visual change on the page. If there is visual change, then run accessibility scanner and report all violations (even if they are not new). But that would include existing violations. That's not good. We want regressions, so we need to compare with baseline violations.
So we need to store baseline violations. Then for a new build:
- For each URL:
- Capture screenshots.
- Compute visual diff (just for information, maybe not used for filtering).
- Run accessibility scanner on new page.
- Load baseline violations for that URL (from a previous run, maybe stored in a database or file).
- Compare: identify new violations (by rule ID and element fingerprint).
- If there are new violations, create a report.
- Optionally, if the visual diff is large but no new violations, maybe we still want to review? Possibly not, since we're focused on accessibility.
But how to fingerprint an element? We could use the element's CSS selector path (like #main > div.content > p). But if the DOM structure changes slightly, the selector may change. We could use a combination: the rule ID and the element's text content? Not reliable if text changes. We could use the element's computed style? That might change due to design changes. Hmm.
Alternatively, we could store the element's bounding box from the baseline (x, y, width, height). Then for a new violation, we can see if there is a baseline violation with similar bounding box (within tolerance). That would be robust to CSS selector changes. But bounding box might change if layout shifts. That's exactly what we want to detect: if an element that was accessible becomes inaccessible due to layout change, its bounding box may change. But we want to know if it's the same element. So we could match by proximity? Not perfect.
Maybe we can avoid element matching and instead just report all new violations. The human reviewer will decide if it's a regression. The pipeline's job is to surface potential regressions. So we can simply report all new violations (compared to baseline) as potential regressions. But we need to compute what is new. For that, we need to match violations across builds. A common approach: for each violation, generate a "fingerprint" that includes:
- ruleId
- the element's selector (if available)
- maybe the element's text (truncated) or attributes.
But if the selector changes, it's considered a different element, so the violation would be new even if it's the same element. That could be a false positive. But that's acceptable? If we refactor HTML and the element's selector changes, but the accessibility issue remains, it's not a regression; it's the same issue. But we want to detect regressions, so it's okay to report it as new? Actually, if the issue existed in baseline and stays, it's not a regression. But if we changed the selector, our matching might think it's new, so we'd report it incorrectly. That would create noise. So we need a robust matching.
Maybe we can use the element's position and size as a fallback. But what if the design changes and the element moves? Then it's a new issue? Actually, if the element moves but still has the same violation, it's still the same issue, but location changed. So we might want to consider it as existing. So we need to match even if position changes. That's hard.
Given the complexity, perhaps we rely on the accessibility scanner's ability to provide a consistent "node" reference? Axe-core, when run on the same page, might give different node references each time. Not helpful.
Another idea: Instead of matching elements, we can compare the total set of violations by rule. But that doesn't tell which element changed. For regression, we want to know if a new violation of a certain rule appeared. If we already had a violation for that rule on that page, it's not new? But it could be a different element. But if it's the same rule, it might still be a regression if we introduced a new element with that issue. So we need to know if it's a new instance.
Perhaps we can use a heuristic: if the number of violations for a rule increases, we report the new ones. But we don't know which are new.
Given the challenges, maybe we start with a simpler approach: just run the accessibility scanner on the new build and compare the total count of violations per page with the baseline. If the count increased, we flag the page for review and provide the list of all violations (so human can see what's new). That's less precise but easier. But we want to pinpoint the exact violation that is new.
Alternatively, we could use the visual diff to identify changed elements and then check if those elements have accessibility violations. That would catch regressions where a change introduced a violation on an element that changed. But it would miss new violations on unchanged elements (like adding a new element that is invisible but has accessibility issues). But maybe those are less common.
Given the requirement of "computer vision: screenshot diffing", we should emphasize the visual diff. So we could do:
- Perform visual diff to get a map of changed pixels.
- Use an object detection model (like YOLO or a custom model) to detect common UI elements (buttons, images, text blocks, etc.) in both screenshots? That would be heavy.
- Or we can use the accessibility scanner's output to get the bounding boxes of elements that have violations. Then check if those bounding boxes intersect with changed regions. If yes, then it's likely a regression because the element's appearance changed and it has a violation. But if the element's appearance changed because we fixed it, then the violation might be fixed? Actually, if we fix the violation, the element might change (e.g., increased contrast). So the violation would be gone. So we are only looking at new violations. So we need new violations and then check if their element changed. But if the element changed and now has a violation, that's a regression. But if the element changed but no violation, that's fine.
So the combination: new violations + element changed visually = high confidence regression.
But we also want to catch new violations on elements that didn't change visually? Possibly if the violation is due to something that doesn't affect visuals, like missing alt text on an image that is decorative? Actually, missing alt on a meaningful image might not change visuals if the alt text is not displayed. So visually it's the same. That would be a regression that our method might miss. But maybe we can still flag new violations regardless, but with lower priority. We could have two categories:
- High: new violation on a changed element.
- Medium: new violation on an unchanged element (maybe due to scanner update or real issue but not visually impacting).
But we need to decide.
Given the complexity, I'll propose a pipeline that:
-
Baseline Management:
- Store for each URL: baseline screenshot, baseline accessibility violations (JSON), timestamp, and metadata (viewport, etc.)
- The baseline is updated after a successful release (or after human review approves the new version as baseline).
-
Regression Check:
For each URL in the test set:
a. Capture new screenshot.
b. Compute visual diff (pixel diff) and generate a diff image. Also compute a diff score (percentage of changed pixels). Also generate a diff mask (binary image).
c. Run accessibility scanner on the new page. Get list of violations with element selectors and bounding boxes (if available).
d. Load baseline violations for the same URL.
e. Identify new violations by comparing the two sets. We need a matching algorithm. We can try:
- For each new violation, see if there is a baseline violation with the same ruleId and similar element selector (maybe using a fuzzy match on the selector path, ignoring dynamic IDs). Or use the element's text content? But text might change.
- Alternatively, we can match by the element's position (center) and size? But these can change due to design updates.
- Perhaps we can use a combination: try to match by ruleId and by approximate position (if within 10% of viewport? But positions can shift). This is tricky.
Given the difficulty, maybe we skip matching and simply report all new violations as potential regressions, but we also check if the page has visual changes. If the page has no visual changes, we might suppress new violations (assuming they are false positives from scanner updates). But if the page has visual changes, we report all new violations (even if the element itself didn't change, but the page changed, maybe the violation is related? Not necessarily). Hmm.
f. For each new violation, we also check if the element's bounding box overlaps with the diff mask (i.e., if there are visual changes in that region). Compute the overlap ratio. If above threshold, mark as "visually impacted".
g. Also, we could check if the element itself changed by comparing the element's appearance in the baseline screenshot vs new. But that would require cropping the element from both screenshots and comparing. That's possible but computationally heavier. We could do that for violations that are not overlapping with diff? Actually, if the diff mask shows changes in that region, it's already impacted. But if the element didn't change but surrounding changed, it might still be considered changed? Not necessarily.
h. Collect all new violations, with details: rule, element, impact, and whether visually impacted.
-
Human Review:
- Create a report (web page or PDF) that lists:
- URL
- Diff image with changes highlighted.
- List of new violations, each with:
- Description
- Impact
- Element selector (or description)
Implementation Considerations:
-
Tools:
-
Screenshot capture: Puppeteer (headless Chrome) or Playwright. They can capture full page or viewport. Need to ensure consistent settings (device scale factor, viewport, user agent, etc.). Also handle authentication if needed.
-
Visual diff: pixelmatch (Node.js) or Resemble.js (browser). We can generate diff image and compute diff metrics.
-
Accessibility scanner: axe-core (via puppeteer-axe or axe-cli), or Google Lighthouse (which includes axe). We can run these headlessly.
-
For element bounding boxes: axe-core provides the node's target and sometimes rect information? Actually, axe-core's getNode provides the element and we can get its bounding box via element.getBoundingClientRect(). So we can get the coordinates relative to the viewport. But note: screenshots might be full page, so we need to account for scroll. We can capture full page screenshots, so the bbox should be in full page coordinates? If we use fullPage: true in Puppeteer, the screenshot includes the entire page. But the element's bounding rect is relative to the viewport; we need to adjust by the scroll position. Actually, if we capture full page, we can get the element's position relative to the document (using element.offsetTop etc.) but easier: when we capture full page, we can also capture the element's bounding rect in document coordinates (by adding scroll offset). Alternatively, we can capture only the viewport and then the bbox is within that. But then if the element is below the fold, we won't see it. So we need to decide: either capture full page or scroll to each element. Better to capture full page to have all elements visible. So we'll capture full page screenshot. Then for each element, we need its bounding box in the full page coordinate system. We can get that by running a script in the page that returns element.getBoundingClientRect() plus the current scroll position? Actually, getBoundingClientRect() returns coordinates relative to the viewport. To get document coordinates, we add window.scrollX and window.scrollY. But if we capture full page, we typically set the page height to the full content height and then take a screenshot without scrolling. So the screenshot's coordinate system is document coordinates (0,0 at top-left of document). So we need the element's position relative to document. We can compute: rect = element.getBoundingClientRect(); docX = rect.left + window.scrollX; docY = rect.top + window.scrollY;. That gives the top-left of the element in document coordinates. That should align with the full page screenshot. So we can do that.
-
We also need to run the scanner on the baseline page to get its violations. But we might not have a live baseline page; we might have stored screenshots only. To get baseline violations, we either need to have stored the violation data from the previous run, or we need to re-run the scanner on the baseline version (by running against the baseline deployment). Since we have the baseline version deployed (maybe in a separate environment), we can access it via URL. So we can store baseline violations by running the scanner on the baseline URL and saving the results. That's better than trying to infer from screenshots. So we need baseline URLs (like production URL) for each page. So we treat baseline as a live site (or a set of URLs). That makes sense: we compare current build (staging) against production (or a baseline environment). So we don't need to store baseline screenshots? Actually, we do for visual diff. So we capture baseline screenshots from the baseline environment and store them. And we also store baseline violations (or we can re-run scanner on baseline each time, but that might be slow if baseline is large; better to store). So we store both baseline screenshots and baseline violations.
Given the requirement: "human review loops", so automation should not auto-fail without human; it should present for review.
Now, let's think about the matching algorithm for violations. This is a known problem. There are tools like "axe-reports" that compare runs. They often use a "fingerprint" based on the element's selector and the rule ID. But to handle selector changes, they might use a "path" that is more robust (like using data-axxess attributes?). Not sure.
A simple approach: For each violation in baseline, we store:
- ruleId
- selector (the CSS selector of the element, as reported by axe)
- page URL
- maybe the element's text (truncated) or some attributes (like alt text, aria-label, etc.)
For new violations, we have similar. Then we match:
- If ruleId matches and selector is exactly the same, it's the same element (so not new).
- If ruleId matches but selector is different, we could try to see if the element in baseline with that ruleId has a selector that is similar (e.g., same length, same number of segments). But that's heuristic.
- Alternatively, we could match by the element's position: compute center point (x,y) of element relative to page. For baseline, store that. For new, compute. Then if the distance between centers is small (e.g., < 50px) and the ruleId matches, consider same element. But if layout shifts, positions may change. We could allow some tolerance, but if layout changes drastically, it might be considered a different element? Actually, if the element moves, it's still the same element. So we need to allow large movement. So position matching might not be robust.
Another idea: Use the element's computed style signature? Not good.
Perhaps we can avoid matching entirely and simply report all violations on the page, but highlight which ones are new by comparing with the baseline list using a combination of ruleId and element's "fingerprint" computed from its text content and some attributes. But text might change for legitimate reasons (like copy updates). So if the text changes, we might consider it a new element even if it's the same spot. That might be okay because if the text changed, the element is semantically different? Not necessarily. But for accessibility, the same element might have different text, but the issue might be the same (e.g., color contrast). If the text changed but the color remains, the contrast issue might still be there. It would be considered a new violation if we can't match. That would be noise.
Given the trade-offs, we might accept some noise and let human reviewers filter. The goal is to catch regressions, not to perfectly classify. So we can take a simple approach: treat any violation that is not an exact match on ruleId and selector as new. This will flag as new if the selector changed (which might be due to refactoring) even if the element is the same. That's acceptable because it will be reviewed; if it's not a real regression, the human will mark it as false positive. The cost is extra review work. But that's okay.
However, we also need to consider that the baseline violations list might be large. So we need an efficient way to compare. We can create a set of keys: ${ruleId}:${selector} for each baseline violation. For new violations, compute the key and check if it exists in the baseline set. If not, it's new. That's simple. But if the selector changed, it's new. That's fine.
But what about the case where the baseline had a violation with selector .nav > a and the new has .nav a? Those are different selectors but may refer to the same element. Our simple key would treat as new. That's a false positive. But we could try to normalize selectors: remove ids? Not easy. Maybe we can use the element's XPath? That might be more stable? Not really. Another idea: use the element's position on the page as a fallback: if the new violation's element's bounding box is very close to one of the baseline violations' bounding boxes (within, say, 20px), and ruleId matches, consider it the same. That could handle selector changes. So we could do:
- First, try exact match on ruleId+selector.
- If not found, try to match by ruleId and bounding box proximity.
But we need baseline bboxes. So we need to store baseline bboxes as well. We can store the bbox from the baseline run. Then for new violation, we have its bbox. We check if there is a baseline violation with same ruleId and bbox centers within, say, 50px, and size similar? That could work.
We'll implement matching in two stages:
Stage 1: exact key match.
Stage 2: if not matched, for each baseline violation with same ruleId, compute Euclidean distance between centers of bboxes. If distance < threshold (e.g., 50), consider match. Also consider if the element is likely the same (maybe check if the element's text is similar? Could be optional). If found, then it's not new.
If still not matched, it's new.
This should reduce false positives due to selector changes while still catching new elements.
We also need to handle multiple violations of the same rule on the same page (e.g., multiple missing alt texts). They might be many. The proximity matching might incorrectly match a new violation to an old one if they are close. But we can also consider the size of the element. If both bbox width and height are similar (within 20%), it's more likely the same element. We can incorporate that.
We'll implement a matching function.
-
Visual diff and element change detection: For each new violation (that we've determined is new), we already have its bbox in the new page. We can compute the overlap with the diff mask:
- The diff mask is a binary image where changed pixels are 1 (or 255). We can crop the region of the bbox from the diff mask and compute the proportion of changed pixels. If above a threshold (say 5% of the region area), then we consider the element's visual appearance changed. This is a proxy for "the element itself changed" because the diff includes the element's pixels. But note: if the element's position changed, the diff might show the element in a new location and the old location as change? Actually, visual diff between two full screenshots will show differences everywhere if elements moved. The region of the element in the new screenshot will show the element, but if the element moved, the old area will show background as change, and the new area will show the element as change compared to baseline (since baseline had something else). So the bbox in the new page might cover the new position; if the element moved, that region might have a lot of change because it's new content. But also the old region (where it used to be) will have change. So the element's new bbox will likely have high diff if it moved or changed style. So this is fine.
We'll compute:
diffMask = global diff mask (same size as screenshot).
For element bbox (x, y, w, h), extract region from diffMask.
changedPixels = count of non-zero pixels in region.
totalPixels = w * h.
ratio = changedPixels / totalPixels.
If ratio > threshold (e.g., 0.05), mark as visually changed.
This is a heuristic.
-
Reporting: For each new violation, we include:
- Rule ID and description
- Impact (minor, moderate, serious, critical)
- Element selector (from new scan)
- Element bbox
- Visually changed? (yes/no) and ratio
- Diff image (maybe with bbox highlighted)
- Maybe a cropped image of the element from new page and baseline? We can extract from the screenshots using the bbox. That would be helpful.
We can generate an HTML report with these details.
-
Human Review Interface: We need a way for reviewers to see the report and mark each item. We could generate a static HTML with checkboxes or a simple server that stores state. But for simplicity, we could have the pipeline generate a markdown file or HTML that is uploaded as an artifact, and then a human manually reviews and creates tickets. But the requirement says "human review loops", implying an integrated loop. We could build a small web service that stores reports in a DB and allows reviewers to approve/reject. Then after review, the pipeline (or a separate process) creates tickets for approved items.
Alternatively, we could integrate with a tool like Jira: create a draft issue for each potential regression, and have the reviewer triage. But that might spam Jira.
Now, let's outline the steps in more detail for a single URL.
Step-by-step for run-regression per URL:
-
Fetch new page screenshot:
- Use Puppeteer to go to target URL (targetEnv + path).
- Set viewport to a standard size (e.g., 1280x800) or as config.
- Wait for network idle or a specific condition.
- Capture full page screenshot as
new.png.
- Also, optionally capture viewport screenshot? Not needed.
- Run accessibility scanner (e.g.,
axe-core via puppeteer-axe) on the page, get violations. This returns a list of violation objects. For each violation, we can also get the element node and compute its bounding rect in document coordinates:
const rect = await page.evaluate(el => {
const r = el.getBoundingClientRect();
return {
x: r.left + window.scrollX,
y: r.top + window.scrollY,
width: r.width,
height: r.height
};
}, element);
- Store new violations as an array of objects:
{ ruleId, selector, bbox, impact, description, help, ... }.
-
Fetch baseline screenshot and violations:
- For the same URL, we have stored baseline data (maybe from a previous run). The baseline data should be stored locally (we might have a baseline capture step that populated it). So we load:
- baseline screenshot:
baseline.png
- baseline violations: array of same structure.
If baseline doesn't exist (first run), we might skip regression and just store as baseline? Or we need to create an initial baseline. Usually, you'd capture baseline first. So we assume baseline exists.
-
Visual diff:
- Load
new.png and baseline.png as images (using sharp or jimp).
- Use
pixelmatch to compute diff. Also generate a diff image where changed pixels are highlighted (e.g., red). We can produce a diff mask (binary: changed=1, unchanged=0). This mask can be used for region checks.
- Compute overall diff score (percentage of changed pixels). We might also store per-channel differences? Not needed.
-
Identify new violations:
- Create a set of keys for baseline violations:
Set of strings ${ruleId}|||${selector}. But note: the selector might be ambiguous if multiple elements? Axe gives a selector for the element. That should be unique enough? Possibly not, but okay.
- Also store a secondary index for matching by bbox: for baseline violations, store an array with ruleId and bbox.
Given the complexity, we'll propose a system with these components:
Components:
-
Baseline Manager (baseline.js):
capture: Given a base URL and a list of paths (or sitemap fetch), for each URL:
- Use Puppeteer to navigate, wait, capture full screenshot.
- Run axe-core, get violations with bboxes.
- Save screenshot to
baseline/screenshots/<url-hash>.png (or use URL path).
- Save violations to
baseline/violations/<url-hash>.json.
- Save metadata (viewport, timestamp).
set-baseline: After a release is approved, we run this to update the baseline with the new version's screenshots and violations. Actually, capture already does that. So maybe we just run capture for the new production version and overwrite baseline.
-
Regression Runner (regression.js):
- Command:
regression --target-base-url=<staging> --baseline-dir=./baseline --output=./reports/run-<timestamp> --config=config.json
- It reads a list of URLs to test (from config or from baseline list? We want to test same set as baseline? Probably yes, we test the same pages that have baseline. So we can read the list of baseline entries (from
baseline/violations/*.json or a manifest). For each baseline entry, get the path and construct target URL by replacing baseline base with target base.
- For each URL:
- Capture new screenshot and run axe.
- Load baseline screenshot and violations.
- Compute diff and new violations.
- For each new violation, compute visual impact.
- Generate element crops (from new and baseline screenshots).
- After all URLs, generate HTML report (with embedded images as data URIs? Might be large. Better to store images as separate files and reference them). The HTML report will list pages, show diff image, and list new violations with their crops.
- Write JSON report data as well.
- If any new violations, exit code 1 (fail).
-
Review UI (review-server):
- A simple Express server that serves the reports. It reads the reports directory, lists runs, and for each run, displays the HTML report. Also provides an API to record reviewer decisions (e.g., POST /api/decision with violation ID and decision). The violation ID could be generated (hash of URL+rule+selector+run). Store decisions in a JSON file or database.
- The UI could also show statistics.
- Alternatively, we could integrate with an existing review tool like GitHub PR reviews, but that's more complex.
Technologies:
- Node.js (for scripts using Puppeteer, pixelmatch, etc.)
- Python could be used but Puppeteer is Node. So Node is fine.
- For the review UI: React or simple server-side HTML. Could use Express with EJS templates.
- Storage: File-based for simplicity (reports as JSON/HTML). Use a directory per run. For review decisions, we could store a
decisions.json in the run directory.
Example Workflow:
- Initial baseline captured from production.
- A feature branch is deployed to staging.
- CI job runs
regression targeting staging, using the baseline from production.
- The job produces a report. If there are new violations, the job fails and posts a link to the report in the PR.
- A reviewer opens the report, sees potential regressions. For each, they can see diff and element crops, and mark as "Confirmed" or "False positive". They submit decisions.
- For confirmed ones, the reviewer clicks a button to "Create tickets". This calls an API that runs
create-tickets for those items, creating issues in the backlog.
- Developers fix the issues, push changes, and the cycle repeats until no new violations are found.
- Once the branch is approved and merged, and deployed to production, a final job runs
baseline capture against production to update the baseline to the new version.
Challenges and Refinements:
-
Dynamic content: Some pages have changing content (e.g., ads, news feeds). This could cause many visual diffs and false positives. We need a way to mask out dynamic regions. Could define ignore regions in config (by CSS selector or coordinates). Or we could use a technique to detect and mask dynamic areas: e.g., take multiple screenshots of baseline and compute stable background? That's heavy. Simpler: allow configuration to ignore certain selectors. For regression, we might only test static pages or specific templates. So we can have an allowlist of URLs and maybe ignore selectors for known dynamic parts.
-
Authentication: Some pages require login. We'll need to handle auth in Puppeteer (set cookies, use credentials). Could be configurable.
-
Performance: Running Puppeteer for many URLs is slow. We can parallelize with multiple browsers, but be careful with resources.
-
Visual diff sensitivity: Pixelmatch is sensitive to subpixel rendering, anti-aliasing. We might need to apply some blur or ignore minor differences. Pixelmatch has options like threshold, includeAntialiasing. We can tune.
-
Element cropping: When cropping an element from baseline and new, if the element moved, the crop from baseline using the new bbox might not contain the element (it might be empty). That's okay; we can show that there is a difference. But we also need to show the baseline element? Actually, to show the change, we might want to show the element as it appears in baseline and new. But if it moved, the baseline element is elsewhere. That's complex. Maybe we just show the new element's crop and indicate that it's new or changed. For visual impact, we already have the diff. So cropping might not be essential. We could instead show a zoomed diff region. Simpler: just show the diff image with the bbox outlined. That might be enough.
We could generate a version of the diff image with bounding boxes drawn (using sharp to draw rectangles). That would be helpful.
-
Heuristic validation: We already include accessibility scanner. That's the heuristic.
-
Backlog integration: We'll implement for one system (e.g., GitHub Issues) as example.
Implementation Plan (Code Structure):
project/
bin/
baseline.js # CLI for capturing baseline
regression.js # CLI for running regression check
create-tickets.js
lib/
capture.js # functions to capture screenshot and run axe
diff.js # functions to compute visual diff
match.js # violation matching logic
report.js # generate HTML and JSON report
storage.js # reading/writing baseline and reports
config.js # load config (baseline dir, URLs, thresholds, etc.)
slack.js # send notifications
tickets.js # create tickets for GitHub/Jira
server/
review-server.js # Express app to serve reports and record decisions
baseline/ # stored baseline data
screenshots/
example.com.png
violations/
example.com.json
manifest.json # list of URLs and metadata
reports/
run-20240101-1200/
report.html
data.json
diffs/
example.com-diff.png
decisions.json # after review
config.json # configuration (target base URL, baseline base URL, URLs list, thresholds, etc.)
Config Example:
{
"baseline": {
"baseUrl": "https://production.example.com",
"paths": ["/", "/about", "/contact", "/products"],
"viewport": { "width": 1280, "height": 800 },
"userAgent": "Mozilla/5.0 ..."
},
"target": {
"baseUrl": "https://staging.example.com"
},
"accessibility": {
"axeOptions": { "rules": {} } // custom config
},
"diff": {
"threshold": 0.1, // pixelmatch threshold
"visualImpactThreshold": 0.05
},
"matching": {
"distanceThreshold": 50,
"sizeSimilarity": 0.8
},
"notifications": {
"slackWebhook": "..."
},
"tickets": {
"github": {
"repo": "org/repo",
"token": "..."
}
}
}
Detailed Steps in regression.js:
-
Load config.
-
Read baseline manifest (list of URLs with local filenames).
-
For each URL:
a. Construct target URL.
b. capturePage(targetUrl) -> returns { screenshotBuffer, violationsArray }.
c. Load baseline screenshot from file, baseline violations from file.
d. Compute diff:
- Load both images into buffers (using sharp).
- Use pixelmatch with options. Get diff metrics and generate diff image (maybe with red pixels where changed). Save diff image to reports/run-.../diffs/<url>-diff.png.
- Also generate a binary mask (0/1) as a buffer or array for region checks. Could be an array of booleans same size as image. But we can also compute region diff by cropping the diff image and counting non-black? Actually, the diff image we generate is typically a grayscale or color diff. We can generate a mask: a new Image where changed pixels are white (255), unchanged black (0). Then we can use that to compute region changes.
e. Match violations:
- Build baselineSet = new Set of ruleId + '|' + selector.
- For each baseline violation, also keep an array for bbox matching: baselineViolationsByRuleId[ruleId] = array of { bbox, selector, maybe id }.
- For each new violation:
* exactKey = ruleId + '|' + selector
* if baselineSet has exactKey -> existing.
* else:
- look in baselineViolationsByRuleId[ruleId] (if any). For each, compute distance and size ratio. If match found (with thresholds), then existing. Note: we should also ensure we don't match multiple new to same baseline; we can track which baseline violations are already matched to avoid double assignment. But we just care if it's new; if it matches any baseline, it's not new. So we can break on first match.
* if no match, new.
f. For each new violation, compute visual impact:
- Get bbox (in document coordinates). The diff mask is the same size as the screenshot (full page). So we can extract the region from the mask. Since we have the mask as an array (e.g., Uint8Array of 0/255), we can compute indices. Or we can use sharp to extract a crop of the mask and then count non-zero pixels? That's heavy per element. Better: keep the mask as a 2D array or a Buffer with one channel. We can compute by iterating over the bbox region in the mask buffer. Since the mask is a buffer of widthheight bytes (assuming 8-bit), we can calculate index = y * width + x. For each pixel in the bbox, check if mask[index] > 0. Count.
- totalPixels = widthheight.
- ratio = changedCount / totalPixels.
- Store ratio.
g. Generate element crops:
- Use sharp to extract region from new screenshot and baseline screenshot using the bbox. But note: baseline screenshot might not have the element at that bbox if it moved. That's okay; we can still extract and it will show whatever was there. That could be interesting: show baseline region vs new region. But if the element moved, the baseline region might show background. That's actually good: it shows that something changed. So we can generate two crops: from baseline (at the same bbox coordinates) and from new. Then we can show side by side. That reveals if something new appeared there.
- Save these crops as small PNGs (maybe resize to max 200px width/height) and embed in report.
h. Also generate a diff image with bbox outlined: we can draw a rectangle on the diff image (using composite with a graphics layer). But that's extra. Could do later in report generation with CSS overlay? Simpler: just list the crops.
Review Server:
- Runs on an internal port.
- When started, it points to a reports directory (e.g.,
./reports).
- It lists runs (folders with
report.html). Clicking a run shows the HTML report (or we serve the generated HTML directly). But the generated HTML might have relative paths to images; we need to serve those as static files.
- Also, the server provides an endpoint to load and save decisions. For each run, we have
decisions.json. The UI loads the report data (from data.json) and decisions. It displays each violation with radio buttons for decision. On submit, it POSTs the decisions to /api/decisions/<run> and saves to file.
- Optionally, a button to "Create tickets" that calls another endpoint to trigger ticket creation for the confirmed items in that run.
Or we could skip the server and just have a static HTML that posts to a serverless function. But a simple server is okay.
Ticket Creation:
- The
create-tickets.js script reads reports/run-.../decisions.json and data.json, filters for items with decision "Confirmed", then for each, creates an issue via GitHub API.
- The issue body includes details: URL, rule, description, impact, selector, visual change, and possibly the diff image and element crops (as attachments or embedded as links). We can attach the diff image and crop images to the issue (if using GitHub API v3, we can upload images as assets? Actually, when creating an issue, we can include images in the body using data URIs, but that might be too large. Better to upload images to a storage and include links. Or we could attach them as comments? Simpler: include links to the report hosted on the review server, where the images are available. So the issue can link to the report page for that violation. So we need the report to be publicly accessible within the organization. That's fine.
Thus, the ticket will have a link to the report for context.
Baseline Update:
After a release, we run baseline.js capture with the production base URL. That will overwrite the baseline screenshots and violations for the set of URLs. This should be done only after we've verified that the new version has no outstanding accessibility regressions (i.e., after tickets are resolved and re-tested). So it's a manual step or automated after successful regression check on production.
We could also automate: after merging to main and deploying to production, run regression check against production. If it passes (no new violations), then automatically update baseline. But be careful: if there are new violations, we don't want to update baseline. So we can have a job that runs after production deployment, runs regression against production (comparing with current baseline, which is previous production). If no new violations, then run baseline capture against production to set new baseline. That would keep baseline always equal to production last known good. But if we accidentally deploy with regressions, we wouldn't update baseline, so the next staging compare would still use the old baseline and detect regressions. That's good.
So we can have a CI job for post-deploy to production:
- Run regression against production (targetUrl = production, baseline = current baseline which is previous production). If it fails, alert and don't update baseline. If it passes, then run
baseline capture against production to update baseline.
This ensures baseline is always the last production version that passed regression.
But note: the regression check might fail due to known violations that we accept? We might have an allowlist. So we need to incorporate allowlist into the regression check so that allowed violations don't count as new. So we need an allowlist config (list of ruleId+selector patterns to ignore). Then the regression check can filter out those violations before reporting. That way, we can have known issues that we are tracking but not blocking. The allowlist can be stored in the repo (config/accessibility-allowlist.json). Then the regression check loads it and ignores any violation that matches (ruleId and selector regex?). Then the new violations set is computed after filtering.
So the flow becomes more robust.
Summary of Pipeline:
- Capture Baseline: Run against production to establish golden screenshots and violations.
- Regression Check (on staging or PR):
- For each URL in baseline set, target same URL in staging.
- Capture screenshot and violations.
- Compare with baseline using diff and violation matching.
- Apply allowlist to ignore known issues.
- Report any new (unignored) violations as potential regressions.
- Generate report and fail if any.
- Human Review: Review report, confirm which are true regressions.
- Ticket Creation: Automatically create backlog items for confirmed regressions.
- Baseline Update: After a successful deployment to production (with no new violations), update baseline to production.
Additional Heuristic Validation:
The accessibility scanner itself is heuristic. We could also add custom checks, like checking for consistent navigation, etc., but not needed.
Now, let's write a high-level design document that describes this pipeline in an engineering form, including components, data flow, and implementation details.
We'll produce a response that is a comprehensive design, potentially with code snippets or pseudo-code.
We need to "Engineer an automated accessibility regression pipeline using computer vision: screenshot diffing, heuristic validation, human review loops, and backlog integration."
So we'll describe:
- Overview
- Components
- Baseline Capture
- Regression Check (including screenshot diffing, heuristic validation)
- Visual Diff and Element Change Detection
- Violation Matching Algorithm
- Report Generation
- Human Review Interface
- Backlog Integration
- Notifications
- Data Storage
- Configuration
- Example Workflow
- Potential Challenges and Mitigations
We'll include code examples for key parts (like matching algorithm, diff computation) in JavaScript (Node).
Let's craft the response.
Automated Accessibility Regression Pipeline Design
1. Overview
This pipeline detects accessibility regressions by comparing visual outputs and heuristic validation results between a baseline (e.g., production) and a target (e.g., staging). It uses computer vision (pixel-level diff) to identify visual changes, correlates those changes with accessibility violations, and feeds confirmed issues into a backlog via human review.
Key goals:
- Catch regressions caused by visual changes (e.g., missing alt text that alters layout, color contrast shifts).
- Reduce noise by correlating visual changes with accessibility violations.
- Involve human reviewers to confirm true regressions and avoid false positives.
- Integrate with existing ticketing systems (Jira, GitHub Issues) to track fixes.
2. System Components
2.1 Baseline Manager (baseline.js)
Captures a "golden" set of screenshots and accessibility violations for a given environment (typically production).
- Command:
node baseline.js --baseUrl=https://production.example.com --paths=/,/about,/contact --output=./baseline
- Process:
- For each URL, launch Puppeteer, wait for network idle, capture full-page screenshot.
- Run
axe-core to collect violations, including element bounding boxes (document coordinates).
- Store:
baseline/screenshots/<url-hash>.png
baseline/violations/<url-hash>.json
baseline/manifest.json (maps URLs to local files, metadata).
- Update baseline: Re-run after a successful release to make the new production the baseline.
2.2 Regression Runner (regression.js)
Core pipeline that compares the target environment (staging) against the baseline.
- Command:
node regression.js --targetBaseUrl=https://staging.example.com --baselineDir=./baseline --output=./reports/run-<timestamp> --config=config.json
- Workflow per URL:
- Capture target: Screenshot (
new.png) and accessibility violations (newViolations[]) with element bounding boxes.
- Load baseline:
baseline.png and baselineViolations[].
- Visual diff:
- Use
pixelmatch to compute diff between screenshots.
- Generate diff image (
diff.png) and binary mask (mask array where 1 = changed pixel).
- Compute overall diff score (percentage changed pixels).
- Match violations to identify new violations:
- Build a
Set of baseline keys: ${ruleId}|${selector}.
- For each new violation:
- If key exists → existing.
- Else, attempt bbox matching with baseline violations of same
ruleId:
- Compute distance between element centers.
- Check size similarity (width/height ratios ≥
sizeSimilarity threshold).
- If distance ≤
distanceThreshold and sizes similar → existing.
- Otherwise → new.
- Visual impact check (for new violations):
- Extract the region of the element’s bbox from the diff mask.
- Compute
changedPixelRatio = (changed pixels in bbox) / (bbox area).
- Mark
visuallyChanged = (ratio > visualImpactThreshold).
- Generate crops:
- Crop the element region from
baseline.png and new.png (using bbox). Resize to max 200×200 for report.
- Collect item for report:
{
"url": "https://...",
"ruleId": "image-alt",
"description": "Images must have alt attributes",
"impact": "critical",
"selector": "img.logo",
"bbox": {"x": 100, "y": 200, "width": 50, "height": 50},
"visuallyChanged": true,
"visualChangeRatio": 0.12,
"newCrop": "data:image/png;base64,...",
"baselineCrop": "data:image/png;base64,...",
"diffCropUrl": "diffs/url-diff.png"
}
2.3 Visual Diff & Element Change Detection
- Pixelmatch: Fast pixel-level comparison with configurable threshold to ignore anti-aliasing.
- Diff mask: Binary array used to quantify change within a bbox.
- Bbox overlap: Simple region check to determine if an element’s visual representation changed.
2.4 Violation Matching Algorithm
See Step 2.2.4 above. The two-stage matching (exact selector → bbox proximity) reduces false positives from DOM refactoring while catching moved elements.
2.5 Report Generator (report.js)
- Reads collected items and generates:
- HTML report: Grouped by URL, each showing:
- Full diff image with optional bbox overlay.
- Table of new violations with crops, impact, visual change flag.
- JSON data for programmatic consumption.
- Allowlist integration: Before reporting, filter out violations that match rules/selectors in
config.allowlist (e.g., known third‑party widget issues).
2.6 Human Review Loop (review-server)
- A lightweight Express server that:
- Serves static reports (HTML, images).
- Provides REST API to record decisions per violation.
- UI displays each new violation with controls: Confirmed, False positive, Needs investigation.
- Stores decisions in
reports/run-<timestamp>/decisions.json.
- Workflow:
- Regression job fails → notification (Slack/email) with link to review server.
- Reviewer examines diff and crops, makes a decision.
- For confirmed items, reviewer clicks Create tickets (triggers ticket creator).
2.7 Backlog Integration (create-tickets.js)
- Reads decisions for a run, filters items marked Confirmed.
- Uses provider‑specific API (GitHub, Jira) to create issues.
- Issue content:
- Title:
[A11y Regression] <ruleId> on <url>
- Body: Description, impact, bbox, visual change, links to diff image and report page.
- Labels:
accessibility, regression.
- Optionally attaches crop images or includes them as inline base64.
2.8 Notifications
2.9 Scheduler/CI Integration
- PR/merge to staging:
- Deploy to staging.
- Run
regression.js with --fail-on-violations.
- If exits non‑zero, post comment on PR with report link and fail the check.
- Post‑production deploy:
- Run
regression.js comparing production (target) vs current baseline (previous production).
- If no new violations, automatically update baseline:
node baseline.js --baseUrl=https://production.example.com --paths=... --output=./baseline.
- If violations exist, alert and do not update baseline.
3. Data Storage
baseline/
manifest.json { "urls": [ { "path": "/", "screenshot": "screensshots/abc.png", "violations": "violations/abc.json" } ] }
screenshots/
<hash>.png
violations/
<hash>.json
reports/
run-<timestamp>/
report.html
data.json
diffs/
<url>-diff.png
crops/
<url>-<ruleId>-new.png
<url>-<ruleId>-baseline.png
decisions.json
4. Configuration (config.json)
{
"baseline": {
"baseUrl": "https://production.example.com",
"paths": ["/", "/about", "/contact"],
"viewport": { "width": 1280, "height": 800 },
"userAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36..."
},
"target": {
"baseUrl": "https://staging.example.com"
},
"accessibility": {
"axeOptions": { "runOnly": { "type": "tag", "values": ["wcag2a", "wcag2aa"] } }
},
"diff": {
"pixelmatchThreshold": 0.1,
"visualImpactThreshold": 0.05,
"ignoreAntialiasing": true
},
"matching": {
"distanceThreshold": 50,
"sizeSimilarity": 0.8
},
"allowlist": [
{ "ruleId": "color-contrast", "selector": ".hero" }
],
"notifications": {
"slackWebhook": "https://hooks.slack.com/..."
},
"tickets": {
"github": {
"owner": "myorg",
"repo": "myrepo",
"token": "ghp_..."
}
}
}
5. Example Code Snippets
5.1 Violation Matching
function matchViolation(newViolation, baselineViolationsByRule) {
// Stage 1: exact selector match
const exactKey = `${newViolation.ruleId}|${newViolation.selector}`;
if (baselineViolationsByRule.exactSet.has(exactKey)) {
return { matched: true, method: 'exact' };
}
// Stage 2: bbox proximity
const candidates = baselineViolationsByRule.array || [];
for (const base of candidates) {
const dx = (newViolation.bbox.x + newViolation.bbox.width/2) - (base.bbox.x + base.bbox.width/2);
const dy = (newViolation.bbox.y + newViolation.bbox.height/2) - (base.bbox.y + base.bbox.height/2);
const distance = Math.sqrt(dx*dx + dy*dy);
const widthRatio = Math.min(newViolation.bbox.width, base.bbox.width) / Math.max(newViolation.bbox.width, base.bbox.width);
const heightRatio = Math.min(newViolation.bbox.height, base.bbox.height) / Math.max(newViolation.bbox.height, base.bbox.height);
if (distance <= config.matching.distanceThreshold && widthRatio >= config.matching.sizeSimilarity && heightRatio >= config.matching.sizeSimilarity) {
return { matched: true, method: 'bbox' };
}
}
return { matched: false };
}
5.2 Visual Impact Calculation
function computeVisualImpact(bbox, diffMask, imgWidth, imgHeight) {
// diffMask is a Uint8Array (0 or 255) of size imgWidth*imgHeight
let changed = 0;
for (let y = bbox.y; y < bbox.y + bbox.height; y++) {
for (let x = bbox.x; x < bbox.x + bbox.width; x++) {
if (y >= imgHeight || x >= imgWidth) continue;
const idx = y * imgWidth + x;
if (diffMask[idx] > 0) changed++;
}
}
const total = bbox.width * bbox.height;
return changed / total;
}
5.3 Puppeteer Capture + Axe
const puppeteer = require('puppeteer');
const axeCore = require('axe-core');
const { PNG } = require('pngjs'); // for pixelmask later
async function capturePage(url, config) {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setViewport(config.viewport);
await page.setUserAgent(config.userAgent);
await page.goto(url, { waitUntil: 'networkidle0' });
// Full page screenshot
const screenshot = await page.screenshot({ fullPage: true });
// Run axe
const results = await page.evaluate(async () => {
const axe = await axeCore.default.create();
return await axe.analyze(document, config.axeOptions);
}, config.axeOptions);
// Extract violations with bbox in document coordinates
const violations = results.violations.map(v => {
const nodes = v.nodes.map(node => {
const rect = node.target.getBoundingClientRect();
return {
ruleId: v.id,
selector: node.target.join(','), // simplified
bbox: {
x: rect.left + window.scrollX,
y: rect.top + window.scrollY,
width: rect.width,
height: rect.height
},
impact: v.impact,
description: v.description,
help: v.help
};
});
return nodes;
}).flat();
await browser.close();
return { screenshot, violations };
}
6. Potential Challenges & Mitigations
| Challenge | Mitigation |
|---|
| Dynamic content (ads, news feeds) causing many diffs | Allowlist URLs or CSS selectors to ignore; take multiple baseline screenshots and compute stable background; or use a "stable region mask". |
| Subpixel rendering / anti‑aliasing causing false diffs | Tune pixelmatch threshold, enable includeAntialiasing: false, optionally apply slight blur before diff. |
| Large number of pages → slow pipeline | Parallelize capture (multiple Puppeteer instances), cache baseline screenshots locally, only test changed URLs (via sitemap diff). |
| Selector instability (DOM refactor) | Use bbox matching fallback to avoid false positives. |
| False positives from scanner updates | Compare baseline violations; allowlist known acceptable issues; human review loop catches remaining. |
| Element movement (layout shift) → visual impact always high | Acceptable; movement itself may be a regression if it causes violation. |
| Storage of images | Store compressed PNGs; prune old runs; use object storage (S3) for reports. |
| Authentication | Provide Puppeteer auth (set cookies, use page.authenticate()). |
| Cross‑browser testing | Run pipeline against multiple browsers (Chrome, Firefox) separately. |
7. Example End‑to‑End Flow
- Baseline established from production via
baseline.js.
- Feature branch deployed to staging; CI triggers
regression.js.
regression.js:
- Captures target pages.
- Computes diffs and new violations.
- Finds 5 new violations (2 with visual change, 3 unchanged).
- Generates report and exits
1.
- CI posts Slack: “5 potential regressions. Review: …”
- Reviewer opens report, examines diff and crops, marks 3 as Confirmed, 2 as False positive.
- Reviewer clicks Create tickets →
create-tickets.js opens 3 GitHub issues.
- Developer fixes issues, pushes; regression re‑runs, now passes (
0).
- After merge and production deploy, a post‑deploy job runs
regression.js vs current baseline. No new violations → runs baseline.js to update baseline to production.
8. Conclusion
This design combines computer vision (pixel diff) with heuristic accessibility scanning to focus on visual changes that may introduce regressions. The human review loop ensures accuracy, and backlog integration streamlines issue tracking. The modular implementation (Node.js scripts, simple web server) integrates smoothly into CI/CD pipelines.