# CSS, Asset & Playwright 1:1 Parity Guide

Visual and CSS regressions are the #1 failure mode when de-frameworking web apps. Treat visual/CSS fidelity as an automated engineering gate—never as a manual afterthought.

---

## 1. Why CSS Breaks During Migrations (and How to Prevent Every Case)

| Common Failure Mode | Root Cause | Mandatory Prevention |
| :--- | :--- | :--- |
| **Missing utility classes / broken layout** | Hand-rewriting Tailwind classes into vanilla CSS by eye and missing responsive (`md:`, `lg:`), state (`hover:`, `focus-visible:`, `group-hover:`), or dark-mode (`dark:`) variants. | **Option A (Recommended for Tailwind apps):** Keep Tailwind as a *build-time-only* CLI step (`@tailwindcss/cli` in Docker Stage 1 scanning Askama templates + Vanilla JS) outputting a single content-hashed `/static/css/app.<hash>.css` with **zero runtime Node**. **Option B (Pure Vanilla CSS):** Extract every CSS custom property, reset/preflight rule, media query, and component rule directly from the prod compiled stylesheet—never from memory—and verify via Playwright computed-style diffing. |
| **Broken cascade / missing CSS reset (Preflight)** | Tailwind/MUI/Bootstrap inject a base reset (`box-sizing: border-box`, button/heading resets, `img { display: block; max-width: 100%; }`). Dropping the framework drops the reset and breaks margins, buttons, and SVG sizing. | Explicitly include the exact base/preflight layer first in cascade order before component and utility styles. |
| **Wrong font family or FOUT/layout shift** | Relying on framework font loaders (`next/font/google`) that injected hidden `@font-face` rules and CSS variables (`--font-inter`, `--font-mono`). | Self-host the exact `.woff2` files under `/static/fonts/`, declare explicit `@font-face` rules + matching CSS variables (`--font-*`), and assert `document.fonts.status === 'loaded'` in Playwright. |
| **Missing or mis-sized icons** | Dropping `lucide-react` / Heroicons and approximating SVGs by hand (wrong `viewBox`, `stroke-width`, or `width`/`height`). | Extract exact SVG paths/attributes from the installed icon package into compile-time template helpers (e.g., `icons::lucide("bell", "w-4 h-4")`). |
| **Broken asset paths / `/_next/image` 404s** | Hardcoded framework paths (`/_next/static/...`, `/_next/image?url=...`) or wrong relative paths on nested routes (`/blog/post` vs `/`). | Serve all `public/` assets at exact root-relative `/...` URLs with immutable caching where hashed; replace `/_next/image` with a native Rust image endpoint or direct static assets. |
| **CSP or MIME-type silently blocking CSS/JS/fonts** | Tightened `Content-Security-Policy` blocking inline styles/fonts/scripts or Rust static handler missing `Content-Type: text/css` / `font/woff2` / `image/svg+xml`. | Assert zero CSP console errors in Playwright and verify exact `Content-Type` headers on every static asset type. |
| **Theme / root class mismatch** | Missing `<html class="dark">`, `data-theme`, or `<body>` utility classes from `layout.tsx` / `_document.tsx`. | Diff `<html>` and `<body>` attributes and computed styles directly between prod and staging. |

---

## 2. Mandatory Playwright 1:1 Parity Gate

Before **any** stage or vertical is marked complete—and before Stage 3 sign-off—run a Playwright comparison script against `PROD_URL` and `STAGING_URL` across **both desktop (`1440×900`) and mobile (`390×844`)** viewports.

### Hard Pass Criteria (All Must Be Zero / 100%)
- **0** uncaught `pageerror` exceptions.
- **0** `console.error` messages (including CSP violations, missing modules, hydration/runtime errors).
- **0** failed network requests (`status >= 400` or `requestfailed`) for HTML, CSS, JS, fonts, images, or API calls.
- **0** broken images (`img.complete === true && img.naturalWidth > 0` for every visible `<img>`).
- **0** unloaded stylesheets (`document.styleSheets.length > 0` and every `<link rel="stylesheet">` has `sheet !== null`).
- **0** unintended horizontal scroll overflow (`document.documentElement.scrollWidth <= window.innerWidth + 1`).
- **100%** font load verification (`document.fonts.ready` resolves with expected primary font families loaded).
- **Computed-style parity** on key landmarks (`html`, `body`, `header`, `nav`, `main`, `h1`, primary button, primary card, `footer`): `fontFamily`, `fontSize`, `fontWeight`, `lineHeight`, `color`, `backgroundColor`, `borderRadius`, `padding`.
- **Visual screenshot parity:** Side-by-side full-page PNGs (`prod` vs `staging` + pixel diff image) reviewed for every route and interactive state (open modals, dropdowns, mobile menu drawer, dark/light toggle, form validation errors, empty states).

---

## 3. Reusable Playwright Parity Script Template (`scripts/parity_check.mjs`)

Adapt the route list, auth setup, and landmark selectors to your application. Run with:
```bash
PROD_URL="https://example.com" \
STAGING_URL="https://staging.example.com" \
STAGING_BASIC_AUTH="user:pass" \
node scripts/parity_check.mjs
```

```javascript
import { chromium } from 'playwright';
import fs from 'node:fs/promises';
import path from 'node:path';

const PROD_URL = process.env.PROD_URL;
const STAGING_URL = process.env.STAGING_URL;
const OUT_DIR = process.env.OUT_DIR || 'parity-artifacts';

if (!PROD_URL || !STAGING_URL) {
  console.error('Set PROD_URL and STAGING_URL');
  process.exit(1);
}

// Replace with the complete route inventory from MIGRATION_AUDIT.md
const ROUTES = [
  '/',
  '/login',
  // Add every public & authenticated route here
];

const VIEWPORTS = [
  { name: 'desktop', width: 1440, height: 900 },
  { name: 'mobile', width: 390, height: 844 },
];

const LANDMARK_SELECTORS = ['html', 'body', 'header', 'nav', 'main', 'h1', 'footer'];
const STYLE_PROPS = [
  'fontFamily',
  'fontSize',
  'fontWeight',
  'lineHeight',
  'color',
  'backgroundColor',
  'borderRadius',
  'paddingTop',
  'paddingBottom',
];

function parseBasicAuth(raw) {
  if (!raw) return undefined;
  const idx = raw.indexOf(':');
  if (idx === -1) return undefined;
  return { username: raw.slice(0, idx), password: raw.slice(idx + 1) };
}

async function inspectTarget(browser, baseUrl, label, route, viewport, httpCredentials) {
  const context = await browser.newContext({ viewport, httpCredentials });
  const page = await context.newPage();

  const pageErrors = [];
  const consoleErrors = [];
  const failedRequests = [];

  page.on('pageerror', (err) => pageErrors.push(err.message));
  page.on('console', (msg) => {
    if (msg.type() === 'error') consoleErrors.push(msg.text());
  });
  page.on('requestfailed', (req) => {
    failedRequests.push({ url: req.url(), reason: req.failure()?.errorText || 'failed' });
  });
  page.on('response', (res) => {
    if (res.status() >= 400) {
      failedRequests.push({ url: res.url(), status: res.status() });
    }
  });

  const url = new URL(route, baseUrl).toString();
  const response = await page.goto(url, { waitUntil: 'networkidle', timeout: 30000 });
  await page.evaluate(() => document.fonts.ready);
  await page.waitForTimeout(300);

  const metrics = await page.evaluate(({ selectors, props }) => {
    const stylesheets = [...document.querySelectorAll('link[rel="stylesheet"]')].map((el) => ({
      href: el.getAttribute('href'),
      loaded: Boolean(el.sheet),
    }));

    const brokenImages = [...document.querySelectorAll('img')]
      .filter((img) => {
        const rect = img.getBoundingClientRect();
        return rect.width > 0 && rect.height > 0 && (!img.complete || img.naturalWidth === 0);
      })
      .map((img) => img.getAttribute('src'));

    const loadedFonts = [...document.fonts]
      .filter((f) => f.status === 'loaded')
      .map((f) => `${f.family}:${f.weight}`);

    const landmarks = {};
    for (const sel of selectors) {
      const el = document.querySelector(sel);
      if (!el) continue;
      const cs = getComputedStyle(el);
      const rect = el.getBoundingClientRect();
      landmarks[sel] = {
        styles: Object.fromEntries(props.map((p) => [p, cs[p]])),
        rect: {
          x: Math.round(rect.x),
          y: Math.round(rect.y),
          w: Math.round(rect.width),
          h: Math.round(rect.height),
        },
      };
    }

    return {
      title: document.title,
      htmlClass: document.documentElement.className,
      bodyClass: document.body.className,
      overflowX: document.documentElement.scrollWidth > window.innerWidth + 1,
      scrollWidth: document.documentElement.scrollWidth,
      innerWidth: window.innerWidth,
      stylesheets,
      brokenImages,
      loadedFonts: [...new Set(loadedFonts)].sort(),
      landmarks,
    };
  }, { selectors: LANDMARK_SELECTORS, props: STYLE_PROPS });

  const slug = route === '/' ? 'home' : route.replace(/[^a-zA-Z0-9]+/g, '_').replace(/^_|_$/g, '');
  const shotPath = path.join(OUT_DIR, `${slug}__${viewport.name}__${label}.png`);
  await page.screenshot({ path: shotPath, fullPage: true });
  await context.close();

  return {
    url,
    status: response?.status() ?? 0,
    pageErrors,
    consoleErrors,
    failedRequests,
    metrics,
    shotPath,
  };
}

function diffLandmarks(prodLandmarks, stagingLandmarks) {
  const diffs = [];
  for (const sel of Object.keys(prodLandmarks)) {
    if (!stagingLandmarks[sel]) {
      diffs.push(`Missing landmark <${sel}> on staging`);
      continue;
    }
    for (const prop of STYLE_PROPS) {
      const a = prodLandmarks[sel].styles[prop];
      const b = stagingLandmarks[sel].styles[prop];
      if (a !== b) {
        diffs.push(`<${sel}>.${prop}: prod="${a}" vs staging="${b}"`);
      }
    }
  }
  return diffs;
}

await fs.mkdir(OUT_DIR, { recursive: true });
const browser = await chromium.launch();
const stagingAuth = parseBasicAuth(process.env.STAGING_BASIC_AUTH);
const report = [];
let failures = 0;

for (const route of ROUTES) {
  for (const viewport of VIEWPORTS) {
    const prod = await inspectTarget(browser, PROD_URL, 'prod', route, viewport, undefined);
    const staging = await inspectTarget(browser, STAGING_URL, 'staging', route, viewport, stagingAuth);

    const issues = [];
    if (staging.status !== prod.status) issues.push(`HTTP status prod=${prod.status} staging=${staging.status}`);
    if (staging.pageErrors.length) issues.push(`pageErrors: ${staging.pageErrors.join('; ')}`);
    if (staging.consoleErrors.length) issues.push(`consoleErrors: ${staging.consoleErrors.join('; ')}`);
    if (staging.failedRequests.length) issues.push(`failedRequests: ${JSON.stringify(staging.failedRequests)}`);
    if (staging.metrics.brokenImages.length) issues.push(`brokenImages: ${staging.metrics.brokenImages.join(', ')}`);
    if (staging.metrics.stylesheets.some((s) => !s.loaded)) issues.push('Unloaded stylesheet detected');
    if (staging.metrics.overflowX && !prod.metrics.overflowX) {
      issues.push(`Horizontal overflow on staging (${staging.metrics.scrollWidth} > ${staging.metrics.innerWidth})`);
    }
    if (staging.metrics.title !== prod.metrics.title) {
      issues.push(`Title mismatch: prod="${staging.metrics.title}" staging="${staging.metrics.title}"`);
    }
    issues.push(...diffLandmarks(prod.metrics.landmarks, staging.metrics.landmarks));

    if (issues.length) failures += 1;
    report.push({ route, viewport: viewport.name, issues, prodShot: prod.shotPath, stagingShot: staging.shotPath });
    console.log(`${issues.length === 0 ? 'PASS' : 'FAIL'} ${route} [${viewport.name}]${issues.length ? ` (${issues.length} issues)` : ''}`);
  }
}

await browser.close();
await fs.writeFile(path.join(OUT_DIR, 'parity-report.json'), JSON.stringify(report, null, 2));
console.log(`\nWrote ${path.join(OUT_DIR, 'parity-report.json')}. Failing route-viewports: ${failures}`);
process.exit(failures > 0 ? 1 : 0);
```

### Extending for Interactive & Authenticated Parity
Always add a second Playwright spec (`tests/e2e_parity.spec.mjs`) covering:
1. Authenticated routes (using a seeded staging test account—never a live prod user).
2. Interactive CSS states: open mobile nav drawer, open/close modals, trigger dropdowns/tabs, toggle dark/light theme, submit invalid forms (verify validation styling), submit valid CRUD forms (verify persistence on reload).
3. Pixel-diffing (optional `pixelmatch` / `playwright` `toHaveScreenshot` with tight threshold) on stabilized screenshots (masking timestamps/live counters).
