iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🤖

Creating a Simple VRT with Box Model Summary: @mizchi/visc

に公開

I wrote a tool that samples from a "known working state", measures the fluctuation in rendering, and automatically performs differential testing based on that.

https://github.com/mizchi/visc

The intended use case is when you want to automatically detect rendering regressions but don't want to write proper E2E tests for it.

$ npx -y @mizchi/visc render https://example.com
# Outputs SVG for visual inspection

Note: This is something I use for my own CSS fixes, and it's also a PoC. It includes many heuristic algorithmic scores, so the output will probably not be stable across updates.

Here is an example SVG output for visual inspection.

What is this

  • Captures the diff of the visual box model and detects differences
  • Internal logic:
    • Crawls the specified URL with Puppeteer, extracts all DOM elements with their bounding rectangles
    • Approximates (heuristically) the coordinate box model and summarizes it into units called VisualNodeGroup
    • Computes the distance between two VisualNodeGroup[] arrays
      • Checks for visually close elements
      • Checks for same accessibility nodes (tree edit distance)
      • Checks for same text content (Levenshtein distance)
  • While AI can look at the raw data directly, the tool outputs the diff as SVG for human verification

The visualization is inspired by pixelmatch.

https://github.com/mapbox/pixelmatch

Why I made it

During manual testing and visual inspection in development, you usually see either JS breaking and nothing rendering, or CSS box models collapsing and shifting wildly. This should be detectable mechanically.

There is VRT for that, but writing a proper E2E VRT is a lot of work.

So, I made a tool that, given a known working state, captures data multiple times, automatically calibrates, and creates settings that account for rendering tolerances.

$ npx -y @mizchi/visc calibrate https://zenn.dev
{
  "url": "https://zenn.dev",
  "settings": {
    "positionTolerance": 2,
    "sizeTolerance": 5,
    "textSimilarityThreshold": 0.95,
    "importanceThreshold": 10
  },
  "calibration": {
    "timestamp": "2025-08-05T09:11:19.097Z",
    "sampleCount": 5,
    "confidence": 75,
    "stats": {
      "avgPositionVariance": 0,
      "avgSizeVariance": 0,
      "avgTextSimilarity": 0.95,
      "stableElementRatio": 1
    },
    "viewport": {
      "width": 1280,
      "height": 800
    }
  }
}

Internally, it uses Puppeteer, waits for LCP, then crawls—so the process is browser-equivalent and not lightweight, but it's nice that it works with zero configuration.

The summary structure used for comparison is compact, and it's convenient to output a lightweight SVG for visual inspection.

Testing with a CLI matrix

Place a config file and test with a matrix of URLs × viewports.

visc.config.json
{
  "version": "1.0",
  "viewports": {
    "mobile": {
      "name": "Mobile",
      "width": 375,
      "height": 667,
      "deviceScaleFactor": 2
    },
    "desktop": {
      "name": "Desktop",
      "width": 1280,
      "height": 800,
      "deviceScaleFactor": 1
    }
  },
  "testCases": [
    {
      "id": "home",
      "url": "https://example.com",
      "description": "Homepage"
    }
  ]
}

The first run performs sampling for automatic calibration.

$ npx @mizchi/visc check -p 2      
🚀 Visual Check

📋 Config loaded: 1 test cases × 2 viewports

📥 Capture Phase (parallel: 2)

[██████████████████████████████] 2/2 100% 
✅ Captured 2 layouts                                                           

📊 Compare Phase

Capturing current layouts (parallel: 2)...

[██████████████████████████████] 2/2 100% 
✅ Captured 2 current layouts                                                   

Comparing layouts...

[██████████████████████████████] 2/2 100% home 1280x800 (100%)
✅ Compared 2 layouts                                                           


home:
  Homepage
  ✅ 375x667: 100.0% similar
  ✅ 1280x800: 100.0% similar

Core functionality

...I created this because I needed it for my current job. The core computation parts are extracted as reusable functions.

import puppeteer from 'puppeteer';
import { promises as fs } from 'fs';
import {
  fetchRawLayoutData,
  extractLayoutTree,
  compareLayoutTrees,
  renderLayoutToSvg,
  renderComparisonToSvg
} from '@mizchi/visc';

// Launch browser and capture layout
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com');

// Fetch and extract layout
const rawData = await fetchRawLayoutData(page);
const layout = await extractLayoutTree(rawData, {
  viewportOnly: true,
  groupingThreshold: 20,
  importanceThreshold: 10
});

// Render layout as SVG
const svg = renderLayoutToSvg(layout, {
  showLabels: true,
  highlightLevel: 'moderate'
});

// Compare two layouts
const comparison = compareLayoutTrees(baselineLayout, currentLayout, {
  threshold: 5,
  ignoreText: true
});

// Render comparison as diff SVG
const diffSvg = renderComparisonToSvg(comparison, baselineLayout, currentLayout, {
  showLabels: true,
  highlightLevel: 'moderate'
});

// Save diff SVG to file
await fs.writeFile('diff.svg', diffSvg);

await browser.close();

When to use this?

Scenarios I envision:

  • Calibrate when manual checks are already passing in the local environment (e.g., http://localhost:3000)
  • While modifying CSS or JS, automatically run visc check to detect layout regressions
  • If something breaks, a link to .visc/output/<id>/diff-<width>x<height>.svg is displayed for visual inspection

It might be handy when you want to quickly check the impact of CSS changes or layout adjustments. I still want to use it more.

Discussion