An open source design system that's fully customizable and agent ready
TypeScript
[Test] Add PR enrichment workflow for component analysis (#71)
David Petersenaa19b82e1bb0
diff --git a/.github/SAMPLE_PR_COMMENT.md b/.github/SAMPLE_PR_COMMENT.mdnew file mode 100644index 0000000000..3538ca2de4--- /dev/null+++ b/.github/SAMPLE_PR_COMMENT.md@@ -0,0 +1,85 @@+# Sample PR Analysis Report++This is an example of what the PR enrichment workflow will post as a comment on pull requests.++---++## PR Analysis Report++### New Components++<details>+<summary><strong>DatePicker</strong></summary>++| Metric | Value |+|--------|-------|+| Bundle Size (ESM) | 4.2KB |+| Bundle Size (CJS) | 4.8KB |+| Exports | XDSDatePicker, DatePickerProps |+| Props Count | 12 |+| Has Tests | Yes |+| Has Stories | Yes |++</details>++<details>+<summary><strong>TimePicker</strong></summary>++| Metric | Value |+|--------|-------|+| Bundle Size (ESM) | 3.1KB |+| Bundle Size (CJS) | 3.5KB |+| Exports | XDSTimePicker |+| Props Count | 8 |+| Has Tests | No |+| Has Stories | Yes |++</details>++### Modified Components++<details>+<summary><strong>Button</strong></summary>++| Metric | Before | After | Delta |+|--------|--------|-------|-------|+| Bundle Size (ESM) | 2.2KB | 2.4KB | +200B |++</details>++<details>+<summary><strong>TextInput</strong></summary>++| Metric | Before | After | Delta |+|--------|--------|-------|-------|+| Bundle Size (ESM) | 2.9KB | 3.0KB | +130B |++</details>++### Bundle Size Summary++| Package | Size (ESM) | Size (CJS) | Gzipped |+|---------|------------|------------|----------|+| @xds/core | 45.2KB | 52.1KB | 12.4KB |++**Bundle size increased:** +850 bytes++### Accessibility Audit++**Status:** 1 accessibility violation(s) found.++<details>+<summary><strong>TimePicker</strong> - 1 issue(s)</summary>++- **critical**: Form elements must have labels+ - Rule: `label`++</details>++### Component Previews++Component screenshots are available in the [workflow artifacts](https://github.com/example/xds/actions/runs/12345).++---++<sub>Generated by PR Enrichment workflow | [View full report](https://github.com/example/xds/actions/runs/12345)</sub>diff --git a/.github/scripts/accessibility-audit.js b/.github/scripts/accessibility-audit.jsnew file mode 100644index 0000000000..317018f8d1--- /dev/null+++ b/.github/scripts/accessibility-audit.js@@ -0,0 +1,307 @@+#!/usr/bin/env node++/**+ * @description Runs accessibility audits on component stories using axe-core+ * @input --storybook-dir <path> --output <file> --components <comma-separated>+ * @output JSON report with accessibility violations+ */++const { chromium } = require('playwright');+const fs = require('fs');+const path = require('path');+const http = require('http');++const args = process.argv.slice(2);+const getArg = (name) => {+ const idx = args.indexOf(`--${name}`);+ return idx !== -1 ? args[idx + 1] : null;+};++const storybookDir = getArg('storybook-dir') || 'apps/storybook/dist';+const outputFile = getArg('output') || 'a11y-report.json';+const componentsArg = getArg('components') || '';+const components = componentsArg.split(',').filter(Boolean);++// Simple static file server+function createServer(dir, port) {+ return new Promise((resolve) => {+ const server = http.createServer((req, res) => {+ let filePath = path.join(dir, req.url === '/' ? 'index.html' : req.url);+ filePath = filePath.split('?')[0];++ const ext = path.extname(filePath);+ const contentTypes = {+ '.html': 'text/html',+ '.js': 'application/javascript',+ '.css': 'text/css',+ '.json': 'application/json',+ '.png': 'image/png',+ '.svg': 'image/svg+xml',+ };++ fs.readFile(filePath, (err, data) => {+ if (err) {+ res.writeHead(404);+ res.end('Not found');+ return;+ }+ res.writeHead(200, { 'Content-Type': contentTypes[ext] || 'text/plain' });+ res.end(data);+ });+ });++ server.listen(port, () => {+ console.log(`Storybook server running on http://localhost:${port}`);+ resolve(server);+ });+ });+}++// Get stories from storybook+async function getStories(storybookPath) {+ const storiesJsonPath = path.join(storybookPath, 'index.json');++ try {+ const content = fs.readFileSync(storiesJsonPath, 'utf8');+ const data = JSON.parse(content);+ return data.entries || data.stories || {};+ } catch (e) {+ console.error('Could not read stories index:', e.message);+ return {};+ }+}++// axe-core script to inject+const AXE_SCRIPT = `+// Minimal axe-core implementation for accessibility testing+window.runAxe = async function() {+ const violations = [];++ // Check for images without alt text+ document.querySelectorAll('img:not([alt])').forEach(el => {+ violations.push({+ id: 'image-alt',+ impact: 'critical',+ description: 'Images must have alternate text',+ nodes: [{ html: el.outerHTML.substring(0, 100) }]+ });+ });++ // Check for buttons without accessible names+ document.querySelectorAll('button').forEach(el => {+ const hasText = el.textContent.trim();+ const hasAriaLabel = el.getAttribute('aria-label');+ const hasAriaLabelledBy = el.getAttribute('aria-labelledby');+ const hasTitle = el.getAttribute('title');++ if (!hasText && !hasAriaLabel && !hasAriaLabelledBy && !hasTitle) {+ violations.push({+ id: 'button-name',+ impact: 'critical',+ description: 'Buttons must have discernible text',+ nodes: [{ html: el.outerHTML.substring(0, 100) }]+ });+ }+ });++ // Check for form inputs without labels+ document.querySelectorAll('input:not([type="hidden"]):not([type="submit"]):not([type="button"])').forEach(el => {+ const id = el.getAttribute('id');+ const hasLabel = id && document.querySelector(\`label[for="\${id}"]\`);+ const hasAriaLabel = el.getAttribute('aria-label');+ const hasAriaLabelledBy = el.getAttribute('aria-labelledby');+ const hasTitle = el.getAttribute('title');+ const hasPlaceholder = el.getAttribute('placeholder');++ if (!hasLabel && !hasAriaLabel && !hasAriaLabelledBy && !hasTitle && !hasPlaceholder) {+ violations.push({+ id: 'label',+ impact: 'critical',+ description: 'Form elements must have labels',+ nodes: [{ html: el.outerHTML.substring(0, 100) }]+ });+ }+ });++ // Check for low color contrast (basic check)+ // This is a simplified check - real axe-core does much more++ // Check for missing lang attribute+ if (!document.documentElement.getAttribute('lang')) {+ violations.push({+ id: 'html-has-lang',+ impact: 'serious',+ description: '<html> element must have a lang attribute',+ nodes: [{ html: '<html>' }]+ });+ }++ // Check for missing main landmark+ if (!document.querySelector('main, [role="main"]')) {+ // Don't flag this for component stories - they're fragments+ }++ // Check for empty links+ document.querySelectorAll('a').forEach(el => {+ const hasText = el.textContent.trim();+ const hasAriaLabel = el.getAttribute('aria-label');+ const hasImage = el.querySelector('img[alt]');++ if (!hasText && !hasAriaLabel && !hasImage) {+ violations.push({+ id: 'link-name',+ impact: 'serious',+ description: 'Links must have discernible text',+ nodes: [{ html: el.outerHTML.substring(0, 100) }]+ });+ }+ });++ // Check for positive tabindex+ document.querySelectorAll('[tabindex]').forEach(el => {+ const tabindex = parseInt(el.getAttribute('tabindex'), 10);+ if (tabindex > 0) {+ violations.push({+ id: 'tabindex',+ impact: 'serious',+ description: 'Elements should not have tabindex greater than zero',+ nodes: [{ html: el.outerHTML.substring(0, 100) }]+ });+ }+ });++ return { violations };+};+`;++async function runAccessibilityAudit() {+ console.log('Starting accessibility audit...');+ console.log(`Components to audit: ${components.length > 0 ? components.join(', ') : 'all affected'}`);++ const storybookPath = path.resolve(process.cwd(), storybookDir);++ if (!fs.existsSync(storybookPath)) {+ console.error(`Storybook build not found at ${storybookPath}`);+ const report = {+ error: 'Storybook not built',+ components: {},+ summary: { total: 0, violations: 0 }+ };+ fs.writeFileSync(outputFile, JSON.stringify(report, null, 2));+ return;+ }++ // Start server+ const port = 6007;+ const server = await createServer(storybookPath, port);++ // Get stories+ const stories = await getStories(storybookPath);+ const storyIds = Object.keys(stories);++ console.log(`Found ${storyIds.length} stories`);++ // Filter stories for relevant components+ const relevantStories = storyIds.filter(id => {+ if (components.length === 0) return true;+ const story = stories[id];+ const title = story.title || '';+ return components.some(comp =>+ title.toLowerCase().includes(comp.toLowerCase()) ||+ id.toLowerCase().includes(comp.toLowerCase())+ );+ });++ // Group stories by component+ const storyGroups = {};+ for (const storyId of relevantStories) {+ const story = stories[storyId];+ const component = (story.title || '').split('/').pop() || storyId;+ if (!storyGroups[component]) {+ storyGroups[component] = [];+ }+ storyGroups[component].push({ id: storyId, ...story });+ }++ console.log(`Auditing ${Object.keys(storyGroups).length} components`);++ const browser = await chromium.launch();+ const context = await browser.newContext({+ viewport: { width: 1280, height: 720 },+ });++ const componentResults = {};+ let totalViolations = 0;++ for (const [component, componentStories] of Object.entries(storyGroups)) {+ const componentViolations = [];++ for (const story of componentStories) {+ const page = await context.newPage();++ try {+ const url = `http://localhost:${port}/iframe.html?id=${story.id}&viewMode=story`;+ await page.goto(url, { waitUntil: 'networkidle', timeout: 10000 });+ await page.waitForTimeout(300);++ // Inject and run accessibility check+ await page.addScriptTag({ content: AXE_SCRIPT });+ const results = await page.evaluate(() => window.runAxe());++ if (results.violations.length > 0) {+ componentViolations.push({+ story: story.name || story.id,+ violations: results.violations,+ });+ totalViolations += results.violations.length;+ }++ console.log(`✓ Audited: ${component} / ${story.name} - ${results.violations.length} issues`);+ } catch (e) {+ console.error(`✗ Failed: ${story.id} - ${e.message}`);+ } finally {+ await page.close();+ }+ }++ // Aggregate violations for component+ const uniqueViolations = [];+ const seenIds = new Set();++ for (const storyResult of componentViolations) {+ for (const violation of storyResult.violations) {+ if (!seenIds.has(violation.id)) {+ seenIds.add(violation.id);+ uniqueViolations.push(violation);+ }+ }+ }++ componentResults[component] = {+ storiesAudited: componentStories.length,+ violations: uniqueViolations,+ storyDetails: componentViolations,+ };+ }++ await browser.close();+ server.close();++ const report = {+ components: componentResults,+ summary: {+ componentsAudited: Object.keys(componentResults).length,+ totalViolations,+ auditedAt: new Date().toISOString(),+ },+ };++ fs.writeFileSync(outputFile, JSON.stringify(report, null, 2));+ console.log(`\nAudit complete: ${totalViolations} total violations found`);+ console.log(`Report written to ${outputFile}`);+}++runAccessibilityAudit().catch(e => {+ console.error('Accessibility audit failed:', e);+ process.exit(1);+});diff --git a/.github/scripts/analyze-pr.js b/.github/scripts/analyze-pr.jsnew file mode 100644index 0000000000..e0a7252059--- /dev/null+++ b/.github/scripts/analyze-pr.js@@ -0,0 +1,372 @@+#!/usr/bin/env node++/**+ * @description Analyzes PR changes to detect new/modified components and gather stats+ * @input --base <branch> --head <ref> --output <file>+ * @output JSON file with component analysis+ */++const fs = require('fs');+const path = require('path');+const { execSync } = require('child_process');++const args = process.argv.slice(2);+const getArg = (name) => {+ const idx = args.indexOf(`--${name}`);+ return idx !== -1 ? args[idx + 1] : null;+};++const baseBranch = getArg('base') || 'main';+const headRef = getArg('head') || 'HEAD';+const outputFile = getArg('output') || 'analysis.json';++const CORE_SRC = 'packages/core/src';+const CORE_DIST = 'packages/core/dist';+const STORYBOOK_STORIES = 'apps/storybook/stories';++// Get list of component directories (excluding utils, hooks, theme)+function getComponentDirs() {+ const srcPath = path.join(process.cwd(), CORE_SRC);+ const entries = fs.readdirSync(srcPath, { withFileTypes: true });+ const excluded = ['hooks', 'theme', 'utils'];++ return entries+ .filter(e => e.isDirectory() && !excluded.includes(e.name))+ .map(e => e.name);+}++// Get changed files between base and head+function getChangedFiles() {+ try {+ const output = execSync(+ `git diff --name-only ${baseBranch}...${headRef}`,+ { encoding: 'utf8' }+ );+ return output.trim().split('\n').filter(Boolean);+ } catch (e) {+ console.error('Error getting changed files:', e.message);+ return [];+ }+}++// Check if component exists in base branch+function componentExistsInBase(componentName) {+ try {+ execSync(+ `git show ${baseBranch}:${CORE_SRC}/${componentName}/index.ts`,+ { encoding: 'utf8', stdio: 'pipe' }+ );+ return true;+ } catch {+ return false;+ }+}++// Get file size in human readable format+function getFileSize(filePath) {+ try {+ const stats = fs.statSync(filePath);+ const bytes = stats.size;+ if (bytes < 1024) return `${bytes}B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;+ return `${(bytes / (1024 * 1024)).toFixed(2)}MB`;+ } catch {+ return null;+ }+}++function getFileSizeBytes(filePath) {+ try {+ return fs.statSync(filePath).size;+ } catch {+ return null;+ }+}++// Get gzipped size+function getGzipSize(filePath) {+ try {+ const output = execSync(`gzip -c "${filePath}" | wc -c`, { encoding: 'utf8' });+ const bytes = parseInt(output.trim(), 10);+ if (bytes < 1024) return `${bytes}B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;+ return `${(bytes / (1024 * 1024)).toFixed(2)}MB`;+ } catch {+ return null;+ }+}++// Get exports from a component+function getExports(componentName) {+ const indexPath = path.join(process.cwd(), CORE_SRC, componentName, 'index.ts');+ try {+ const content = fs.readFileSync(indexPath, 'utf8');+ const exportMatches = content.match(/export\s+{\s*([^}]+)\s*}/g) || [];+ const exports = [];++ for (const match of exportMatches) {+ const inner = match.replace(/export\s*{\s*/, '').replace(/\s*}/, '');+ exports.push(...inner.split(',').map(e => e.trim().split(' ')[0]));+ }++ // Also check for default exports+ if (content.includes('export default')) {+ exports.push('default');+ }++ return exports.filter(Boolean);+ } catch {+ return [];+ }+}++// Count props for main component+function getPropsCount(componentName) {+ const componentDir = path.join(process.cwd(), CORE_SRC, componentName);+ try {+ const files = fs.readdirSync(componentDir);+ const mainFile = files.find(f => f.startsWith('XDS') && f.endsWith('.tsx'));++ if (!mainFile) return null;++ const content = fs.readFileSync(path.join(componentDir, mainFile), 'utf8');++ // Look for Props type/interface+ const propsMatch = content.match(/(?:type|interface)\s+\w*Props\w*\s*=?\s*{([^}]+)}/);+ if (propsMatch) {+ const propsContent = propsMatch[1];+ const props = propsContent.split('\n').filter(line =>+ line.trim() &&+ !line.trim().startsWith('//') &&+ !line.trim().startsWith('*') &&+ line.includes(':')+ );+ return props.length;+ }++ return null;+ } catch {+ return null;+ }+}++// Check if component has tests+function hasTests(componentName) {+ const testPath = path.join(process.cwd(), CORE_SRC, componentName);+ try {+ const files = fs.readdirSync(testPath);+ return files.some(f => f.endsWith('.test.ts') || f.endsWith('.test.tsx'));+ } catch {+ return false;+ }+}++// Check if component has stories+function hasStories(componentName) {+ const storiesDir = path.join(process.cwd(), STORYBOOK_STORIES);+ try {+ const files = fs.readdirSync(storiesDir);+ return files.some(f =>+ f.toLowerCase().includes(componentName.toLowerCase()) &&+ f.endsWith('.stories.tsx')+ );+ } catch {+ return false;+ }+}++// Count lines of code in a file (excluding blank lines and comments)+function countLOC(filePath) {+ try {+ const content = fs.readFileSync(filePath, 'utf8');+ const lines = content.split('\n');+ let loc = 0;+ let inBlockComment = false;++ for (const line of lines) {+ const trimmed = line.trim();++ // Track block comments+ if (trimmed.startsWith('/*')) inBlockComment = true;+ if (trimmed.endsWith('*/')) {+ inBlockComment = false;+ continue;+ }++ if (inBlockComment) continue;+ if (!trimmed) continue;+ if (trimmed.startsWith('//')) continue;+ if (trimmed.startsWith('*')) continue;++ loc++;+ }++ return loc;+ } catch {+ return 0;+ }+}++// Get total LOC for a component+function getComponentLOC(componentName) {+ const componentDir = path.join(process.cwd(), CORE_SRC, componentName);+ try {+ const files = fs.readdirSync(componentDir);+ let totalLOC = 0;+ let fileCount = 0;++ for (const file of files) {+ if (file.endsWith('.ts') || file.endsWith('.tsx')) {+ // Skip test files+ if (file.includes('.test.')) continue;+ totalLOC += countLOC(path.join(componentDir, file));+ fileCount++;+ }+ }++ return { totalLOC, fileCount };+ } catch {+ return { totalLOC: 0, fileCount: 0 };+ }+}++// Calculate cyclomatic complexity (simplified - counts decision points)+function getComplexity(componentName) {+ const componentDir = path.join(process.cwd(), CORE_SRC, componentName);+ try {+ const files = fs.readdirSync(componentDir);+ let complexity = 1; // Base complexity++ for (const file of files) {+ if (!file.endsWith('.tsx')) continue;+ if (file.includes('.test.')) continue;++ const content = fs.readFileSync(path.join(componentDir, file), 'utf8');++ // Count decision points (simplified cyclomatic complexity)+ const patterns = [+ /\bif\s*\(/g,+ /\belse\s+if\s*\(/g,+ /\bswitch\s*\(/g,+ /\bcase\s+/g,+ /\?\s*[^:]/g, // Ternary operators+ /\|\|/g, // Logical OR (short-circuit)+ /&&/g, // Logical AND (short-circuit)+ /\.map\s*\(/g, // Array iterations+ /\.filter\s*\(/g,+ /\.reduce\s*\(/g,+ /\.forEach\s*\(/g,+ ];++ for (const pattern of patterns) {+ const matches = content.match(pattern);+ if (matches) {+ complexity += matches.length;+ }+ }+ }++ // Categorize complexity+ let rating;+ if (complexity <= 5) rating = 'Low';+ else if (complexity <= 15) rating = 'Medium';+ else if (complexity <= 30) rating = 'High';+ else rating = 'Very High';++ return { score: complexity, rating };+ } catch {+ return { score: 0, rating: 'Unknown' };+ }+}++// Get component stats+function getComponentStats(componentName) {+ const distPath = path.join(process.cwd(), CORE_DIST, componentName);+ const loc = getComponentLOC(componentName);+ const complexity = getComplexity(componentName);++ return {+ esmSize: getFileSize(path.join(distPath, 'index.mjs')),+ esmBytes: getFileSizeBytes(path.join(distPath, 'index.mjs')),+ cjsSize: getFileSize(path.join(distPath, 'index.js')),+ cjsBytes: getFileSizeBytes(path.join(distPath, 'index.js')),+ exports: getExports(componentName),+ propsCount: getPropsCount(componentName),+ hasTests: hasTests(componentName),+ hasStories: hasStories(componentName),+ linesOfCode: loc.totalLOC,+ fileCount: loc.fileCount,+ complexity: complexity.score,+ complexityRating: complexity.rating,+ };+}++// Get total bundle stats+function getTotalBundleStats() {+ const distPath = path.join(process.cwd(), CORE_DIST);+ const esmPath = path.join(distPath, 'index.mjs');+ const cjsPath = path.join(distPath, 'index.js');++ return {+ esmSize: getFileSize(esmPath),+ esmBytes: getFileSizeBytes(esmPath),+ cjsSize: getFileSize(cjsPath),+ cjsBytes: getFileSizeBytes(cjsPath),+ gzipSize: getGzipSize(esmPath),+ };+}++// Main analysis+function analyze() {+ console.log(`Analyzing changes from ${baseBranch} to ${headRef}...`);++ const allComponents = getComponentDirs();+ const changedFiles = getChangedFiles();++ console.log(`Found ${allComponents.length} components`);+ console.log(`Found ${changedFiles.length} changed files`);++ // Detect which components are new or modified+ const newComponents = [];+ const modifiedComponents = [];++ for (const file of changedFiles) {+ if (!file.startsWith(CORE_SRC + '/')) continue;++ const relativePath = file.replace(CORE_SRC + '/', '');+ const componentName = relativePath.split('/')[0];++ if (!allComponents.includes(componentName)) continue;+ if (newComponents.includes(componentName) || modifiedComponents.includes(componentName)) continue;++ if (componentExistsInBase(componentName)) {+ modifiedComponents.push(componentName);+ } else {+ newComponents.push(componentName);+ }+ }++ console.log(`New components: ${newComponents.join(', ') || 'none'}`);+ console.log(`Modified components: ${modifiedComponents.join(', ') || 'none'}`);++ // Gather stats for affected components+ const componentStats = {};+ for (const comp of [...newComponents, ...modifiedComponents]) {+ componentStats[comp] = getComponentStats(comp);+ }++ const result = {+ newComponents,+ modifiedComponents,+ componentStats,+ totalBundle: getTotalBundleStats(),+ analyzedAt: new Date().toISOString(),+ };++ fs.writeFileSync(outputFile, JSON.stringify(result, null, 2));+ console.log(`Analysis written to ${outputFile}`);++ return result;+}++analyze();diff --git a/.github/scripts/capture-screenshots.js b/.github/scripts/capture-screenshots.jsnew file mode 100644index 0000000000..7cd64a9e06--- /dev/null+++ b/.github/scripts/capture-screenshots.js@@ -0,0 +1,472 @@+#!/usr/bin/env node++/**+ * @description Captures screenshots and videos of component stories using Playwright+ * @input --storybook-dir <path> --output-dir <path> --components <comma-separated> --video+ * @output PNG screenshots and GIF videos in output directory with manifest+ */++const { chromium } = require('playwright');+const fs = require('fs');+const path = require('path');+const http = require('http');+const { execSync } = require('child_process');++const args = process.argv.slice(2);+const getArg = (name) => {+ const idx = args.indexOf(`--${name}`);+ return idx !== -1 ? args[idx + 1] : null;+};+const hasFlag = (name) => args.includes(`--${name}`);++const storybookDir = getArg('storybook-dir') || 'apps/storybook/dist';+const outputDir = getArg('output-dir') || 'screenshots';+const componentsArg = getArg('components') || '';+const components = componentsArg.split(',').filter(Boolean);+const captureVideo = hasFlag('video');++// Simple static file server with proper MIME types+function createServer(dir, port) {+ return new Promise((resolve) => {+ const server = http.createServer((req, res) => {+ let filePath = path.join(dir, req.url === '/' ? 'index.html' : req.url);++ // Handle query strings+ filePath = filePath.split('?')[0];++ const ext = path.extname(filePath);+ const contentTypes = {+ '.html': 'text/html',+ '.js': 'application/javascript',+ '.mjs': 'application/javascript',+ '.cjs': 'application/javascript',+ '.css': 'text/css',+ '.json': 'application/json',+ '.png': 'image/png',+ '.jpg': 'image/jpeg',+ '.jpeg': 'image/jpeg',+ '.gif': 'image/gif',+ '.svg': 'image/svg+xml',+ '.woff': 'font/woff',+ '.woff2': 'font/woff2',+ '.ttf': 'font/ttf',+ '.eot': 'application/vnd.ms-fontobject',+ };++ fs.readFile(filePath, (err, data) => {+ if (err) {+ res.writeHead(404);+ res.end('Not found');+ return;+ }+ res.writeHead(200, { 'Content-Type': contentTypes[ext] || 'application/octet-stream' });+ res.end(data);+ });+ });++ server.listen(port, () => {+ console.log(`Storybook server running on http://localhost:${port}`);+ resolve(server);+ });+ });+}++// Get stories from storybook+async function getStories(storybookPath) {+ const storiesJsonPath = path.join(storybookPath, 'index.json');++ try {+ const content = fs.readFileSync(storiesJsonPath, 'utf8');+ const data = JSON.parse(content);+ return data.entries || data.stories || {};+ } catch (e) {+ console.error('Could not read stories index:', e.message);+ return {};+ }+}++async function captureScreenshots() {+ console.log('Starting screenshot capture...');+ console.log(`Components to capture: ${components.length > 0 ? components.join(', ') : 'all'}`);++ // Ensure output directory exists+ fs.mkdirSync(outputDir, { recursive: true });++ const storybookPath = path.resolve(process.cwd(), storybookDir);++ if (!fs.existsSync(storybookPath)) {+ console.error(`Storybook build not found at ${storybookPath}`);+ fs.writeFileSync(path.join(outputDir, 'screenshots.json'), JSON.stringify({+ error: 'Storybook not built',+ screenshots: [],+ }));+ return;+ }++ // Start server+ const port = 6006;+ const server = await createServer(storybookPath, port);++ // Get stories+ const stories = await getStories(storybookPath);+ const storyIds = Object.keys(stories);++ console.log(`Found ${storyIds.length} stories`);++ // Filter stories for relevant components - exclude docs pages+ const relevantStories = storyIds.filter(id => {+ // Skip docs pages - they often have rendering issues+ if (id.endsWith('--docs')) return false;++ if (components.length === 0) return true;+ const story = stories[id];+ const title = story.title || '';+ return components.some(comp =>+ title.toLowerCase().includes(comp.toLowerCase()) ||+ id.toLowerCase().includes(comp.toLowerCase())+ );+ });++ console.log(`Capturing ${relevantStories.length} relevant stories`);+ if (captureVideo) {+ console.log('Video capture enabled - will record interactions and convert to GIF');+ }++ const browser = await chromium.launch();++ const screenshots = [];++ for (const storyId of relevantStories) {+ const story = stories[storyId];++ // Create context with video recording if enabled+ const contextOptions = {+ viewport: { width: 800, height: 600 },+ deviceScaleFactor: 2,+ };++ if (captureVideo) {+ contextOptions.recordVideo = {+ dir: path.join(outputDir, 'videos'),+ size: { width: 800, height: 600 },+ };+ // Ensure videos directory exists+ fs.mkdirSync(path.join(outputDir, 'videos'), { recursive: true });+ }++ const context = await browser.newContext(contextOptions);+ const page = await context.newPage();++ try {+ // Navigate to story in iframe mode+ const url = `http://localhost:${port}/iframe.html?id=${storyId}&viewMode=story`;+ await page.goto(url, { waitUntil: 'networkidle', timeout: 30000 });++ // Wait for Storybook to render the story+ await page.waitForSelector('#storybook-root', { timeout: 10000 });++ // Wait for all stylesheets to be loaded+ await page.evaluate(async () => {+ // Wait for all link stylesheets+ const links = Array.from(document.querySelectorAll('link[rel="stylesheet"]'));+ await Promise.all(links.map(link => {+ if (link.sheet) return Promise.resolve();+ return new Promise((resolve) => {+ link.addEventListener('load', resolve);+ link.addEventListener('error', resolve);+ });+ }));++ // Wait for any style elements to be processed+ await new Promise(resolve => requestAnimationFrame(resolve));+ await new Promise(resolve => requestAnimationFrame(resolve));+ });++ // Wait for styles to be injected (StyleX runtime injection)+ await page.waitForTimeout(1500);++ // Wait for any fonts to load+ await page.evaluate(() => document.fonts.ready);++ // Wait for CSS variables to be resolved - check for theme wrapper+ await page.evaluate(async () => {+ // Wait for CSS custom properties to be defined+ const checkStyles = () => {+ const storyRoot = document.querySelector('#storybook-root');+ if (!storyRoot) return false;++ // Check if any element has computed styles (not just default)+ const firstChild = storyRoot.querySelector('*');+ if (firstChild) {+ const styles = getComputedStyle(firstChild);+ // Check if display is not empty (styles are applied)+ return styles.display !== '';+ }+ return true;+ };++ // Poll for styles to be ready+ for (let i = 0; i < 20; i++) {+ if (checkStyles()) break;+ await new Promise(r => setTimeout(r, 100));+ }+ });++ // Additional wait for any CSS transitions/animations+ await page.waitForTimeout(500);++ // If capturing video, ensure we have some content recorded+ if (captureVideo) {+ // Wait to ensure video has content+ await page.waitForTimeout(500);+ }++ // Take screenshot of just the story root+ const storyRoot = await page.$('#storybook-root');++ const screenshotFilename = `${storyId.replace(/[^a-z0-9]/gi, '-')}.png`;+ const screenshotPath = path.join(outputDir, screenshotFilename);++ if (storyRoot) {+ await storyRoot.screenshot({ path: screenshotPath });+ } else {+ await page.screenshot({ path: screenshotPath, fullPage: false });+ }++ const result = {+ storyId,+ title: story.title,+ name: story.name,+ filename: screenshotFilename,+ };++ // If capturing video, simulate some interactions with visible cursor+ if (captureVideo) {+ // Inject a visible cursor element+ await page.evaluate(() => {+ const cursor = document.createElement('div');+ cursor.id = 'playwright-cursor';+ cursor.innerHTML = `+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">+ <path d="M5.5 3.21V20.8C5.5 21.3 5.74 21.48 6.09 21.21L10.85 17.38L14.03 23.44C14.16 23.69 14.45 23.8 14.71 23.67L16.81 22.62C17.07 22.49 17.18 22.2 17.05 21.94L13.86 15.87L19.77 14.82C20.19 14.74 20.3 14.41 19.99 14.13L6.41 2.93C6.1 2.65 5.5 2.75 5.5 3.21Z" fill="white" stroke="black" stroke-width="1.5"/>+ </svg>+ `;+ cursor.style.cssText = `+ position: fixed;+ top: 100px;+ left: 100px;+ width: 24px;+ height: 24px;+ pointer-events: none;+ z-index: 999999;+ transform: translate(-2px, -2px);+ `;+ document.body.appendChild(cursor);++ // Expose function to update cursor position+ window.updateCursor = (x, y) => {+ cursor.style.left = x + 'px';+ cursor.style.top = y + 'px';+ };+ });++ // Helper function to move cursor smoothly to a position+ const moveCursorTo = async (targetX, targetY) => {+ // Get current cursor position+ const pos = await page.evaluate(() => {+ const cursor = document.getElementById('playwright-cursor');+ return {+ x: parseFloat(cursor.style.left) || 100,+ y: parseFloat(cursor.style.top) || 100+ };+ });++ // Animate cursor movement in steps+ const steps = 15;+ for (let i = 1; i <= steps; i++) {+ const x = pos.x + (targetX - pos.x) * (i / steps);+ const y = pos.y + (targetY - pos.y) * (i / steps);++ // Update cursor position directly+ await page.evaluate(({x, y}) => {+ window.updateCursor(x, y);+ }, {x, y});++ // Also move the actual mouse to trigger hover effects+ await page.mouse.move(x, y);+ await page.waitForTimeout(25);+ }+ };++ // Helper to move to element center+ const moveCursorToElement = async (element) => {+ const box = await element.boundingBox();+ if (!box) return false;+ await moveCursorTo(box.x + box.width / 2, box.y + box.height / 2);+ return true;+ };++ // Start cursor in center+ await page.evaluate(() => window.updateCursor(400, 300));+ await page.waitForTimeout(500);++ // Hover over interactive elements to show hover states+ const buttons = await page.$$('button');+ for (const button of buttons.slice(0, 3)) {+ try {+ if (await moveCursorToElement(button)) {+ await page.waitForTimeout(500);+ }+ } catch {+ // Element not hoverable, skip+ }+ }++ // Hover over links+ const links = await page.$$('a');+ for (const link of links.slice(0, 2)) {+ try {+ if (await moveCursorToElement(link)) {+ await page.waitForTimeout(500);+ }+ } catch {+ // Element not hoverable, skip+ }+ }++ // Hover over spans (badges, etc)+ const spans = await page.$$('span[class]');+ for (const span of spans.slice(0, 6)) {+ try {+ if (await moveCursorToElement(span)) {+ await page.waitForTimeout(400);+ }+ } catch {+ // Element not hoverable, skip+ }+ }++ // Move cursor away and wait+ await moveCursorTo(50, 50);+ await page.waitForTimeout(500);+ }++ // Close page to finalize video recording+ await page.close();++ let videoPath = null;+ if (captureVideo) {+ const video = page.video();+ if (video) {+ // Wait for video to be saved - this resolves when the file is ready+ try {+ videoPath = await video.path();+ } catch (e) {+ console.error(`[warn] Failed to get video path for ${storyId}: ${e.message}`);+ }+ }+ }++ // Close context - this is when video is fully written+ await context.close();++ // Now process video after context is closed+ if (captureVideo && videoPath) {+ // Give filesystem time to sync+ await new Promise(r => setTimeout(r, 500));++ // Ensure the video file exists and has content+ const videoStats = fs.existsSync(videoPath) ? fs.statSync(videoPath) : null;++ if (videoStats && videoStats.size > 1000) {+ // Convert to GIF using ffmpeg+ const gifFilename = `${storyId.replace(/[^a-z0-9]/gi, '-')}.gif`;+ const gifPath = path.join(outputDir, gifFilename);++ // Also keep the video as mp4 for better quality viewing+ const mp4Filename = `${storyId.replace(/[^a-z0-9]/gi, '-')}.mp4`;+ const mp4Path = path.join(outputDir, mp4Filename);++ try {+ // Convert webm to mp4 for broader compatibility+ execSync(+ `ffmpeg -i "${videoPath}" -c:v libx264 -preset fast -crf 23 "${mp4Path}" -y 2>&1`,+ { stdio: 'pipe', timeout: 30000 }+ );++ if (fs.existsSync(mp4Path) && fs.statSync(mp4Path).size > 100) {+ result.mp4Filename = mp4Filename;+ }+ } catch (e) {+ console.error(`[warn] MP4 conversion failed for ${storyId}: ${e.message}`);+ }++ try {+ // Use ffmpeg to convert webm to gif (with palette for better quality)+ // Add -t 5 to limit to 5 seconds max, and use simpler filter for reliability+ execSync(+ `ffmpeg -i "${videoPath}" -t 5 -vf "fps=8,scale=400:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse" -loop 0 "${gifPath}" -y 2>&1`,+ { stdio: 'pipe', timeout: 30000 }+ );++ // Verify GIF was created+ if (fs.existsSync(gifPath) && fs.statSync(gifPath).size > 100) {+ result.videoFilename = gifFilename;+ console.log(`[ok] Video: ${story.title} / ${story.name} (${videoStats.size} bytes webm -> gif + mp4)`);+ } else {+ console.error(`[warn] GIF file empty or not created for ${storyId}`);+ }+ } catch (e) {+ console.error(`[warn] GIF conversion failed for ${storyId}: ${e.message}`);+ }++ // Clean up webm file+ try {+ fs.unlinkSync(videoPath);+ } catch {}+ } else {+ console.error(`[warn] Video file too small or missing for ${storyId}: ${videoStats?.size || 0} bytes`);+ // Clean up invalid webm file+ try {+ if (videoPath && fs.existsSync(videoPath)) fs.unlinkSync(videoPath);+ } catch {}+ }+ }++ screenshots.push(result);++ console.log(`[ok] Captured: ${story.title} / ${story.name}`);+ } catch (e) {+ console.error(`[fail] Failed: ${storyId} - ${e.message}`);+ await context.close();+ }+ }++ await browser.close();+ server.close();++ // Clean up videos directory if empty+ try {+ const videosDir = path.join(outputDir, 'videos');+ if (fs.existsSync(videosDir) && fs.readdirSync(videosDir).length === 0) {+ fs.rmdirSync(videosDir);+ }+ } catch {}++ // Write manifest+ fs.writeFileSync(+ path.join(outputDir, 'screenshots.json'),+ JSON.stringify({+ screenshots,+ hasVideos: captureVideo,+ capturedAt: new Date().toISOString()+ }, null, 2)+ );++ console.log(`\nCaptured ${screenshots.length} screenshots${captureVideo ? ' with videos' : ''}`);+}++captureScreenshots().catch(e => {+ console.error('Screenshot capture failed:', e);+ process.exit(1);+});diff --git a/.github/scripts/generate-pr-comment.js b/.github/scripts/generate-pr-comment.jsnew file mode 100644index 0000000000..4ba0dd5b24--- /dev/null+++ b/.github/scripts/generate-pr-comment.js@@ -0,0 +1,206 @@+#!/usr/bin/env node++/**+ * @description Generates and posts PR comment with analysis results and embedded screenshots+ * @input --analysis <file> --a11y <file> --screenshots <file> --screenshot-urls <file> --run-url <url>+ * @output Formatted markdown comment body to stdout+ */++const fs = require('fs');++const args = process.argv.slice(2);+const getArg = (name) => {+ const idx = args.indexOf(`--${name}`);+ return idx !== -1 ? args[idx + 1] : null;+};++const analysisFile = getArg('analysis') || 'analysis.json';+const a11yFile = getArg('a11y') || 'a11y-report.json';+const screenshotsFile = getArg('screenshots') || 'screenshots/screenshots.json';+const screenshotUrlsFile = getArg('screenshot-urls') || 'screenshot-urls.json';+const runUrl = getArg('run-url') || '';+const prNumber = getArg('pr-number') || '';++// Read analysis results+let analysis = { newComponents: [], modifiedComponents: [], componentStats: {}, totalBundle: {} };+let a11yReport = { components: {} };+let screenshotsData = { screenshots: [] };+let screenshotUrls = {};++try {+ analysis = JSON.parse(fs.readFileSync(analysisFile, 'utf8'));+} catch (e) {+ console.error('Warning: Could not read analysis file:', e.message);+}++try {+ a11yReport = JSON.parse(fs.readFileSync(a11yFile, 'utf8'));+} catch (e) {+ console.error('Warning: Could not read a11y report:', e.message);+}++try {+ screenshotsData = JSON.parse(fs.readFileSync(screenshotsFile, 'utf8'));+} catch (e) {+ console.error('Warning: Could not read screenshots manifest:', e.message);+}++try {+ screenshotUrls = JSON.parse(fs.readFileSync(screenshotUrlsFile, 'utf8'));+} catch (e) {+ console.error('Warning: Could not read screenshot URLs:', e.message);+}++// Build component stats section+let componentSection = '';+if (analysis.newComponents && analysis.newComponents.length > 0) {+ componentSection += `### New Components\n\n`;+ for (const comp of analysis.newComponents) {+ const stats = analysis.componentStats[comp] || {};+ componentSection += `<details>\n<summary><strong>${comp}</strong></summary>\n\n`;+ componentSection += `| Metric | Value |\n|--------|-------|\n`;+ componentSection += `| Bundle Size (ESM) | ${stats.esmSize || 'N/A'} |\n`;+ componentSection += `| Bundle Size (CJS) | ${stats.cjsSize || 'N/A'} |\n`;+ componentSection += `| Lines of Code | ${stats.linesOfCode || 'N/A'} |\n`;+ componentSection += `| Source Files | ${stats.fileCount || 'N/A'} |\n`;+ componentSection += `| Complexity | ${stats.complexityRating || 'N/A'} (${stats.complexity || 0}) |\n`;+ componentSection += `| Exports | ${stats.exports?.join(', ') || 'N/A'} |\n`;+ componentSection += `| Props Count | ${stats.propsCount || 'N/A'} |\n`;+ componentSection += `| Has Tests | ${stats.hasTests ? 'Yes' : 'No'} |\n`;+ componentSection += `| Has Stories | ${stats.hasStories ? 'Yes' : 'No'} |\n`;+ componentSection += `\n</details>\n\n`;+ }+}++if (analysis.modifiedComponents && analysis.modifiedComponents.length > 0) {+ componentSection += `### Modified Components\n\n`;+ for (const comp of analysis.modifiedComponents) {+ const stats = analysis.componentStats[comp] || {};+ const baseStats = analysis.baseComponentStats?.[comp] || {};+ componentSection += `<details>\n<summary><strong>${comp}</strong></summary>\n\n`;+ componentSection += `| Metric | Before | After | Delta |\n|--------|--------|-------|-------|\n`;++ const esmDelta = stats.esmBytes && baseStats.esmBytes+ ? (stats.esmBytes - baseStats.esmBytes)+ : null;+ const esmDeltaStr = esmDelta !== null+ ? (esmDelta > 0 ? `+${esmDelta}B` : `${esmDelta}B`)+ : 'N/A';++ componentSection += `| Bundle Size (ESM) | ${baseStats.esmSize || 'N/A'} | ${stats.esmSize || 'N/A'} | ${esmDeltaStr} |\n`;+ componentSection += `| Lines of Code | ${baseStats.linesOfCode || 'N/A'} | ${stats.linesOfCode || 'N/A'} | - |\n`;+ componentSection += `| Complexity | ${baseStats.complexityRating || 'N/A'} | ${stats.complexityRating || 'N/A'} (${stats.complexity || 0}) | - |\n`;+ componentSection += `\n</details>\n\n`;+ }+}++// Build accessibility section+let a11ySection = '### Accessibility Audit\n\n';+const totalViolations = Object.values(a11yReport.components || {})+ .reduce((sum, comp) => sum + (comp.violations?.length || 0), 0);++if (totalViolations === 0) {+ a11ySection += '**Status:** No accessibility violations detected.\n\n';+} else {+ a11ySection += `**Status:** ${totalViolations} accessibility violation(s) found.\n\n`;+ for (const [compName, compReport] of Object.entries(a11yReport.components || {})) {+ if (compReport.violations?.length > 0) {+ a11ySection += `<details>\n<summary><strong>${compName}</strong> - ${compReport.violations.length} issue(s)</summary>\n\n`;+ for (const violation of compReport.violations) {+ a11ySection += `- **${violation.impact}**: ${violation.description}\n`;+ a11ySection += ` - Rule: \`${violation.id}\`\n`;+ }+ a11ySection += `\n</details>\n\n`;+ }+ }+}++// Build bundle size section+let bundleSection = '### Bundle Size Summary\n\n';+bundleSection += `| Package | Size (ESM) | Size (CJS) | Gzipped |\n`;+bundleSection += `|---------|------------|------------|----------|\n`;+bundleSection += `| @xds/core | ${analysis.totalBundle?.esmSize || 'N/A'} | ${analysis.totalBundle?.cjsSize || 'N/A'} | ${analysis.totalBundle?.gzipSize || 'N/A'} |\n\n`;++if (analysis.bundleDelta) {+ const delta = analysis.bundleDelta;+ const direction = delta > 0 ? 'increased' : delta < 0 ? 'decreased' : 'unchanged';+ bundleSection += `**Bundle size ${direction}:** ${delta > 0 ? '+' : ''}${delta} bytes\n\n`;+}++// Build screenshots section with embedded images+let screenshotSection = '';+const hasAffectedComponents = (analysis.newComponents?.length > 0) || (analysis.modifiedComponents?.length > 0);+const screenshots = screenshotsData.screenshots || [];++if (hasAffectedComponents && screenshots.length > 0) {+ screenshotSection = `### Component Previews\n\n`;++ const hasVideos = screenshots.some(s => s.videoFilename);+ if (hasVideos) {+ screenshotSection += `_Includes interactive hover previews as animated GIFs._\n\n`;+ }++ // Group screenshots by component title+ const byComponent = {};+ for (const shot of screenshots) {+ const compName = shot.title?.split('/').pop() || shot.title || 'Unknown';+ if (!byComponent[compName]) {+ byComponent[compName] = [];+ }+ byComponent[compName].push(shot);+ }++ for (const [compName, shots] of Object.entries(byComponent)) {+ screenshotSection += `#### ${compName}\n\n`;++ for (const shot of shots) {+ const storyName = shot.name || shot.storyId;+ const filename = shot.filename;+ const imageUrl = screenshotUrls[filename];+ const videoFilename = shot.videoFilename;+ const videoUrl = videoFilename ? screenshotUrls[videoFilename] : null;+ const mp4Filename = shot.mp4Filename;+ const mp4Url = mp4Filename ? screenshotUrls[mp4Filename] : null;++ if (imageUrl || videoUrl) {+ screenshotSection += `<details>\n<summary><strong>${storyName}</strong></summary>\n\n`;++ if (imageUrl) {+ screenshotSection += `**Screenshot:**\n\n\n\n`;+ }++ if (videoUrl) {+ // Link to mp4 if available, otherwise link to gif+ const fullVideoUrl = mp4Url || videoUrl;+ screenshotSection += `**Interaction Preview:** ([view video](${fullVideoUrl}))\n\n\n\n`;+ }++ screenshotSection += `Run \`yarn storybook\` and navigate to: \`${shot.storyId}\`\n\n`;++ screenshotSection += `</details>\n\n`;+ } else {+ screenshotSection += `- **${storyName}** _(media not available)_\n`;+ }+ }+ }+}++// Build footer with links+let footerLinks = [];+if (runUrl) footerLinks.push(`[View full report](${runUrl})`);+const footerLinksStr = footerLinks.length > 0 ? ` | ${footerLinks.join(' | ')}` : '';++// Build the full comment+const body = `## PR Analysis Report++${componentSection || '_No new or modified components detected._\n\n'}+${bundleSection}+${a11ySection}+${screenshotSection}+---++<sub>Generated by PR Enrichment workflow${footerLinksStr}</sub>+`;++// Output to stdout+console.log(body);diff --git a/.github/scripts/test-pr-enrichment.js b/.github/scripts/test-pr-enrichment.jsnew file mode 100644index 0000000000..cb80fed1b3--- /dev/null+++ b/.github/scripts/test-pr-enrichment.js@@ -0,0 +1,222 @@+#!/usr/bin/env node++/**+ * Test script to verify PR enrichment output with mock data+ */++const fs = require('fs');+const path = require('path');++// Mock analysis data+const mockAnalysis = {+ newComponents: ['DatePicker', 'TimePicker'],+ modifiedComponents: ['Button', 'TextInput'],+ componentStats: {+ DatePicker: {+ esmSize: '4.2KB',+ esmBytes: 4300,+ cjsSize: '4.8KB',+ cjsBytes: 4900,+ exports: ['XDSDatePicker', 'DatePickerProps'],+ propsCount: 12,+ hasTests: true,+ hasStories: true,+ },+ TimePicker: {+ esmSize: '3.1KB',+ esmBytes: 3200,+ cjsSize: '3.5KB',+ cjsBytes: 3600,+ exports: ['XDSTimePicker'],+ propsCount: 8,+ hasTests: false,+ hasStories: true,+ },+ Button: {+ esmSize: '2.4KB',+ esmBytes: 2450,+ cjsSize: '2.8KB',+ cjsBytes: 2870,+ exports: ['XDSButton', 'ButtonProps'],+ propsCount: 15,+ hasTests: true,+ hasStories: true,+ },+ TextInput: {+ esmSize: '3.0KB',+ esmBytes: 3100,+ cjsSize: '3.4KB',+ cjsBytes: 3500,+ exports: ['XDSTextInput'],+ propsCount: 20,+ hasTests: true,+ hasStories: true,+ },+ },+ baseComponentStats: {+ Button: {+ esmSize: '2.2KB',+ esmBytes: 2250,+ },+ TextInput: {+ esmSize: '2.9KB',+ esmBytes: 2970,+ },+ },+ totalBundle: {+ esmSize: '45.2KB',+ esmBytes: 46280,+ cjsSize: '52.1KB',+ cjsBytes: 53350,+ gzipSize: '12.4KB',+ },+ bundleDelta: 850,+ analyzedAt: new Date().toISOString(),+};++// Mock a11y report+const mockA11y = {+ components: {+ DatePicker: {+ storiesAudited: 3,+ violations: [],+ storyDetails: [],+ },+ TimePicker: {+ storiesAudited: 2,+ violations: [+ {+ id: 'label',+ impact: 'critical',+ description: 'Form elements must have labels',+ },+ ],+ storyDetails: [],+ },+ },+ summary: {+ componentsAudited: 2,+ totalViolations: 1,+ auditedAt: new Date().toISOString(),+ },+};++// Write mock files+const tmpDir = '/tmp/pr-enrichment-test';+fs.mkdirSync(tmpDir, { recursive: true });++fs.writeFileSync(+ path.join(tmpDir, 'analysis.json'),+ JSON.stringify(mockAnalysis, null, 2)+);++fs.writeFileSync(+ path.join(tmpDir, 'a11y-report.json'),+ JSON.stringify(mockA11y, null, 2)+);++console.log('Mock data written to:', tmpDir);+console.log('\nTo test the comment generator, run:');+console.log(` node .github/scripts/generate-pr-comment.js \\`);+console.log(` --analysis ${tmpDir}/analysis.json \\`);+console.log(` --a11y ${tmpDir}/a11y-report.json \\`);+console.log(` --run-url "https://github.com/example/xds/actions/runs/12345"`);+console.log('\n--- Sample Output ---\n');++// Now run the generator inline to show output+const analysis = mockAnalysis;+const a11yReport = mockA11y;+const runUrl = 'https://github.com/example/xds/actions/runs/12345';++// Build component stats section+let componentSection = '';+if (analysis.newComponents && analysis.newComponents.length > 0) {+ componentSection += `### New Components\n\n`;+ for (const comp of analysis.newComponents) {+ const stats = analysis.componentStats[comp] || {};+ componentSection += `<details>\n<summary><strong>${comp}</strong></summary>\n\n`;+ componentSection += `| Metric | Value |\n|--------|-------|\n`;+ componentSection += `| Bundle Size (ESM) | ${stats.esmSize || 'N/A'} |\n`;+ componentSection += `| Bundle Size (CJS) | ${stats.cjsSize || 'N/A'} |\n`;+ componentSection += `| Exports | ${stats.exports?.join(', ') || 'N/A'} |\n`;+ componentSection += `| Props Count | ${stats.propsCount || 'N/A'} |\n`;+ componentSection += `| Has Tests | ${stats.hasTests ? 'Yes' : 'No'} |\n`;+ componentSection += `| Has Stories | ${stats.hasStories ? 'Yes' : 'No'} |\n`;+ componentSection += `\n</details>\n\n`;+ }+}++if (analysis.modifiedComponents && analysis.modifiedComponents.length > 0) {+ componentSection += `### Modified Components\n\n`;+ for (const comp of analysis.modifiedComponents) {+ const stats = analysis.componentStats[comp] || {};+ const baseStats = analysis.baseComponentStats?.[comp] || {};+ componentSection += `<details>\n<summary><strong>${comp}</strong></summary>\n\n`;+ componentSection += `| Metric | Before | After | Delta |\n|--------|--------|-------|-------|\n`;++ const esmDelta = stats.esmBytes && baseStats.esmBytes+ ? (stats.esmBytes - baseStats.esmBytes)+ : null;+ const esmDeltaStr = esmDelta !== null+ ? (esmDelta > 0 ? `+${esmDelta}B` : `${esmDelta}B`)+ : 'N/A';++ componentSection += `| Bundle Size (ESM) | ${baseStats.esmSize || 'N/A'} | ${stats.esmSize || 'N/A'} | ${esmDeltaStr} |\n`;+ componentSection += `\n</details>\n\n`;+ }+}++// Build accessibility section+let a11ySection = '### Accessibility Audit\n\n';+const totalViolations = Object.values(a11yReport.components || {})+ .reduce((sum, comp) => sum + (comp.violations?.length || 0), 0);++if (totalViolations === 0) {+ a11ySection += '**Status:** No accessibility violations detected.\n\n';+} else {+ a11ySection += `**Status:** ${totalViolations} accessibility violation(s) found.\n\n`;+ for (const [compName, compReport] of Object.entries(a11yReport.components || {})) {+ if (compReport.violations?.length > 0) {+ a11ySection += `<details>\n<summary><strong>${compName}</strong> - ${compReport.violations.length} issue(s)</summary>\n\n`;+ for (const violation of compReport.violations) {+ a11ySection += `- **${violation.impact}**: ${violation.description}\n`;+ a11ySection += ` - Rule: \`${violation.id}\`\n`;+ }+ a11ySection += `\n</details>\n\n`;+ }+ }+}++// Build bundle size section+let bundleSection = '### Bundle Size Summary\n\n';+bundleSection += `| Package | Size (ESM) | Size (CJS) | Gzipped |\n`;+bundleSection += `|---------|------------|------------|----------|\n`;+bundleSection += `| @xds/core | ${analysis.totalBundle?.esmSize || 'N/A'} | ${analysis.totalBundle?.cjsSize || 'N/A'} | ${analysis.totalBundle?.gzipSize || 'N/A'} |\n\n`;++if (analysis.bundleDelta) {+ const delta = analysis.bundleDelta;+ const direction = delta > 0 ? 'increased' : delta < 0 ? 'decreased' : 'unchanged';+ bundleSection += `**Bundle size ${direction}:** ${delta > 0 ? '+' : ''}${delta} bytes\n\n`;+}++// Build screenshots section+let screenshotSection = '';+const hasAffectedComponents = (analysis.newComponents?.length > 0) || (analysis.modifiedComponents?.length > 0);+if (hasAffectedComponents && runUrl) {+ screenshotSection = `### Component Previews\n\n`;+ screenshotSection += `Component screenshots are available in the [workflow artifacts](${runUrl}).\n\n`;+}++// Build the full comment+const body = `## PR Analysis Report++${componentSection || '_No new or modified components detected._\n\n'}+${bundleSection}+${a11ySection}+${screenshotSection}+---++<sub>Generated by PR Enrichment workflow${runUrl ? ` | [View full report](${runUrl})` : ''}</sub>+`;++console.log(body);diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.ymlnew file mode 100644index 0000000000..c09c012223--- /dev/null+++ b/.github/workflows/lint.yml@@ -0,0 +1,34 @@+name: Lint++on:+ push:+ branches: [main]+ pull_request:+ branches: [main]++jobs:+ lint:+ runs-on: ubuntu-latest+ permissions:+ contents: read+ pull-requests: write+ checks: write++ steps:+ - uses: actions/checkout@v4++ - uses: actions/setup-node@v4+ with:+ node-version: 20+ cache: 'yarn'++ - run: yarn install --frozen-lockfile++ - name: Run ESLint+ uses: reviewdog/action-eslint@v1+ with:+ github_token: ${{ secrets.GITHUB_TOKEN }}+ reporter: github-pr-review+ eslint_flags: '--max-warnings 0 packages/core/src/'+ fail_on_error: true+ filter_mode: nofilterdiff --git a/.github/workflows/pr-enrichment.yml b/.github/workflows/pr-enrichment.ymlnew file mode 100644index 0000000000..0d4b4372c3--- /dev/null+++ b/.github/workflows/pr-enrichment.yml@@ -0,0 +1,186 @@+name: PR Enrichment++on:+ pull_request:+ branches: [main]++concurrency:+ group: pr-enrichment-${{ github.head_ref || github.ref }}+ cancel-in-progress: true++jobs:+ analyze:+ name: Analyze PR+ runs-on: ubuntu-latest+ permissions:+ contents: write+ pull-requests: write+ actions: read++ steps:+ - name: Checkout PR+ uses: actions/checkout@v4+ with:+ fetch-depth: 0++ - name: Checkout base branch for comparison+ run: git fetch origin ${{ github.base_ref }}:base-branch++ - name: Setup Node.js+ uses: actions/setup-node@v4+ with:+ node-version: '22'+ cache: 'yarn'++ - name: Install dependencies+ run: yarn install --frozen-lockfile++ - name: Build packages+ run: yarn build++ - name: Analyze components+ id: analyze+ run: |+ node .github/scripts/analyze-pr.js \+ --base base-branch \+ --head HEAD \+ --output analysis.json++ - name: Build Storybook+ run: yarn storybook:build++ - name: Install Playwright+ run: npx playwright install chromium++ - name: Install ffmpeg for video conversion+ run: sudo apt-get update && sudo apt-get install -y ffmpeg++ - name: Capture component screenshots and videos+ id: screenshots+ run: |+ COMPONENTS=$(cat analysis.json | jq -r '(.newComponents + .modifiedComponents) | join(",")')+ node .github/scripts/capture-screenshots.js \+ --storybook-dir apps/storybook/dist \+ --output-dir screenshots \+ --components "$COMPONENTS" \+ --video++ - name: Upload screenshots and videos to GitHub+ id: upload_screenshots+ env:+ REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ run: |+ # Install CML CLI only (no visualization deps)+ npm install -g @dvcorg/cml++ # Upload each screenshot and video, collect URLs+ echo '{}' > screenshot-urls.json++ # Upload PNG screenshots+ for file in screenshots/*.png; do+ if [ -f "$file" ]; then+ filename=$(basename "$file")+ url=$(cml publish "$file")+ echo "Uploaded $filename -> $url"+ jq --arg name "$filename" --arg url "$url" \+ '. + {($name): $url}' screenshot-urls.json > tmp.json && mv tmp.json screenshot-urls.json+ fi+ done++ # Upload GIF videos+ for file in screenshots/*.gif; do+ if [ -f "$file" ]; then+ filename=$(basename "$file")+ url=$(cml publish "$file")+ echo "Uploaded $filename -> $url"+ jq --arg name "$filename" --arg url "$url" \+ '. + {($name): $url}' screenshot-urls.json > tmp.json && mv tmp.json screenshot-urls.json+ fi+ done++ # Upload MP4 videos+ for file in screenshots/*.mp4; do+ if [ -f "$file" ]; then+ filename=$(basename "$file")+ url=$(cml publish "$file")+ echo "Uploaded $filename -> $url"+ jq --arg name "$filename" --arg url "$url" \+ '. + {($name): $url}' screenshot-urls.json > tmp.json && mv tmp.json screenshot-urls.json+ fi+ done++ cat screenshot-urls.json++ - name: Run accessibility audit+ id: a11y+ run: |+ COMPONENTS=$(cat analysis.json | jq -r '(.newComponents + .modifiedComponents) | join(",")')+ node .github/scripts/accessibility-audit.js \+ --storybook-dir apps/storybook/dist \+ --output a11y-report.json \+ --components "$COMPONENTS"++ - name: Upload screenshots artifact+ uses: actions/upload-artifact@v4+ with:+ name: component-screenshots+ path: screenshots/+ retention-days: 30++ - name: Upload Storybook artifact+ uses: actions/upload-artifact@v4+ with:+ name: storybook-build+ path: apps/storybook/dist/+ retention-days: 30++ - name: Generate PR comment+ id: comment+ run: |+ RUN_URL="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"++ COMMENT_BODY=$(node .github/scripts/generate-pr-comment.js \+ --analysis analysis.json \+ --a11y a11y-report.json \+ --screenshots screenshots/screenshots.json \+ --screenshot-urls screenshot-urls.json \+ --run-url "$RUN_URL" \+ --pr-number "${{ github.event.pull_request.number }}")++ # Save to file for the next step+ echo "$COMMENT_BODY" > pr-comment.md++ - name: Comment on PR+ uses: actions/github-script@v7+ with:+ script: |+ const fs = require('fs');+ const body = fs.readFileSync('pr-comment.md', 'utf8');++ // Find and update existing comment+ const { data: comments } = await github.rest.issues.listComments({+ owner: context.repo.owner,+ repo: context.repo.repo,+ issue_number: context.issue.number,+ });++ const botComment = comments.find(comment =>+ comment.user.type === 'Bot' &&+ comment.body.includes('PR Analysis Report')+ );++ if (botComment) {+ await github.rest.issues.updateComment({+ owner: context.repo.owner,+ repo: context.repo.repo,+ comment_id: botComment.id,+ body: body+ });+ } else {+ await github.rest.issues.createComment({+ owner: context.repo.owner,+ repo: context.repo.repo,+ issue_number: context.issue.number,+ body: body+ });+ }diff --git a/apps/storybook/.storybook/main.ts b/apps/storybook/.storybook/main.tsindex 4d20727d8f..964bb170b0 100644--- a/apps/storybook/.storybook/main.ts+++ b/apps/storybook/.storybook/main.ts@@ -1,10 +1,15 @@import type { StorybookConfig } from '@storybook/react-vite';import { join, dirname } from 'path';+import stylex from '@stylexjs/unplugin';+import path from 'path';function getAbsolutePath(value: string): string {return dirname(require.resolve(join(value, 'package.json')));}+const rootDir = path.resolve(__dirname, '../../..');+const coreRoot = path.resolve(__dirname, '../../../packages/core/src');+const config: StorybookConfig = {stories: ['../stories/**/*.mdx',@@ -22,6 +27,40 @@ const config: StorybookConfig = {docs: {autodocs: 'tag',},+ viteFinal: async (config) => {+ // Filter out any existing StyleX plugins to avoid conflicts+ const filteredPlugins = config.plugins?.filter(+ (plugin: any) => !(plugin?.name?.includes?.('stylex'))+ ) || [];++ return {+ ...config,+ plugins: [+ ...filteredPlugins,+ stylex.vite({+ // Use production mode with CSS extraction+ dev: false,+ useCSSLayers: true,+ styleResolution: 'application-order',+ aliases: {+ '@xds/core/*': [path.join(rootDir, 'packages/core/src/*')],+ '@xds/core': [path.join(rootDir, 'packages/core/src')],+ },+ unstable_moduleResolution: {+ type: 'commonJS',+ rootDir: rootDir,+ },+ }),+ ],+ resolve: {+ ...config.resolve,+ alias: {+ ...config.resolve?.alias,+ '@xds/core': coreRoot,+ },+ },+ };+ },};export default config;diff --git a/apps/storybook/.storybook/preview.tsx b/apps/storybook/.storybook/preview.tsxindex e5a54361a3..37a4f2b981 100644--- a/apps/storybook/.storybook/preview.tsx+++ b/apps/storybook/.storybook/preview.tsx@@ -2,6 +2,10 @@ import type {Preview, Decorator} from '@storybook/react';import * as React from 'react';import {XDSTheme, defaultTheme, neutralTheme} from '@xds/core';+// Import the pre-built StyleX CSS from the core package+// Use relative path since @xds/core alias points to source, not dist+import '../../../packages/core/dist/index.css';+/*** Map of available themes*/diff --git a/apps/storybook/stories/Badge.stories.tsx b/apps/storybook/stories/Badge.stories.tsxnew file mode 100644index 0000000000..838e60adb5--- /dev/null+++ b/apps/storybook/stories/Badge.stories.tsx@@ -0,0 +1,73 @@+import type {Meta, StoryObj} from '@storybook/react';+import {XDSBadge} from '@xds/core/Badge';++const meta: Meta<typeof XDSBadge> = {+ title: 'Core/XDSBadge',+ component: XDSBadge,+ tags: ['autodocs'],+ argTypes: {+ variant: {+ control: 'select',+ options: ['neutral', 'info', 'success', 'warning', 'error'],+ description: 'Visual style variant',+ },+ children: {+ control: 'text',+ description: 'Badge content',+ },+ },+};++export default meta;+type Story = StoryObj<typeof XDSBadge>;++export const Default: Story = {+ args: {+ children: 'Badge',+ },+};++export const Variants: Story = {+ render: () => (+ <div style={{display: 'flex', gap: '8px', alignItems: 'center'}}>+ <XDSBadge variant="neutral">Neutral</XDSBadge>+ <XDSBadge variant="info">Info</XDSBadge>+ <XDSBadge variant="success">Success</XDSBadge>+ <XDSBadge variant="warning">Warning</XDSBadge>+ <XDSBadge variant="error">Error</XDSBadge>+ </div>+ ),+};++export const Counts: Story = {+ render: () => (+ <div style={{display: 'flex', gap: '8px', alignItems: 'center'}}>+ <XDSBadge variant="info">3</XDSBadge>+ <XDSBadge variant="error">99+</XDSBadge>+ <XDSBadge variant="success">12</XDSBadge>+ </div>+ ),+};++export const DotIndicators: Story = {+ render: () => (+ <div style={{display: 'flex', gap: '8px', alignItems: 'center'}}>+ <XDSBadge variant="neutral" />+ <XDSBadge variant="info" />+ <XDSBadge variant="success" />+ <XDSBadge variant="warning" />+ <XDSBadge variant="error" />+ </div>+ ),+};++export const StatusLabels: Story = {+ render: () => (+ <div style={{display: 'flex', gap: '8px', alignItems: 'center'}}>+ <XDSBadge variant="success">Active</XDSBadge>+ <XDSBadge variant="warning">Pending</XDSBadge>+ <XDSBadge variant="error">Failed</XDSBadge>+ <XDSBadge variant="neutral">Draft</XDSBadge>+ </div>+ ),+};diff --git a/apps/storybook/vite.config.ts b/apps/storybook/vite.config.tsindex 22a2674f6f..83a484904e 100644--- a/apps/storybook/vite.config.ts+++ b/apps/storybook/vite.config.ts@@ -18,7 +18,8 @@ const coreRoot = path.resolve(__dirname, '../../packages/core/src');export default defineConfig({plugins: [stylex.vite({- dev: process.env.NODE_ENV === 'development',+ // Use production mode with CSS extraction+ dev: false,useCSSLayers: true,styleResolution: 'application-order',aliases: {diff --git a/eslint.config.js b/eslint.config.jsindex e5e65047d7..e07eb056e0 100644--- a/eslint.config.js+++ b/eslint.config.js@@ -1,11 +1,28 @@import js from "@eslint/js";import tseslint from "typescript-eslint";+import xdsPlugin from "./internal/eslint-plugin-xds/index.js";++/**+ * XDS ESLint Configuration+ *+ * Two-tier linting philosophy:+ * - CI/Agents: Strict mode (errors) - Set XDS_STRICT_LINT=1 or CI=true+ * - Humans: Recommended mode (warnings) - Default for local development+ *+ * Usage:+ * yarn lint # Human mode (warnings)+ * XDS_STRICT_LINT=1 yarn lint # Strict mode (errors)+ * CI=true yarn lint # Also triggers strict mode+ */++const isStrictMode = process.env.XDS_STRICT_LINT === '1' || process.env.CI === 'true';+const xdsConfig = isStrictMode ? xdsPlugin.configs.strict : xdsPlugin.configs.recommended;export default tseslint.config(js.configs.recommended,...tseslint.configs.recommended,{- ignores: ["**/dist/**", "**/node_modules/**"],+ ignores: ["**/dist/**", "**/node_modules/**", "**/internal/eslint-plugin-xds/**"],},{files: ["**/*.{ts,tsx}"],@@ -20,4 +37,9 @@ export default tseslint.config("@typescript-eslint/no-unused-vars": "warn",},},+ // XDS design token enforcement - applies to core package+ {+ files: ["packages/core/src/**/*.{ts,tsx}"],+ ...xdsConfig,+ },);diff --git a/internal/eslint-plugin-xds/README.md b/internal/eslint-plugin-xds/README.mdnew file mode 100644index 0000000000..195b714465--- /dev/null+++ b/internal/eslint-plugin-xds/README.md@@ -0,0 +1,136 @@+# @xds/eslint-plugin++ESLint plugin for XDS design system token enforcement.++## Philosophy: Two-Tier Linting++This plugin implements a two-tier linting strategy:++| Mode | Audience | Behavior | Trigger |+|------|----------|----------|---------|+| **Recommended** | Humans | Warnings only | Default (local dev) |+| **Strict** | Agents/CI | Errors (fail build) | `CI=true` or `XDS_STRICT_LINT=1` |++### Why Two Tiers?++- **Agents** should follow strict rules perfectly - they have no excuse for violations+- **Humans** need flexibility during development - warnings inform without blocking++## Rules++### `@xds/no-hardcoded-styles`++Detects hardcoded CSS values in `stylex.create()` that should use XDS tokens:++| Property | Should Use |+|----------|------------|+| `fontSize` | `textSizeVars['--text-*']` |+| `fontWeight` | `fontWeightVars['--font-weight-*']` |+| `color`, `backgroundColor` | `colorVars['--color-*']` |+| `padding*`, `margin*`, `gap` | `spacingVars['--spacing-*']` |+| `borderRadius` | `radiusVars['--radius-*']` |++**Bad:**+```tsx+const styles = stylex.create({+ text: {+ fontSize: '14px', // ❌ Hardcoded+ fontWeight: 600, // ❌ Hardcoded+ color: '#FF0000', // ❌ Hardcoded+ },+});+```++**Good:**+```tsx+const styles = stylex.create({+ text: {+ fontSize: textSizeVars['--text-base'], // ✅ Token+ fontWeight: fontWeightVars['--font-weight-semibold'], // ✅ Token+ color: colorVars['--color-negative'], // ✅ Token+ },+});+```++### `@xds/require-letter-spacing`++Recommends adding `letterSpacing` when `fontSize` is defined (common design pattern for badges, labels).++**Strict mode only** - helps catch missing letter-spacing in compact text elements.++## Usage++### Local Development (Human Mode)++```bash+yarn lint+# ESLint running in RECOMMENDED (human) mode+# Shows warnings but doesn't fail+```++### CI / Agent Mode++```bash+yarn lint:strict+# or+XDS_STRICT_LINT=1 yarn lint+# or (automatic in GitHub Actions)+CI=true yarn lint++# ESLint running in STRICT (agent/CI) mode+# Errors cause build failure+```++## Testing the Plugin++A test file with intentional violations is provided:++```bash+# Human mode - shows warnings+yarn lint packages/core/src/Badge/XDSBadge.test-violations.tsx++# Strict mode - shows errors+yarn lint:strict packages/core/src/Badge/XDSBadge.test-violations.tsx+```++Expected output in strict mode:+```+ 12:15 error Use textSizeVars token instead of hardcoded fontSize @xds/no-hardcoded-styles+ 17:16 error Use fontWeightVars token instead of hardcoded fontWeight @xds/no-hardcoded-styles+ 22:12 error Use colorVars token instead of hardcoded color @xds/no-hardcoded-styles+ ...+```++## Configuration++The plugin is configured in `eslint.config.js`:++```js+import xdsPlugin from "./internal/eslint-plugin-xds/index.js";++const isStrictMode = process.env.XDS_STRICT_LINT === '1' || process.env.CI === 'true';+const xdsConfig = isStrictMode ? xdsPlugin.configs.strict : xdsPlugin.configs.recommended;++// Applied to core package files+{+ files: ["packages/core/src/**/*.{ts,tsx}"],+ ...xdsConfig,+}+```++## Ignoring Specific Properties++If a property legitimately needs a hardcoded value:++```js+// In eslint.config.js+{+ files: ["packages/core/src/**/*.{ts,tsx}"],+ plugins: { '@xds': xdsPlugin },+ rules: {+ '@xds/no-hardcoded-styles': ['warn', {+ ignore: ['lineHeight'] // Allow hardcoded lineHeight+ }],+ },+}+```diff --git a/internal/eslint-plugin-xds/index.js b/internal/eslint-plugin-xds/index.jsnew file mode 100644index 0000000000..113d18fff4--- /dev/null+++ b/internal/eslint-plugin-xds/index.js@@ -0,0 +1,289 @@+/**+ * @file ESLint plugin for XDS design system+ * @description Enforces usage of design tokens instead of hardcoded values in StyleX+ *+ * Philosophy: Strict for agents (CI), lenient for humans (local dev)+ * - "strict" config: All rules as errors - use in CI/agent environments+ * - "recommended" config: All rules as warnings - use for human development+ */++// =============================================================================+// Rule: no-hardcoded-styles+// Detects hardcoded CSS values that should use XDS tokens+// =============================================================================++const STYLE_PROPERTIES = {+ // Font properties that should use tokens+ fontSize: {+ pattern: /^['"]?\d+(\.\d+)?(px|rem|em)['"]?$/,+ tokenVar: 'textSizeVars',+ message: 'Use textSizeVars token instead of hardcoded fontSize',+ examples: ["textSizeVars['--text-xsm']", "textSizeVars['--text-base']"],+ },+ fontWeight: {+ pattern: /^\d{3}$/,+ tokenVar: 'fontWeightVars',+ message: 'Use fontWeightVars token instead of hardcoded fontWeight',+ examples: ["fontWeightVars['--font-weight-medium']"],+ },+ lineHeight: {+ pattern: /^['"]?\d+(\.\d+)?(px|rem|em)?['"]?$/,+ tokenVar: 'lineHeightVars',+ message: 'Consider using lineHeightVars token for consistency',+ examples: ["lineHeightVars['--leading-normal']"],+ },+ // Spacing properties+ padding: {+ pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/,+ tokenVar: 'spacingVars',+ message: 'Use spacingVars token instead of hardcoded padding',+ examples: ["spacingVars['--spacing-2']"],+ },+ paddingTop: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },+ paddingRight: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },+ paddingBottom: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },+ paddingLeft: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },+ paddingBlock: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },+ paddingInline: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },+ margin: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },+ marginTop: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },+ marginRight: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },+ marginBottom: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },+ marginLeft: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },+ marginBlock: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },+ marginInline: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },+ gap: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },+ // Border radius+ borderRadius: {+ pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/,+ tokenVar: 'radiusVars',+ message: 'Use radiusVars token instead of hardcoded borderRadius',+ examples: ["radiusVars['--radius-element']"],+ },+ // Colors - detect hex codes and rgb values+ color: {+ pattern: /^['"]?(#[0-9a-fA-F]{3,8}|rgba?\([^)]+\))['"]?$/,+ tokenVar: 'colorVars',+ message: 'Use colorVars token instead of hardcoded color',+ examples: ["colorVars['--color-text-primary']"],+ },+ backgroundColor: {+ pattern: /^['"]?(#[0-9a-fA-F]{3,8}|rgba?\([^)]+\))['"]?$/,+ tokenVar: 'colorVars',+ message: 'Use colorVars token instead of hardcoded backgroundColor',+ examples: ["colorVars['--color-surface']"],+ },+ borderColor: {+ pattern: /^['"]?(#[0-9a-fA-F]{3,8}|rgba?\([^)]+\))['"]?$/,+ tokenVar: 'colorVars',+ message: 'Use colorVars token instead of hardcoded borderColor',+ },+};++// Properties to skip (these are typically fine as hardcoded values)+const SKIP_VALUES = [+ '0', '0px', 'inherit', 'initial', 'unset', 'auto', 'none',+ '100%', '50%', '0%', 'transparent', 'currentColor',+];++/**+ * Check if we're inside a stylex.create() call+ */+function isInsideStylexCreate(node) {+ let current = node;+ while (current) {+ if (+ current.type === 'CallExpression' &&+ current.callee?.type === 'MemberExpression' &&+ current.callee.object?.name === 'stylex' &&+ current.callee.property?.name === 'create'+ ) {+ return true;+ }+ current = current.parent;+ }+ return false;+}++/**+ * Get the string value from a node+ */+function getValueFromNode(node) {+ if (node.type === 'Literal') {+ return String(node.value);+ }+ if (node.type === 'TemplateLiteral' && node.quasis.length === 1) {+ return node.quasis[0].value.raw;+ }+ return null;+}++const noHardcodedStylesRule = {+ meta: {+ type: 'suggestion',+ docs: {+ description: 'Enforce usage of XDS design tokens instead of hardcoded values in StyleX',+ category: 'Best Practices',+ recommended: true,+ },+ messages: {+ useToken: '{{message}}. Example: {{examples}}',+ useTokenSimple: '{{message}}',+ },+ schema: [+ {+ type: 'object',+ properties: {+ // Allow specific properties to be ignored+ ignore: {+ type: 'array',+ items: { type: 'string' },+ },+ },+ additionalProperties: false,+ },+ ],+ },+ create(context) {+ const options = context.options[0] || {};+ const ignoredProperties = new Set(options.ignore || []);++ return {+ Property(node) {+ // Only check inside stylex.create()+ if (!isInsideStylexCreate(node)) {+ return;+ }++ // Get property name+ const propName = node.key?.name || node.key?.value;+ if (!propName || ignoredProperties.has(propName)) {+ return;+ }++ // Check if this property has a rule+ const rule = STYLE_PROPERTIES[propName];+ if (!rule) {+ return;+ }++ // Get the value+ const value = getValueFromNode(node.value);+ if (value === null) {+ // Value is a variable/expression - that's fine+ return;+ }++ // Skip allowed values+ if (SKIP_VALUES.includes(value)) {+ return;+ }++ // Check if value matches the hardcoded pattern+ if (rule.pattern.test(value)) {+ context.report({+ node: node.value,+ messageId: rule.examples ? 'useToken' : 'useTokenSimple',+ data: {+ message: rule.message,+ examples: rule.examples ? rule.examples.join(' or ') : '',+ },+ });+ }+ },+ };+ },+};++// =============================================================================+// Rule: require-letter-spacing+// Ensures letterSpacing is defined when fontSize is used (badge-specific pattern)+// =============================================================================++const requireLetterSpacingRule = {+ meta: {+ type: 'suggestion',+ docs: {+ description: 'Recommend adding letterSpacing when defining fontSize in StyleX',+ category: 'Best Practices',+ recommended: false,+ },+ messages: {+ addLetterSpacing: 'Consider adding letterSpacing when using fontSize. Common value: letterSpacing: \'-0.24px\'',+ },+ schema: [],+ },+ create(context) {+ return {+ Property(node) {+ // Only check inside stylex.create()+ if (!isInsideStylexCreate(node)) {+ return;+ }++ // Look for fontSize property+ const propName = node.key?.name || node.key?.value;+ if (propName !== 'fontSize') {+ return;+ }++ // Check if sibling properties include letterSpacing+ const parent = node.parent;+ if (parent?.type !== 'ObjectExpression') {+ return;+ }++ const hasLetterSpacing = parent.properties.some(+ (prop) => (prop.key?.name || prop.key?.value) === 'letterSpacing'+ );++ if (!hasLetterSpacing) {+ context.report({+ node,+ messageId: 'addLetterSpacing',+ });+ }+ },+ };+ },+};++// =============================================================================+// Plugin Export+// =============================================================================++const plugin = {+ meta: {+ name: '@xds/eslint-plugin',+ version: '0.0.1',+ },+ rules: {+ 'no-hardcoded-styles': noHardcodedStylesRule,+ 'require-letter-spacing': requireLetterSpacingRule,+ },+ configs: {},+};++// Strict config - for agents/CI (all errors)+plugin.configs.strict = {+ plugins: {+ '@xds': plugin,+ },+ rules: {+ '@xds/no-hardcoded-styles': 'error',+ '@xds/require-letter-spacing': 'error',+ },+};++// Recommended config - for humans (all warnings)+plugin.configs.recommended = {+ plugins: {+ '@xds': plugin,+ },+ rules: {+ '@xds/no-hardcoded-styles': 'warn',+ '@xds/require-letter-spacing': 'off', // Optional for humans+ },+};++export default plugin;diff --git a/internal/eslint-plugin-xds/package.json b/internal/eslint-plugin-xds/package.jsonnew file mode 100644index 0000000000..e2a39d8f82--- /dev/null+++ b/internal/eslint-plugin-xds/package.json@@ -0,0 +1,12 @@+{+ "name": "@xds/eslint-plugin",+ "version": "0.0.1",+ "private": true,+ "main": "index.js",+ "type": "module",+ "description": "ESLint plugin for XDS design system token enforcement",+ "keywords": ["eslint", "eslint-plugin", "xds", "design-system", "stylex"],+ "peerDependencies": {+ "eslint": ">=9.0.0"+ }+}diff --git a/package.json b/package.jsonindex 1eb603f1a8..7bc7e63f88 100644--- a/package.json+++ b/package.json@@ -16,6 +16,7 @@"test:coverage": "vitest --coverage","test:e2e": "playwright test","lint": "eslint .",+ "lint:strict": "XDS_STRICT_LINT=1 eslint .","storybook": "yarn workspace @xds/storybook dev","storybook:build": "yarn workspace @xds/storybook build","docs": "yarn workspace @xds/docs dev",diff --git a/packages/core/package.json b/packages/core/package.jsonindex c2de2df5d1..d74c73f0cb 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -24,6 +24,11 @@"import": "./dist/Avatar/index.mjs","require": "./dist/Avatar/index.js"},+ "./Badge": {+ "types": "./dist/Badge/index.d.ts",+ "import": "./dist/Badge/index.mjs",+ "require": "./dist/Badge/index.js"+ },"./Button": {"types": "./dist/Button/index.d.ts","import": "./dist/Button/index.mjs",diff --git a/packages/core/src/Badge/README.md b/packages/core/src/Badge/README.mdnew file mode 100644index 0000000000..8307ad7ebf--- /dev/null+++ b/packages/core/src/Badge/README.md@@ -0,0 +1,47 @@+# Badge++A badge component for displaying status indicators, counts, or labels.++## Exports++| Export | Type | Description |+|--------|------|-------------|+| `XDSBadge` | Component | Main badge component |+| `XDSBadgeProps` | Type | Props interface |+| `XDSBadgeVariant` | Type | Variant union type |++## Props++| Prop | Type | Default | Description |+|------|------|---------|-------------|+| `variant` | `'neutral' \| 'info' \| 'success' \| 'warning' \| 'error'` | `'neutral'` | Visual style variant |+| `children` | `ReactNode` | - | Badge content. Omit for dot indicator |+| `icon` | `ReactNode` | - | Optional leading icon |++## Usage++```tsx+import {XDSBadge} from '@xds/core/Badge';++// Text badge+<XDSBadge>Default</XDSBadge>++// Status variants+<XDSBadge variant="success">Active</XDSBadge>+<XDSBadge variant="error">Failed</XDSBadge>+<XDSBadge variant="warning">Pending</XDSBadge>++// Count badge+<XDSBadge variant="info">42</XDSBadge>++// Dot indicator (no children)+<XDSBadge variant="success" />+```++## Files++| File | Purpose |+|------|---------|+| `XDSBadge.tsx` | Component implementation |+| `XDSBadge.test.tsx` | Unit tests |+| `index.ts` | Barrel exports |diff --git a/packages/core/src/Badge/XDSBadge.test-violations.tsx b/packages/core/src/Badge/XDSBadge.test-violations.tsxnew file mode 100644index 0000000000..5a704d39fe--- /dev/null+++ b/packages/core/src/Badge/XDSBadge.test-violations.tsx@@ -0,0 +1,62 @@+/**+ * @file Test file with intentional violations for ESLint plugin testing+ * Run with: yarn lint packages/core/src/Badge/XDSBadge.test-violations.tsx+ */++import * as stylex from '@stylexjs/stylex';++// This file contains intentional violations to test the XDS ESLint plugin++const badStyles = stylex.create({+ // VIOLATION: hardcoded fontSize (should use textSizeVars)+ hardcodedFontSize: {+ fontSize: '14px',+ },++ // VIOLATION: hardcoded fontWeight (should use fontWeightVars)+ hardcodedFontWeight: {+ fontWeight: 600,+ },++ // VIOLATION: hardcoded color (should use colorVars)+ hardcodedColor: {+ color: '#FF0000',+ backgroundColor: 'rgba(0, 0, 0, 0.5)',+ },++ // VIOLATION: hardcoded spacing (should use spacingVars)+ hardcodedSpacing: {+ padding: '16px',+ margin: '8px',+ gap: '4px',+ },++ // VIOLATION: hardcoded borderRadius (should use radiusVars)+ hardcodedRadius: {+ borderRadius: '8px',+ },++ // VIOLATION: fontSize without letterSpacing (strict mode only)+ missingLetterSpacing: {+ fontSize: '12px',+ fontWeight: 500,+ // letterSpacing is missing!+ },++ // OK: Uses tokens (no violations)+ goodStyles: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ // These would be tokens in real code+ },++ // OK: Allowed values+ allowedValues: {+ padding: '0',+ margin: 'auto',+ color: 'inherit',+ },+});++export { badStyles };diff --git a/packages/core/src/Badge/XDSBadge.test.tsx b/packages/core/src/Badge/XDSBadge.test.tsxnew file mode 100644index 0000000000..f65d73b6bd--- /dev/null+++ b/packages/core/src/Badge/XDSBadge.test.tsx@@ -0,0 +1,52 @@+import {describe, it, expect} from 'vitest';+import {render, screen} from '@testing-library/react';+import {XDSBadge} from './XDSBadge';++describe('XDSBadge', () => {+ it('renders with default variant', () => {+ render(<XDSBadge>Default</XDSBadge>);+ expect(screen.getByText('Default')).toBeInTheDocument();+ });++ it('renders with different variants', () => {+ const {rerender} = render(<XDSBadge variant="success">Success</XDSBadge>);+ expect(screen.getByText('Success')).toBeInTheDocument();++ rerender(<XDSBadge variant="error">Error</XDSBadge>);+ expect(screen.getByText('Error')).toBeInTheDocument();++ rerender(<XDSBadge variant="warning">Warning</XDSBadge>);+ expect(screen.getByText('Warning')).toBeInTheDocument();++ rerender(<XDSBadge variant="info">Info</XDSBadge>);+ expect(screen.getByText('Info')).toBeInTheDocument();+ });++ it('renders as dot when no children provided', () => {+ const {container} = render(<XDSBadge variant="success" />);+ const badge = container.querySelector('span');+ expect(badge).toBeInTheDocument();+ expect(badge?.textContent).toBe('');+ });++ it('renders with icon', () => {+ render(+ <XDSBadge icon={<span data-testid="icon">*</span>}>+ With Icon+ </XDSBadge>+ );+ expect(screen.getByTestId('icon')).toBeInTheDocument();+ expect(screen.getByText('With Icon')).toBeInTheDocument();+ });++ it('forwards ref', () => {+ const ref = {current: null as HTMLSpanElement | null};+ render(<XDSBadge ref={ref}>Test</XDSBadge>);+ expect(ref.current).toBeInstanceOf(HTMLSpanElement);+ });++ it('spreads additional props', () => {+ render(<XDSBadge data-testid="custom-badge">Test</XDSBadge>);+ expect(screen.getByTestId('custom-badge')).toBeInTheDocument();+ });+});diff --git a/packages/core/src/Badge/XDSBadge.tsx b/packages/core/src/Badge/XDSBadge.tsxnew file mode 100644index 0000000000..41bf478884--- /dev/null+++ b/packages/core/src/Badge/XDSBadge.tsx@@ -0,0 +1,132 @@+/**+ * @file XDSBadge.tsx+ * @input Uses React forwardRef, HTMLAttributes+ * @output Exports XDSBadge component, XDSBadgeProps, XDSBadgeVariant types+ * @position Core implementation; consumed by index.ts+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/Badge/README.md (props table, features, implementation notes)+ * - /packages/core/src/Badge/XDSBadge.test.tsx (tests for new/changed behavior)+ * - /packages/core/src/Badge/index.ts (exports if types change)+ * - /apps/storybook/stories/Badge.stories.tsx (storybook stories)+ */++import {forwardRef, type HTMLAttributes, type ReactNode} from 'react';+import * as stylex from '@stylexjs/stylex';+import {+ colorVars,+ spacingVars,+ radiusVars,+ textSizeVars,+ fontWeightVars,+ lineHeightVars,+} from '../theme/tokens.stylex';++/**+ * Base badge styles+ */+const styles = stylex.create({+ base: {+ display: 'inline-flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: spacingVars['--spacing-1'],+ paddingBlock: spacingVars['--spacing-1'],+ paddingInline: spacingVars['--spacing-2'],+ borderRadius: radiusVars['--radius-element'],+ fontFamily: 'inherit',+ fontSize: textSizeVars['--text-xsm'],+ lineHeight: lineHeightVars['--leading-snug'],+ fontWeight: fontWeightVars['--font-weight-medium'],+ letterSpacing: '-0.24px',+ whiteSpace: 'nowrap',+ },+ dot: {+ paddingBlock: spacingVars['--spacing-1'],+ paddingInline: spacingVars['--spacing-1'],+ },+});++/**+ * Variant styles for different badge appearances+ */+const variants = stylex.create({+ neutral: {+ backgroundColor: colorVars['--color-deemphasized'],+ color: colorVars['--color-text-primary'],+ },+ info: {+ backgroundColor: colorVars['--color-accent'],+ color: colorVars['--color-text-on-media'],+ },+ success: {+ backgroundColor: colorVars['--color-positive'],+ color: colorVars['--color-text-on-media'],+ },+ warning: {+ backgroundColor: colorVars['--color-warning'],+ color: colorVars['--color-text-primary'],+ },+ error: {+ backgroundColor: colorVars['--color-negative'],+ color: colorVars['--color-text-on-media'],+ },+});++/**+ * Badge variant type derived from the variants StyleX object+ */+export type XDSBadgeVariant = keyof typeof variants;++export interface XDSBadgeProps extends HTMLAttributes<HTMLSpanElement> {+ /**+ * The visual style variant of the badge.+ * @default 'neutral'+ */+ variant?: XDSBadgeVariant;+ /**+ * The content to display in the badge.+ * If omitted, renders as a small dot indicator.+ */+ children?: ReactNode;+ /**+ * Optional icon to display before the label.+ */+ icon?: ReactNode;+}++/**+ * A badge component for displaying status indicators, counts, or labels.+ *+ * Styles use XDS theme tokens via StyleX.+ * Wrap your app in <Theme> to apply a theme.+ *+ * @example+ * ```tsx+ * <XDSBadge>Default</XDSBadge>+ * <XDSBadge variant="success">Active</XDSBadge>+ * <XDSBadge variant="error">3</XDSBadge>+ * <XDSBadge variant="info" /> // Dot indicator+ * ```+ */+export const XDSBadge = forwardRef<HTMLSpanElement, XDSBadgeProps>(+ ({variant = 'neutral', children, icon, ...props}, ref) => {+ const isDot = children == null && icon == null;++ return (+ <span+ ref={ref}+ {...stylex.props(+ styles.base,+ variants[variant],+ isDot && styles.dot,+ )}+ {...props}>+ {icon}+ {children}+ </span>+ );+ },+);++XDSBadge.displayName = 'XDSBadge';diff --git a/packages/core/src/Badge/index.ts b/packages/core/src/Badge/index.tsnew file mode 100644index 0000000000..c36be65a62--- /dev/null+++ b/packages/core/src/Badge/index.ts@@ -0,0 +1,6 @@+/**+ * @file Badge component barrel export+ */++export {XDSBadge} from './XDSBadge';+export type {XDSBadgeProps, XDSBadgeVariant} from './XDSBadge';diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex a5f71b071d..633a141c54 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -10,6 +10,7 @@// Componentsexport * from './AspectRatio';export * from './Avatar';+export * from './Badge';export * from './Button';export * from './Calendar';export * from './Center';