The user wants a UI build pipeline that performs specific actions per Pull Request (PR).
The key actions are:
- Auto-extract documentation snippets: Probably from code comments or dedicated doc files.
- Auto-extract Storybook stories: Likely running Storybook or checking for existing stories.
- Auto-extract design tokens: Pulling variables (colors, spacing, typography) from CSS/SCSS/JSON/JS.
The context is a "build pipeline," which implies CI/CD (e.g., GitHub Actions, GitLab CI, Jenkins).
The goal is to automate this per PR, meaning it should be fast, feedback-oriented, and likely generate artifacts or comments on the PR.
Key Components of the Solution:
- Trigger: A Pull Request event (open, synchronize).
- Environment: Node.js/JavaScript ecosystem is the standard for UI (React, Vue, Angular, CSS/SCSS, Style Dictionary).
- Tooling:
- Docs: TypeDoc, JSDoc, or custom scripts parsing comments.
- Storybook:
@storybook/cli, sb extract (for internal representation), or visual regression tools like Chromatic (though the prompt asks for "extracting," I should focus on generating/validating the story artifacts).
- Design Tokens: Style Dictionary, Theo, or CSS parser scripts.
- Reporting: How do we surface this?
- Build artifacts (ZIP files).
- PR Comments (Bot posting a summary).
- Static Site Generation (deploying a preview).
Architecture Plan:
- Step 1: Setup & Config. Define the project structure.
- Step 2: Design Token Extraction. Use
style-dictionary to compile tokens into JSON/CSS.
- Step 3: Documentation Extraction. Use a parser (like
jsdoc or react-docgen) to read component prop types and comments.
- Step 4: Storybook Integration. Build Storybook static files to extract component usage.
- Step 5: CI/CD Workflow. Create a GitHub Actions workflow that orchestrates these steps.
Refining the Approach:
- Design Tokens: Usually stored in JSON/JS. I need a script to parse these and output a summary.
- Documentation:
react-docgen is great for React. vue-docgen-api for Vue. Let's assume a generic JS/React approach but keep it adaptable.
- Storybook: Just building Storybook is usually enough, but "extracting" might mean generating a visual snapshot or an index of stories. The prompt implies capturing the state of these artifacts for review.
- Pipeline Output: The most useful thing for a PR is a report. I will engineer a script that aggregates these three things and posts a summary comment on the PR.
Drafting the Code Structure:
package.json: Dependencies (style-dictionary, react-docgen, etc.).
scripts/:
extract-tokens.js: Reads source tokens, outputs JSON.
extract-docs.js: Reads component files, outputs markdown or JSON.
aggregate-report.js: Combines everything for the PR comment.
.github/workflows/ui-pipeline.yml: The CI definition.
Detailed Steps for the User:
- Prerequisites: Tech stack assumptions (React, CSS/JSON tokens).
- Token Extraction: Show how to use Style Dictionary.
- Documentation Extraction: Show a Node script using
react-docgen (or generic AST parsing) to pull comments.
- Storybook Extraction: Explain how to build Storybook and maybe capture the
stories.json index.
- The Pipeline (GitHub Actions): Tie it all together.
- The Reporting Mechanism: A script to comment on the PR.
Self-Correction during thought process:
- Initial thought: Just run standard builds.
- Correction: The prompt asks to auto-extract. Standard builds just produce a bundle. I need to specifically target the data inside the code. I should write a custom Node.js script that performs this "extraction" logic to produce a JSON report, which the CI can then use.
Let's structure the "Extraction Script":
It needs to:
- Parse
tokens.json -> Output list of changed tokens.
- Parse
src/**/*.tsx -> Output list of components + props (Documentation).
- Parse
src/**/*.stories.tsx -> Output list of story IDs (Storybook).
Final Deliverable Structure:
- Architecture Overview: High-level diagram description.
- Project Structure: Folder layout.
- The Extraction Engine (Node.js): The core scripts to perform the work.
- CI/CD Configuration (GitHub Actions): How to run it automatically.
- Output: What the developer sees (PR Comment).
Let's write the actual code snippets.
- Tokens: Assume
design-tokens.json.
- Docs: Use
react-docgen as it's the industry standard for UI components.
- Storybook: Use the
sb CLI or just parse the story files to list them.
Refining the PR Comment:
The comment should look like:
UI Pipeline Report
- Tokens: 5 changed (PrimaryColor, SpacingSmall...)
- Components: Button, Modal (Docs generated)
- Stories: 12 stories found (View in Storybook)
This provides high value.
Let's proceed with generating the response based on this plan. I will focus on a modern stack (Node.js, React, Style Dictionary, GitHub Actions) as it's the most common, but keep the logic generic enough.
Code specifics:
extract-tokens.js: Simple JSON require and format.
extract-docs.js: react-docgen parsing.
extract-stories.js: Simple AST parse or file glob match.
Okay, ready to generate.
This solution engineers a CI pipeline using GitHub Actions and a Node.js extraction toolkit.
This pipeline triggers on every Pull Request, parses the raw source files (irrespective of framework), and produces three specific artifacts:
- Design Tokens: Compiled JSON/CSS variables from source definition files.
- Documentation: Markdown snippets extracted from JSDoc/TSDoc comments.
- Storybook Stories: A static build and an index of available stories.
Architecture Overview
- The Extractor: A Node.js script responsible for static analysis of the codebase.
- The Workflow: A GitHub Actions YAML file to orchestrate the pipeline.
- The Reporter: A mechanism to post the extracted data back to the PR (as a comment or artifact).
1. The Project Structure
Assume a standard component library structure:
/src
/components
/Button
- Button.tsx
- button.tokens.json
- Button.stories.tsx
/tokens
- global.json
2. The Extraction Engine (scripts/extract-ui-data.js)
This script uses AST (Abstract Syntax Tree) parsing and file system reads to "detonate" the component library and retrieve the raw data.
Dependencies:
glob: For file matching.
react-docgen (or similar): For extracting component prop types and comments.
style-dictionary: For transforming raw JSON tokens into standard formats.
// scripts/extract-ui-data.js
const fs = require('fs');
const path = require('path');
const glob = require('glob');
const reactDocgen = require('react-docgen');
// 1. Configuration
const CONFIG = {
components: './src/components/**/*.tsx',
tokens: './src/tokens/**/*.json',
stories: './src/**/*.stories.tsx',
outFile: './ui-extract-report.json'
};
// 2. Extract Design Tokens (JSON -> CSS/JS)
// Ideally, this uses 'style-dictionary', but here is a simplified aggregation
function extractTokens() {
const tokenFiles = glob.sync(CONFIG.tokens);
const aggregatedTokens = {};
tokenFiles.forEach(file => {
const content = JSON.parse(fs.readFileSync(file, 'utf8'));
Object.assign(aggregatedTokens, content);
});
return {
count: Object.keys(aggregatedTokens).length,
preview: JSON.stringify(aggregatedTokens, null, 2).slice(0, 500) + '...' // Truncate for report
};
}
// 3. Extract Documentation (JSDoc/Props)
function extractDocs() {
const componentFiles = glob.sync(CONFIG.components);
const docsData = [];
componentFiles.forEach(file => {
try {
const content = fs.readFileSync(file, 'utf8');
// Extracts displayName, props, description via AST
const doc = reactDocgen.parse(content, reactDocgen.resolver.findExportedComponentDefinition);
docsData.push({
component: doc.displayName || path.basename(file),
description: doc.description,
props: Object.keys(doc.props || {})
});
} catch (e) {
// Skip files that aren't react components or have errors
}
});
return docsData;
}
// 4. Extract Storybook Metadata
function extractStories() {
const storyFiles = glob.sync(CONFIG.stories);
return storyFiles.map(file => {
const content = fs.readFileSync(file, 'utf8');
// Naive regex to extract story names (CSF detection)
const titleMatch = content.match(/title:\s*['"](.*)['"]/);
return {
file: file,
title: titleMatch ? titleMatch[1] : path.basename(file)
};
});
}
// 5. Run & Write Report
function run() {
console.log("🚀 Starting UI Extraction...");
const report = {
timestamp: new Date().toISOString(),
tokens: extractTokens(),
documentation: extractDocs(),
stories: extractStories()
};
fs.writeFileSync(CONFIG.outFile, JSON.stringify(report, null, 2));
console.log(`✅ Extraction complete. Report saved to ${CONFIG.outFile}`);
}
run();
3. The Build Pipeline (.github/workflows/ui-pr-check.yml)
This workflow runs the script, builds the static storybook site, and uploads the artifacts. It ensures the PR doesn't break the "component contract."
name: UI Component Pipeline
on:
pull_request:
branches: [main]
paths:
- 'src/**' # Only run if UI files change
jobs:
extract-and-build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node
uses: actions/setup-node@v3
with:
node-version: 18
cache: 'npm'
- name: Install Dependencies
run: npm ci
# STEP 1: Extract Tokens & Docs via Script
- name: Run Extraction Engine
run: node scripts/extract-ui-data.js
# STEP 2: Build Static Storybook
# This verifies stories compile and creates a browsable artifact
- name: Build Storybook
run: npm run build-storybook -- --output-dir ./storybook-static
# STEP 3: Upload Artifacts for Review
- name: Upload Extraction Report
uses: actions/upload-artifact@v3
with:
name: ui-extract-report
path: ui-extract-report.json
- name: Upload Storybook Static Site
uses: actions/upload-artifact@v3
with:
name: storybook-preview
path: storybook-static
# STEP 4: (Optional) Comment on PR
- name: Comment on PR
uses: actions/github-script@v6
with:
script: |
const fs = require('fs');
const report = JSON.parse(fs.readFileSync('./ui-extract-report.json'));
const summary = `
## 📦 UI Build Report
### 🎨 Design Tokens
Detected **${report.tokens.count}** tokens.
### 📚 Documentation
Extracted docs for **${report.documentation.length}** components.
### 📖 Storybook
Found **${report.stories.length}** stories.
[Download the Static Site Artifact to preview]
`;
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: summary
})
4. Integration: How to Use This
1. Visual Regression (Optional Advanced Step)
You can extend the workflow to use the extracted story list to trigger Chromatic or Percy snapshots only for the changed stories, rather than the entire library.
2. Living Style Guide
The ui-extract-report.json generated by this pipeline is machine-readable. You can feed this into your backend documentation portal (e.g., a Next.js site) to auto-generate API pages for your components.
3. Token Validation
By hooking into extractTokens(), you can enforce rules such as "No hardcoded hex values allowed" or "All spacing must use global tokens," failing the PR build if violations are found.
Summary of Outputs
- PR Comment: A summary of changes (e.g., "You added 2 components and modified 5 tokens").
- Artifact (ZIP): A fully compiled static Storybook site that stakeholders can download and run locally to verify visual changes without needing to set up a dev environment.
- JSON Data: A structured snapshot of the design system's state at that specific commit.