AIStoreHub Package Vault: Stitch Skills
Package Slug: stitch-skills
Archetype: mcp_server
Upstream Repository: https://github.com/google-labs-code/stitch-skills
Workspace Files & Specifications (69 files)
- .agents/plugins/marketplace.json (938 bytes)
{ "name": "stitch-skills", "interface": { "displayName": "Stitch Skills" }, "plugins": [ { "name": "stitch-design", "source": { "source": "local", "path": "./plugins/stitch-design" }, "policy": { "installation": "AVAILABLE", "authentication": "ON_INSTALL" }, "category": "Productivity" }, { "name": "stitch-build", "source": { "source": "local", "path": "./plugins/stitch-build" }, "policy": { "installation": "AVAILABLE", "authentication": "ON_INSTALL" }, "category": "Productivity" }, { "name": "stitch-utilities", "source": { "source": "local", "path": "./plugins/stitch-utilities" }, "policy": { "installation": "AVAILABLE", "authentication": "ON_INSTALL" }, "category": "Productivity" } ] } - aistorehub.json (612 bytes)
{ "name": "Stitch Skills", "slug": "stitch-skills", "version": "1.0.0", "type": "mcp_server", "description": "A library of Agent Skills designed to work with the Stitch MCP server. Each skill follows the Agent Skills open standard, for compatibility with coding agents such as Antigravity, Gemini CLI, Claude Code, Cursor.", "owner": "community", "repository": "catalog", "github_repo_url": "https://github.com/google-labs-code/stitch-skills", "tags": [ "trending", "typescript", "github", "open-source", "google-labs-code" ], "imported_at": "2026-11-22T00:08:40.441Z" } - INSTRUCTIONS.md (12568 bytes)
--- name: taste-design description: Semantic Design System Skill for Google Stitch. Generates agent-friendly DESIGN.md files that enforce premium, anti-generic UI standards — strict typography, calibrated color, asymmetric layouts, perpetual micro-motion, and hardware-accelerated performance. allowed-tools: - "StitchMCP" - "Read" - "Write" --- # Stitch Design Taste — Semantic Design System Skill ## Overview This skill generates `DESIGN.md` files optimized for Google Stitch screen generation. It translates the battle-tested anti-slop frontend engineering directives into Stitch's native semantic design language — descriptive, natural-language rules paired with precise values that Stitch's AI agent can interpret to produce premium, non-generic interfaces. The generated `DESIGN.md` serves as the **single source of truth** for prompting Stitch to generate new screens that align with a curated, high-agency design language. Stitch interprets design through **"Visual Descriptions"** supported by specific color values, typography specs, and component behaviors. ## Prerequisites - Access to Google Stitch via [labs.google.com/stitch](https://labs.google.com/stitch) - Optionally: Stitch MCP Server for programmatic integration with Cursor, Antigravity, or Gemini CLI ## The Goal Generate a `DESIGN.md` file that encodes: 1. **Visual atmosphere** — the mood, density, and design philosophy 2. **Color calibration** — neutrals, accents, and banned patterns with hex codes 3. **Typographic architecture** — font stacks, scale hierarchy, and anti-patterns 4. **Component behaviors** — buttons, cards, inputs with interaction states 5. **Layout principles** — grid systems, spacing philosophy, responsive strategy 6. **Motion philosophy** — animation engine specs, spring physics, perpetual micro-interactions 7. **Anti-patterns** — explicit list of banned AI design clichés ## Analysis & Synthesis Instructions ### 1. Define the Atmosphere Evaluate the target project's intent. Use evocative adjectives from the taste spectrum: - **Density:** "Art Gallery Airy" (1–3) → "Daily App Balanced" (4–7) → "Cockpit Dense" (8–10) - **Variance:** "Predictable Symmetric" (1–3) → "Offset Asymmetric" (4–7) → "Artsy Chaotic" (8–10) - **Motion:** "Static Restrained" (1–3) → "Fluid CSS" (4–7) → "Cinematic Choreography" (8–10) Default baseline: Creativity 9, Variance 8, Motion 6, Density 5. Adapt dynamically based on user's vibe description. ### 2. Map the Color Palette For each color provide: **Descriptive Name** + **Hex Code** + **Functional Role**. **Mandatory constraints:** - Maximum 1 accent color. Saturation below 80% - The "AI Purple/Blue Neon" aesthetic is strictly BANNED — no purple button glows, no neon gradients - Use absolute neutral bases (Zinc/Slate) with high-contrast singular accents - Stick to one palette for the entire output — no warm/cool gray fluctuation - Never use pure black (`#000000`) — use Off-Black, Zinc-950, or Charcoal ### 3. Establish Typography Rules - **Display/Headlines:** Track-tight, controlled scale. Not screaming. Hierarchy through weight and color, not just massive size - **Body:** Relaxed leading, max 65 characters per line - **Font Selection:** `Inter` is BANNED for premium/creative contexts. Force unique character: `Geist`, `Outfit`, `Cabinet Grotesk`, or `Satoshi` - **Serif Ban:** Generic serif fonts (`Times New Roman`, `Georgia`, `Garamond`, `Palatino`) are BANNED. If serif is needed for editorial/creative contexts, use only distinctive modern serifs: `Fraunces`, `Gambarino`, `Editorial New`, or `Instrument Serif`. Serif is always BANNED in dashboards or software UIs - **Dashboard Constraint:** Use Sans-Serif pairings exclusively (`Geist` + `Geist Mono` or `Satoshi` + `JetBrains Mono`) - **High-Density Override:** When density exceeds 7, all numbers must use Monospace ### 4. Define the Hero Section The Hero is the first impression and must be creative, striking, and never generic: - **Inline Image Typography:** Embed small, contextual photos or visuals directly between words or letters in the headline. Images sit inline at type-height, rounded, acting as visual punctuation. This is the signature creative technique - **No Overlapping:** Text must never overlap images or other text. Every element occupies its own clean spatial zone - **No Filler Text:** "Scroll to explore", "Swipe down", scroll arrow icons, bouncing chevrons are BANNED. The content should pull users in naturally - **Asymmetric Structure:** Centered Hero layouts BANNED when variance exceeds 4 - **CTA Restraint:** Maximum one primary CTA. No secondary "Learn more" links ### 5. Describe Component Stylings For each component type, describe shape, color, shadow depth, and interaction behavior: - **Buttons:** Tactile push feedback on active state. No neon outer glows. No custom mouse cursors - **Cards:** Use ONLY when elevation communicates hierarchy. Tint shadows to background hue. For high-density layouts, replace cards with border-top dividers or negative space - **Inputs/Forms:** Label above input, helper text optional, error text below. Standard gap spacing - **Loading States:** Skeletal loaders matching layout dimensions — no generic circular spinners - **Empty States:** Composed compositions indicating how to populate data - **Error States:** Clear, inline error reporting ### 6. Define Layout Principles - No overlapping elements — every element occupies its own clear spatial zone. No absolute-positioned content stacking - Centered Hero sections are BANNED when variance exceeds 4 — force Split Screen, Left-Aligned, or Asymmetric Whitespace - The generic "3 equal cards horizontally" feature row is BANNED — use 2-column Zig-Zag, asymmetric grid, or horizontal scroll - CSS Grid over Flexbox math — never use `calc()` percentage hacks - Contain layouts using max-width constraints (e.g., 1400px centered) - Full-height sections must use `min-h-[100dvh]` — never `h-screen` (iOS Safari catastrophic jump) ### 7. Define Responsive Rules Every design must work across all viewports: - **Mobile-First Collapse (< 768px):** All multi-column layouts collapse to single column. No exceptions - **No Horizontal Scroll:** Horizontal overflow on mobile is a critical failure - **Typography Scaling:** Headlines scale via `clamp()`. Body text minimum `1rem`/`14px` - **Touch Targets:** All interactive elements minimum `44px` tap target - **Image Behavior:** Inline typography images (photos between words) stack below headline on mobile - **Navigation:** Desktop horizontal nav collapses to clean mobile menu - **Spacing:** Vertical section gaps reduce proportionally (`clamp(3rem, 8vw, 6rem)`) ### 8. Encode Motion Philosophy - **Spring Physics default:** `stiffness: 100, damping: 20` — premium, weighty feel. No linear easing - **Perpetual Micro-Interactions:** Every active component should have an infinite loop state (Pulse, Typewriter, Float, Shimmer) - **Staggered Orchestration:** Never mount lists instantly — use cascade delays for waterfall reveals - **Performance:** Animate exclusively via `transform` and `opacity`. Never animate `top`, `left`, `width`, `height`. Grain/noise filters on fixed pseudo-elements only ### 9. List Anti-Patterns (AI Tells) Encode these as explicit "NEVER DO" rules in the DESIGN.md: - No emojis anywhere - No `Inter` font - No generic serif fonts (`Times New Roman`, `Georgia`, `Garamond`) — distinctive modern serifs only if needed - No pure black (`#000000`) - No neon/outer glow shadows - No oversaturated accents - No excessive gradient text on large headers - No custom mouse cursors - No overlapping elements — clean spatial separation always - No 3-column equal card layouts - No generic names ("John Doe", "Acme", "Nexus") - No fake round numbers (`99.99%`, `50%`) - No fabricated data or statistics — never generate metrics, performance numbers, uptime percentages, response times, or any data that the user did not explicitly provide. "99.98% UPTIME SLA", "124ms AVG. RESPONSE", "18.5k DEPLOY CYCLES" are invented AI filler. If real data is not available, use clear placeholder labels like `[metric]` instead of making up numbers - No fake system/metric sections — "SYSTEM PERFORMANCE METRICS", "KEY STATISTICS", "BY THE NUMBERS" dashboard cards filled with invented data are BANNED - No `LABEL // YEAR` formatting — "SYSTEM // 2024", "METRICS // 2025" is a lazy AI convention, not real design typography - No AI copywriting clichés ("Elevate", "Seamless", "Unleash", "Next-Gen") - No filler UI text: "Scroll to explore", "Swipe down", scroll arrows, bouncing chevrons - No broken Unsplash links — use `picsum.photos` or SVG avatars - No centered Hero sections (for high-variance projects) ## Output Format (DESIGN.md Structure) ```markdown # Design System: [Project Title] ## 1. Visual Theme & Atmosphere (Evocative description of the mood, density, variance, and motion intensity. Example: "A restrained, gallery-airy interface with confident asymmetric layouts and fluid spring-physics motion. The atmosphere is clinical yet warm — like a well-lit architecture studio.") ## 2. Color Palette & Roles - **Canvas White** (#F9FAFB) — Primary background surface - **Pure Surface** (#FFFFFF) — Card and container fill - **Charcoal Ink** (#18181B) — Primary text, Zinc-950 depth - **Muted Steel** (#71717A) — Secondary text, descriptions, metadata - **Whisper Border** (rgba(226,232,240,0.5)) — Card borders, 1px structural lines - **[Accent Name]** (#XXXXXX) — Single accent for CTAs, active states, focus rings (Max 1 accent. Saturation < 80%. No purple/neon.) ## 3. Typography Rules - **Display:** [Font Name] — Track-tight, controlled scale, weight-driven hierarchy - **Body:** [Font Name] — Relaxed leading, 65ch max-width, neutral secondary color - **Mono:** [Font Name] — For code, metadata, timestamps, high-density numbers - **Banned:** Inter, generic system fonts for premium contexts. Serif fonts banned in dashboards. ## 4. Component Stylings * **Buttons:** Flat, no outer glow. Tactile -1px translate on active. Accent fill for primary, ghost/outline for secondary. * **Cards:** Generously rounded corners (2.5rem). Diffused whisper shadow. Used only when elevation serves hierarchy. High-density: replace with border-top dividers. * **Inputs:** Label above, error below. Focus ring in accent color. No floating labels. * **Loaders:** Skeletal shimmer matching exact layout dimensions. No circular spinners. * **Empty States:** Composed, illustrated compositions — not just "No data" text. ## 5. Layout Principles (Grid-first responsive architecture. Asymmetric splits for Hero sections. Strict single-column collapse below 768px. Max-width containment. No flexbox percentage math. Generous internal padding.) ## 6. Motion & Interaction (Spring physics for all interactive elements. Staggered cascade reveals. Perpetual micro-loops on active dashboard components. Hardware-accelerated transforms only. Isolated Client Components for CPU-heavy animations.) ## 7. Anti-Patterns (Banned) (Explicit list of forbidden patterns: no emojis, no Inter, no pure black, no neon glows, no 3-column equal grids, no AI copywriting clichés, no generic placeholder names, no broken image links.) ``` ## Best Practices - **Be Descriptive:** "Deep Charcoal Ink (#18181B)" — not just "dark text" - **Be Functional:** Explain what each element is used for - **Be Consistent:** Same terminology throughout the document - **Be Precise:** Include exact hex codes, rem values, pixel values in parentheses - **Be Opinionated:** This is not a neutral template — it enforces a specific, premium aesthetic ## Tips for Success 1. Start with the atmosphere — understand the vibe before detailing tokens 2. Look for patterns — identify consistent spacing, sizing, and styling 3. Think semantically — name colors by purpose, not just appearance 4. Consider hierarchy — document how visual weight communicates importance 5. Encode the bans — anti-patterns are as important as the rules themselves ## Common Pitfalls to Avoid - Using technical jargon without translation ("rounded-xl" instead of "generously rounded corners") - Omitting hex codes or using only descriptive names - Forgetting functional roles of design elements - Being too vague in atmosphere descriptions - Ignoring the anti-pattern list — these are what make the output premium - Defaulting to generic "safe" designs instead of enforcing the curated aesthetic - plugins/stitch-build/skills/react-components/examples/gold-standard-card.tsx (1995 bytes)
import React from 'react'; // Note for Agent: The '@' alias refers to the target project's src directory. // Ensure src/data/mockData.ts is created before generating this component. import { cardData } from '../data/mockData'; /** * Gold Standard: ActivityCard * This file serves as the definitive reference for the agent. */ interface ActivityCardProps { readonly id: string; readonly username: string; readonly action: 'MERGED' | 'COMMIT'; readonly timestamp: string; readonly avatarUrl: string; readonly repoName: string; } export const ActivityCard: React.FC<ActivityCardProps> = ({ username, action, timestamp, avatarUrl, repoName, }) => { const isMerged = action === 'MERGED'; return ( <div className="flex items-center justify-between gap-4 rounded-lg bg-surface-dark p-4 min-h-14 shadow-sm ring-1 ring-white/10"> <div className="flex items-center gap-4 overflow-hidden"> <div className="aspect-square h-10 w-10 flex-shrink-0 rounded-full bg-cover bg-center bg-no-repeat" style={{ backgroundImage: `url(${avatarUrl})` }} aria-label={`Avatar for ${username}`} /> <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm sm:text-base"> <a href="#" className="font-semibold text-primary hover:underline truncate"> {username} </a> <span className={`inline-block px-2 py-0.5 text-xs font-semibold rounded-full ${isMerged ? 'bg-purple-500/30 text-purple-300' : 'bg-primary/30 text-primary' }`}> {action} </span> <span className="text-white/60">in</span> <a href="#" className="text-primary hover:underline truncate"> {repoName} </a> </div> </div> <div className="shrink-0"> <p className="text-sm font-normal leading-normal text-white/50"> {timestamp} </p> </div> </div> ); }; export default ActivityCard; - plugins/stitch-build/skills/react-components/package.json (398 bytes)
{ "name": "react-components", "version": "1.0.0", "description": "Design-to-code prompt to React components for Stitch MCP", "type": "module", "scripts": { "validate": "node scripts/validate.js", "fetch": "bash scripts/fetch-stitch.sh", "test": "node --test test/*.test.js" }, "dependencies": { "@swc/core": "^1.3.100" }, "engines": { "node": ">=18.0.0" } } - plugins/stitch-build/skills/react-components/README.md (1369 bytes)
# Stitch to React Components Skill ## Install ```bash npx skills add google-labs-code/stitch-skills --skill react:components --global ``` ## Example Prompt ```text Convert my Landing Page screen in my Podcast Stitch Project to a React component system. ``` ## Skill Structure This repository follows the **Agent Skills** open standard. Each skill is self-contained with its own logic, validation scripts, and design tokens. ```text skills/react-components/ ├── SKILL.md — Core instructions & workflow ├── package.json — Validator dependencies ├── scripts/ — Networking & AST validation ├── resources/ — Style guides & API references └── examples/ — Gold-standard code samples ``` ## How it Works When activated, the agent follows a high-fidelity engineering pipeline: 1. **Retrieval**: Uses a system-level `curl` script to bypass TLS/SNI issues on Google Cloud Storage. 2. **Mapping**: Cross-references Stitch metadata with the local `style-guide.json` to ensure token consistency. 3. **Generation**: Scaffolds components using a strict Atomic Design pattern. 4. **Validation**: Runs an automated AST check using `@swc/core` to prevent hardcoded hex values or missing interfaces. 5. **Audit**: Performs a final self-correction check against a 20-point architecture checklist.
- plugins/stitch-build/skills/react-components/resources/architecture-checklist.md (613 bytes)
# Architecture Quality Gate ### Structural integrity - [ ] Logic extracted to custom hooks in `src/hooks/`. - [ ] No monolithic files; strictly Atomic/Composite modularity. - [ ] All static text/URLs moved to `src/data/mockData.ts`. ### Type safety and syntax - [ ] Props use `Readonly<T>` interfaces. - [ ] File is syntactically valid TypeScript (no red squiggles). - [ ] Placeholders from templates (e.g., `StitchComponent`) have been replaced with actual names. ### Styling and theming - [ ] Dark mode (`dark:`) applied to all color classes. - [ ] No hardcoded hex values; use theme-mapped Tailwind classes.
- plugins/stitch-build/skills/react-components/resources/component-template.tsx (1049 bytes)
/** * Copyright 2026 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import React from 'react'; // Use a valid identifier like 'StitchComponent' as the placeholder interface StitchComponentProps { readonly children?: React.ReactNode; readonly className?: string; } export const StitchComponent: React.FC<StitchComponentProps> = ({ children, className = '', ...props }) => { return ( <div className={`relative ${className}`} {...props}> {children} </div> ); }; export default StitchComponent; - plugins/stitch-build/skills/react-components/resources/stitch-api-reference.md (1225 bytes)
# Stitch API reference This document describes the data structures returned by the Stitch MCP server to ensure accurate component mapping. ### Metadata schema When calling `get_screen`, the server returns a JSON object with these key properties: * **htmlCode**: Contains a `downloadUrl`. This is a signed URL that requires a system-level fetch (curl) to handle redirects and security handshakes. * **screenshot**: Includes a `downloadUrl` for the visual design. Use this to verify layout intent that might not be obvious in the raw HTML. * **deviceType**: Usually set to `DESKTOP`. All generated components should prioritize the corresponding viewport (2560px width) as the base layout. ### Technical mapping rules 1. **Element tracking**: Preserve `data-stitch-id` attributes as comments in the TSX to allow for future design synchronization. 2. **Asset handling**: Treat background images in the HTML as dynamic data. Extract the URLs into `mockData.ts` rather than hardcoding them into the component styles. 3. **Style extraction**: The HTML `<head>` contains a localized `tailwind.config`. This config must be merged with the local project theme to ensure colors like `primary` and `background-dark` render correctly.
- plugins/stitch-build/skills/react-components/resources/style-guide.json (496 bytes)
{ "theme": { "colors": { "primary": "#19e66f", "background": { "light": "#f6f8f7", "dark": "#112118", "elevated": "#1A1A1A" }, "accent": { "purple": "#8A2BE2", "lavender": "#D0A9F5" } }, "typography": { "display": [ "Space Grotesk", "sans-serif" ], "icons": "Material Symbols Outlined" }, "spacing": { "header-h": "72px", "container-max": "960px" } } } - plugins/stitch-build/skills/react-components/scripts/fetch-stitch.sh (1009 bytes)
#!/bin/bash # Copyright 2026 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. URL=$1 OUTPUT=$2 if [ -z "$URL" ] || [ -z "$OUTPUT" ]; then echo "Usage: $0 <url> <output_path>" exit 1 fi echo "Initiating high-reliability fetch for Stitch HTML..." curl -L -f -sS --connect-timeout 10 --compressed "$URL" -o "$OUTPUT" if [ $? -eq 0 ]; then echo "✅ Successfully retrieved HTML at: $OUTPUT" exit 0 else echo "❌ Error: Failed to retrieve content. Check TLS/SNI or URL expiration." exit 1 fi
- plugins/stitch-build/skills/react-components/scripts/validate.js (3193 bytes)
/** * Copyright 2026 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import swc from '@swc/core'; import fs from 'node:fs'; import path from 'node:path'; const HEX_COLOR_REGEX = /#[0-9A-Fa-f]{3,8}\b/; async function validateComponent(filePath) { if (!filePath) { console.error("Usage: node validate.js <path-to-component>"); process.exit(1); } try { const code = fs.readFileSync(filePath, 'utf-8'); const filename = path.basename(filePath); const ast = await swc.parse(code, { syntax: "typescript", tsx: true }); let hasInterface = false; let tailwindIssues = []; console.log("🔍 Scanning AST..."); const scanClassName = (node) => { if (!node || typeof node !== 'object') return; const text = node.type === 'StringLiteral' ? node.value : node.type === 'TemplateElement' ? (node.cooked ?? node.raw) : null; if (typeof text === 'string' && HEX_COLOR_REGEX.test(text)) { tailwindIssues.push(text); } for (const key in node) { if (key !== 'span' && node[key] && typeof node[key] === 'object') { scanClassName(node[key]); } } }; const walk = (node) => { if (!node || typeof node !== 'object') return; if (Array.isArray(node)) { for (const item of node) walk(item); return; } if (typeof node.type !== 'string') return; if (node.type === 'TsInterfaceDeclaration' && node.id.value.endsWith('Props')) hasInterface = true; if (node.type === 'JSXAttribute' && (node.name?.value === 'className' || node.name?.name === 'className')) { scanClassName(node.value); } for (const key in node) { if (key === 'span') continue; if (node[key] && typeof node[key] === 'object') walk(node[key]); } }; walk(ast); console.log(`--- Validation for: ${filename} ---`); if (hasInterface) { console.log("✅ Props declaration found."); } else { console.error("❌ MISSING: Props interface (must end in 'Props')."); } if (tailwindIssues.length === 0) { console.log("✅ No hardcoded hex values found."); } else { console.error(`❌ STYLE: Found ${tailwindIssues.length} hardcoded hex codes.`); tailwindIssues.forEach(hex => console.error(` - ${hex}`)); } if (hasInterface && tailwindIssues.length === 0) { console.log("\n✨ COMPONENT VALID."); process.exit(0); } else { console.error("\n🚫 VALIDATION FAILED."); process.exit(1); } } catch (err) { console.error("❌ ERROR:", err.message); process.exit(1); } } validateComponent(process.argv[2]); - plugins/stitch-build/skills/react-components/SKILL.md (8769 bytes)
--- name: stitch::react-components description: >- Converts Stitch designs into modular Vite and React components, or syncs/updates existing React components to align with the latest Stitch designs, using system-level networking and AST-based validation. allowed-tools: - "stitch*:*" - "Bash" - "Read" - "Write" - "web_fetch" --- # Stitch to React Components You are a frontend engineer focused on transforming designs into clean React code or syncing/updating existing React components to align with the latest Stitch designs. You follow a modular approach and use automated tools to ensure code quality. > **CRITICAL: Every step in this skill is MANDATORY. Do NOT skip any step or take shortcuts. Each section contains a GATE that must be satisfied before proceeding.** ## Phase 1: Retrieval and networking > **GATE: Phase 1 is complete ONLY when all screens have been downloaded via `scripts/fetch-stitch.sh` AND visually audited. Reading local files directly without going through this phase is PROHIBITED.** 1. **Namespace discovery**: Run `list_tools` to find the Stitch MCP prefix. Use this prefix (e.g., `stitch:`) for all subsequent calls. 2. **Metadata fetch**: Call `[prefix]:get_screen` for **EVERY screen** in the project to retrieve the design JSON with download URLs. Do NOT skip any screen. 3. **Check for existing designs**: Before downloading, check if `.stitch/designs/{page}.html` and `.stitch/designs/{page}.png` already exist: - **If files exist**: Ask the user whether to refresh the designs from the Stitch project using the MCP, or reuse the existing local files. **You MUST ask — do not assume.** Only re-download if the user confirms. - **If files do not exist**: Proceed to step 4. 4. **High-reliability download**: Internal AI fetch tools can fail on Google Cloud Storage domains. You MUST use the provided script. - **HTML**: `bash scripts/fetch-stitch.sh "[htmlCode.downloadUrl]" ".stitch/designs/{page}.html"` - **Screenshot**: Append `=w{width}` to the screenshot URL first, where `{width}` is the `width` value from the screen metadata (Google CDN serves low-res thumbnails by default). Then run: `bash scripts/fetch-stitch.sh "[screenshot.downloadUrl]=w{width}" ".stitch/designs/{page}.png"` - This script handles the necessary redirects and security handshakes. 5. **Visual audit**: Review the downloaded screenshot (`.stitch/designs/{page}.png`) to confirm design intent and layout details. **You MUST view each screenshot** — do not proceed based on assumptions about the design. 6. **Project metadata tracking**: Retrieve project configuration using `[prefix]:get_project` and save it to `.stitch/metadata.json` (inside the app folder, and mirrored in the workspace root). Ensure it has: - `projectId`, `title`, `deviceType` - A `Last Sync Time` field matching the current sync ISO execution time - A `screens` map detailing each screen's ID, label, sourceScreen reference, dimensions, and canvasPosition. ### Anti-patterns for Phase 1 - ❌ Reading `.stitch/designs/*.html` directly without calling MCP `get_screen` first. - ❌ Skipping the `fetch-stitch.sh` download script. - ❌ Not asking the user when existing files are found. - ❌ Skipping the visual audit of `.png` screenshots. - ❌ Failing to generate or update `.stitch/metadata.json` and its `Last Sync Time` field upon syncing. ## Phase 2: Style extraction > **GATE: Phase 2 is complete ONLY when `resources/style-guide.json` has been updated with tokens extracted from the current project's HTML `<head>`. Tokens from a previous project are NOT acceptable.** 1. **Extract `tailwind.config`**: Open each downloaded HTML file and locate the `tailwind.config` object in the `<head>` `<script>` block. Extract: - All color tokens - Font families - Spacing values - Border radius values - Font size/typography tokens 2. **Sync `resources/style-guide.json`**: Overwrite the file with the extracted tokens from THIS project. The style guide MUST match the Stitch project being converted. 3. **Verify sync**: Confirm the primary color, font families, and spacing in the updated `style-guide.json` match what you extracted. ### Anti-patterns for Phase 2 - ❌ Using `style-guide.json` as-is without verifying it matches the current project. - ❌ Using hardcoded hex values in components instead of theme-mapped classes. ## Phase 3: Architectural rules > **GATE: Every component MUST satisfy ALL of the following rules. Violations will cause `npm run validate` to fail.** * **Modular components**: Break the design into independent files. **Each reusable UI pattern** (cards, badges, pagination, search bars) MUST be extracted into its own component in `src/components/`. Monolithic page files that contain everything are PROHIBITED. * **Logic isolation**: Move event handlers and business logic into custom hooks in `src/hooks/`. Examples: pagination logic → `usePagination`, filtering → `useFilter`. * **Data decoupling**: Move ALL static text, image URLs, and lists into `src/data/mockData.ts`. No hardcoded content in components. * **Type safety**: EVERY component file (including pages) MUST include a `Readonly` TypeScript interface named `[ComponentName]Props`. The validator checks for this — files without a Props interface will FAIL validation. * **Project specific**: Focus on the target project's needs and constraints. Leave Google license headers out of the generated React components. * **Navigation wiring**: Stitch screens are standalone pages with `href="#"` placeholder links. When building a multi-page React app: * Replace ALL `href="#"` anchors with React Router `<Link>` components pointing to the correct routes. * **Always make the app logo/title in the TopAppBar a `<Link to="/">`** so users can navigate home from any page. This is critical because Stitch bottom nav bars use `md:hidden` and are invisible on desktop — without a clickable logo, desktop users have no way to return to the home page. * Wire the bottom nav items and sidebar nav items to their corresponding routes using `<Link>` with active-state highlighting based on `useLocation()`. * **Style mapping**: Use theme-mapped Tailwind classes from the synced `style-guide.json`. No arbitrary hex codes. * **Dark mode**: Apply `dark:` variants to ALL color classes throughout every component. ### Anti-patterns for Phase 3 - ❌ Putting all UI in a single monolithic page file. - ❌ Inline event handlers or business logic without hooks. - ❌ Hardcoding text, URLs, or data in component files. - ❌ Components without a `[Name]Props` interface. - ❌ Using hex color values instead of theme tokens. - ❌ Leaving `href="#"` links unconverted. ## Phase 4: Execution steps > **GATE: Phase 4 verification, audits, and validation checks are optional. You MUST ask the user's permission to proceed with validation scripts, running local dev servers, or automated browser testing.** 1. **Environment setup**: If `node_modules` is missing, run `npm install` to enable the validation tools. 2. **Data layer**: Create `src/data/mockData.ts` based on the design content. 3. **Component drafting**: Use `resources/component-template.tsx` as a base. Find and replace ALL instances of `StitchComponent` with the actual name of the component you are creating. 4. **Application wiring**: Update the project entry point (like `App.tsx`) to render the new components. 5. **Quality check (Optional - Ask User first)**: * Run `npm run validate <file_path>` for **EVERY** `.tsx` file in `src/components/` and `src/pages/` to report component validity. * Run `tsc --noEmit` to verify TypeScript compile status. * Check output against `resources/architecture-checklist.md`. * Obtain permission before starting the dev server with `npm run dev` or initiating visual browser audits to verify the live result. ### Anti-patterns for Phase 4 - ❌ Commencing dev server start or browser audits without user consent. - ❌ Declaring task "done" without verifying code compiles. ## Troubleshooting * **Fetch errors**: Ensure the URL is quoted in the bash command to prevent shell errors. * **Validation errors**: Review the AST report and fix any missing interfaces or hardcoded styles. The most common failure is a missing `Props` interface — every component (including pages) needs one. * **Dead navigation links**: Stitch HTML uses `href="#"` placeholders everywhere. Every `<a href="#">` must be converted to a `<Link to="/route">` with a real route. Verify all nav items are clickable and lead to the correct page. * **Stale style-guide.json**: If colors or fonts look wrong, the `style-guide.json` likely has tokens from a different project. Re-extract from the current HTML `<head>`. - plugins/stitch-build/skills/react-native/examples/gold-standard-card.tsx (3826 bytes)
/** * Copyright 2026 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import React from 'react'; import { View, Text, Image, Pressable, StyleSheet, Platform } from 'react-native'; import { colors, shadows } from '../src/theme'; /** * Gold Standard: ActivityCard * This file is the definitive reference for the agent. */ export interface ActivityCardProps { readonly id: string; readonly username: string; readonly action: 'MERGED' | 'COMMIT'; readonly timestamp: string; readonly avatarUrl: string; readonly repoName: string; readonly onPress?: () => void; } export const ActivityCard: React.FC<ActivityCardProps> = ({ username, action, timestamp, avatarUrl, repoName, onPress, }) => { const isMerged = action === 'MERGED'; return ( <Pressable style={({ pressed }) => [styles.container, pressed && styles.pressed]} onPress={onPress} accessibilityRole="button" accessibilityLabel={`${username} ${action.toLowerCase()} in ${repoName}`} > <View style={styles.leftContent}> <Image source={{ uri: avatarUrl }} style={styles.avatar} accessibilityLabel={`Avatar for ${username}`} /> <View style={styles.textContent}> <Text style={styles.username} numberOfLines={1}> {username} </Text> <View style={[ styles.badge, isMerged ? styles.badgeMerged : styles.badgeCommit, ]} > <Text style={[ styles.badgeText, isMerged ? styles.badgeTextMerged : styles.badgeTextCommit, ]} > {action} </Text> </View> <Text style={styles.separator}>in</Text> <Text style={styles.repoName} numberOfLines={1}> {repoName} </Text> </View> </View> <Text style={styles.timestamp}>{timestamp}</Text> </Pressable> ); }; const styles = StyleSheet.create({ container: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: 16, borderRadius: 8, padding: 16, minHeight: 56, ...shadows.card, }, pressed: { opacity: 0.7, }, leftContent: { flexDirection: 'row', alignItems: 'center', gap: 16, flex: 1, overflow: 'hidden', }, avatar: { width: 40, height: 40, borderRadius: 20, }, textContent: { flexDirection: 'row', flexWrap: 'wrap', alignItems: 'center', columnGap: 8, rowGap: 4, flex: 1, }, username: { fontWeight: '600', fontSize: 14, }, badge: { paddingHorizontal: 8, paddingVertical: 2, borderRadius: 12, }, badgeMerged: { backgroundColor: colors.badgeMergedBg, }, badgeCommit: { backgroundColor: colors.badgeCommitBg, }, badgeText: { fontSize: 12, fontWeight: '600', }, badgeTextMerged: { color: colors.badgeMergedText, }, badgeTextCommit: { color: colors.badgeCommitText, }, separator: { fontSize: 14, opacity: 0.6, }, repoName: { fontSize: 14, }, timestamp: { fontSize: 14, fontWeight: '400', opacity: 0.5, flexShrink: 0, }, }); export default ActivityCard; - plugins/stitch-build/skills/react-native/package.json (412 bytes)
{ "name": "react-native-components", "version": "1.0.0", "description": "Design-to-code prompt to React Native components for Stitch MCP", "type": "module", "scripts": { "validate": "node scripts/validate.js", "fetch": "bash scripts/fetch-stitch.sh", "test": "node --test test/*.test.js" }, "dependencies": { "@swc/core": "^1.3.100" }, "engines": { "node": ">=18.0.0" } } - plugins/stitch-build/skills/react-native/README.md (1423 bytes)
# Stitch to React Native Components Skill ## Install ```bash npx skills add google-labs-code/stitch-skills --skill react-native --global ``` ## Example Prompt ```text Convert my Login screen in my Stitch Project to React Native components. ``` ## Skill Structure This skill follows the **Agent Skills** open standard. Each skill is self-contained with its own logic, validation scripts, and design tokens. ```text skills/react-native/ ├── SKILL.md — Core instructions & workflow ├── package.json — Validator dependencies ├── scripts/ — Networking & AST validation ├── resources/ — Architecture checklist & component templates └── examples/ — Gold-standard code samples ``` ## How it Works When activated, the agent follows a design-to-native pipeline: 1. **Retrieval**: Uses a system-level `curl` script to download Stitch HTML and screenshots from Google Cloud Storage. 2. **Mapping**: Translates HTML elements to React Native primitives (`View`, `Text`, `Pressable`, `Image`, etc.) and converts CSS/Tailwind to `StyleSheet.create()` calls. 3. **Generation**: Scaffolds components using Atomic Design (atoms, molecules, organisms). 4. **Validation**: Runs an automated AST check to catch missing Props interfaces or hardcoded style values. 5. **Audit**: Performs a final self-correction check against the architecture checklist.
- plugins/stitch-build/skills/react-native/resources/architecture-checklist.md (2060 bytes)
# Architecture Quality Gate ### Structural integrity - [ ] Components organized by Atomic Design: atoms, molecules, organisms in `src/components/`. - [ ] Logic extracted to custom hooks in `src/hooks/`. - [ ] No monolithic files. Each component in its own file. - [ ] All static text, image URIs, and list data moved to `src/data/mockData.ts`. ### Type safety and syntax - [ ] Every component exports a `[ComponentName]Props` interface with `readonly` property modifiers. - [ ] File is syntactically valid TypeScript (no parse errors). - [ ] Placeholders from template (e.g., `StitchComponent`) have been replaced with actual names. - [ ] Navigation screen params are typed with `NativeStackScreenProps` or equivalent. ### React Native primitives - [ ] No HTML elements (`div`, `span`, `p`, `img`, `button`). Only React Native components. - [ ] All text wrapped in `Text` components. No raw strings inside `View`. - [ ] `Pressable` used for interactive elements (not `TouchableOpacity` or `TouchableHighlight`). - [ ] `FlatList` used for dynamic/long lists (not `ScrollView` with `.map()`). - [ ] `Image` components have explicit `width` and `height` or `aspectRatio`. ### Styling - [ ] All styles defined via `StyleSheet.create()` at the bottom of the file. - [ ] No inline style objects (use `StyleSheet` references). - [ ] No hardcoded hex values. Colors referenced from `src/theme.ts`. - [ ] Shadows use `Platform.select()` for iOS/Android differences. - [ ] `flexDirection` explicitly set where row layout is needed (default is `column`). ### Accessibility - [ ] Interactive elements have `accessibilityLabel` and `accessibilityRole`. - [ ] Images have descriptive `accessibilityLabel`. - [ ] Toggle/checkbox elements use `accessibilityState`. ### Platform handling - [ ] Top-level screens wrapped with `SafeAreaView` from `react-native-safe-area-context`. - [ ] Platform-specific code uses `Platform.select()` or `Platform.OS` checks. - [ ] Responsive dimensions use `useWindowDimensions()` (not hardcoded pixel values for screen-relative sizing).
- plugins/stitch-build/skills/react-native/resources/component-template.tsx (498 bytes)
import React from 'react'; import { View, StyleSheet } from 'react-native'; export interface StitchComponentProps { readonly children?: React.ReactNode; readonly testID?: string; } export const StitchComponent: React.FC<StitchComponentProps> = ({ children, testID, }) => { return ( <View style={styles.container} testID={testID} accessibilityRole="none"> {children} </View> ); }; const styles = StyleSheet.create({ container: {}, }); export default StitchComponent; - plugins/stitch-build/skills/react-native/scripts/fetch-stitch.sh (1033 bytes)
#!/bin/bash # Copyright 2026 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. URL=$1 OUTPUT=$2 if [ -z "$URL" ] || [ -z "$OUTPUT" ]; then echo "Usage: $0 <url> <output_path>" exit 1 fi mkdir -p "$(dirname "$OUTPUT")" echo "Initiating high-reliability fetch for Stitch HTML..." curl -L -f -sS --connect-timeout 10 --compressed "$URL" -o "$OUTPUT" if [ $? -eq 0 ]; then echo "Successfully retrieved HTML at: $OUTPUT" exit 0 else echo "Error: Failed to retrieve content. Check TLS/SNI or URL expiration." exit 1 fi
- plugins/stitch-build/skills/react-native/scripts/validate.js (5304 bytes)
/** * Copyright 2026 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import swc from '@swc/core'; import fs from 'node:fs'; import path from 'node:path'; const HEX_COLOR_REGEX = /#[0-9A-Fa-f]{3,8}\b/; const RGBA_COLOR_REGEX = /^rgba?\(\s*\d/; // Standard HTML and SVG host elements have no React Native implementation. // Unknown names can belong to a custom native view manager and are left alone. const WEB_ELEMENTS = new Set(` a abbr address area article aside audio b base bdi bdo blockquote body br button canvas caption cite code col colgroup data datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe img input ins kbd label legend li link main map mark menu meta meter nav noscript object ol optgroup option output p picture pre progress q rp rt ruby s samp script search section select slot small source span strong style sub summary sup table tbody td template textarea tfoot th thead time title tr track u ul var video wbr svg animate animateMotion animateTransform circle clipPath defs desc ellipse feBlend feColorMatrix feComponentTransfer feComposite feConvolveMatrix feDiffuseLighting feDisplacementMap feDistantLight feDropShadow feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur feImage feMerge feMergeNode feMorphology feOffset fePointLight feSpecularLighting feSpotLight feTile feTurbulence filter foreignObject g image line linearGradient marker mask metadata mpath path pattern polygon polyline radialGradient rect set stop switch symbol text textPath tspan use view `.trim().split(/\s+/)); async function validateComponent(filePath) { if (!filePath) { console.error("Usage: node validate.js <path-to-component>"); process.exit(1); } try { const code = fs.readFileSync(filePath, 'utf-8'); const filename = path.basename(filePath); const ast = await swc.parse(code, { syntax: "typescript", tsx: true }); let hasInterface = false; let hasExportedInterface = false; let colorIssues = []; let htmlElements = []; console.log("Scanning AST..."); const walk = (node, parent) => { if (!node || typeof node !== 'object') return; if (Array.isArray(node)) { for (const item of node) walk(item, parent); return; } if (typeof node.type !== 'string') return; if (node.type === 'TsInterfaceDeclaration' && node.id.value.endsWith('Props')) { hasInterface = true; if (parent?.type === 'ExportDeclaration') { hasExportedInterface = true; } } // Check for hardcoded hex values in strings if (node.type === 'StringLiteral' && HEX_COLOR_REGEX.test(node.value)) { colorIssues.push(node.value); } // Check for rgba() color strings if (node.type === 'StringLiteral' && RGBA_COLOR_REGEX.test(node.value)) { colorIssues.push(node.value); } // Check for HTML elements used as JSX tags if (node.type === 'JSXOpeningElement' && node.name?.type === 'Identifier') { const tagName = node.name.value; if (WEB_ELEMENTS.has(tagName)) { htmlElements.push(tagName); } } for (const key in node) { if (key === 'span') continue; if (node[key] && typeof node[key] === 'object') walk(node[key], node); } }; walk(ast, null); console.log(`--- Validation for: ${filename} ---`); let valid = true; if (hasExportedInterface) { console.log("PASS: Exported Props interface found."); } else if (hasInterface) { console.error("WARN: Props interface found but not exported. Add 'export' keyword."); valid = false; } else { console.error("FAIL: Missing Props interface (must end in 'Props' and be exported)."); valid = false; } if (colorIssues.length === 0) { console.log("PASS: No hardcoded color values found."); } else { console.error(`FAIL: Found ${colorIssues.length} hardcoded colors. Use theme.ts instead.`); colorIssues.forEach(c => console.error(` - ${c}`)); valid = false; } if (htmlElements.length === 0) { console.log("PASS: No HTML elements found. Using React Native primitives."); } else { const unique = [...new Set(htmlElements)]; console.error(`FAIL: Found HTML elements: ${unique.join(', ')}. Replace with React Native components.`); valid = false; } if (valid) { console.log("\nCOMPONENT VALID."); process.exit(0); } else { console.error("\nVALIDATION FAILED."); process.exit(1); } } catch (err) { console.error("ERROR:", err.message); process.exit(1); } } validateComponent(process.argv[2]); - plugins/stitch-build/skills/react-native/SKILL.md (12427 bytes)
--- name: stitch::react-native description: >- Convert Stitch HTML designs to React Native components, or syncs/updates existing native components to align with the latest Stitch designs, using StyleSheet. allowed-tools: - "stitch*:*" - "Bash" - "Read" - "Write" - "web_fetch" --- # Stitch to React Native Components You are a mobile engineer focused on transforming Stitch web designs into clean, production-ready React Native code or syncing/updating existing native components to align with the latest Stitch designs. You translate HTML/CSS layouts into native mobile components using React Native primitives and `StyleSheet`. > **CRITICAL: Every step in this skill is MANDATORY. Do NOT skip any step or take shortcuts. Each section contains a GATE that must be satisfied before proceeding.** ## Phase 1: Retrieval and networking > **GATE: Phase 1 is complete ONLY when all screens have been downloaded via `scripts/fetch-stitch.sh` AND visually audited. Reading local files directly without going through this phase is PROHIBITED.** 1. **Namespace discovery**: Run `list_tools` to find the Stitch MCP prefix. Use this prefix (e.g., `stitch:`) for all subsequent calls. 2. **Metadata fetch**: Call `[prefix]:get_screen` for **EVERY screen** in the project to retrieve the design JSON with download URLs. Do NOT skip any screen. 3. **Check for existing designs**: Before downloading, check if `.stitch/designs/{page}.html` and `.stitch/designs/{page}.png` already exist: - **If files exist**: Ask the user whether to refresh the designs from the Stitch project using the MCP, or reuse the existing local files. **You MUST ask — do not assume.** Only re-download if the user confirms. - **If files do not exist**: Proceed to step 4. 4. **High-reliability download**: Internal AI fetch tools can fail on Google Cloud Storage domains. You MUST use the provided script. - **HTML**: `bash scripts/fetch-stitch.sh "[htmlCode.downloadUrl]" ".stitch/designs/{page}.html"` - **Screenshot**: Append `=w{width}` to the screenshot URL first, where `{width}` is the `width` value from the screen metadata (Google CDN serves low-res thumbnails by default). Then run: `bash scripts/fetch-stitch.sh "[screenshot.downloadUrl]=w{width}" ".stitch/designs/{page}.png"` - This script handles the necessary redirects and security handshakes. 5. **Visual audit**: Review the downloaded screenshot (`.stitch/designs/{page}.png`) to confirm design intent and layout details. **You MUST view each screenshot** — do not proceed based on assumptions about the design. 6. **Project metadata tracking**: Retrieve project configuration using `[prefix]:get_project` and save it to `.stitch/metadata.json` (inside the app folder, and mirrored in the workspace root). Ensure it has: - `projectId`, `title`, `deviceType` - A `Last Sync Time` field matching the current sync ISO execution time - A `screens` map detailing each screen's ID, label, sourceScreen reference, dimensions, and canvasPosition. ### Anti-patterns for Phase 1 - ❌ Reading `.stitch/designs/*.html` directly without calling MCP `get_screen` first. - ❌ Skipping the `fetch-stitch.sh` download script. - ❌ Not asking the user when existing files are found. - ❌ Skipping the visual audit of `.png` screenshots. - ❌ Failing to generate or update `.stitch/metadata.json` and its `Last Sync Time` field upon syncing. ## Phase 2: Theme extraction > **GATE: Phase 2 is complete ONLY when `src/theme.ts` has been created or updated with tokens extracted from the current project's HTML `<head>`. Hardcoding color hex codes or using themes from a different project is NOT acceptable.** 1. **Extract `tailwind.config`**: Open each downloaded HTML file and locate the `tailwind.config` object in the `<head>` `<script>` block. Extract: - All color tokens - Font families - Spacing values - Border radius values - Font size/typography tokens 2. **Create/Sync `src/theme.ts`**: Write the extracted tokens to `src/theme.ts` as TypeScript constants. Ensure every color, spacing, and typography value has a corresponding token. 3. **Verify theme**: Confirm the theme colors and fonts in `src/theme.ts` match what you extracted from the HTML design. ### Anti-patterns for Phase 2 - ❌ Hardcoding color hex codes or rgba strings directly inside component StyleSheet declarations. - ❌ Using theme tokens from a previous project without extracting them from the new design. - ❌ Skipping the creation/update of `src/theme.ts`. ## Phase 3: Architectural rules and HTML mapping > **GATE: Every component MUST satisfy ALL of the following rules. Violations will cause `npm run validate` to fail.** ### Element mapping Map HTML elements to React Native components using these rules: | HTML | React Native | Notes | |------|-------------|-------| | `<div>` | `View` | Default container | | `<span>`, `<p>`, `<h1>`-`<h6>` | `Text` | All text must be wrapped in `Text`. Nest `Text` for inline styling. | | `<img>` | `Image` | Use `source={{ uri }}` for remote images, `require()` for local assets. | | `<button>`, `<a>` | `Pressable` | Prefer `Pressable` over `TouchableOpacity`. Use `onPress` instead of `onClick`. | | `<input>` | `TextInput` | Map `placeholder`, `value`, `onChangeText`. | | `<scroll container>` | `ScrollView` | For short lists only. Use `FlatList` for long or dynamic lists. | | `<ul>`/`<ol>` with many items | `FlatList` | Requires `data`, `renderItem`, `keyExtractor`. | | `<section>` with grouped data | `SectionList` | For grouped data with headers. Use tab navigator for tab-based layouts. | | `<select>` | Third-party picker or custom modal | React Native has no built-in select. | | `<svg>` | `react-native-svg` | Convert SVG markup to `Svg`, `Path`, `Circle`, etc. | | Root wrapper | `SafeAreaView` | Wrap top-level screens to avoid notch/status bar overlap. | ### Style mapping CSS and Tailwind classes do not work in React Native. Convert all styles to `StyleSheet.create()`: * **Layout**: Flexbox is the default layout system. `flexDirection` defaults to `'column'` (not `'row'` like web CSS). - `display: flex` is implicit on every `View`. - `justify-content` maps to `justifyContent`. - `align-items` maps to `alignItems`. - `gap` maps to `gap` (React Native 0.71+). For older versions, use `marginBottom` on children. * **Dimensions**: Use numbers (not strings). `width: 100` means 100 density-independent pixels. - Percentage strings are supported: `width: '100%'`. - For responsive sizing, use `useWindowDimensions()` from `react-native`. - There is no `vw`/`vh`. Calculate from `Dimensions.get('window')`. * **Typography**: All text styles must be on `Text` components, never on `View`. - `font-size` maps to `fontSize` (number, not string). - `font-weight` maps to `fontWeight` (string: `'400'`, `'700'`, `'bold'`). - `line-height` maps to `lineHeight` (number). - `letter-spacing` maps to `letterSpacing`. - `text-transform` maps to `textTransform`. - `color` applies to `Text` only. * **Borders and shadows**: - `border-radius` maps to `borderRadius`. - `box-shadow` does not exist. Use `elevation` (Android) and `shadowColor`/`shadowOffset`/`shadowOpacity`/`shadowRadius` (iOS). Use `Platform.select()` to apply platform-specific shadow styles. * **Unsupported CSS properties**: Do not use `hover`, `transition`, `animation` (use `react-native-reanimated` for animations), or `position: fixed` (use absolute positioning instead). ### Architectural Rules * **Modular components (Atomic Design)**: Break the design into independent files. Organize components as atoms (buttons, labels, icons), molecules (input groups, cards), and organisms (headers, lists, forms). Place them in `src/components/atoms/`, `src/components/molecules/`, and `src/components/organisms/`. Monolithic page/screen files are PROHIBITED. * **Logic isolation**: Move event handlers, API calls, and business logic into custom hooks in `src/hooks/`. Components should only handle rendering. * **Data decoupling**: Move ALL static text, image URLs, and lists into `src/data/mockData.ts`. No hardcoded content in components. * **Type safety**: EVERY component file (including screens) MUST export a TypeScript interface named `[ComponentName]Props` with `readonly` property modifiers. The validator requires the interface to be **exported** — files without an exported Props interface will FAIL validation. * **No hardcoded styles**: Extract colors, spacing, and font sizes into `src/theme.ts`. Reference them in `StyleSheet.create()`. Absolutely no raw color hex codes or rgba strings are allowed in component files. * **Navigation**: Use React Navigation for screen transitions. Define screen types with `NativeStackScreenProps` or `BottomTabScreenProps`. * **Accessibility**: Every interactive element must have `accessibilityLabel` and `accessibilityRole`. Images need `accessibilityLabel`. Use `accessibilityState` for toggles and checkboxes. * **Safe areas**: Wrap top-level screen components with `SafeAreaView` from `react-native-safe-area-context` (not the default one from `react-native`). * **Project specific**: Focus on the target project's needs and constraints. Leave Google license headers out of the generated components. ### Platform-specific code When the design requires different behavior on iOS and Android: ```typescript import { Platform } from 'react-native'; const styles = StyleSheet.create({ shadow: Platform.select({ ios: { shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.1, shadowRadius: 4, }, android: { elevation: 4, }, }), }); ``` ### Anti-patterns for Phase 3 - ❌ Putting all UI in a single monolithic screen file. - ❌ Using HTML tags (like `div`, `span`, `p`) instead of React Native components. - ❌ Inline event handlers or business logic without custom hooks. - ❌ Hardcoding text, URLs, or colors in component files. - ❌ Components without an **exported** `[Name]Props` interface. - ❌ Using raw hex color values or rgba strings in `StyleSheet.create()`. ## Phase 4: Execution steps > **GATE: Phase 4 verification, audits, and simulator/packager testing are optional. You MUST ask the user's permission to proceed with validation scripts, starting packagers, or simulator audits.** 1. **Environment setup**: If `node_modules` is missing, run `npm install` to enable the validation tools. 2. **Theme layer**: Create `src/theme.ts` from the extracted Tailwind config. 3. **Data layer**: Create `src/data/mockData.ts` based on the design content. 4. **Component drafting**: Use `resources/component-template.tsx` as a base. Find and replace ALL instances of `StitchComponent` with the actual component name. Map HTML elements to React Native primitives. 5. **Navigation wiring**: If the design has multiple screens, set up a `NavigationContainer` with a stack or tab navigator in `App.tsx`. 6. **Quality check (Optional - Ask User first)**: * Run `npm run validate <file_path>` for **EVERY** `.tsx` file in components and screens to report component validity. * Run `tsc --noEmit` to verify TypeScript compile status. * Check output against `resources/architecture-checklist.md`. * Obtain permission before starting the packager (`npx react-native start` or `npx expo start`) or starting visual simulator audits to verify the app renders correctly on a simulator/device. ### Anti-patterns for Phase 4 - ❌ Launching packagers or simulators without user consent. - ❌ Declaring task "done" without verifying code compiles. ## Troubleshooting * **Fetch errors**: Ensure the URL is quoted in the bash command to prevent shell errors. * **Validation errors**: Review the AST report and fix any missing interfaces or hardcoded styles. The most common failures are missing an **exported** `Props` interface or leaving raw hex colors in `StyleSheet.create()`. * **Text outside Text component**: React Native crashes if raw strings appear outside `<Text>`. Verify all text nodes are wrapped. * **Image sizing**: Unlike web `<img>`, React Native `Image` has no intrinsic size. Always specify `width` and `height` in styles or use `aspectRatio`. * **FlatList vs ScrollView**: If you see a "VirtualizedList inside ScrollView" warning, replace the outer `ScrollView` with a plain `View` or use `FlatList` `ListHeaderComponent`/`ListFooterComponent`. - plugins/stitch-build/skills/react-vite-dashboard/README.md (624 bytes)
# React + Vite Dashboard Skill Convert Stitch screens into production React dashboards with Vite, TanStack Query, and optional Web3 reads. ## Install ```bash npx skills add google-labs-code/stitch-skills --skill react-vite-dashboard --global ``` ## Example prompts ``` Convert the Stitch dashboard screen into React + Vite components using our DESIGN.md tokens ``` ``` Wire the portfolio summary cards with TanStack Query and ethers read-only calls ``` ## Related skills - `design-md` — author and lint DESIGN.md before building UI - `shadcn-ui` — add accessible component primitives on top of generated layouts
- plugins/stitch-build/skills/react-vite-dashboard/SKILL.md (3702 bytes)
--- name: react-vite-dashboard description: Convert Stitch designs into production React + Vite dashboards with TanStack Query, accessible tokens from DESIGN.md, and Web3-ready patterns (ethers/viem). allowed-tools: - "stitch*:*" - "Read" - "Write" - "Bash" - "web_fetch" --- # Stitch to React + Vite Dashboard You are a frontend engineer building **data-dense dashboards** from Stitch screens. Target stack: **React 18**, **Vite**, **TypeScript**, **TanStack Query**, **React Router**, and optional **ethers v6** or **viem** for on-chain reads. ## Prerequisites - Stitch MCP configured ([setup guide](https://stitch.withgoogle.com/docs/mcp/setup/)) - A project `DESIGN.md` (see the `design-md` skill) for token fidelity - Vite + React + TypeScript scaffold (`npm create vite@latest`) ## Workflow 1. **Discover MCP prefix** — run `list_tools`, note the Stitch prefix (e.g. `stitch:`). 2. **Fetch screen** — `[prefix]:get_screen` with project and screen IDs. 3. **Download assets** — persist HTML/screenshot under `.stitch/designs/{screen}.html` and `.png`. 4. **Read DESIGN.md** — map `colors.*`, `typography.*`, `spacing.*` to CSS variables in `src/index.css`. 5. **Generate components** — split into `src/components/`, `src/pages/`, `src/hooks/`. 6. **Wire data** — use TanStack Query for async fetches; keep presentational components pure. ## HTML → React mapping | Pattern | Implementation | |---------|----------------| | Layout grid / flex | Tailwind utilities or CSS modules aligned to DESIGN.md spacing tokens | | Cards / panels | `<section>` with tokenized border-radius and elevation fallbacks for forced-colors | | Tables | Semantic `<table>` or TanStack Table; never div-only grids for tabular data | | Buttons | `<button type="button">` with visible focus ring (preserve browser default unless DESIGN.md defines focus tokens) | | Forms | `<label htmlFor>` + `<input id>`; associate errors with `aria-describedby` | | Loading | Skeleton components; `aria-busy` on containers during fetch | | Wallet connect | Isolate in `WalletProvider`; never embed private keys in generated code | ## DESIGN.md integration ```css /* src/index.css — example token bridge */ :root { --color-primary: /* from DESIGN.md colors.primary */; --font-body: /* typography.body-md.fontFamily */; } ``` Run the design.md linter locally before shipping UI: ```bash npx @google/design.md lint DESIGN.md ``` ## Web3 dashboard conventions - Read-only contract calls via `useReadContract` (viem/wagmi) or ethers `Contract` + TanStack Query `queryFn`. - Format token amounts with `formatUnits`; show network name and chain ID in settings footer. - Surface transaction errors in plain language; link to block explorer when `txHash` exists. - Gas-sensitive flows: batch reads, avoid redundant `eth_call` in render loops. ## File structure ``` src/ ├── components/ # Presentational UI from Stitch ├── pages/ # Route-level screens ├── hooks/ # useQuery wrappers, wallet hooks ├── lib/ # ABI helpers, formatters └── styles/ # Token CSS variables ``` ## Quality checklist - [ ] WCAG 2.2 AA: contrast from DESIGN.md component pairs passes linter - [ ] Keyboard navigable: focus order matches visual order - [ ] Responsive: test at 375px and 1280px widths - [ ] No secrets in repo: RPC URLs from env (`VITE_*` prefix only for public endpoints) - [ ] TypeScript strict: no `any` on contract ABIs ## Stitch docs note When following links on [stitch.withgoogle.com/docs](https://stitch.withgoogle.com/docs/), use the full `https://stitch.withgoogle.com/docs/...` URL if relative navigation redirects incorrectly. - plugins/stitch-build/skills/remotion/examples/screens.json (1451 bytes)
{ "projectName": "Calculator App", "projectId": "projects/13534454087919359824", "videoConfig": { "fps": 30, "width": 1920, "height": 1080, "durationInSeconds": 20 }, "screens": [ { "id": "1", "screenId": "12345", "title": "Home Screen", "description": "Main calculator interface with number pad and basic operations", "imagePath": "assets/screens/home.png", "width": 1200, "height": 800, "duration": 5, "transitionType": "fade" }, { "id": "2", "screenId": "12346", "title": "History View", "description": "View of previous calculations with option to reuse results", "imagePath": "assets/screens/history.png", "width": 1200, "height": 800, "duration": 4, "transitionType": "slide" }, { "id": "3", "screenId": "12347", "title": "Settings Panel", "description": "Customize calculator behavior and appearance", "imagePath": "assets/screens/settings.png", "width": 1200, "height": 800, "duration": 4, "transitionType": "fade" }, { "id": "4", "screenId": "12348", "title": "Scientific Mode", "description": "Advanced mathematical functions and operations", "imagePath": "assets/screens/scientific.png", "width": 1200, "height": 800, "duration": 5, "transitionType": "zoom" } ] } - plugins/stitch-build/skills/remotion/examples/WalkthroughComposition.tsx (2295 bytes)
import {Composition} from 'remotion'; import {Sequence} from 'remotion'; import {fade} from '@remotion/transitions/fade'; import {slide} from '@remotion/transitions/slide'; import {TransitionSeries} from '@remotion/transitions'; import {ScreenSlide} from './ScreenSlide'; import screensManifest from '../screens.json'; // Calculate total duration in frames const calculateDuration = () => { const totalSeconds = screensManifest.screens.reduce( (sum, screen) => sum + screen.duration, 0 ); return totalSeconds * screensManifest.videoConfig.fps; }; export const WalkthroughComposition: React.FC = () => { const {fps, width, height} = screensManifest.videoConfig; return ( <TransitionSeries> {screensManifest.screens.map((screen, index) => { const durationInFrames = screen.duration * fps; // Select transition based on screen config const transition = screen.transitionType === 'slide' ? slide() : screen.transitionType === 'zoom' ? fade() // Can customize with zoom effect : fade(); return ( <TransitionSeries.Sequence key={screen.id} durationInFrames={durationInFrames} > <ScreenSlide imageSrc={screen.imagePath} title={screen.title} description={screen.description} width={screen.width} height={screen.height} /> {index < screensManifest.screens.length - 1 && ( <TransitionSeries.Transition presentation={transition} timing={{ durationInFrames: 20, // 20 frames for transition }} /> )} </TransitionSeries.Sequence> ); })} </TransitionSeries> ); }; // Register composition export const RemotionRoot: React.FC = () => { const {fps, width, height} = screensManifest.videoConfig; const durationInFrames = calculateDuration(); return ( <> <Composition id="WalkthroughComposition" component={WalkthroughComposition} durationInFrames={durationInFrames} fps={fps} width={width} height={height} /> </> ); }; - plugins/stitch-build/skills/remotion/README.md (3500 bytes)
# Stitch-Remotion Video Walkthrough Skill Generate professional walkthrough videos from Stitch app designs using Remotion. ## What This Skill Does This skill bridges Stitch (UI design platform) and Remotion (programmatic video library) to automatically create walkthrough videos showcasing app screens with: - **Smooth transitions**: Cross-fades, slides, and zoom effects - **Text overlays**: Screen titles, descriptions, and feature callouts - **Professional animations**: Spring-based natural motion - **Customizable timing**: Control display duration per screen ## Prerequisites 1. **Stitch MCP Server**: Access to retrieve screens from Stitch projects 2. **Node.js**: For running Remotion 3. **Remotion**: Either Remotion MCP Server or Remotion CLI ## Example Use Case **User Request:** > "Look up the screens in my Stitch project 'Calculator App' and build a remotion video that shows a walkthrough of the screens." **What Happens:** 1. Agent retrieves all screens from the Stitch project 2. Downloads screenshots for each screen 3. Creates a Remotion composition with transitions 4. Generates video with smooth animations and text overlays 5. Renders final MP4 video ## Key Features - **Automated asset retrieval** from Stitch projects - **Modular Remotion components** for easy customization - **Multiple transition styles** (fade, slide, zoom) - **Text overlay system** for annotations - **Configurable timing** per screen - **Professional rendering** with quality optimization ## Installation Install this skill using: ```bash npx skills add google-labs-code/stitch-skills --skill remotion --global ``` ## File Structure When using this skill, the agent will create: ``` project/ ├── video/ # Remotion project │ ├── src/ │ │ ├── WalkthroughComposition.tsx │ │ ├── ScreenSlide.tsx │ │ └── components/ │ ├── public/assets/screens/ # Stitch screenshots │ └── remotion.config.ts ├── screens.json # Screen manifest └── output.mp4 # Final video ``` ## How It Works 1. **Discovery**: Identifies Stitch and Remotion MCP servers 2. **Retrieval**: Fetches screens and metadata from Stitch project 3. **Asset Download**: Downloads screenshots for each screen 4. **Composition**: Generates Remotion React components 5. **Preview**: Opens Remotion Studio for refinement (optional) 6. **Render**: Produces final video file ## Integration Points **With Stitch:** - Uses Stitch MCP to list projects and screens - Downloads screenshots and HTML code - Extracts screen metadata (title, dimensions) **With Remotion:** - Creates TypeScript/React components - Configures composition settings - Renders video using Remotion CLI or MCP ## Advanced Capabilities - **Dynamic text extraction**: Parse Stitch HTML to auto-generate annotations - **Interactive hotspots**: Highlight clickable elements - **Voiceover integration**: Sync narration with screen transitions - **Multiple video patterns**: Slide show, feature highlight, user flow ## Related Skills - **design-md**: Extract design system from Stitch projects (useful for consistent branding in videos) - **react-components**: Convert Stitch designs to React (if you want interactive demos instead of videos) ## Learn More See the full [SKILL.md](./SKILL.md) for detailed instructions, troubleshooting, and best practices. ## License This is not an officially supported Google product.
- plugins/stitch-build/skills/remotion/resources/composition-checklist.md (3748 bytes)
# Remotion Composition Checklist Use this checklist to ensure your Remotion walkthrough video composition is complete and follows best practices. ## ✅ Project Setup - [ ] Remotion project initialized (or existing project verified) - [ ] Dependencies installed (`@remotion/transitions`, etc.) - [ ] Asset directory created (`public/assets/screens/`) - [ ] Screen manifest created (`screens.json`) ## ✅ Asset Preparation - [ ] All Stitch screenshots downloaded - [ ] Images saved with descriptive names - [ ] Image dimensions recorded in manifest - [ ] Images optimized for size (if needed) - [ ] Asset paths are correct and relative to `public/` ## ✅ Component Structure - [ ] `ScreenSlide.tsx` component created - [ ] Props interface defined - [ ] Zoom animation implemented - [ ] Fade animation implemented - [ ] Text overlay included - [ ] `WalkthroughComposition.tsx` created - [ ] Screen manifest imported - [ ] `<Sequence>` components for each screen - [ ] Transitions between screens configured - [ ] Proper timing offsets calculated ## ✅ Configuration - [ ] `remotion.config.ts` updated - [ ] Composition ID set - [ ] Video dimensions configured - [ ] Frame rate set (30 or 60 fps) - [ ] Duration calculated correctly - [ ] Video metadata set (if applicable) - [ ] Title - [ ] Description ## ✅ Animations & Transitions - [ ] Spring animations use appropriate configs - [ ] Damping values (8-15 typical) - [ ] Stiffness values (60-100 typical) - [ ] Transitions feel smooth - [ ] Text overlays timed correctly - [ ] No jarring or abrupt changes ## ✅ Visual Quality - [ ] Text is readable at all times - [ ] Sufficient contrast between text and background - [ ] Font sizes appropriate for video resolution - [ ] Images display without distortion - [ ] Aspect ratios maintained ## ✅ Timing - [ ] Each screen displays for appropriate duration - [ ] Total video length is reasonable (not too long/short) - [ ] Transitions don't feel rushed - [ ] Text has time to be read ## ✅ Preview & Testing - [ ] Preview in Remotion Studio (`npm run dev`) - [ ] Scrub through timeline to check all frames - [ ] Verify smooth playback - [ ] Check for any rendering errors - [ ] Test on different screen sizes (if responsive) ## ✅ Rendering - [ ] Render command tested and works - [ ] Output format chosen (MP4, WebM, etc.) - [ ] Quality settings configured - [ ] Codec specified (h264 recommended) - [ ] Final video renders without errors ## ✅ Final Output - [ ] Video file generated successfully - [ ] File size is reasonable - [ ] Video plays correctly in media players - [ ] Audio included (if applicable) - [ ] Metadata embedded (if needed) ## 🎨 Optional Enhancements - [ ] Progress indicator showing current screen - [ ] Custom logo or branding - [ ] Background music or sound effects - [ ] Voiceover narration - [ ] Interactive hotspots highlighting features - [ ] Call-to-action at end ## 📋 Best Practices Verified - [ ] Component code is modular and reusable - [ ] TypeScript interfaces used for props - [ ] No hardcoded values (use manifest/config) - [ ] Code follows Remotion conventions - [ ] Comments added for complex logic - [ ] Assets organized in clear folder structure ## 🐛 Common Issues Checked - [ ] No blurry images (check source resolution) - [ ] No misaligned text (verify positioning) - [ ] No choppy animations (check spring configs) - [ ] No missing assets (verify all paths) - [ ] No build errors (run `npm run build` test) --- **Notes:** - Mark items with `[x]` as you complete them - Add custom checklist items specific to your project - Review Remotion documentation for updates - Test final video on target platform (YouTube, social, etc.)
- plugins/stitch-build/skills/remotion/resources/screen-slide-template.tsx (2412 bytes)
import {AbsoluteFill, spring, useCurrentFrame, useVideoConfig} from 'remotion'; import {Img} from 'remotion'; interface ScreenSlideProps { imageSrc: string; title: string; description?: string; width: number; height: number; } export const ScreenSlide: React.FC<ScreenSlideProps> = ({ imageSrc, title, description, width, height, }) => { const frame = useCurrentFrame(); const {fps} = useVideoConfig(); // Zoom in animation const zoom = spring({ frame, fps, from: 0.95, to: 1, config: { damping: 12, stiffness: 80, }, }); // Fade in animation const opacity = spring({ frame, fps, from: 0, to: 1, config: { damping: 10, }, }); // Text overlay fade in (delayed) const textOpacity = spring({ frame: frame - 15, // Delay by 15 frames fps, from: 0, to: 1, config: { damping: 10, }, }); return ( <AbsoluteFill style={{ backgroundColor: '#000', justifyContent: 'center', alignItems: 'center', }} > {/* Screen Image */} <div style={{ transform: `scale(${zoom})`, opacity, maxWidth: '90%', maxHeight: '80%', position: 'relative', }} > <Img src={imageSrc} style={{ width: '100%', height: 'auto', borderRadius: '8px', boxShadow: '0 20px 60px rgba(0, 0, 0, 0.3)', }} /> </div> {/* Text Overlay */} <div style={{ position: 'absolute', bottom: '10%', left: '50%', transform: 'translateX(-50%)', textAlign: 'center', opacity: textOpacity, width: '80%', }} > <h1 style={{ fontSize: '48px', fontWeight: 'bold', color: '#fff', margin: '0 0 12px 0', textShadow: '0 2px 10px rgba(0, 0, 0, 0.5)', }} > {title} </h1> {description && ( <p style={{ fontSize: '24px', color: '#ddd', margin: 0, textShadow: '0 1px 5px rgba(0, 0, 0, 0.5)', }} > {description} </p> )} </div> </AbsoluteFill> ); }; - plugins/stitch-build/skills/remotion/scripts/download-stitch-asset.sh (1112 bytes)
#!/bin/bash # Download Stitch screen asset with proper handling of Google Cloud Storage URLs # Usage: ./download-stitch-asset.sh "https://storage.googleapis.com/..." "output-path.png" set -e if [ $# -ne 2 ]; then echo "Usage: $0 <download_url> <output_path>" echo "Example: $0 'https://storage.googleapis.com/stitch/screenshot.png' 'assets/screen.png'" exit 1 fi DOWNLOAD_URL="$1" OUTPUT_PATH="$2" # Create directory if it doesn't exist OUTPUT_DIR=$(dirname "$OUTPUT_PATH") mkdir -p "$OUTPUT_DIR" echo "Downloading from: $DOWNLOAD_URL" echo "Saving to: $OUTPUT_PATH" # Use curl with follow redirects; -f fails on HTTP errors so an error # response (e.g. an expired signed URL) is not saved as the asset if curl -L -f -o "$OUTPUT_PATH" "$DOWNLOAD_URL"; then echo "✓ Successfully downloaded to $OUTPUT_PATH" # Display file size for verification if command -v stat &> /dev/null; then FILE_SIZE=$(stat -f%z "$OUTPUT_PATH" 2>/dev/null || stat -c%s "$OUTPUT_PATH" 2>/dev/null) echo " File size: $FILE_SIZE bytes" fi else echo "✗ Download failed" rm -f "$OUTPUT_PATH" exit 1 fi - plugins/stitch-build/skills/remotion/SKILL.md (12942 bytes)
--- name: remotion description: Generate walkthrough videos from Stitch projects using Remotion with smooth transitions, zooming, and text overlays allowed-tools: - "stitch*:*" - "remotion*:*" - "Bash" - "Read" - "Write" - "web_fetch" --- # Stitch to Remotion Walkthrough Videos You are a video production specialist focused on creating engaging walkthrough videos from app designs. You combine Stitch's screen retrieval capabilities with Remotion's programmatic video generation to produce smooth, professional presentations. ## Overview This skill enables you to create walkthrough videos that showcase app screens with professional transitions, zoom effects, and contextual text overlays. The workflow retrieves screens from Stitch projects and orchestrates them into a Remotion video composition. ## Prerequisites **Required:** - Access to the Stitch MCP Server - Access to the Remotion MCP Server (or Remotion CLI) - Node.js and npm installed - A Stitch project with designed screens **Recommended:** - Familiarity with Remotion's video capabilities - Understanding of React components (Remotion uses React) ## Retrieval and Networking ### Step 1: Discover Available MCP Servers Run `list_tools` to identify available MCP servers and their prefixes: - **Stitch MCP**: Look for `stitch:` or `mcp_stitch:` prefix - **Remotion MCP**: Look for `remotion:` or `mcp_remotion:` prefix ### Step 2: Retrieve Stitch Project Information 1. **Project lookup** (if Project ID is not provided): - Call `[stitch_prefix]:list_projects` with `filter: "view=owned"` - Identify target project by title (e.g., "Calculator App") - Extract Project ID from `name` field (e.g., `projects/13534454087919359824`) 2. **Screen retrieval**: - Call `[stitch_prefix]:list_screens` with the project ID (numeric only) - Review screen titles to identify all screens for the walkthrough - Extract Screen IDs from each screen's `name` field 3. **Screen metadata fetch**: For each screen: - Call `[stitch_prefix]:get_screen` with `projectId` and `screenId` - Retrieve: - `screenshot.downloadUrl` — Visual asset for the video - `htmlCode.downloadUrl` — Optional: for extracting text/content - `width`, `height` — Screen dimensions for proper scaling - Screen title and description for text overlays 4. **Asset download**: - Use `web_fetch` or `Bash` with `curl` to download screenshots - Save to a staging directory: `assets/screens/{screen-name}.png` - Organize assets in order of the intended walkthrough flow ### Step 3: Set Up Remotion Project 1. **Check for existing Remotion project**: - Look for `remotion.config.ts` or `package.json` with Remotion dependencies - If exists, use the existing project structure 2. **Create new Remotion project** (if needed): ```bash npm create video@latest -- --blank ``` - Choose TypeScript template - Set up in a dedicated `video/` directory 3. **Install dependencies**: ```bash cd video npm install @remotion/transitions @remotion/animated-emoji ``` ## Video Composition Strategy ### Architecture Create a modular Remotion composition with these components: 1. **`ScreenSlide.tsx`** — Individual screen display component - Props: `imageSrc`, `title`, `description`, `width`, `height` - Features: Zoom-in animation, fade transitions - Duration: Configurable (default 3-5 seconds per screen) 2. **`WalkthroughComposition.tsx`** — Main video composition - Sequences multiple `ScreenSlide` components - Handles transitions between screens - Adds text overlays and annotations 3. **`config.ts`** — Video configuration - Frame rate (default: 30 fps) - Video dimensions (match Stitch screen dimensions or scale appropriately) - Total duration calculation ### Transition Effects Use Remotion's `@remotion/transitions` for professional effects: - **Fade**: Smooth cross-fade between screens ```tsx import {fade} from '@remotion/transitions/fade'; ``` - **Slide**: Directional slide transitions ```tsx import {slide} from '@remotion/transitions/slide'; ``` - **Zoom**: Zoom in/out effects for emphasis - Use `spring()` animation for smooth zoom - Apply to important UI elements ### Text Overlays Add contextual information using Remotion's text rendering: 1. **Screen titles**: Display at the top or bottom of each frame 2. **Feature callouts**: Highlight specific UI elements with animated pointers 3. **Descriptions**: Fade in descriptive text for each screen 4. **Progress indicator**: Show current screen position in walkthrough ## Execution Steps ### Step 1: Gather Screen Assets 1. Identify target Stitch project 2. List all screens in the project 3. Download screenshots for each screen 4. Organize in order of walkthrough flow 5. Create a manifest file (`screens.json`): ```json { "projectName": "Calculator App", "screens": [ { "id": "1", "title": "Home Screen", "description": "Main calculator interface with number pad", "imagePath": "assets/screens/home.png", "width": 1200, "height": 800, "duration": 4 }, { "id": "2", "title": "History View", "description": "View of previous calculations", "imagePath": "assets/screens/history.png", "width": 1200, "height": 800, "duration": 3 } ] } ``` ### Step 2: Generate Remotion Components Create the video components following Remotion best practices: 1. **Create `ScreenSlide.tsx`**: - Use `useCurrentFrame()` and `spring()` for animations - Implement zoom and fade effects - Add text overlays with proper timing 2. **Create `WalkthroughComposition.tsx`**: - Import screen manifest - Sequence screens with `<Sequence>` components - Apply transitions between screens - Calculate proper timing and offsets 3. **Update `remotion.config.ts`**: - Set composition ID - Configure video dimensions - Set frame rate and duration **Reference Resources:** - Use `resources/screen-slide-template.tsx` as starting point - Follow `resources/composition-checklist.md` for completeness - Review examples in `examples/` directory ### Step 3: Preview and Refine 1. **Start Remotion Studio**: ```bash npm run dev ``` - Opens browser-based preview - Allows real-time editing and refinement 2. **Adjust timing**: - Ensure each screen has appropriate display duration - Verify transitions are smooth - Check text overlay timing 3. **Fine-tune animations**: - Adjust spring configurations for zoom effects - Modify easing functions for transitions - Ensure text is readable at all times ### Step 4: Render Video 1. **Render using Remotion CLI**: ```bash npx remotion render WalkthroughComposition output.mp4 ``` 2. **Alternative: Use Remotion MCP** (if available): - Call `[remotion_prefix]:render` with composition details - Specify output format (MP4, WebM, etc.) 3. **Optimization options**: - Set quality level (`--quality`) - Configure codec (`--codec h264` or `h265`) - Enable parallel rendering (`--concurrency`) ## Advanced Features ### Interactive Hotspots Highlight clickable elements or important features: ```tsx import {interpolate, useCurrentFrame} from 'remotion'; const Hotspot = ({x, y, label}) => { const frame = useCurrentFrame(); const scale = spring({ frame, fps: 30, config: {damping: 10, stiffness: 100} }); return ( <div style={{ position: 'absolute', left: x, top: y, transform: `scale(${scale})` }}> <div className="pulse-ring" /> <span>{label}</span> </div> ); }; ``` ### Voiceover Integration Add narration to the walkthrough: 1. Generate voiceover script from screen descriptions 2. Use text-to-speech or record audio 3. Import audio into Remotion with `<Audio>` component 4. Sync screen timing with voiceover pacing ### Dynamic Text Extraction Extract text from Stitch HTML code for automatic annotations: 1. Download `htmlCode.downloadUrl` for each screen 2. Parse HTML to extract key text elements (headings, buttons, labels) 3. Generate automatic callouts for important UI elements 4. Add to composition as timed text overlays ## File Structure ``` project/ ├── video/ # Remotion project directory │ ├── src/ │ │ ├── WalkthroughComposition.tsx │ │ ├── ScreenSlide.tsx │ │ ├── components/ │ │ │ ├── Hotspot.tsx │ │ │ └── TextOverlay.tsx │ │ └── Root.tsx │ ├── public/ │ │ └── assets/ │ │ └── screens/ # Downloaded Stitch screenshots │ │ ├── home.png │ │ └── history.png │ ├── remotion.config.ts │ └── package.json ├── screens.json # Screen manifest └── output.mp4 # Rendered video ``` ## Integration with Remotion Skills Remotion maintains its own Agent Skills that define best practices. Review these for advanced techniques: - **Repository**: https://github.com/remotion-dev/remotion/tree/main/packages/skills - **Installation**: `npx skills add remotion-dev/skills` Key Remotion skills to leverage: - Animation timing and easing - Composition architecture patterns - Performance optimization - Audio synchronization ## Common Patterns ### Pattern 1: Simple Slide Show Basic walkthrough with fade transitions: - 3-5 seconds per screen - Cross-fade transitions - Bottom text overlay with screen title - Progress bar at top ### Pattern 2: Feature Highlight Focus on specific UI elements: - Zoom into specific regions - Animated circles/arrows pointing to features - Slow-motion emphasis on key interactions - Side-by-side before/after comparisons ### Pattern 3: User Flow Show step-by-step user journey: - Sequential screen flow with directional slides - Numbered steps overlay - Highlight user actions (clicks, taps) - Connect screens with animated paths ## Troubleshooting | Issue | Solution | |-------|----------| | **Blurry screenshots** | Ensure downloaded images are at full resolution; check `screenshot.downloadUrl` quality settings | | **Misaligned text** | Verify screen dimensions match composition size; adjust text positioning based on actual screen size | | **Choppy animations** | Increase frame rate to 60fps; use proper spring configurations with appropriate damping | | **Remotion build fails** | Check Node version compatibility; ensure all dependencies are installed; review Remotion docs | | **Timing feels off** | Adjust duration per screen in manifest; preview in Remotion Studio; test with actual users | ## Best Practices 1. **Maintain aspect ratio**: Use actual Stitch screen dimensions or scale proportionally 2. **Consistent timing**: Keep screen display duration consistent unless emphasizing specific screens 3. **Readable text**: Ensure sufficient contrast; use appropriate font sizes; avoid cluttered overlays 4. **Smooth transitions**: Use spring animations for natural motion; avoid jarring cuts 5. **Preview thoroughly**: Always preview in Remotion Studio before final render 6. **Optimize assets**: Compress images appropriately; use efficient formats (PNG for UI, JPG for photos) ## Example Usage **User prompt:** ``` Look up the screens in my Stitch project "Calculator App" and build a remotion video that shows a walkthrough of the screens. ``` **Agent workflow:** 1. List Stitch projects → Find "Calculator App" → Extract project ID 2. List screens in project → Identify all screens (Home, History, Settings) 3. Download screenshots for each screen → Save to `assets/screens/` 4. Create `screens.json` manifest with screen metadata 5. Generate Remotion components (`ScreenSlide.tsx`, `WalkthroughComposition.tsx`) 6. Preview in Remotion Studio → Refine timing and transitions 7. Render final video → `calculator-walkthrough.mp4` 8. Report completion with video preview link ## Tips for Success - **Start simple**: Begin with basic fade transitions before adding complex animations - **Follow Remotion patterns**: Leverage Remotion's official skills and documentation - **Use manifest files**: Keep screen data organized in JSON for easy updates - **Preview frequently**: Use Remotion Studio to catch issues early - **Consider accessibility**: Add captions; ensure text is readable; use clear visuals - **Optimize for platform**: Match video dimensions to target platform (YouTube, social media, etc.) ## References - **Stitch Documentation**: https://stitch.withgoogle.com/docs/ - **Remotion Documentation**: https://www.remotion.dev/docs/ - **Remotion Skills**: https://www.remotion.dev/docs/ai/skills - **Remotion MCP**: https://www.remotion.dev/docs/ai/mcp - **Remotion Transitions**: https://www.remotion.dev/docs/transitions - plugins/stitch-build/skills/shadcn-ui/examples/auth-layout.tsx (5770 bytes)
// Example: Authentication Layout with shadcn/ui // Demonstrates: Layout composition, card usage, form integration "use client" import { Button } from "@/components/ui/button" import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, } from "@/components/ui/card" import { Input } from "@/components/ui/input" import { Label } from "@/components/ui/label" import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" import { useState } from "react" export function AuthLayout() { const [isLoading, setIsLoading] = useState<boolean>(false) async function onSubmit(event: React.FormEvent<HTMLFormElement>) { event.preventDefault() setIsLoading(true) // Simulate API call setTimeout(() => { setIsLoading(false) }, 2000) } return ( <div className="flex min-h-screen items-center justify-center bg-muted/40"> <Tabs defaultValue="login" className="w-[400px]"> <TabsList className="grid w-full grid-cols-2"> <TabsTrigger value="login">Login</TabsTrigger> <TabsTrigger value="register">Register</TabsTrigger> </TabsList> <TabsContent value="login"> <Card> <CardHeader> <CardTitle>Login</CardTitle> <CardDescription> Enter your credentials to access your account. </CardDescription> </CardHeader> <form onSubmit={onSubmit}> <CardContent className="space-y-4"> <div className="space-y-2"> <Label htmlFor="email">Email</Label> <Input id="email" type="email" placeholder="[email protected]" required /> </div> <div className="space-y-2"> <Label htmlFor="password">Password</Label> <Input id="password" type="password" required /> </div> </CardContent> <CardFooter className="flex flex-col space-y-4"> <Button type="submit" className="w-full" disabled={isLoading} > {isLoading ? "Signing in..." : "Sign in"} </Button> <Button type="button" variant="link" className="w-full text-sm text-muted-foreground" > Forgot password? </Button> </CardFooter> </form> </Card> </TabsContent> <TabsContent value="register"> <Card> <CardHeader> <CardTitle>Create an account</CardTitle> <CardDescription> Enter your information to create an account. </CardDescription> </CardHeader> <form onSubmit={onSubmit}> <CardContent className="space-y-4"> <div className="space-y-2"> <Label htmlFor="name">Name</Label> <Input id="name" placeholder="John Doe" required /> </div> <div className="space-y-2"> <Label htmlFor="register-email">Email</Label> <Input id="register-email" type="email" placeholder="[email protected]" required /> </div> <div className="space-y-2"> <Label htmlFor="register-password">Password</Label> <Input id="register-password" type="password" required /> </div> <div className="space-y-2"> <Label htmlFor="confirm-password">Confirm Password</Label> <Input id="confirm-password" type="password" required /> </div> </CardContent> <CardFooter> <Button type="submit" className="w-full" disabled={isLoading} > {isLoading ? "Creating account..." : "Create account"} </Button> </CardFooter> </form> </Card> </TabsContent> </Tabs> </div> ) } /** * Key Patterns Demonstrated: * * 1. Layout Composition: Centered authentication card with full-height viewport * 2. Card Usage: Structured content with header, body, and footer * 3. Tabs: Switch between login and register forms * 4. Form Structure: Proper labeling and input grouping * 5. Loading States: Button disabled state during form submission * 6. Responsive Design: Mobile-friendly with max-width constraint * 7. Tailwind Utilities: Using spacing, flexbox, and grid utilities * * Design Choices: * - Minimal, clean interface focusing on the task at hand * - Proper semantic HTML with form elements * - Accessible labels and inputs * - Clear visual hierarchy with card components * - Loading feedback for better UX * * Required Dependencies: * None beyond React and shadcn/ui components * * Installation: * npx shadcn@latest add card * npx shadcn@latest add input * npx shadcn@latest add label * npx shadcn@latest add button * npx shadcn@latest add tabs */ - plugins/stitch-build/skills/shadcn-ui/examples/data-table.tsx (8903 bytes)
// Example: Data Table with Sorting and Filtering // Demonstrates: Table composition, TanStack Table integration, responsive design "use client" import { ColumnDef, ColumnFiltersState, flexRender, getCoreRowModel, getFilteredRowModel, getPaginationRowModel, getSortedRowModel, SortingState, useReactTable, } from "@tanstack/react-table" import { ArrowUpDown, ChevronDown, MoreHorizontal } from "lucide-react" import * as React from "react" import { Button } from "@/components/ui/button" import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu" import { Input } from "@/components/ui/input" import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table" // Define data type export type User = { id: string name: string email: string role: "admin" | "user" | "viewer" status: "active" | "inactive" } // Sample data const data: User[] = [ { id: "1", name: "Alice Johnson", email: "[email protected]", role: "admin", status: "active", }, { id: "2", name: "Bob Smith", email: "[email protected]", role: "user", status: "active", }, { id: "3", name: "Carol White", email: "[email protected]", role: "viewer", status: "inactive", }, ] // Define columns export const columns: ColumnDef<User>[] = [ { accessorKey: "name", header: ({ column }) => { return ( <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} > Name <ArrowUpDown className="ml-2 h-4 w-4" /> </Button> ) }, cell: ({ row }) => <div className="capitalize">{row.getValue("name")}</div>, }, { accessorKey: "email", header: ({ column }) => { return ( <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} > Email <ArrowUpDown className="ml-2 h-4 w-4" /> </Button> ) }, cell: ({ row }) => <div className="lowercase">{row.getValue("email")}</div>, }, { accessorKey: "role", header: "Role", cell: ({ row }) => ( <div className="capitalize">{row.getValue("role")}</div> ), }, { accessorKey: "status", header: "Status", cell: ({ row }) => ( <div className="capitalize">{row.getValue("status")}</div> ), }, { id: "actions", enableHiding: false, cell: ({ row }) => { const user = row.original return ( <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant="ghost" className="h-8 w-8 p-0"> <span className="sr-only">Open menu</span> <MoreHorizontal className="h-4 w-4" /> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end"> <DropdownMenuLabel>Actions</DropdownMenuLabel> <DropdownMenuItem onClick={() => navigator.clipboard.writeText(user.id)} > Copy user ID </DropdownMenuItem> <DropdownMenuSeparator /> <DropdownMenuItem>View user</DropdownMenuItem> <DropdownMenuItem>Edit user</DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> ) }, }, ] export function DataTableExample() { const [sorting, setSorting] = React.useState<SortingState>([]) const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([]) const [columnVisibility, setColumnVisibility] = React.useState({}) const [rowSelection, setRowSelection] = React.useState({}) const table = useReactTable({ data, columns, onSortingChange: setSorting, onColumnFiltersChange: setColumnFilters, getCoreRowModel: getCoreRowModel(), getPaginationRowModel: getPaginationRowModel(), getSortedRowModel: getSortedRowModel(), getFilteredRowModel: getFilteredRowModel(), onColumnVisibilityChange: setColumnVisibility, onRowSelectionChange: setRowSelection, state: { sorting, columnFilters, columnVisibility, rowSelection, }, }) return ( <div className="w-full"> <div className="flex items-center py-4"> <Input placeholder="Filter names..." value={(table.getColumn("name")?.getFilterValue() as string) ?? ""} onChange={(event) => table.getColumn("name")?.setFilterValue(event.target.value) } className="max-w-sm" /> <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant="outline" className="ml-auto"> Columns <ChevronDown className="ml-2 h-4 w-4" /> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end"> {table .getAllColumns() .filter((column) => column.getCanHide()) .map((column) => { return ( <DropdownMenuCheckboxItem key={column.id} className="capitalize" checked={column.getIsVisible()} onCheckedChange={(value) => column.toggleVisibility(!!value) } > {column.id} </DropdownMenuCheckboxItem> ) })} </DropdownMenuContent> </DropdownMenu> </div> <div className="rounded-md border"> <Table> <TableHeader> {table.getHeaderGroups().map((headerGroup) => ( <TableRow key={headerGroup.id}> {headerGroup.headers.map((header) => { return ( <TableHead key={header.id}> {header.isPlaceholder ? null : flexRender( header.column.columnDef.header, header.getContext() )} </TableHead> ) })} </TableRow> ))} </TableHeader> <TableBody> {table.getRowModel().rows?.length ? ( table.getRowModel().rows.map((row) => ( <TableRow key={row.id} data-state={row.getIsSelected() && "selected"} > {row.getVisibleCells().map((cell) => ( <TableCell key={cell.id}> {flexRender( cell.column.columnDef.cell, cell.getContext() )} </TableCell> ))} </TableRow> )) ) : ( <TableRow> <TableCell colSpan={columns.length} className="h-24 text-center" > No results. </TableCell> </TableRow> )} </TableBody> </Table> </div> <div className="flex items-center justify-end space-x-2 py-4"> <div className="flex-1 text-sm text-muted-foreground"> {table.getFilteredSelectedRowModel().rows.length} of{" "} {table.getFilteredRowModel().rows.length} row(s) selected. </div> <div className="space-x-2"> <Button variant="outline" size="sm" onClick={() => table.previousPage()} disabled={!table.getCanPreviousPage()} > Previous </Button> <Button variant="outline" size="sm" onClick={() => table.nextPage()} disabled={!table.getCanNextPage()} > Next </Button> </div> </div> </div> ) } /** * Key Patterns Demonstrated: * * 1. TanStack Table Integration: Using @tanstack/react-table with shadcn/ui * 2. Sorting: Click headers to sort ascending/descending * 3. Filtering: Text input to filter table data * 4. Column Visibility: Toggle columns via dropdown menu * 5. Pagination: Built-in pagination controls * 6. Row Actions: Dropdown menu per row for context actions * 7. Responsive Design: Table adapts to different screen sizes * * Required Dependencies: * - @tanstack/react-table * - lucide-react * * Installation: * npx shadcn@latest add table * npx shadcn@latest add button * npx shadcn@latest add input * npx shadcn@latest add dropdown-menu * npm install @tanstack/react-table lucide-react */ - plugins/stitch-build/skills/shadcn-ui/examples/form-pattern.tsx (4954 bytes)
// Example: Form Pattern with shadcn/ui components // Demonstrates: Form building, validation, and composition "use client" import { Button } from "@/components/ui/button" import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form" import { Input } from "@/components/ui/input" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select" import { Textarea } from "@/components/ui/textarea" import { toast } from "@/components/ui/use-toast" import { zodResolver } from "@hookform/resolvers/zod" import { useForm } from "react-hook-form" import * as z from "zod" // Define form schema with zod const formSchema = z.object({ username: z.string().min(2, { message: "Username must be at least 2 characters.", }), email: z.string().email({ message: "Please enter a valid email address.", }), role: z.enum(["admin", "user", "viewer"], { required_error: "Please select a role.", }), bio: z.string().max(160, { message: "Bio must not be longer than 160 characters.", }).optional(), }) type FormValues = z.infer<typeof formSchema> export function UserProfileForm() { // Initialize form with react-hook-form and zod validation const form = useForm<FormValues>({ resolver: zodResolver(formSchema), defaultValues: { username: "", email: "", bio: "", }, }) // Handle form submission function onSubmit(values: FormValues) { // In a real app, send to API console.log(values) toast({ title: "Profile updated", description: "Your profile has been successfully updated.", }) } return ( <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8"> <FormField control={form.control} name="username" render={({ field }) => ( <FormItem> <FormLabel>Username</FormLabel> <FormControl> <Input placeholder="johndoe" {...field} /> </FormControl> <FormDescription> This is your public display name. </FormDescription> <FormMessage /> </FormItem> )} /> <FormField control={form.control} name="email" render={({ field }) => ( <FormItem> <FormLabel>Email</FormLabel> <FormControl> <Input type="email" placeholder="[email protected]" {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <FormField control={form.control} name="role" render={({ field }) => ( <FormItem> <FormLabel>Role</FormLabel> <Select onValueChange={field.onChange} defaultValue={field.value}> <FormControl> <SelectTrigger> <SelectValue placeholder="Select a role" /> </SelectTrigger> </FormControl> <SelectContent> <SelectItem value="admin">Admin</SelectItem> <SelectItem value="user">User</SelectItem> <SelectItem value="viewer">Viewer</SelectItem> </SelectContent> </Select> <FormDescription> Your role determines your access level. </FormDescription> <FormMessage /> </FormItem> )} /> <FormField control={form.control} name="bio" render={({ field }) => ( <FormItem> <FormLabel>Bio</FormLabel> <FormControl> <Textarea placeholder="Tell us about yourself" className="resize-none" {...field} /> </FormControl> <FormDescription> Optional. Maximum 160 characters. </FormDescription> <FormMessage /> </FormItem> )} /> <Button type="submit">Update profile</Button> </form> </Form> ) } /** * Key Patterns Demonstrated: * * 1. Form Composition: Using shadcn/ui's Form components with react-hook-form * 2. Validation: Zod schema for type-safe validation * 3. Error Handling: Automatic error messages via FormMessage * 4. Accessibility: All fields properly labeled with descriptions * 5. Type Safety: TypeScript types inferred from Zod schema * * Required Dependencies: * - react-hook-form * - @hookform/resolvers * - zod * * Installation: * npx shadcn@latest add form * npx shadcn@latest add input * npx shadcn@latest add select * npx shadcn@latest add textarea * npx shadcn@latest add button */ - plugins/stitch-build/skills/shadcn-ui/README.md (6836 bytes)
# shadcn/ui Integration Skill ## Install ```bash npx skills add google-labs-code/stitch-skills --skill shadcn-ui --global ``` ## What It Does This skill provides expert guidance for integrating shadcn/ui components into your React applications. It helps you discover, install, customize, and optimize shadcn/ui components while following best practices. ## Example Prompts ```text Help me set up shadcn/ui in my Next.js project Add a data table component with sorting and filtering to my app Show me how to customize the button component with a new variant Create a login form using shadcn/ui components with validation Build a dashboard layout with sidebar navigation using shadcn/ui blocks ``` ## What is shadcn/ui? shadcn/ui is a collection of beautifully designed, accessible, and customizable components built with: - **Radix UI or Base UI**: Unstyled, accessible component primitives - **Tailwind CSS**: Utility-first styling framework - **TypeScript**: Full type safety **Key Difference**: Unlike traditional component libraries, shadcn/ui copies components directly into your project. This gives you: - Full control over the code - No version lock-in - Complete customization freedom - Zero runtime overhead ## Skill Structure ```text skills/shadcn-ui/ ├── SKILL.md — Core instructions & workflow ├── README.md — This file ├── examples/ — Example implementations │ ├── form-pattern.tsx — Form with validation │ ├── data-table.tsx — Advanced table with sorting │ └── auth-layout.tsx — Authentication flow ├── resources/ — Reference documentation │ ├── setup-guide.md — Project initialization │ ├── component-catalog.md — Component reference │ ├── customization-guide.md — Theming patterns │ └── migration-guide.md — Migration from other libraries └── scripts/ — Utility scripts └── verify-setup.sh — Validate project configuration ``` ## How It Works When activated, the agent follows this workflow: ### 1. **Discovery & Planning** - Lists available components using shadcn MCP tools - Identifies required dependencies - Plans component composition strategy ### 2. **Setup & Configuration** - Verifies or initializes `components.json` - Checks Tailwind CSS configuration - Validates import aliases and paths ### 3. **Component Integration** - Retrieves component source code - Installs via CLI or manual integration - Handles dependency installation ### 4. **Customization** - Applies theme customization - Creates component variants - Extends components with custom logic ### 5. **Quality Assurance** - Validates TypeScript types - Checks accessibility compliance - Verifies responsive behavior ## Prerequisites Your project should have: - **React 18+** - **Tailwind CSS 3.0+** - **TypeScript** (recommended) - **Node.js 18+** ## Quick Start ### For New Projects ```bash # Create Next.js project with shadcn/ui npx create-next-app@latest my-app cd my-app npx shadcn@latest init # Add components npx shadcn@latest add button npx shadcn@latest add card ``` ### For Existing Projects ```bash # Initialize shadcn/ui npx shadcn@latest init # Configure when prompted: # - Choose style (default/new-york) # - Select base color # - Configure CSS variables # - Set import aliases # Add your first component npx shadcn@latest add button ``` ## Available Components shadcn/ui provides 50+ components including: **Layout**: Accordion, Card, Separator, Tabs, Collapsible **Forms**: Button, Input, Label, Checkbox, Radio Group, Select, Textarea **Data Display**: Table, Badge, Avatar, Progress, Skeleton **Overlays**: Dialog, Sheet, Popover, Tooltip, Dropdown Menu **Navigation**: Navigation Menu, Tabs, Breadcrumb, Pagination **Feedback**: Alert, Alert Dialog, Toast, Command Plus complete **Blocks** like: - Authentication forms - Dashboard layouts - Calendar interfaces - Sidebar navigation - E-commerce components ## Customization Approach ### Theme-Level Customization Modify CSS variables in `globals.css`: ```css :root { --primary: 221.2 83.2% 53.3%; --secondary: 210 40% 96.1%; /* ... */ } ``` ### Component-Level Customization Components use `class-variance-authority` for variants: ```typescript const buttonVariants = cva( "base-classes", { variants: { variant: { default: "...", destructive: "..." }, size: { default: "...", sm: "..." }, } } ) ``` ### Composition Create higher-level components: ```typescript // Compose existing components export function FeatureCard({ title, description, icon }) { return ( <Card> <CardHeader> {icon} <CardTitle>{title}</CardTitle> </CardHeader> <CardContent> <p>{description}</p> </CardContent> </Card> ) } ``` ## Integration with MCP Tools This skill leverages shadcn MCP server capabilities: - `list_components` - Browse component catalog - `get_component` - Retrieve component source - `get_component_metadata` - View props and dependencies - `get_component_demo` - See usage examples - `list_blocks` - Browse UI blocks - `get_block` - Retrieve block source with all files - `search_items_in_registries` - Find components in custom registries ## Best Practices 1. **Keep `ui/` pure**: Don't modify components in `components/ui/` directly 2. **Compose, don't fork**: Create wrapper components instead of editing originals 3. **Use the CLI**: Let `shadcn add` handle dependencies and updates 4. **Maintain consistency**: Use the `cn()` utility for all class merging 5. **Respect accessibility**: Preserve ARIA attributes and keyboard handlers 6. **Test responsiveness**: shadcn components are responsive by default—keep it that way ## Troubleshooting ### "Module not found" errors Check your `tsconfig.json` includes path aliases: ```json { "compilerOptions": { "paths": { "@/*": ["./src/*"] } } } ``` ### Styles not applying - Import `globals.css` in your root layout - Verify Tailwind config includes component paths - Check CSS variable definitions match component expectations ### TypeScript errors - Ensure all Radix UI peer dependencies are installed - Run `npm install` after adding components via CLI - Check that React types are up to date ## Further Reading - [Official Documentation](https://ui.shadcn.com) - [Component Source](https://github.com/shadcn-ui/ui) - [Radix UI Docs](https://www.radix-ui.com) - [Tailwind CSS Docs](https://tailwindcss.com) ## Contributing Contributions to improve this skill are welcome! See the root [CONTRIBUTING.md](../../../../CONTRIBUTING.md) for guidelines. ## License See [LICENSE](../../../../LICENSE) in the repository root. - plugins/stitch-build/skills/shadcn-ui/resources/component-catalog.md (12254 bytes)
# shadcn/ui Component Catalog Complete reference of all available shadcn/ui components, organized by category. > **Note**: This catalog lists dependencies based on **Radix UI**. If you are using **Base UI**, the `add` command will handle the correct dependencies automatically. ## Layout Components ### Accordion Collapsible content sections. ```bash npx shadcn@latest add accordion ``` **Use cases**: FAQs, settings panels, navigation menus **Key props**: `type` (single/multiple), `collapsible` **Dependencies**: @radix-ui/react-accordion ### Card Container for grouping related content. ```bash npx shadcn@latest add card ``` **Sub-components**: CardHeader, CardTitle, CardDescription, CardContent, CardFooter **Use cases**: Product cards, profile cards, dashboard widgets **Dependencies**: None ### Separator Visual divider between content sections. ```bash npx shadcn@latest add separator ``` **Props**: `orientation` (horizontal/vertical), `decorative` **Dependencies**: @radix-ui/react-separator ### Tabs Organize content into multiple panels, one visible at a time. ```bash npx shadcn@latest add tabs ``` **Sub-components**: TabsList, TabsTrigger, TabsContent **Use cases**: Settings pages, dashboards, multi-step forms **Dependencies**: @radix-ui/react-tabs ### Collapsible Show/hide content with smooth animation. ```bash npx shadcn@latest add collapsible ``` **Props**: `open`, `onOpenChange`, `disabled` **Dependencies**: @radix-ui/react-collapsible ## Form Components ### Button Clickable button with variants and sizes. ```bash npx shadcn@latest add button ``` **Variants**: default, destructive, outline, secondary, ghost, link **Sizes**: default, sm, lg, icon **Dependencies**: @radix-ui/react-slot ### Input Text input field. ```bash npx shadcn@latest add input ``` **Types**: text, email, password, number, tel, url **Use cases**: Forms, search bars, filters **Dependencies**: None ### Label Accessible label for form fields. ```bash npx shadcn@latest add label ``` **Use with**: All form inputs for accessibility **Dependencies**: @radix-ui/react-label ### Textarea Multi-line text input. ```bash npx shadcn@latest add textarea ``` **Props**: `rows`, `cols`, `resize` (via className) **Dependencies**: None ### Checkbox Binary toggle control. ```bash npx shadcn@latest add checkbox ``` **Props**: `checked`, `onCheckedChange`, `disabled` **Dependencies**: @radix-ui/react-checkbox ### Radio Group Select one option from a set. ```bash npx shadcn@latest add radio-group ``` **Sub-components**: RadioGroupItem **Dependencies**: @radix-ui/react-radio-group ### Select Dropdown selection control. ```bash npx shadcn@latest add select ``` **Sub-components**: SelectTrigger, SelectContent, SelectItem, SelectValue **Use cases**: Country selectors, category filters **Dependencies**: @radix-ui/react-select ### Switch Binary toggle with visual feedback. ```bash npx shadcn@latest add switch ``` **Props**: `checked`, `onCheckedChange`, `disabled` **Use cases**: Settings toggles, feature flags **Dependencies**: @radix-ui/react-switch ### Slider Select value from a range. ```bash npx shadcn@latest add slider ``` **Props**: `min`, `max`, `step`, `value`, `onValueChange` **Use cases**: Volume controls, filters, settings **Dependencies**: @radix-ui/react-slider ### Form Comprehensive form component with validation. ```bash npx shadcn@latest add form ``` **Sub-components**: FormField, FormItem, FormLabel, FormControl, FormDescription, FormMessage **Best used with**: react-hook-form, zod **Dependencies**: @radix-ui/react-label, @radix-ui/react-slot ## Data Display ### Table Display structured data in rows and columns. ```bash npx shadcn@latest add table ``` **Sub-components**: TableHeader, TableBody, TableHead, TableRow, TableCell, TableFooter, TableCaption **Best used with**: @tanstack/react-table **Dependencies**: None ### Badge Highlight status or category. ```bash npx shadcn@latest add badge ``` **Variants**: default, secondary, destructive, outline **Use cases**: Status indicators, tags, notifications **Dependencies**: None ### Avatar Display user profile images with fallback. ```bash npx shadcn@latest add avatar ``` **Sub-components**: AvatarImage, AvatarFallback **Dependencies**: @radix-ui/react-avatar ### Progress Visual indicator of task completion. ```bash npx shadcn@latest add progress ``` **Props**: `value` (0-100) **Dependencies**: @radix-ui/react-progress ### Skeleton Loading placeholder with animation. ```bash npx shadcn@latest add skeleton ``` **Use cases**: Content loading states **Dependencies**: None ### Calendar Date selection interface. ```bash npx shadcn@latest add calendar ``` **Props**: `mode` (single/multiple/range), `selected`, `onSelect` **Dependencies**: react-day-picker ## Overlay Components ### Dialog Modal dialog overlay. ```bash npx shadcn@latest add dialog ``` **Sub-components**: DialogTrigger, DialogContent, DialogHeader, DialogFooter, DialogTitle, DialogDescription **Use cases**: Confirmations, forms, detailed views **Dependencies**: @radix-ui/react-dialog ### Sheet Side panel that slides in from edge. ```bash npx shadcn@latest add sheet ``` **Sides**: top, right, bottom, left **Sub-components**: SheetTrigger, SheetContent, SheetHeader, SheetFooter, SheetTitle, SheetDescription **Use cases**: Navigation menus, filters, settings **Dependencies**: @radix-ui/react-dialog ### Popover Floating content container. ```bash npx shadcn@latest add popover ``` **Sub-components**: PopoverTrigger, PopoverContent **Use cases**: Tooltips with actions, mini forms **Dependencies**: @radix-ui/react-popover ### Tooltip Contextual information on hover. ```bash npx shadcn@latest add tooltip ``` **Sub-components**: TooltipProvider, TooltipTrigger, TooltipContent **Props**: `side`, `sideOffset`, `delayDuration` **Dependencies**: @radix-ui/react-tooltip ### Dropdown Menu Context menu with actions. ```bash npx shadcn@latest add dropdown-menu ``` **Sub-components**: DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuCheckboxItem, DropdownMenuRadioGroup, DropdownMenuSeparator, DropdownMenuLabel **Use cases**: Action menus, settings **Dependencies**: @radix-ui/react-dropdown-menu ### Context Menu Right-click menu. ```bash npx shadcn@latest add context-menu ``` **Sub-components**: Similar to DropdownMenu **Use cases**: Right-click actions, advanced UIs **Dependencies**: @radix-ui/react-context-menu ### Menubar Horizontal menu bar. ```bash npx shadcn@latest add menubar ``` **Sub-components**: MenubarMenu, MenubarTrigger, MenubarContent, MenubarItem **Use cases**: Application menus (File, Edit, View) **Dependencies**: @radix-ui/react-menubar ### Alert Dialog Modal dialog for important confirmations. ```bash npx shadcn@latest add alert-dialog ``` **Sub-components**: AlertDialogTrigger, AlertDialogContent, AlertDialogHeader, AlertDialogFooter, AlertDialogTitle, AlertDialogDescription, AlertDialogAction, AlertDialogCancel **Use cases**: Delete confirmations, destructive actions **Dependencies**: @radix-ui/react-alert-dialog ### Hover Card Content card revealed on hover. ```bash npx shadcn@latest add hover-card ``` **Sub-components**: HoverCardTrigger, HoverCardContent **Use cases**: User previews, detailed information **Dependencies**: @radix-ui/react-hover-card ## Navigation ### Navigation Menu Accessible navigation with dropdowns. ```bash npx shadcn@latest add navigation-menu ``` **Sub-components**: NavigationMenuList, NavigationMenuItem, NavigationMenuTrigger, NavigationMenuContent, NavigationMenuLink **Use cases**: Main site navigation **Dependencies**: @radix-ui/react-navigation-menu ### Breadcrumb Show current page location in hierarchy. ```bash npx shadcn@latest add breadcrumb ``` **Sub-components**: BreadcrumbList, BreadcrumbItem, BreadcrumbLink, BreadcrumbPage, BreadcrumbSeparator **Use cases**: Multi-level navigation **Dependencies**: None ### Pagination Navigate through pages of content. ```bash npx shadcn@latest add pagination ``` **Sub-components**: PaginationContent, PaginationItem, PaginationLink, PaginationPrevious, PaginationNext, PaginationEllipsis **Dependencies**: None ## Feedback Components ### Alert Display important messages. ```bash npx shadcn@latest add alert ``` **Variants**: default, destructive **Sub-components**: AlertTitle, AlertDescription **Use cases**: Error messages, warnings, info **Dependencies**: None ### Toast Temporary notification message. ```bash npx shadcn@latest add toast ``` **Props**: `title`, `description`, `action`, `variant` **Usage**: Via `useToast()` hook **Dependencies**: @radix-ui/react-toast ### Sonner Alternative toast implementation. ```bash npx shadcn@latest add sonner ``` **Better for**: Rich notifications, multiple toasts **Dependencies**: sonner ## Command & Search ### Command Command palette with search and keyboard navigation. ```bash npx shadcn@latest add command ``` **Sub-components**: CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem, CommandSeparator **Use cases**: Command palettes, search interfaces **Dependencies**: cmdk ### Combobox Searchable select dropdown. ```bash npx shadcn@latest add combobox ``` **Use cases**: Autocomplete, country selectors **Dependencies**: cmdk (via command) ## Utility Components ### Aspect Ratio Maintain consistent width-height ratio. ```bash npx shadcn@latest add aspect-ratio ``` **Props**: `ratio` (e.g., 16/9, 4/3) **Dependencies**: @radix-ui/react-aspect-ratio ### Scroll Area Custom scrollbar styling. ```bash npx shadcn@latest add scroll-area ``` **Use cases**: Custom scrollable areas **Dependencies**: @radix-ui/react-scroll-area ### Resizable Resizable panel layout. ```bash npx shadcn@latest add resizable ``` **Sub-components**: ResizablePanelGroup, ResizablePanel, ResizableHandle **Use cases**: Split views, adjustable layouts **Dependencies**: react-resizable-panels ## Date & Time ### Date Picker Select dates with calendar popup. ```bash npx shadcn@latest add date-picker ``` **Variants**: Single date, date range **Dependencies**: react-day-picker, date-fns ## Advanced Components ### Carousel Slideshow component. ```bash npx shadcn@latest add carousel ``` **Sub-components**: CarouselContent, CarouselItem, CarouselPrevious, CarouselNext **Dependencies**: embla-carousel-react ### Drawer Bottom drawer for mobile interfaces. ```bash npx shadcn@latest add drawer ``` **Best for**: Mobile-first designs **Dependencies**: vaul ## Component Composition Patterns ### Form + Validation Pattern ```bash npx shadcn@latest add form input label button npm install react-hook-form zod @hookform/resolvers ``` ### Data Table Pattern ```bash npx shadcn@latest add table button dropdown-menu npm install @tanstack/react-table ``` ### Dashboard Layout Pattern ```bash npx shadcn@latest add card tabs badge avatar ``` ### Authentication Pattern ```bash npx shadcn@latest add card input label button tabs ``` ## Quick Reference | Component | Category | Complexity | Dependencies | |-----------|----------|------------|--------------| | Button | Form | Simple | radix-slot | | Input | Form | Simple | None | | Card | Layout | Simple | None | | Dialog | Overlay | Medium | radix-dialog | | Table | Data | Simple | None | | Form | Form | Complex | radix-label/slot | | Command | Search | Complex | cmdk | | Calendar | Date | Medium | react-day-picker | ## Installation Shortcuts Common component bundles: ```bash # Essential forms npx shadcn@latest add form input label button select checkbox # Data display npx shadcn@latest add table badge avatar progress skeleton # Overlay/modal components npx shadcn@latest add dialog sheet popover tooltip alert-dialog # Navigation npx shadcn@latest add navigation-menu breadcrumb pagination # Layout npx shadcn@latest add card accordion tabs separator ``` ## Component Updates To update components to the latest version: ```bash # Re-add component (will prompt to overwrite) npx shadcn@latest add button # Or use diff command to see changes npx shadcn@latest diff button ``` ## Further Reading - [Official Component Docs](https://ui.shadcn.com/docs/components) - [Component Examples](https://ui.shadcn.com/examples) - [Radix UI Primitives](https://www.radix-ui.com/primitives)
- plugins/stitch-build/skills/shadcn-ui/resources/customization-guide.md (12100 bytes)
# shadcn/ui Customization Guide Learn how to customize shadcn/ui components to match your brand and design requirements. ## Theming Approach shadcn/ui uses a CSS variable-based theming system, making it easy to customize colors, spacing, and other design tokens globally. ## Color Customization ### Understanding the Color System shadcn/ui uses HSL color values stored as CSS variables. Each color has a base value and a foreground variant for text/content that appears on top of it. **Base Color Variables** (in `globals.css`): ```css :root { --background: 0 0% 100%; /* Page background */ --foreground: 222.2 84% 4.9%; /* Primary text color */ --primary: 221.2 83.2% 53.3%; /* Primary brand color */ --primary-foreground: 210 40% 98%; /* Text on primary */ --secondary: 210 40% 96.1%; /* Secondary actions */ --accent: 210 40% 96.1%; /* Accent highlights */ --muted: 210 40% 96.1%; /* Muted backgrounds */ --destructive: 0 84.2% 60.2%; /* Error/danger */ --border: 214.3 31.8% 91.4%; /* Border colors */ --input: 214.3 31.8% 91.4%; /* Input borders */ --ring: 221.2 83.2% 53.3%; /* Focus rings */ } ``` ### Changing Brand Colors To match your brand, update the primary color: ```css :root { /* Original blue */ --primary: 221.2 83.2% 53.3%; /* Change to brand purple */ --primary: 270 91% 65%; /* Adjust foreground for contrast */ --primary-foreground: 0 0% 100%; } ``` **HSL Format**: `hue saturation lightness` - Hue: 0-360 (color wheel position) - Saturation: 0-100% (color intensity) - Lightness: 0-100% (brightness) ### Tools for Color Selection 1. **HSL Color Picker**: https://hslpicker.com/ 2. **Shadcn Theme Generator**: https://ui.shadcn.com/themes 3. **Coolors**: https://coolors.co/ (generates palettes) ### Creating a Color Scheme Start with your primary brand color, then derive other colors: ```css :root { /* 1. Primary brand color */ --primary: 230 90% 60%; --primary-foreground: 0 0% 100%; /* 2. Lighter variant for secondary */ --secondary: 230 30% 95%; --secondary-foreground: 230 90% 30%; /* 3. Subtle accent (shift hue slightly) */ --accent: 200 90% 60%; --accent-foreground: 0 0% 100%; /* 4. Muted backgrounds (low saturation) */ --muted: 230 20% 96%; --muted-foreground: 230 20% 40%; /* 5. Keep destructive red-based */ --destructive: 0 84% 60%; --destructive-foreground: 0 0% 100%; } ``` ## Dark Mode ### Setting Up Dark Mode shadcn/ui includes dark mode support out of the box. Add dark mode colors: ```css .dark { --background: 222.2 84% 4.9%; --foreground: 210 40% 98%; --primary: 221.2 83.2% 53.3%; --primary-foreground: 210 40% 98%; /* ... all color variables */ } ``` ### Toggle Dark Mode **Next.js with next-themes**: ```bash npm install next-themes ``` ```tsx // app/providers.tsx "use client" import { ThemeProvider } from "next-themes" export function Providers({ children }: { children: React.ReactNode }) { return ( <ThemeProvider attribute="class" defaultTheme="system" enableSystem> {children} </ThemeProvider> ) } // app/layout.tsx import { Providers } from "./providers" export default function RootLayout({ children }) { return ( <html suppressHydrationWarning> <body> <Providers>{children}</Providers> </body> </html> ) } // components/theme-toggle.tsx "use client" import { Moon, Sun } from "lucide-react" import { useTheme } from "next-themes" import { Button } from "@/components/ui/button" export function ThemeToggle() { const { setTheme, theme } = useTheme() return ( <Button variant="ghost" size="icon" onClick={() => setTheme(theme === "light" ? "dark" : "light")} > <Sun className="h-5 w-5 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" /> <Moon className="absolute h-5 w-5 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" /> <span className="sr-only">Toggle theme</span> </Button> ) } ``` ## Component Customization ### Using Variants shadcn/ui components use `class-variance-authority` (cva) for variants. Example from Button: ```typescript // components/ui/button.tsx import { cva, type VariantProps } from "class-variance-authority" const buttonVariants = cva( "inline-flex items-center justify-center rounded-md text-sm font-medium", { variants: { variant: { default: "bg-primary text-primary-foreground hover:bg-primary/90", destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90", outline: "border border-input bg-background hover:bg-accent", ghost: "hover:bg-accent hover:text-accent-foreground", link: "text-primary underline-offset-4 hover:underline", }, size: { default: "h-10 px-4 py-2", sm: "h-9 rounded-md px-3", lg: "h-11 rounded-md px-8", icon: "h-10 w-10", }, }, defaultVariants: { variant: "default", size: "default", }, } ) ``` ### Adding Custom Variants To add a new variant, edit the component file in `components/ui/`: ```typescript // Add new "success" variant to button const buttonVariants = cva( "...", { variants: { variant: { default: "...", destructive: "...", // Add new variant success: "bg-green-600 text-white hover:bg-green-700", }, // Add new size size: { default: "...", xl: "h-12 rounded-md px-10 text-base", }, }, } ) // Update TypeScript interface export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement>, VariantProps<typeof buttonVariants> { asChild?: boolean } ``` Usage: ```tsx <Button variant="success" size="xl">Save Changes</Button> ``` ### Creating Composite Components Don't modify `components/ui/` directly. Instead, create wrapper components: ```tsx // components/loading-button.tsx import { Button, ButtonProps } from "@/components/ui/button" import { Loader2 } from "lucide-react" interface LoadingButtonProps extends ButtonProps { loading?: boolean } export function LoadingButton({ loading, children, disabled, ...props }: LoadingButtonProps) { return ( <Button disabled={loading || disabled} {...props}> {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />} {children} </Button> ) } ``` ## Typography Customization ### Font Family Update `tailwind.config.js`: ```javascript module.exports = { theme: { extend: { fontFamily: { sans: ['Inter', 'system-ui', 'sans-serif'], heading: ['Poppins', 'system-ui', 'sans-serif'], mono: ['Fira Code', 'monospace'], }, }, }, } ``` Import fonts in your layout: ```tsx // app/layout.tsx import { Inter, Poppins } from 'next/font/google' const inter = Inter({ subsets: ['latin'], variable: '--font-sans' }) const poppins = Poppins({ weight: ['600', '700'], subsets: ['latin'], variable: '--font-heading', }) export default function RootLayout({ children }) { return ( <html className={`${inter.variable} ${poppins.variable}`}> <body className="font-sans">{children}</body> </html> ) } ``` Use in components: ```tsx <h1 className="font-heading text-3xl">Heading</h1> <p className="font-sans">Body text</p> ``` ### Font Sizes Extend Tailwind's font scale: ```javascript // tailwind.config.js module.exports = { theme: { extend: { fontSize: { 'xs': '0.75rem', // 12px 'sm': '0.875rem', // 14px 'base': '1rem', // 16px 'lg': '1.125rem', // 18px 'xl': '1.25rem', // 20px '2xl': '1.5rem', // 24px '3xl': '1.875rem', // 30px '4xl': '2.25rem', // 36px '5xl': '3rem', // 48px '6xl': '3.75rem', // 60px '7xl': '4.5rem', // 72px }, }, }, } ``` ## Spacing & Layout ### Border Radius Customize roundedness globally: ```css /* globals.css */ :root { --radius: 0.5rem; /* Default (8px) */ /* More rounded */ --radius: 1rem; /* 16px */ /* Sharp edges */ --radius: 0; /* No rounding */ /* Very rounded */ --radius: 1.5rem; /* 24px */ } ``` This affects all components using `rounded-lg`, `rounded-md`, `rounded-sm`. ### Custom Spacing Extend Tailwind's spacing scale: ```javascript // tailwind.config.js module.exports = { theme: { extend: { spacing: { '72': '18rem', '84': '21rem', '96': '24rem', }, }, }, } ``` ## Animation Customization ### Adjusting Existing Animations ```javascript // tailwind.config.js module.exports = { theme: { extend: { keyframes: { // Make accordion faster "accordion-down": { from: { height: 0 }, to: { height: "var(--radix-accordion-content-height)" }, }, "accordion-up": { from: { height: "var(--radix-accordion-content-height)" }, to: { height: 0 }, }, }, animation: { "accordion-down": "accordion-down 0.15s ease-out", // Faster "accordion-up": "accordion-up 0.15s ease-out", }, }, }, } ``` ### Adding New Animations ```javascript // tailwind.config.js module.exports = { theme: { extend: { keyframes: { "fade-in": { "0%": { opacity: 0 }, "100%": { opacity: 1 }, }, "slide-in-bottom": { "0%": { transform: "translateY(100%)" }, "100%": { transform: "translateY(0)" }, }, }, animation: { "fade-in": "fade-in 0.3s ease-out", "slide-in-bottom": "slide-in-bottom 0.3s ease-out", }, }, }, } ``` Use in components: ```tsx <div className="animate-fade-in">Content</div> ``` ## Advanced Customization ### Creating a Design System Structure your customizations: ``` src/ ├── styles/ │ ├── globals.css # CSS variables & base styles │ ├── themes/ │ │ ├── default.css # Default theme │ │ └── brand.css # Brand-specific overrides │ └── components/ │ └── custom.css # Component-specific styles ├── lib/ │ └── design-tokens.ts # Shared constants └── components/ ├── ui/ # shadcn components (don't modify) └── custom/ # Your wrapper components ``` ### Design Tokens File ```typescript // lib/design-tokens.ts export const designTokens = { colors: { brand: { primary: 'hsl(230, 90%, 60%)', secondary: 'hsl(230, 30%, 95%)', }, }, spacing: { section: '5rem', card: '1.5rem', }, radius: { card: '1rem', button: '0.5rem', }, typography: { h1: 'text-5xl font-heading font-bold', h2: 'text-4xl font-heading font-semibold', h3: 'text-3xl font-heading font-semibold', body: 'text-base font-sans', small: 'text-sm text-muted-foreground', }, } as const ``` Use in components: ```tsx import { designTokens } from "@/lib/design-tokens" <h1 className={designTokens.typography.h1}>Title</h1> ``` ## Best Practices 1. **Don't modify `components/ui/` files directly**: Create wrapper components instead 2. **Use CSS variables for theming**: Easier to maintain and switch themes 3. **Leverage Tailwind's `extend`**: Don't replace defaults, extend them 4. **Keep variants in component files**: Co-locate variant logic with components 5. **Test dark mode**: Ensure all customizations work in both themes 6. **Document custom variants**: Add comments for custom additions 7. **Use consistent spacing**: Stick to Tailwind's spacing scale 8. **Maintain accessibility**: Don't sacrifice contrast for aesthetics ## Resources - [Tailwind CSS Customization](https://tailwindcss.com/docs/theme) - [CVA Documentation](https://cva.style/docs) - [Radix UI Theming](https://www.radix-ui.com/themes/docs/theme/overview) - [HSL Color Theory](https://www.w3.org/TR/css-color-3/#hsl-color) - plugins/stitch-build/skills/shadcn-ui/resources/migration-guide.md (10945 bytes)
# Migration Guide to shadcn/ui This guide helps you migrate from other UI libraries to shadcn/ui. ## Why Migrate to shadcn/ui? - **Full ownership**: Code lives in your project, not node_modules - **Customizable**: Modify any component to fit your needs - **No breaking changes**: Update components individually - **Smaller bundles**: Only include what you use - **Modern stack**: Built with Radix UI and Tailwind CSS - **Type-safe**: Full TypeScript support ## Migration Strategies ### Strategy 1: Incremental Migration (Recommended) Gradually replace components over time: 1. Install shadcn/ui alongside existing library 2. Replace components page by page or feature by feature 3. Remove old library once migration is complete **Pros**: Low risk, can be done alongside feature work **Cons**: Temporary bundle size increase ### Strategy 2: Big Bang Migration Replace all components at once: 1. Set up shadcn/ui 2. Create component mapping document 3. Replace all components in one effort 4. Test thoroughly **Pros**: Clean cutover, no mixed UI **Cons**: High risk, requires dedicated time ## Internal Migrations (shadcn specific) ### RTL Support Migration If you need to support RTL languages (like Arabic or Hebrew) in an existing shadcn/ui project: ```bash npx shadcn@latest migrate rtl ``` This CLI command transforms your components to use **logical properties**: - `ml-4` -> `ms-4` (margin-start) - `pl-4` -> `ps-4` (padding-start) - `text-left` -> `text-start` It ensures your UI adapts correctly to layout direction without manual refactoring. ## From Material-UI (MUI) ### Component Mapping | MUI Component | shadcn/ui Equivalent | Notes | |---------------|----------------------|-------| | Button | Button | Similar API | | TextField | Input + Label | Separate components | | Select | Select | Different structure | | Dialog | Dialog | Similar concept | | Drawer | Sheet | Side panel | | Card | Card | Very similar | | Table | Table | Use with TanStack Table | | Checkbox | Checkbox | Similar API | | Switch | Switch | Similar API | | Tabs | Tabs | Similar structure | | Tooltip | Tooltip | Simpler API | | Menu | Dropdown Menu | Different trigger model | | Snackbar | Toast | Different implementation | | Autocomplete | Combobox | Use with Command | ### Key Differences **1. Import Structure** ```tsx // MUI import Button from '@mui/material/Button' // shadcn/ui import { Button } from '@/components/ui/button' ``` **2. Form Components** ```tsx // MUI <TextField label="Email" value={email} onChange={(e) => setEmail(e.target.value)} error={!!errors.email} helperText={errors.email} /> // shadcn/ui <div className="space-y-2"> <Label htmlFor="email">Email</Label> <Input id="email" value={email} onChange={(e) => setEmail(e.target.value)} /> {errors.email && ( <p className="text-sm text-destructive">{errors.email}</p> )} </div> // Or with Form component <FormField control={form.control} name="email" render={({ field }) => ( <FormItem> <FormLabel>Email</FormLabel> <FormControl> <Input {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> ``` **3. Theming** ```tsx // MUI import { ThemeProvider, createTheme } from '@mui/material/styles' const theme = createTheme({ palette: { primary: { main: '#1976d2' }, }, }) <ThemeProvider theme={theme}> <App /> </ThemeProvider> // shadcn/ui // Edit globals.css :root { --primary: 215 100% 50%; } ``` **4. Styling Approach** ```tsx // MUI (sx prop) <Button sx={{ px: 4, py: 2, borderRadius: 2 }}> Click me </Button> // shadcn/ui (Tailwind classes) <Button className="px-4 py-2 rounded-lg"> Click me </Button> ``` ### Migration Example: Login Form **Before (MUI)**: ```tsx import { TextField, Button, Box } from '@mui/material' export function LoginForm() { return ( <Box component="form" sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}> <TextField label="Email" type="email" required /> <TextField label="Password" type="password" required /> <Button variant="contained" type="submit"> Sign In </Button> </Box> ) } ``` **After (shadcn/ui)**: ```tsx import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Button } from '@/components/ui/button' export function LoginForm() { return ( <form className="flex flex-col gap-4"> <div className="space-y-2"> <Label htmlFor="email">Email</Label> <Input id="email" type="email" required /> </div> <div className="space-y-2"> <Label htmlFor="password">Password</Label> <Input id="password" type="password" required /> </div> <Button type="submit">Sign In</Button> </form> ) } ``` ## From Chakra UI ### Component Mapping | Chakra UI | shadcn/ui | Notes | |-----------|-----------|-------| | Button | Button | Similar variants | | Input | Input | More basic | | Select | Select | Different structure | | Modal | Dialog | Similar concept | | Drawer | Sheet | Very similar | | Box | div | Use Tailwind classes | | Flex | div | Use flex utilities | | Stack | div | Use space-y-* classes | | Text | p/span | Use typography classes | | Heading | h1/h2/etc | Use typography classes | | useToast | useToast | Different API | | Menu | Dropdown Menu | Similar | ### Key Differences **1. Layout Components** ```tsx // Chakra UI <Stack spacing={4} direction="column"> <Box>Item 1</Box> <Box>Item 2</Box> </Stack> // shadcn/ui <div className="flex flex-col space-y-4"> <div>Item 1</div> <div>Item 2</div> </div> ``` **2. Responsive Styles** ```tsx // Chakra UI <Box display={{ base: 'block', md: 'flex' }} /> // shadcn/ui <div className="block md:flex" /> ``` **3. Color Mode** ```tsx // Chakra UI import { useColorMode } from '@chakra-ui/react' const { colorMode, toggleColorMode } = useColorMode() // shadcn/ui (with next-themes) import { useTheme } from 'next-themes' const { theme, setTheme } = useTheme() ``` ## From Ant Design ### Component Mapping | Ant Design | shadcn/ui | Notes | |------------|-----------|-------| | Button | Button | Similar | | Input | Input | More basic | | Form | Form | Different approach | | Table | Table | Use TanStack Table | | Modal | Dialog | Similar | | Drawer | Sheet | Similar | | Select | Select | Different API | | DatePicker | Calendar + Popover | More manual | | Menu | Navigation Menu | Different | | message | Toast | Different API | | notification | Toast | Similar concept | ### Key Differences **1. Form Handling** ```tsx // Ant Design <Form form={form} onFinish={onSubmit} > <Form.Item name="email" rules={[{ required: true }]}> <Input /> </Form.Item> <Form.Item> <Button type="primary" htmlType="submit">Submit</Button> </Form.Item> </Form> // shadcn/ui (with react-hook-form) <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)}> <FormField control={form.control} name="email" render={({ field }) => ( <FormItem> <FormControl> <Input {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <Button type="submit">Submit</Button> </form> </Form> ``` **2. Notifications** ```tsx // Ant Design import { message } from 'antd' message.success('Success!') // shadcn/ui import { useToast } from '@/components/ui/use-toast' const { toast } = useToast() toast({ title: "Success!", description: "Operation completed.", }) ``` ## From Bootstrap ### Component Mapping | Bootstrap | shadcn/ui | Notes | |-----------|-----------|-------| | btn | Button | Similar variants | | form-control | Input | Similar | | card | Card | Very similar structure | | modal | Dialog | Different API | | dropdown | Dropdown Menu | Similar concept | | nav/navbar | Navigation Menu | Different | | alert | Alert | Similar | | badge | Badge | Similar | | table | Table | Use with TanStack Table | ### Key Differences **1. Class-Based vs Component-Based** ```tsx // Bootstrap <button className="btn btn-primary btn-lg"> Click me </button> // shadcn/ui <Button variant="default" size="lg"> Click me </Button> ``` **2. Cards** ```html <!-- Bootstrap --> <div class="card"> <div class="card-header">Title</div> <div class="card-body">Content</div> <div class="card-footer">Footer</div> </div> <!-- shadcn/ui --> <Card> <CardHeader> <CardTitle>Title</CardTitle> </CardHeader> <CardContent>Content</CardContent> <CardFooter>Footer</CardFooter> </Card> ``` ## Migration Checklist ### Before Migration - [ ] Audit current component usage - [ ] Set up shadcn/ui in a test branch - [ ] Create component mapping document - [ ] Plan migration order (start with simple components) - [ ] Set up Tailwind CSS properly - [ ] Configure path aliases ### During Migration - [ ] Install shadcn/ui components as needed - [ ] Replace components incrementally - [ ] Update styling to use Tailwind classes - [ ] Test each page/feature after migration - [ ] Update tests to match new components - [ ] Handle form validation (switch to react-hook-form + zod) - [ ] Migrate theme/color variables ### After Migration - [ ] Remove old UI library dependencies - [ ] Clean up unused imports - [ ] Optimize bundle size - [ ] Update documentation - [ ] Review and update design system - [ ] Train team on new components ## Common Pitfalls ### 1. Not Setting Up Tailwind Properly shadcn/ui requires Tailwind. Ensure: - `tailwind.config.js` includes correct content paths - CSS variables are defined in `globals.css` - Tailwind plugins are installed (e.g., `tailwindcss-animate`) ### 2. Forgetting Path Aliases Components use `@/` imports. Configure: - `tsconfig.json` with path aliases - Vite/Next.js config for runtime resolution ### 3. Trying to Match Old Library Exactly Don't force shadcn/ui to work like your old library. Embrace the new patterns: - Use composition over configuration - Leverage Tailwind utilities - Create wrapper components for custom needs ### 4. Not Using Form Libraries shadcn/ui form components are basic. For complex forms, use: - `react-hook-form` for form state - `zod` for validation - shadcn's `Form` component for integration ### 5. Ignoring Accessibility While shadcn/ui is accessible by default, custom modifications can break this. Test with: - Keyboard navigation - Screen readers - ARIA attribute validation ## Getting Help - **Discord**: [shadcn/ui Discord](https://discord.com/invite/vNvTqVaWm6) - **GitHub Discussions**: [shadcn/ui Discussions](https://github.com/shadcn-ui/ui/discussions) - **Documentation**: [ui.shadcn.com](https://ui.shadcn.com) ## Next Steps After migration: 1. Review the [Customization Guide](./customization-guide.md) 2. Explore the [Component Catalog](./component-catalog.md) 3. Check out [Examples](../examples/) 4. Consider building a component library on top of shadcn/ui - plugins/stitch-build/skills/shadcn-ui/resources/setup-guide.md (9866 bytes)
# shadcn/ui Setup Guide This guide walks you through setting up shadcn/ui in both new and existing projects. ## Prerequisites Before you begin, ensure you have: - **Node.js 18+** installed - **React 18+** in your project - **Tailwind CSS 3.0+** configured - A package manager: npm, yarn, pnpm, or bun ## Quick Start (New Project) ### Option 1: npx shadcn create (Recommended) The easiest way to start a new project with shadcn/ui is using the `create` command, which allows you to customize everything (framework, library, style, font, etc.). ```bash npx shadcn@latest create ``` This interactive command will guide you through: 1. **Project Name**: Directory for your app. 2. **Visual Style**: Choose from Vega, Nova, Maia, Lyra, Mira, or Classic. 3. **Base Color**: Select your primary theme color. 4. **Framework**: Next.js, Vite, Laravel, etc. 5. **Component Library**: Choose **Radix UI** or **Base UI**. 6. **RTL Support**: Enable Right-to-Left support if needed. ### Option 2: Classic Manual Setup (Next.js) ```bash # Create a new Next.js project npx create-next-app@latest my-app cd my-app # Initialize shadcn/ui npx shadcn@latest init # Add your first component npx shadcn@latest add button ``` ### Option 3: Classic Manual Setup (Vite + React) ```bash # Create a new Vite project npm create vite@latest my-app -- --template react-ts cd my-app npm install # Install Tailwind CSS npm install -D tailwindcss postcss autoprefixer npx tailwindcss init -p # Initialize shadcn/ui npx shadcn@latest init # Add your first component npx shadcn@latest add button ``` ## Existing Project Setup ### Step 1: Ensure Tailwind CSS is Installed If Tailwind is not installed: ```bash npm install -D tailwindcss postcss autoprefixer npx tailwindcss init -p ``` Configure `tailwind.config.js`: ```javascript /** @type {import('tailwindcss').Config} */ export default { content: [ "./index.html", "./src/**/*.{js,ts,jsx,tsx}", ], theme: { extend: {}, }, plugins: [], } ``` ### Step 2: Initialize shadcn/ui Run the initialization command: ```bash npx shadcn@latest init ``` You'll be asked to configure: 1. **Style**: Choose between `default`, `new-york`, or one of the new styles (Vega, Nova, etc.) - `default`: Clean and minimal design - `new-york`: More refined with subtle details 2. **Base Color**: Choose your primary color palette - slate, gray, zinc, neutral, or stone 3. **CSS Variables**: Recommend `yes` for easier theming 4. **TypeScript**: Recommend `yes` for type safety 5. **Import Alias**: Default is `@/components` (recommended) 6. **React Server Components**: Choose based on your framework - `yes` for Next.js 13+ with app directory - `no` for Vite, CRA, or Next.js pages directory 7. **RTL Support**: Answer `yes` if you need Right-to-Left layout support (this will use logical properties like `ms-4` instead of `ml-4`). ## Advanced Features ### Visual Styles shadcn/ui now offers multiple visual styles beyond the defaults: - **Vega**: The classic shadcn/ui look. - **Nova**: Reduced padding/margins, compact. - **Maia**: Soft, rounded, generous spacing. - **Lyra**: Boxy, sharp, mono font friendly. - **Mira**: Dense, compact. ### Base UI Support You can now choose between **Radix UI** and **Base UI** as the underlying primitive library. They share the same component API/abstraction, so your usage remains consistent. ### Step 3: Verify Configuration The init command creates/updates several files: **components.json** (root of project): ```json { "$schema": "https://ui.shadcn.com/schema.json", "style": "default", "rsc": false, "tsx": true, "tailwind": { "config": "tailwind.config.js", "css": "src/index.css", "baseColor": "slate", "cssVariables": true }, "aliases": { "components": "@/components", "utils": "@/lib" } } ``` **src/lib/utils.ts**: ```typescript import { clsx, type ClassValue } from "clsx" import { twMerge } from "tailwind-merge" export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) } ``` **Updated tailwind.config.js**: ```javascript /** @type {import('tailwindcss').Config} */ module.exports = { darkMode: ["class"], content: [ './pages/**/*.{ts,tsx}', './components/**/*.{ts,tsx}', './app/**/*.{ts,tsx}', './src/**/*.{ts,tsx}', ], theme: { container: { center: true, padding: "2rem", screens: { "2xl": "1400px", }, }, extend: { colors: { border: "hsl(var(--border))", input: "hsl(var(--input))", ring: "hsl(var(--ring))", background: "hsl(var(--background))", foreground: "hsl(var(--foreground))", primary: { DEFAULT: "hsl(var(--primary))", foreground: "hsl(var(--primary-foreground))", }, // ... more colors }, borderRadius: { lg: "var(--radius)", md: "calc(var(--radius) - 2px)", sm: "calc(var(--radius) - 4px)", }, keyframes: { "accordion-down": { from: { height: 0 }, to: { height: "var(--radix-accordion-content-height)" }, }, "accordion-up": { from: { height: "var(--radix-accordion-content-height)" }, to: { height: 0 }, }, }, animation: { "accordion-down": "accordion-down 0.2s ease-out", "accordion-up": "accordion-up 0.2s ease-out", }, }, }, plugins: [require("tailwindcss-animate")], } ``` **Updated globals.css** (or equivalent): ```css @tailwind base; @tailwind components; @tailwind utilities; @layer base { :root { --background: 0 0% 100%; --foreground: 222.2 84% 4.9%; --card: 0 0% 100%; --card-foreground: 222.2 84% 4.9%; --popover: 0 0% 100%; --popover-foreground: 222.2 84% 4.9%; --primary: 221.2 83.2% 53.3%; --primary-foreground: 210 40% 98%; --secondary: 210 40% 96.1%; --secondary-foreground: 222.2 47.4% 11.2%; --muted: 210 40% 96.1%; --muted-foreground: 215.4 16.3% 46.9%; --accent: 210 40% 96.1%; --accent-foreground: 222.2 47.4% 11.2%; --destructive: 0 84.2% 60.2%; --destructive-foreground: 210 40% 98%; --border: 214.3 31.8% 91.4%; --input: 214.3 31.8% 91.4%; --ring: 221.2 83.2% 53.3%; --radius: 0.5rem; } .dark { --background: 222.2 84% 4.9%; --foreground: 210 40% 98%; /* ... dark mode variables */ } } @layer base { * { @apply border-border; } body { @apply bg-background text-foreground; } } ``` ### Step 4: Configure Path Aliases Ensure your `tsconfig.json` includes path aliases: ```json { "compilerOptions": { "baseUrl": ".", "paths": { "@/*": ["./src/*"] } } } ``` For Vite, also update `vite.config.ts`: ```typescript import path from "path" import { defineConfig } from "vite" import react from "@vitejs/plugin-react" export default defineConfig({ plugins: [react()], resolve: { alias: { "@": path.resolve(__dirname, "./src"), }, }, }) ``` ### Step 5: Add Components Now you can add components: ```bash # Add individual components npx shadcn@latest add button npx shadcn@latest add card npx shadcn@latest add dialog # Add multiple components at once npx shadcn@latest add button card dialog input label ``` Components will be added to `src/components/ui/` by default. ## Framework-Specific Considerations ### Next.js App Router - Set `rsc: true` in `components.json` - Add `"use client"` to stateful components - Import components work from server components by default ### Next.js Pages Router - Set `rsc: false` in `components.json` - All components are client-side by default ### Vite - Ensure path aliases are configured in `vite.config.ts` - Import `globals.css` in your main entry point (`main.tsx`) ### Create React App - Use `craco` or `react-app-rewired` for path alias support - Or use relative imports instead of aliases ## Verification Steps 1. **Check file structure**: ``` src/ ├── components/ │ └── ui/ ├── lib/ │ └── utils.ts └── index.css (or globals.css) ``` 2. **Test a simple component**: ```tsx import { Button } from "@/components/ui/button" export default function App() { return <Button>Click me</Button> } ``` 3. **Verify Tailwind is working**: - Component should render with proper styling - Check browser dev tools for applied classes 4. **Test dark mode** (if using CSS variables): ```tsx <html className="dark"> ``` ## Troubleshooting ### "Cannot find module '@/components/ui/button'" **Solution**: Check path alias configuration in `tsconfig.json` and framework config. ### Styles not applying **Solution**: - Ensure `globals.css` is imported in your app entry point - Verify Tailwind config `content` paths include your files - Check CSS variables are defined in `globals.css` ### TypeScript errors in components **Solution**: - Run `npm install` to ensure all dependencies are installed - Check that `@types/react` is installed - Restart TypeScript server in your editor ### Components look broken **Solution**: - Verify `tailwindcss-animate` is installed: `npm install tailwindcss-animate` - Check that CSS variables are properly defined - Ensure you're not overriding component styles globally ## Next Steps 1. Browse the [component catalog](./component-catalog.md) 2. Read the [customization guide](./customization-guide.md) 3. Check out example implementations in `/examples` 4. Join the [shadcn/ui Discord](https://discord.com/invite/vNvTqVaWm6) ## Additional Resources - [Official Documentation](https://ui.shadcn.com) - [Component Examples](https://ui.shadcn.com/examples) - [GitHub Repository](https://github.com/shadcn-ui/ui) - [Tailwind CSS Docs](https://tailwindcss.com/docs) - plugins/stitch-build/skills/shadcn-ui/scripts/verify-setup.sh (5309 bytes)
#!/usr/bin/env bash # shadcn/ui Setup Verification Script # Validates that a project is correctly configured for shadcn/ui set -e GREEN='\033[0;32m' RED='\033[0;31m' YELLOW='\033[1;33m' NC='\033[0m' # No Color echo "🔍 Verifying shadcn/ui setup..." echo "" # Check if components.json exists if [ -f "components.json" ]; then echo -e "${GREEN}✓${NC} components.json found" else echo -e "${RED}✗${NC} components.json not found" echo -e " ${YELLOW}Run:${NC} npx shadcn@latest init" exit 1 fi # Read the configured CSS path. Tailwind v4 deliberately has no config file. if ! command -v node >/dev/null 2>&1; then echo -e "${RED}✗${NC} Node.js is required to read components.json" exit 1 fi CSS_FILE=$(node -e ' const fs = require("node:fs"); const config = JSON.parse(fs.readFileSync("components.json", "utf8")); process.stdout.write(config.tailwind?.css || ""); ') if [ -z "$CSS_FILE" ]; then for candidate in src/index.css src/globals.css app/globals.css; do if [ -f "$candidate" ]; then CSS_FILE=$candidate break fi done fi TAILWIND_V4=false if [ -f "$CSS_FILE" ] && node -e ' const fs = require("node:fs"); const css = fs.readFileSync(process.argv[1], "utf8").replace(/\/\*[\s\S]*?\*\//g, ""); process.exit(/@import\s+(["\x27])tailwindcss\1/.test(css) ? 0 : 1); ' "$CSS_FILE"; then TAILWIND_V4=true fi if [ "$TAILWIND_V4" = true ]; then echo -e "${GREEN}✓${NC} Tailwind CSS-first setup found" elif [ -f "tailwind.config.js" ] || [ -f "tailwind.config.ts" ]; then echo -e "${GREEN}✓${NC} Tailwind config found" else echo -e "${RED}✗${NC} Tailwind config or CSS-first import not found" exit 1 fi # Check if tsconfig.json has path aliases if [ -f "tsconfig.json" ]; then if grep -q '"@/\*"' tsconfig.json; then echo -e "${GREEN}✓${NC} Path aliases configured in tsconfig.json" else echo -e "${YELLOW}⚠${NC} Path aliases not found in tsconfig.json" echo " Add to compilerOptions.paths:" echo ' "@/*": ["./src/*"]' fi else echo -e "${YELLOW}⚠${NC} tsconfig.json not found (TypeScript not configured)" fi # Check if globals.css or equivalent exists if [ -n "$CSS_FILE" ] && [ -f "$CSS_FILE" ]; then echo -e "${GREEN}✓${NC} Global CSS file found" # Check for Tailwind directives if [ "$TAILWIND_V4" = true ] || grep -q "@tailwind base" "$CSS_FILE"; then echo -e "${GREEN}✓${NC} Tailwind directives present" else echo -e "${RED}✗${NC} Tailwind directives missing" echo " Add to your CSS file:" echo " @tailwind base;" echo " @tailwind components;" echo " @tailwind utilities;" fi # Check for CSS variables if grep -q "^:root" "$CSS_FILE" || grep -q "@layer base" "$CSS_FILE" || grep -q "@theme" "$CSS_FILE"; then echo -e "${GREEN}✓${NC} CSS variables defined" else echo -e "${YELLOW}⚠${NC} CSS variables not found" echo " shadcn/ui requires CSS variables for theming" fi else echo -e "${RED}✗${NC} Global CSS file not found" fi # Check if components/ui directory exists if [ -d "src/components/ui" ] || [ -d "components/ui" ]; then echo -e "${GREEN}✓${NC} components/ui directory exists" # Count components COMPONENT_COUNT=$(find . -not -path "*/node_modules/*" \( -path "*/components/ui/*.tsx" -o -path "*/components/ui/*.jsx" \) | wc -l) echo -e " ${COMPONENT_COUNT} components installed" else echo -e "${YELLOW}⚠${NC} components/ui directory not found" echo " Add your first component: npx shadcn@latest add button" fi # Check if lib/utils exists if [ -f "src/lib/utils.ts" ] || [ -f "lib/utils.ts" ]; then echo -e "${GREEN}✓${NC} lib/utils.ts exists" # Check for cn function UTILS_FILE=$(find . -not -path "*/node_modules/*" -name "utils.ts" | grep "lib" | head -n 1) if grep -q "export function cn" "$UTILS_FILE"; then echo -e "${GREEN}✓${NC} cn() utility function present" else echo -e "${RED}✗${NC} cn() utility function missing" fi else echo -e "${RED}✗${NC} lib/utils.ts not found" fi # Check package.json dependencies if [ -f "package.json" ]; then echo "" echo "📦 Checking dependencies..." # Required dependencies REQUIRED_DEPS=("react" "tailwindcss") RECOMMENDED_DEPS=("class-variance-authority" "clsx" "tailwind-merge" "tailwindcss-animate") for dep in "${REQUIRED_DEPS[@]}"; do if grep -q "\"$dep\"" package.json; then echo -e "${GREEN}✓${NC} $dep installed" else echo -e "${RED}✗${NC} $dep not installed" fi done echo "" echo "Recommended dependencies:" for dep in "${RECOMMENDED_DEPS[@]}"; do if grep -q "\"$dep\"" package.json; then echo -e "${GREEN}✓${NC} $dep installed" else echo -e "${YELLOW}⚠${NC} $dep not installed (recommended)" fi done fi echo "" echo -e "${GREEN}✓${NC} Setup verification complete!" echo "" echo "Next steps:" echo " 1. Add components: npx shadcn@latest add [component]" echo " 2. View catalog: npx shadcn@latest add --help" echo " 3. Browse docs: https://ui.shadcn.com" - plugins/stitch-build/skills/shadcn-ui/SKILL.md (9207 bytes)
--- name: shadcn-ui description: Expert guidance for integrating and building applications with shadcn/ui components, including component discovery, installation, customization, and best practices. allowed-tools: - "shadcn*:*" - "mcp_shadcn*" - "Read" - "Write" - "Bash" - "web_fetch" --- # shadcn/ui Component Integration You are a frontend engineer specialized in building applications with shadcn/ui—a collection of beautifully designed, accessible, and customizable components built with Radix UI or Base UI and Tailwind CSS. You help developers discover, integrate, and customize components following best practices. ## Core Principles shadcn/ui is **not a component library**—it's a collection of reusable components that you copy into your project. This gives you: - **Full ownership**: Components live in your codebase, not node_modules - **Complete customization**: Modify styling, behavior, and structure freely, including choosing between Radix UI or Base UI primitives - **No version lock-in**: Update components selectively at your own pace - **Zero runtime overhead**: No library bundle, just the code you need ## Component Discovery and Installation ### 1. Browse Available Components Use the shadcn MCP tools to explore the component catalog and Registry Directory: - **List all components**: Use `list_components` to see the complete catalog - **Get component metadata**: Use `get_component_metadata` to understand props, dependencies, and usage - **View component demos**: Use `get_component_demo` to see implementation examples ### 2. Component Installation There are two approaches to adding components: **A. Direct Installation (Recommended)** ```bash npx shadcn@latest add [component-name] ``` This command: - Downloads the component source code (adapting to your config: Radix vs Base UI) - Installs required dependencies - Places files in `components/ui/` - Updates your `components.json` config **B. Manual Integration** 1. Use `get_component` to retrieve the source code 2. Create the file in `components/ui/[component-name].tsx` 3. Install peer dependencies manually 4. Adjust imports if needed ### 3. Registry and Custom Registries If working with a custom registry (defined in `components.json`) or exploring the Registry Directory: - Use `get_project_registries` to list available registries - Use `list_items_in_registries` to see registry-specific components - Use `view_items_in_registries` for detailed component information - Use `search_items_in_registries` to find specific components ## Project Setup ### Initial Configuration For **new projects**, use the `create` command to customize everything (style, fonts, component library): ```bash npx shadcn@latest create ``` For **existing projects**, initialize configuration: ```bash npx shadcn@latest init ``` This creates `components.json` with your configuration: - **style**: default, new-york (classic) OR choose new visual styles like Vega, Nova, Maia, Lyra, Mira - **baseColor**: slate, gray, zinc, neutral, stone - **cssVariables**: true/false for CSS variable usage - **tailwind config**: paths to Tailwind files - **aliases**: import path shortcuts - **rsc**: Use React Server Components (yes/no) - **rtl**: Enable RTL support (optional) ### Required Dependencies shadcn/ui components require: - **React** (18+) - **Tailwind CSS** (3.0+) - **Primitives**: Radix UI OR Base UI (depending on your choice) - **class-variance-authority** (for variant styling) - **clsx** and **tailwind-merge** (for class composition) ## Component Architecture ### File Structure ``` src/ ├── components/ │ ├── ui/ # shadcn components │ │ ├── button.tsx │ │ ├── card.tsx │ │ └── dialog.tsx │ └── [custom]/ # your composed components │ └── user-card.tsx ├── lib/ │ └── utils.ts # cn() utility └── app/ └── page.tsx ``` ### The `cn()` Utility All shadcn components use the `cn()` helper for class merging: ```typescript import { clsx, type ClassValue } from "clsx" import { twMerge } from "tailwind-merge" export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) } ``` This allows you to: - Override default styles without conflicts - Conditionally apply classes - Merge Tailwind classes intelligently ## Customization Best Practices ### 1. Theme Customization Edit your Tailwind config and CSS variables in `app/globals.css`: ```css @layer base { :root { --background: 0 0% 100%; --foreground: 222.2 84% 4.9%; --primary: 221.2 83.2% 53.3%; /* ... more variables */ } .dark { --background: 222.2 84% 4.9%; --foreground: 210 40% 98%; /* ... dark mode overrides */ } } ``` ### 2. Component Variants Use `class-variance-authority` (cva) for variant logic: ```typescript import { cva } from "class-variance-authority" const buttonVariants = cva( "inline-flex items-center justify-center rounded-md", { variants: { variant: { default: "bg-primary text-primary-foreground", outline: "border border-input", }, size: { default: "h-10 px-4 py-2", sm: "h-9 rounded-md px-3", }, }, defaultVariants: { variant: "default", size: "default", }, } ) ``` ### 3. Extending Components Create wrapper components in `components/` (not `components/ui/`): ```typescript // components/custom-button.tsx import { Button } from "@/components/ui/button" import { Loader2 } from "lucide-react" export function LoadingButton({ loading, children, ...props }: ButtonProps & { loading?: boolean }) { return ( <Button disabled={loading} {...props}> {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />} {children} </Button> ) } ``` ## Blocks and Complex Components shadcn/ui provides complete UI blocks (authentication forms, dashboards, etc.): 1. **List available blocks**: Use `list_blocks` with optional category filter 2. **Get block source**: Use `get_block` with the block name 3. **Install blocks**: Many blocks include multiple component files Blocks are organized by category: - **calendar**: Calendar interfaces - **dashboard**: Dashboard layouts - **login**: Authentication flows - **sidebar**: Navigation sidebars - **products**: E-commerce components ## Accessibility All shadcn/ui components are built on Radix UI primitives, ensuring: - **Keyboard navigation**: Full keyboard support out of the box - **Screen reader support**: Proper ARIA attributes - **Focus management**: Logical focus flow - **Disabled states**: Proper disabled and aria-disabled handling When customizing, maintain accessibility: - Keep ARIA attributes - Preserve keyboard handlers - Test with screen readers - Maintain focus indicators ## Common Patterns ### Form Building ```typescript import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" import { Label } from "@/components/ui/label" // Use with react-hook-form for validation import { useForm } from "react-hook-form" ``` ### Dialog/Modal Patterns ```typescript import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog" ``` ### Data Display ```typescript import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table" ``` ## Troubleshooting ### Import Errors - Check `components.json` for correct alias configuration - Verify `tsconfig.json` includes the `@` path alias: ```json { "compilerOptions": { "paths": { "@/*": ["./src/*"] } } } ``` ### Style Conflicts - Ensure Tailwind CSS is properly configured - Check that `globals.css` is imported in your root layout - Verify CSS variable names match between components and theme ### Missing Dependencies - Run component installation via CLI to auto-install deps - Manually check `package.json` for required Radix UI packages - Use `get_component_metadata` to see dependency lists ### Version Compatibility - shadcn/ui v4 requires React 18+ and Next.js 13+ (if using Next.js) - Some components require specific Radix UI versions - Check documentation for breaking changes between versions ## Validation and Quality Before committing components: 1. **Type check**: Run `tsc --noEmit` to verify TypeScript 2. **Lint**: Run your linter to catch style issues 3. **Test accessibility**: Use tools like axe DevTools 4. **Visual QA**: Test in light and dark modes 5. **Responsive check**: Verify behavior at different breakpoints ## Resources Refer to the following resource files for detailed guidance: - `resources/setup-guide.md` - Step-by-step project initialization - `resources/component-catalog.md` - Complete component reference - `resources/customization-guide.md` - Theming and variant patterns - `resources/migration-guide.md` - Upgrading from other UI libraries ## Examples See the `examples/` directory for: - Complete component implementations - Form patterns with validation - Dashboard layouts - Authentication flows - Data table implementations - plugins/stitch-design/skills/code-to-design/SKILL.md (3649 bytes)
--- name: stitch::code-to-design description: >- Convert frontend code (Vite, React, Angular, Vue, etc.) to a Stitch Design by chaining static HTML extraction, design system extraction, and file upload. **ALWAYS** use this skill when the user's intent is to move existing web apps or React/Angular/Vue components into Stitch (e.g., requests to "save", "migrate", or "upload"). You must use this skill even for simple "save" operations, as it is the only way to ensure the design system is extracted and assets are properly linked. allowed-tools: - "stitch*:*" - "Bash" - "Read" - "Write" - "web_fetch" --- # Code to Design Transform your existing frontend code (React + Vite, Next.js, Angular, Vue, etc.) into a Stitch Design so you can iterate and improve it using Stitch. This skill orchestrates three other skills in sequence: 1. `extract-static-html`: Extract a single self-contained HTML file from your build output or running dev server (e.g., Vite dev server or Angular CLI `ng serve`). 2. `extract-design-md`: Analyze the source code (including Angular `angular.json`, external `.html` templates, theme files, and components) to create a design system (DESIGN.md). 3. `upload-to-stitch`: Upload that HTML file and the design system to your Stitch project. ## Workflow Follow these steps to convert your existing code. ### Prerequisites - A running local dev server (e.g. `npm run dev`, `ng serve`) OR a built web application directory containing `index.html` and assets. - Target Stitch `projectId` (use `list_projects` if unknown). ### Steps #### 1. Extract Self-Contained HTML Delegate to the `extract-static-html` skill to generate a standalone HTML file. Read [skills/extract-static-html/SKILL.md](../extract-static-html/SKILL.md) for detailed instructions and script usage. Expected output: A single file like `/path/to/extracted/standalone.html`. #### 2. Verify HTML (Optional — User-Driven) After extraction, inform the user of the output file path so they can manually verify in a browser if desired. **Do not block on verification** — proceed directly to Step 3. If the user reports issues after reviewing, fix them before continuing. #### 3. Extract Design System (File) Delegate to the `extract-design-md` skill to analyze the project's source files (components, stylesheets, theme configs) and produce a design system. Read [skills/extract-design-md/SKILL.md](../extract-design-md/SKILL.md) for the full analysis workflow. Write `.stitch/DESIGN.md` following the `extract-design-md` skill's output structure. #### 4. Upload DESIGN.md and Create Design System in Stitch Delegate to the `manage-design-system` skill to upload the `DESIGN.md` and create the design system in Stitch. Read [skills/manage-design-system/SKILL.md](../manage-design-system/SKILL.md) for the full workflow (upload script usage, `create_design_system_from_design_md` call, and required schemas). Pass `--generated-by 'stitch::code-to-design'` when uploading. #### 5. Upload HTML to Stitch Use the same `upload-to-stitch` skill's script to upload the extracted HTML file. Read [skills/upload-to-stitch/SKILL.md](../upload-to-stitch/SKILL.md) for detailed instructions and script usage. You will need: - The path to the standalone HTML file generated in Step 1. - Your Stitch API Key (same key used in Step 4). - The target `projectId`. - The `--generated-by` argument set to `'stitch::extract-static-html'`. - The `--title` argument set to the **route path** of the page (e.g., `'/dashboard'`, `'/settings/profile'`, `'/inbox'`) so that the screen name/title in Stitch clearly identifies its route in the application.
- plugins/stitch-design/skills/extract-design-md/examples/DESIGN.md (6960 bytes)
--- name: Alpine Peak colors: surface: '#fcf8fa' surface-dim: '#dcd9db' surface-bright: '#fcf8fa' surface-container-lowest: '#ffffff' surface-container-low: '#f6f3f5' surface-container: '#f0edef' surface-container-high: '#eae7e9' surface-container-highest: '#e4e2e4' on-surface: '#1b1b1d' on-surface-variant: '#45464d' inverse-surface: '#303032' inverse-on-surface: '#f3f0f2' outline: '#76777d' outline-variant: '#c6c6cd' surface-tint: '#565e74' primary: '#000000' on-primary: '#ffffff' primary-container: '#131b2e' on-primary-container: '#7c839b' inverse-primary: '#bec6e0' secondary: '#5c5f61' on-secondary: '#ffffff' secondary-container: '#e0e3e5' on-secondary-container: '#626567' tertiary: '#000000' on-tertiary: '#ffffff' tertiary-container: '#161c22' on-tertiary-container: '#7e848c' error: '#ba1a1a' on-error: '#ffffff' error-container: '#ffdad6' on-error-container: '#93000a' primary-fixed: '#dae2fd' primary-fixed-dim: '#bec6e0' on-primary-fixed: '#131b2e' on-primary-fixed-variant: '#3f465c' secondary-fixed: '#e0e3e5' secondary-fixed-dim: '#c4c7c9' on-secondary-fixed: '#191c1e' on-secondary-fixed-variant: '#444749' tertiary-fixed: '#dde3eb' tertiary-fixed-dim: '#c1c7cf' on-tertiary-fixed: '#161c22' on-tertiary-fixed-variant: '#41474e' background: '#fcf8fa' on-background: '#1b1b1d' surface-variant: '#e4e2e4' typography: display-lg: fontFamily: Inter fontSize: 48px fontWeight: '800' lineHeight: 56px letterSpacing: -0.02em headline-md: fontFamily: Inter fontSize: 24px fontWeight: '700' lineHeight: 32px letterSpacing: -0.01em body-base: fontFamily: Inter fontSize: 16px fontWeight: '400' lineHeight: 24px letterSpacing: '0' body-bold: fontFamily: Inter fontSize: 16px fontWeight: '600' lineHeight: 24px letterSpacing: '0' label-caps: fontFamily: Lexend fontSize: 12px fontWeight: '700' lineHeight: 16px letterSpacing: 0.05em stat-lg: fontFamily: Lexend fontSize: 32px fontWeight: '600' lineHeight: 40px letterSpacing: -0.02em rounded: sm: 0.25rem DEFAULT: 0.5rem md: 0.75rem lg: 1rem xl: 1.5rem full: 9999px spacing: unit: 4px xs: 4px sm: 8px md: 16px lg: 24px xl: 32px gutter: 16px margin-mobile: 20px margin-desktop: 40px --- ## Brand & Style The brand personality is high-performance, sophisticated, and dependable. It is designed for the modern skier who demands clarity and precision in harsh environments. The visual language evokes the crystalline beauty of a mountain peak while prioritizing the rugged utility required for outdoor navigation. The design system utilizes **Glassmorphism** to achieve a "frozen" aesthetic, mimicking the properties of ice and packed snow. This is paired with a **High-Contrast** philosophy to ensure that critical data—like trail status and weather alerts—remains legible under intense mountain sunlight or the low-visibility conditions of a snowstorm. ## Colors The palette is anchored by **Deep Peak Blue**, a dark navy that provides a grounding contrast for white text and maps. **Powder White** serves as the primary canvas, ensuring the interface feels airy and cold. **Safety Orange** is reserved strictly for primary calls to action, hazard warnings, and emergency trail closures, ensuring immediate eye-tracking. **Electric Blue** (the info status) is used for weather updates and general interactivity. For trail difficulty levels, standard industry colors (Green, Blue, Black) are used but rendered with high-saturation values to pop against the white backgrounds. ## Typography The typography system uses **Inter** for core functional text and body copy due to its exceptional x-height and legibility at small sizes. **Lexend** is introduced for labels and statistics; its hyper-readable, athletic character suits the "active" nature of skiing data like speed and vertical drop. To combat outdoor glare, font weights are generally heavier than standard web applications. Display styles use tight tracking and heavy weights to create a sense of strength. Labels always utilize high-contrast coloring against their backgrounds. ## Layout & Spacing This design system uses a **Fluid Grid** model with generous safe areas. Elements are spaced using a strict 4px/8px baseline rhythm to maintain a disciplined, professional appearance. Touch targets are intentionally oversized (minimum 48x48px) to accommodate users wearing gloves. Padding within cards and containers is kept spacious (`lg` or `xl`) to prevent the interface from feeling cluttered when displaying complex trail data. ## Elevation & Depth Depth is conveyed through **Glassmorphism** and backdrop filters rather than traditional heavy shadows. Surfaces use a hierarchy of transparency: 1. **Base Layer:** Solid 'Powder White' or 'Deep Peak Blue'. 2. **Middle Layer (Cards/Modals):** 70% opacity white with a 20px backdrop blur and a thin 1px 'Ice' border (white at 40% opacity). 3. **Top Layer (Floating Actions):** 90% opacity with a subtle 4px ambient shadow to separate the element from the blurred background. This creates a "stacked ice" effect that maintains visual clarity while giving the UI a premium, modern feel. ## Shapes The shape language is defined by modern, organic **rounded corners**. This softens the high-contrast color palette and makes the app feel approachable. Interactive elements like buttons and chips utilize `rounded-lg` (1rem) or `rounded-xl` (1.5rem) to suggest a tactile, "pebble" feel. Large containers like map overlays use 1rem corners, while small status indicators for trail difficulty may use pill shapes for instant recognition. ## Components ### Buttons Primary buttons use a solid 'Safety Orange' or 'Deep Peak Blue' fill with white text. High-contrast outlines are used for secondary actions. All buttons must feature a minimum height of 52px for gloved-hand accessibility. ### Cards & Modals Cards utilize the glassmorphism effect—semi-transparent backgrounds with a 1px white border. This ensures that map imagery or photos underneath remain slightly visible, maintaining the "frozen" aesthetic. ### Trail Status Chips Pill-shaped indicators with high-saturation icons. Green (Easy), Blue (Intermediate), Black (Expert), and Double Black (Extreme). These must include text labels alongside icons to ensure accessibility for colorblind users. ### Input Fields Fields feature a 'Cloud Gray' background with a thick bottom border that transforms into 'Electric Blue' on focus. Labels are always visible above the field to ensure the user doesn't lose context in bright environments. ### Weather Widgets Bold, thick-stroke iconography (minimum 2pt stroke) to represent sun, snow, or wind. These icons should be large and accompanied by 'Lexend' typography for temperature and wind speed. - plugins/stitch-design/skills/extract-design-md/references/angular.md (5237 bytes)
# Angular Extraction Patterns Angular projects use a structured, convention-heavy approach to styling. Design systems often live in SCSS/CSS files with clear separation between global themes and component-scoped styles. ## File Discovery Order 1. **`angular.json`** — Lists global style files under `projects.*.architect.build.options.styles`. These are the entry-point CSS/SCSS files. 2. **`src/styles.scss` / `src/styles.css`** — Global stylesheet. CSS custom properties, font imports, and base styles live here. 3. **`src/theme.scss` / `src/theme/`** — Explicit theme directory. Custom Material/component palettes. 4. **Tailwind Config (`tailwind.config.js` or Tailwind v4 `@theme {}`)** — For Tailwind v3, read `tailwind.config.js`. For Tailwind v4, inspect `@theme {}` blocks, `@custom-variant`, and `@plugin 'tailwindcss-primeui'` in your global CSS/SCSS (e.g. `src/styles.css` or `src/assets/tailwind.css`) for CSS custom property tokens (`--color-*`, `--font-*`, `--text-*`, `--breakpoint-*`). 5. **`src/app/app.component.scss`** — Root component styles, reveals global layout patterns. 6. **Component `.scss` / `.css` files** — Co-located styles (ViewEncapsulation scoped by default). 7. **External Template `.html` files (`src/app/**/*.component.html`)** — Essential for Angular 17+ standalone components using Tailwind CSS utility classes (`bg-*`, `text-*`, `p-*`, `rounded-*`) or structural class bindings (`[ngClass]`, `[class.*]`). Always inspect `.html` templates when styling uses utility classes. ## Angular Material Theme Extraction Angular Material is the most common component library. Themes are SCSS-based: ```scss // src/theme.scss @use '@angular/material' as mat; $primary-palette: mat.m2-define-palette(mat.$m2-teal-palette, 800); $accent-palette: mat.m2-define-palette(mat.$m2-blue-grey-palette); $warn-palette: mat.m2-define-palette(mat.$m2-red-palette); $theme: mat.m2-define-light-theme(( color: ( primary: $primary-palette, accent: $accent-palette, warn: $warn-palette, ), typography: mat.m2-define-typography-config( $font-family: 'Manrope, sans-serif', $headline-1: mat.m2-define-typography-level(3.5rem, 4rem, 600), $headline-5: mat.m2-define-typography-level(1.5rem, 2rem, 500), $body-1: mat.m2-define-typography-level(1rem, 1.7, 400), ), )); @include mat.all-component-themes($theme); ``` **What to extract:** - Palette choices → map to functional color roles - Typography config → maps directly to the hierarchy section - Light vs dark theme → atmosphere For Angular Material 3 (MDC-based), look for `mat.define-theme()` using the new token system with `--mat-*` CSS custom properties. ## SCSS Variable Patterns Many Angular projects use SCSS variables for tokens: ```scss // _variables.scss $color-primary: #294056; $color-background: #FCFAFA; $color-surface: #F5F5F5; $color-text: #2C2C2C; $font-heading: 'Manrope', sans-serif; $font-body: 'Inter', sans-serif; $radius-button: 8px; $radius-card: 12px; $breakpoint-mobile: 768px; $breakpoint-desktop: 1024px; $spacing-section: 5rem; $spacing-component: 2rem; ``` These are explicit design tokens. Map them directly. ## ViewEncapsulation and Scoped Styles Angular scopes styles by default (similar to Vue's `scoped`). When scanning component styles: - Look for `:host` selectors — these style the component's root element - `::ng-deep` (deprecated but still used) — styles that pierce encapsulation - Repeated values across components indicate design system conventions ## PrimeNG / Nebular / NG-ZORRO If component libraries are used: - **PrimeNG (v17/v18/v19+)**: Look for modern theme configuration in `src/app.config.ts` (e.g., `providePrimeNG({ theme: { preset: Aura, options: { darkModeSelector: '.app-dark' } } })`). Check for Tailwind v4 integration via `@plugin 'tailwindcss-primeui'` in CSS assets. Inspect CSS custom properties defined by PrimeNG tokens (`--primary-color`, `--surface-*`). - **Nebular**: `nb-theme()` in `styles.scss` with custom theme object. - **NG-ZORRO (Ant Design for Angular)**: `ng-zorro-antd.less` variables or custom theme config in `angular.json`. ## Modern Angular (v17 - v19) Standalone Components & Control Flow In modern Angular repositories: - **Standalone Components (`@Component({ standalone: true })`)**: Components import their own dependencies directly without NgModules. Inspect `templateUrl` and `styleUrl(s)` in component metadata to locate the template and style files. - **Control Flow (`@if`, `@for`, `@switch`)**: Notice how conditional layouts and lists are structured in `.html` templates when analyzing component density and spacing rules. - **Signals & Zoneless (`signal()`, `input()`, `computed()`, `provideZonelessChangeDetection()`)**: Dynamic styling or theme toggling is often driven by signals bound to `[class.dark]` or custom CSS classes in templates. Notice `app.config.ts` for app-wide providers. ## Responsive Patterns Check for: - `@media` queries in `styles.scss` and component styles - Angular CDK `BreakpointObserver` usage in components - Tailwind responsive prefixes if Tailwind is configured - Angular Flex-Layout directives (`fxLayout`, `fxFlex`) in templates - plugins/stitch-design/skills/extract-design-md/references/plain-css.md (3991 bytes)
# Plain CSS / SASS / Less Extraction Patterns For projects without a JavaScript framework — static sites, WordPress themes, vanilla HTML/CSS, or CSS preprocessor-heavy projects. ## File Discovery Order 1. **`index.html` / `*.html`** — Check `<link>` tags and `<style>` blocks for stylesheet references, inline styles, and font loading. 2. **Main stylesheet** (`style.css`, `main.css`, `app.css`) — The primary CSS file. Look for custom properties, base styles, and typography. 3. **`_variables.scss` / `_tokens.scss` / `variables.less`** — Preprocessor variable files containing design tokens. 4. **`_mixins.scss`** — Reusable style patterns reveal design conventions. 5. **Component/module stylesheets** — Individual CSS files for UI components. ## CSS Custom Properties (Modern CSS) Modern vanilla CSS projects often define a design system via custom properties: ```css :root { /* Colors */ --color-primary: #294056; --color-bg: #FCFAFA; --color-surface: #F5F5F5; --color-text: #2C2C2C; --color-text-secondary: #6B6B6B; --color-border: #E0E0E0; --color-success: #10B981; --color-error: #EF4444; /* Typography */ --font-heading: 'Manrope', sans-serif; --font-body: 'Inter', sans-serif; --font-size-base: 1rem; --line-height-body: 1.7; /* Spacing */ --spacing-xs: 0.5rem; --spacing-sm: 1rem; --spacing-md: 2rem; --spacing-lg: 4rem; --spacing-xl: 6rem; /* Shapes */ --radius-button: 8px; --radius-card: 12px; /* Shadows */ --shadow-card: 0 2px 8px rgba(0,0,0,0.06); } ``` This is the cleanest source of truth. Extract directly and name each token. ## SASS/SCSS Token Patterns ```scss // _variables.scss $colors: ( 'primary': #294056, 'background': #FCFAFA, 'surface': #F5F5F5, 'text': #2C2C2C, 'text-muted': #6B6B6B, ); $font-stack-heading: 'Manrope', sans-serif; $font-stack-body: 'Inter', sans-serif; $breakpoints: ( 'mobile': 768px, 'tablet': 1024px, 'desktop': 1280px, ); $spacers: ( 'section': 5rem, 'component': 2rem, 'element': 1rem, ); ``` SASS maps are essentially design token dictionaries. Extract all values. ## Less Variable Patterns ```less @primary-color: #294056; @bg-color: #FCFAFA; @text-color: #2C2C2C; @font-heading: 'Manrope', sans-serif; @border-radius-base: 8px; ``` Same extraction approach — map each variable to a descriptive name and role. ## Static Sites and WordPress For static sites or WordPress themes: - **WordPress**: Check `style.css` header comment for theme metadata. Look for `wp-content/themes/<name>/assets/css/` for stylesheets. `functions.php` may enqueue Google Fonts. - **Jekyll/Hugo**: Check `_sass/` or `assets/css/` directories. - **Static HTML**: Everything is in the CSS files and `<style>` blocks. ## Inline Style Scanning For projects heavy on inline styles (legacy codebases, email templates): Search HTML files for `style="..."` attributes. Group unique values by property type: ``` background-color: #FCFAFA, #F5F5F5, #294056 color: #2C2C2C, #6B6B6B, white border-radius: 8px, 12px font-family: 'Manrope', 'Inter' ``` Then deduplicate and assign roles. ## Color Extraction Strategy When there's no explicit token system, you need to discover colors across all stylesheets. Search for: ``` background-color: background: color: border-color: border: outline-color: box-shadow: fill: stroke: ``` Collect all unique hex values, `rgb()`, `rgba()`, and `hsl()` values. Group by proximity (similar colors within a few shades) and assign roles based on context (which selectors use them). ## Responsive Patterns Look for `@media` queries in all stylesheets. Common patterns: ```css @media (max-width: 768px) { ... } /* Mobile-first breakpoint */ @media (min-width: 1024px) { ... } /* Desktop enhancement */ @media (prefers-color-scheme: dark) { ... } /* Dark mode support */ ``` Document all breakpoints and the content strategy at each (column changes, padding adjustments, navigation transformations). - plugins/stitch-design/skills/extract-design-md/references/react-tailwind.md (4583 bytes)
# React / Next.js / Tailwind Extraction Patterns This reference covers the most common frontend stack: React components with Tailwind CSS (and optionally CSS Modules, styled-components, or Emotion). ## File Discovery Order Read these files in priority order — higher-priority files give you the intended design system, lower-priority files show what actually shipped: 1. **`tailwind.config.js` / `tailwind.config.ts`** — The single most important file. Custom `theme.extend.colors`, `fontFamily`, `spacing`, `borderRadius`, and `screens` are the design system definition. 2. **`globals.css` / `global.css` / `index.css`** — CSS custom properties (`--*`), `@layer` directives, `@font-face` declarations, and base styles. 3. **`theme.ts` / `theme.js` / `tokens.ts`** — Explicit design token files. May export objects consumed by Tailwind config or CSS-in-JS providers. 4. **`src/app/layout.tsx` or `src/App.tsx`** — Root layout. Shows the global font setup (via `next/font` or `<link>`), body background, and overall structure. 5. **Component files (`*.tsx` / `*.jsx`)** — Look at 5-8 representative components to understand usage patterns. ## Tailwind Config Extraction The Tailwind config is structured and machine-readable. Extract directly: ```js // tailwind.config.js module.exports = { theme: { extend: { colors: { primary: '#294056', // → "Deep Muted Teal-Navy" — Primary CTA background: '#FCFAFA', // → "Warm Barely-There Cream" — Page BG }, fontFamily: { sans: ['Manrope', 'sans-serif'], }, borderRadius: { card: '12px', button: '8px', }, spacing: { section: '5rem', } } } } ``` Map each custom value to a descriptive name and role. ## CSS Custom Properties Look for `:root` or `html` blocks in global CSS: ```css :root { --color-primary: #294056; --color-bg: #FCFAFA; --font-heading: 'Manrope', sans-serif; --radius-card: 12px; --spacing-section: 5rem; } ``` These are explicitly declared tokens — use their names as clues for their intended role. ## Next.js Font Patterns Next.js uses `next/font` for optimized font loading: ```tsx import { Inter, Playfair_Display } from 'next/font/google' const inter = Inter({ subsets: ['latin'], variable: '--font-inter' }) const playfair = Playfair_Display({ subsets: ['latin'], variable: '--font-display' }) ``` The `variable` names hint at usage: `--font-display` for headlines, `--font-inter` for body. ## Component Scanning Strategy Don't read every component. Focus on these archetypes: | Component Type | What to Extract | |:---|:---| | Layout / Shell | Max-width, padding, grid structure | | Button / CTA | Border radius, colors, hover states, padding | | Card | Shadow, border, radius, internal spacing | | Nav / Header | Typography treatment, active states | | Form / Input | Border, focus state, padding | | Hero / Landing section | Spacing, typography scale, alignment | For each, look at the `className` prop for Tailwind classes or the `styled()` / `css()` calls for CSS-in-JS values. ## CSS-in-JS Patterns (styled-components / Emotion) If the project uses CSS-in-JS, look for theme providers: ```tsx // ThemeProvider wrapping the app const theme = { colors: { primary: '#294056', background: '#FCFAFA', }, fonts: { heading: 'Manrope, sans-serif', }, radii: { card: '12px', button: '8px', } } ``` This theme object *is* the design system. Extract directly. ## Component Library Integration If the project uses Chakra UI, Material UI, Ant Design, or shadcn/ui: - **Chakra**: Look for `extendTheme()` calls — these override defaults. - **MUI**: Look for `createTheme()` — palette, typography, and spacing overrides. - **Ant Design**: Look for `ConfigProvider` theme prop or `theme.ts` overrides. - **shadcn/ui**: Colors are defined as CSS custom properties in `globals.css`. Check `components.json` for the style configuration. The overrides are the design system — default values are the library's generic styling and should be noted but not emphasized. ## Responsive Patterns Check Tailwind's `screens` config and look for responsive class prefixes (`sm:`, `md:`, `lg:`, `xl:`) in components: ```js screens: { sm: '640px', // Mobile landscape md: '768px', // Tablet lg: '1024px', // Desktop xl: '1280px', // Large desktop '2xl': '1536px' } ``` Look for `container` configuration and `max-width` patterns on layout components to determine content width strategy. - plugins/stitch-design/skills/extract-design-md/references/svelte.md (2714 bytes)
# Svelte / SvelteKit Extraction Patterns Svelte co-locates styles even more tightly than Vue. Every `.svelte` file has a `<style>` block that is scoped by default. Design systems in Svelte projects typically live in global CSS, CSS custom properties, or a shared theme store. ## File Discovery Order 1. **`src/app.css` / `src/app.postcss`** — Global styles and CSS custom properties. The most important file. 2. **`svelte.config.js`** — May reference CSS preprocessors, Tailwind, or UnoCSS configuration. 3. **`tailwind.config.js`** (if Tailwind/UnoCSS) — Same extraction as React. 4. **`src/lib/theme.ts` / `src/lib/tokens.ts`** — Shared design tokens exported as JS objects. 5. **`src/routes/+layout.svelte`** — Root layout. Shows global font loading, background, and structural patterns. 6. **Component `<style>` blocks** — Scoped styles revealing component patterns. ## Svelte Component Style Patterns ```svelte <script> export let variant = 'primary' </script> <button class="btn btn-{variant}"> <slot /> </button> <style> .btn { border-radius: 8px; padding: 0.875rem 2rem; font-weight: 500; transition: all 250ms ease-in-out; } .btn-primary { background-color: var(--color-primary); color: white; } .btn-primary:hover { filter: brightness(0.9); } </style> ``` **Extraction points:** - Component props (like `variant`) reveal the intended variant system - `var(--*)` references → trace to `app.css` - Transition values reveal the interaction design philosophy ## SvelteKit Layout Patterns - **`+layout.svelte`** at route root — Global header, footer, font loading - **`+layout.ts/js`** — May load theme data or tokens - **`$lib/`** directory — Reusable components and shared utilities ## CSS Custom Properties Strategy Svelte projects heavily use CSS custom properties for theming: ```css /* app.css */ :root { --color-primary: #294056; --color-bg: #FCFAFA; --color-surface: #F5F5F5; --color-text: #2C2C2C; --color-text-muted: #6B6B6B; --font-heading: 'Manrope', sans-serif; --font-body: 'Inter', sans-serif; --radius-sm: 8px; --radius-md: 12px; --radius-full: 9999px; --shadow-hover: 0 2px 8px rgba(0,0,0,0.06); --spacing-section: 5rem; } ``` These variable names are highly intentional. Use them as the foundation of your design system extraction. ## Skeleton UI / DaisyUI / Flowbite-Svelte If component libraries are used: - **Skeleton UI**: Theme defined in `tailwind.config.js` using Skeleton's design token system. Look for custom theme config object. - **DaisyUI**: Theme in `tailwind.config.js` → `daisyui.themes` array. - **Flowbite-Svelte**: Standard Tailwind theming. - plugins/stitch-design/skills/extract-design-md/references/vue.md (3077 bytes)
# Vue / Nuxt Extraction Patterns Vue projects have a distinctive styling architecture. Styles are often co-located with components inside `<style>` blocks, and Nuxt adds convention-based directories. ## File Discovery Order 1. **`nuxt.config.ts` / `nuxt.config.js`** — May contain global CSS paths, font configuration, and Tailwind/UnoCSS module config. 2. **`assets/css/main.css`** (or similar) — Global styles, CSS custom properties, and font imports. 3. **`tailwind.config.js`** (if Tailwind is used) — Same as React; extract custom theme values directly. 4. **`plugins/vuetify.ts`** (if Vuetify) — Theme definition with custom palette and typography. 5. **Component `<style>` blocks** — Co-located styles (scoped or global). ## Single-File Component (SFC) Patterns Vue components bundle template, script, and style together: ```vue <template> <div class="card"> <h2 class="card__title">{{ title }}</h2> </div> </template> <style scoped> .card { background: var(--color-surface); border-radius: 12px; padding: 2rem; box-shadow: 0 2px 8px rgba(0,0,0,0.06); } .card__title { font-size: 1.5rem; font-weight: 600; color: var(--color-text-primary); } </style> ``` **Key extraction points:** - `var(--*)` references → trace back to global CSS for the actual values - `scoped` styles → component-specific, but reveal consistent patterns - BEM naming (`.card__title`) → hints at component hierarchy ## Vuetify Theme Extraction Vuetify projects define their design system explicitly: ```ts // plugins/vuetify.ts export default createVuetify({ theme: { defaultTheme: 'light', themes: { light: { colors: { primary: '#294056', secondary: '#6B6B6B', background: '#FCFAFA', surface: '#F5F5F5', error: '#EF4444', success: '#10B981', } } } } }) ``` This is the design system declaration. Map each key to a functional role and descriptive name. ## Quasar / PrimeVue / Element Plus These component libraries use their own theming systems: - **Quasar**: `quasar.config.js` → `framework.config.brand` for colors - **PrimeVue**: CSS themes in `assets/` or theme preset configuration - **Element Plus**: SCSS variables in `element-variables.scss` Look for the override file — that's where the project's unique values live. ## CSS Scoping Behavior Vue's `scoped` attribute adds data attributes for CSS isolation. When scanning for patterns, look at multiple components to find repeated values (same `border-radius`, similar `padding`, consistent color references). Repeated patterns across scoped styles = design system conventions. ## Nuxt-Specific Patterns - **`app.vue`** or **`layouts/default.vue`** — Root layout, reveals global background, font loading, and overall structure. - **`assets/`** — Global CSS, fonts, and images. - **`composables/`** — May contain `useTheme` or `useDesignTokens`. - **`nuxt.config.ts`** `css` array — Lists global stylesheets automatically injected into every page. - plugins/stitch-design/skills/extract-design-md/SKILL.md (14078 bytes)
--- name: stitch::extract-design-md description: >- Extract a comprehensive design system (DESIGN.md) directly from frontend source code — React, Vue, Svelte, Angular, plain HTML/CSS, or any web framework. Analyzes component files, stylesheets, Tailwind configs, theme definitions, and design tokens to produce a rich, Stitch-compatible design system document. Use this skill whenever the user wants to reverse-engineer a design system from an existing codebase, audit the visual language of a project, extract design tokens from source files, or understand the styling patterns in a frontend repo — even if they just say "what does this app look like?" or "pull out the design from this code." allowed-tools: - "stitch*:*" - "Bash" - "Read" - "Write" - "web_fetch" --- # Extract Design System from Frontend Code Analyze frontend source code to extract a comprehensive design system document (DESIGN.md) that captures the project's visual language — colors, typography, spacing, component patterns, and layout principles — directly from the source files, without needing to build or render the application. ## Why This Exists The `design-md` skill works from rendered HTML. But often you have a codebase and want to understand its design system before you can even run the app — maybe dependencies are missing, the build is broken, or you just want a quick audit. This skill reads the source files themselves: stylesheets, component files, theme configs, and Tailwind setups. It's faster and works anywhere. ## When to Use - User has a frontend codebase and wants to extract or document its design system - User wants to migrate a project's visual identity into Stitch - User asks to "audit the styling" or "understand the design language" of a repo - User wants to create a DESIGN.md from existing source code - The app can't be built/rendered but the source is available - User wants to unify or reconcile inconsistent styles across a codebase ## Prerequisites - Access to the frontend project's source directory - No build or runtime dependencies needed — this skill reads source files only --- ## Workflow ### Phase 1: Project Discovery Start by understanding what you're working with. This determines which extraction patterns to use. #### 1. Detect the Framework and Stack Scan the project root for telltale files: | Signal File | Framework / Tool | |:---|:---| | `package.json` with `react` | React / Next.js | | `package.json` with `vue` | Vue / Nuxt | | `package.json` with `svelte` | Svelte / SvelteKit | | `package.json` with `@angular/core` | Angular | | `tailwind.config.js/ts` | Tailwind CSS | | `postcss.config.js` | PostCSS pipeline | | `styled-components` or `@emotion` in deps | CSS-in-JS | | `.css` / `.scss` / `.less` files only | Plain CSS / SASS | | `theme.js` / `theme.ts` / `tokens.js` | Design token files | Read `package.json` first — it reveals the framework, CSS tooling, and any design-token libraries (e.g., `style-dictionary`, `@chakra-ui/react`, `@mui/material`, `ant-design`). This context tells you *where* to look for styling information. #### 2. Map the Source Tree Identify the key directories and files you'll analyze: ``` src/ ├── components/ ← Component-level styles ├── styles/ ← Global stylesheets ├── theme/ ← Theme definitions, tokens ├── assets/ ← Fonts, images ├── app.css ← Root styles └── index.css ← Entry CSS ``` Also check for: - `tailwind.config.js` / `tailwind.config.ts` — Custom colors, fonts, spacing - `globals.css` / `global.css` — CSS custom properties (variables) - Any `theme.*` or `tokens.*` files - Component library config (e.g., `chakra-theme.ts`, `vuetify.config.ts`) #### 3. Read Framework-Specific Guidance Consult the appropriate reference for extraction patterns: - **React / Next.js / Tailwind** → [references/react-tailwind.md](references/react-tailwind.md) - **Vue / Nuxt** → [references/vue.md](references/vue.md) - **Svelte / SvelteKit** → [references/svelte.md](references/svelte.md) - **Angular** → [references/angular.md](references/angular.md) - **Plain CSS / SASS / Less** → [references/plain-css.md](references/plain-css.md) These references contain framework-specific patterns for locating colors, typography, spacing, and component styles. Read the one that matches before proceeding. --- ### Phase 2: Deep Extraction Work through each design dimension systematically. For each one, gather raw data from the source files, then synthesize it into descriptive language. The goal isn't to dump every CSS property — it's to understand the *intent* behind the styling choices and describe them in human, editorial language that another designer (or Stitch) can use to recreate the same visual feel. #### 1. Visual Theme & Atmosphere Read the broadest styling first to understand the overall mood: - **Root background**: What's the `body` or root element background? Light cream (#f-range) signals airy/clean; dark (#0-#2 range) signals moody/dramatic. - **Whitespace philosophy**: Are spacing values generous (32px+) or tight? Check padding/margin values on root containers, section wrappers, and card components. - **Density**: Count the components per page/section. Few with space = minimal; many packed tight = information-dense. - **Color temperature**: Are the neutrals warm (creams, tans) or cool (blue-grays, slates)? - **Overall feel**: Synthesize into 1-2 rich sentences that capture the mood. Look for these signals in the source: | Source Location | What It Tells You | |:---|:---| | Root `background-color` or Tailwind `bg-*` on layouts | Overall lightness/darkness | | Spacing scale in Tailwind config or CSS vars | Whitespace philosophy | | Number of components vs. wrapper padding | Density | | Custom property naming (`--warm-*` vs `--cool-*`) | Color temperature intent | | Comments in theme files | Design intent in the developer's own words | #### 2. Color Palette & Roles Extract every unique color from the codebase and assign functional roles. Search across all layers: **Where to find colors:** | Layer | What to Search | |:---|:---| | CSS custom properties | `--color-*`, `--primary`, `--bg-*` | | Tailwind config | `theme.extend.colors` | | Theme/token files | Color objects, palettes | | Component styles | `background-color`, `color`, `border-color` | | Inline/scoped styles | `bg-*`, `text-*` classes in templates | | CSS-in-JS theme objects | `colors`, `palette` keys | **How to organize:** Group colors by function, not by hue: 1. **Primary Foundation** — Background and surface colors 2. **Accent & Interactive** — CTA buttons, active states, links 3. **Typography & Text Hierarchy** — Primary, secondary, tertiary text 4. **Functional States** — Success, error, warning, info For each color, create a descriptive name that evokes the color's character rather than its raw hex value: - ❌ `#294056` → "Blue" - ✅ `#294056` → **"Deep Muted Teal-Navy"** — Primary CTA, active navigation **Deduplication matters.** Codebases often have near-duplicate colors (e.g., `#333` and `#2C2C2C`). Consolidate them under one name that best represents the intended color. #### 3. Typography Rules Extract the complete typographic system: **Font families:** - Check CSS `font-family`, Tailwind `fontFamily`, Google Fonts links, or local `@font-face` declarations. - Note the **character** of each font: geometric vs humanist, serif vs sans, the feeling it evokes. **Type scale (hierarchy):** - Find every heading level (H1-H6) and body text, noting: - `font-size` (in rem or px) - `font-weight` (numeric value + descriptive name) - `letter-spacing` (and why — elegance? compactness?) - `line-height` (generous for readability? tight for display?) - Map component usage: Which heading level do product cards use? What about hero sections? **Spacing principles:** - How does text spacing relate to the overall spacing scale? - Letter-spacing patterns on headings vs body - Line-height philosophy (generous/relaxed for body, tighter for display) #### 4. Component Stylings Analyze the 4-5 most important UI primitives: **Buttons:** - Corner radius (and what it communicates — playful? professional? minimal?) - Color scheme for primary, secondary, and ghost variants - Hover/focus/active states and transition timing - Padding ratios (horizontal vs vertical) **Cards / Containers:** - Corner radius (often different from buttons — slightly rounder) - Shadow strategy: flat, subtle hover shadows, or always elevated? - Border treatment: hairline borders, colored accents, or none? - Internal padding (generous or compact?) - Image treatment within cards (full-bleed, padded, rounded?) **Navigation:** - Layout pattern (horizontal bar, vertical sidebar, drawer) - Typography treatment (uppercase, letter-spacing, weight) - Active/hover state indicators (underline, color, background) - Mobile behavior (hamburger, bottom nav, drawer) **Inputs & Forms:** - Border style and focus state behavior - Corner style consistency with buttons - Padding and touch-target sizing **Domain-Specific Components:** - Identify 1-2 components unique to this project (e.g., product cards, dashboard widgets, chat bubbles) and describe their styling patterns. #### 5. Layout Principles Extract the structural system: **Grid & Structure:** - Max content width (from `max-width` on containers) - Column system (CSS Grid, Flexbox patterns, defined breakpoints) - Responsive breakpoints (from media queries or Tailwind config) **Whitespace Strategy:** - Base spacing unit (8px grid? 4px? custom?) - Section margins (how much space between major sections) - Edge padding (page margins at different breakpoints) **Alignment & Visual Balance:** - Text alignment patterns (centered heroes, left-aligned body) - Image-to-text ratios - Visual weight distribution **Responsive Behavior:** - Mobile-first or desktop-first? - How do grids collapse? Padding scale? - Touch target sizing #### 6. Stitch Generation Notes Synthesize the extraction into actionable prompts for Stitch: - **Atmosphere language**: Translate the mood into natural descriptors - **Color references**: List colors by descriptive name + hex - **Component prompts**: Write 2-3 example prompts that would recreate key components in Stitch - **Iteration guidance**: Tips for refining screens in this design system --- ### Phase 3: Write the DESIGN.md Assemble everything into the standard DESIGN.md format. Place it at `.stitch/DESIGN.md` in the project directory (create the `.stitch/` directory if it doesn't exist). > [!IMPORTANT] > You **MUST** include the YAML frontmatter at the top of the file with `name` and `colors` mapping, exactly as shown in the example at [examples/DESIGN.md](examples/DESIGN.md). This structured data is required for other skills to parse the design system. > > Failure to include this YAML block with at least the core color tokens is a failure to use this skill correctly. Use the format from the example at [examples/DESIGN.md](examples/DESIGN.md) as your template. The file must start with the YAML block, followed by the markdown sections: ```markdown # Design System: [Project Name] **Project ID:** [If known, otherwise omit] ## 1. Visual Theme & Atmosphere [Rich 2-paragraph description of mood, philosophy, and key characteristics] ## 2. Color Palette & Roles ### Primary Foundation ### Accent & Interactive ### Typography & Text Hierarchy ### Functional States ## 3. Typography Rules ### Hierarchy & Weights ### Spacing Principles ## 4. Component Stylings ### Buttons ### Cards & [Domain-Specific Containers] ### Navigation ### Inputs & Forms ### [Domain-Specific Components] ## 5. Layout Principles ### Grid & Structure ### Whitespace Strategy ### Alignment & Visual Balance ### Responsive Behavior & Touch ## 6. Design System Notes for Stitch Generation ### Language to Use ### Color References ### Component Prompts ### Incremental Iteration ``` --- ### Phase 4: Integration (Optional) If the user wants to push the design system into Stitch: 1. Hand off to the `manage-design-system` skill for the MCP create/update calls 2. The DESIGN.md you wrote is the input — the manage-design-system skill handles the Stitch API integration If the user just wants the document, you're done after Phase 3. --- ## Quality Checklist Before delivering the DESIGN.md, verify: - [ ] Every color has a descriptive name, hex code, and functional role - [ ] Typography includes font family, character description, and full hierarchy - [ ] Component styles describe shape, color, states, and transitions - [ ] Layout includes max-width, grid, breakpoints, and spacing strategy - [ ] Stitch generation notes use natural language, not CSS syntax - [ ] The atmosphere section reads like editorial copy, not technical docs - [ ] Near-duplicate colors are consolidated - [ ] The document captures the *intent* behind styling, not just raw values ## Tips for Better Extraction - **Read comments and commit messages.** Developers often document design intent in code comments (`/* hero section — breathable */`) and commit messages. These are gold for understanding the *why*. - **Check for design-token libraries.** If the project uses `style-dictionary`, `@tokens-studio`, or similar, these files are the most authoritative source of design values. - **Theme files are higher-signal than component styles.** A `theme.ts` that defines a palette tells you the intended design system; scattered inline styles in components tell you what actually shipped. Both matter, but start from the theme. - **Tailwind config is a design system.** If a project has a customized `tailwind.config.js`, that *is* the design system — extract from it first, then spot-check components for overrides. - **CSS custom properties are intentional.** If a developer defined `--brand-primary`, they're telling you this is a design token. Respect that.
- plugins/stitch-design/skills/extract-static-html/scripts/extract_inline_html.ts (34450 bytes)
#!/usr/bin/env npx tsx /** * extract_inline_html.ts — Convert JSX/React mock files to self-contained HTML. * * Uses @babel/parser for proper JSX parsing instead of fragile regex. * Replaces the old extract_inline_html.py script. * * Usage: * npx tsx extract_inline_html.ts \ * --page src/MockPage.jsx:home.html:"Home Page" \ * --index-css src/index.css \ * --extra-css index.html \ * --outdir .stitch * * Flags: * --page Page spec as src_file:dst_filename:title (repeatable) * --tailwind-config Path to tailwind.config.js (auto-detected if omitted) * --no-tailwind Skip Tailwind CDN injection * --index-css Path to main CSS file * --css-files Additional CSS files (repeatable) * --extra-css Path to index.html to extract <style>/<link> from * --html-class Class(es) for <html> element (e.g., "dark") * --outdir Output directory (default: .stitch) * --exclude-pattern Literal string to exclude from body HTML * --concurrency Max concurrent image fetches (default: 6) * --timeout HTTP request timeout in ms (default: 15000) * --json Output machine-readable JSON stats */ import * as parser from '@babel/parser'; import traverse from '@babel/traverse'; import generate from '@babel/generator'; import fs from 'node:fs'; import path from 'node:path'; import https from 'node:https'; import http from 'node:http'; import type { Node } from '@babel/types'; // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- interface Opts { pages: string[]; tailwindConfig: string | null; noTailwind: boolean; indexCss: string | null; cssFiles: string[]; extraCss: string | null; htmlClass: string | null; outdir: string; excludePattern: RegExp | null; concurrency: number; timeout: number; json: boolean; } interface CssUrlRef { url: string; fullMatch: string; start: number; end: number; } interface PageStats { src: string; dst: string; sizeBytes: number; imagesEmbedded: number; } interface AllStats { pages: PageStats[]; totalImages: number; durationMs: number; warnings: string[]; } // --------------------------------------------------------------------------- // Argument parsing // --------------------------------------------------------------------------- // Escape all regex metacharacters in user input so it is treated as a literal // string match when used in new RegExp(). Prevents regex injection (ReDoS). function escapeRegExp(str: string): string { return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } function parseArgs(): Opts { const args = process.argv.slice(2); const opts: Opts = { pages: [], tailwindConfig: null, noTailwind: false, indexCss: null, cssFiles: [], extraCss: null, htmlClass: null, outdir: '.stitch', excludePattern: null, concurrency: 6, timeout: 15000, json: false, }; for (let i = 0; i < args.length; i++) { switch (args[i]) { case '--page': opts.pages.push(args[++i]); break; case '--tailwind-config': opts.tailwindConfig = args[++i]; break; case '--no-tailwind': opts.noTailwind = true; break; case '--index-css': opts.indexCss = args[++i]; break; case '--css-files': opts.cssFiles.push(args[++i]); break; case '--extra-css': opts.extraCss = args[++i]; break; case '--html-class': opts.htmlClass = args[++i]; break; case '--outdir': opts.outdir = args[++i]; break; case '--exclude-pattern': { const rawPattern = args[++i]; // Escape metacharacters so user input is treated as a literal string opts.excludePattern = new RegExp(escapeRegExp(rawPattern), 'gs'); break; } case '--concurrency': opts.concurrency = parseInt(args[++i], 10); break; case '--timeout': opts.timeout = parseInt(args[++i], 10); break; case '--json': opts.json = true; break; case '--help': console.log(` Usage: npx tsx extract_inline_html.ts --page <spec> [options] Options: --page src_file:dst_filename:title (repeatable) --tailwind-config Path to tailwind.config.js (auto-detected) --no-tailwind Skip Tailwind CDN injection --index-css Path to main CSS file --css-files Additional CSS files (repeatable) --extra-css Path to index.html for <style>/<link> extraction --html-class Class for <html> element (e.g., "dark") --outdir Output directory (default: .stitch) --exclude-pattern Literal string to exclude from body --concurrency Max concurrent image fetches (default: 6) --timeout HTTP request timeout in ms (default: 15000) --json Output machine-readable JSON stats `); process.exit(0); default: console.error(`Unknown argument: ${args[i]}`); process.exit(1); } } return opts; } // --------------------------------------------------------------------------- // Input validation // --------------------------------------------------------------------------- function validateOpts(opts: Opts): void { const errors: string[] = []; if (opts.pages.length === 0) { errors.push('No pages specified. Use --page src:dst:title'); } for (const spec of opts.pages) { const parts = spec.split(':'); if (parts.length !== 3) { errors.push(`Invalid page spec '${spec}'. Must be src:dst:title`); } else { const [src] = parts; if (!fs.existsSync(src)) { errors.push(`Source file not found: ${src}`); } } } if (opts.indexCss && !fs.existsSync(opts.indexCss)) { errors.push(`CSS file not found: ${opts.indexCss}`); } for (const f of opts.cssFiles) { if (!fs.existsSync(f)) { errors.push(`CSS file not found: ${f}`); } } if (opts.extraCss && !fs.existsSync(opts.extraCss)) { errors.push(`Extra CSS file not found: ${opts.extraCss}`); } if (isNaN(opts.concurrency) || opts.concurrency < 1 || opts.concurrency > 20) { errors.push('--concurrency must be between 1 and 20'); } if (isNaN(opts.timeout) || opts.timeout < 1000) { errors.push('--timeout must be at least 1000ms'); } if (errors.length > 0) { console.error('❌ Validation errors:'); errors.forEach((e) => console.error(` • ${e}`)); process.exit(1); } } // --------------------------------------------------------------------------- // Concurrency limiter // --------------------------------------------------------------------------- function createLimiter(concurrency: number): <T>(fn: () => Promise<T>) => Promise<T> { let active = 0; const queue: Array<() => void> = []; return function limit<T>(fn: () => Promise<T>): Promise<T> { return new Promise((resolve, reject) => { const run = async () => { active++; try { resolve(await fn()); } catch (e) { reject(e); } finally { active--; if (queue.length > 0) queue.shift()!(); } }; if (active < concurrency) { run(); } else { queue.push(run); } }); }; } // --------------------------------------------------------------------------- // Image embedding (with concurrency, redirect-loop protection, timeouts) // --------------------------------------------------------------------------- const imgCache = new Map<string, string>(); const MAX_REDIRECTS = 5; function isImageUrl(url: string): boolean { const skip = ['cdn.tailwindcss.com', 'fonts.googleapis.com', '.js', '.css']; return !skip.some((s) => url.includes(s)); } /** * Validate that a URL is safe for outbound requests (SSRF protection). * Blocks private/internal network addresses and non-HTTP protocols. * URLs parsed from HTML files could be attacker-controlled, so we must * ensure they only target public internet hosts. */ function isSafeUrl(parsed: URL): boolean { // Only allow http and https protocols if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { return false; } const hostname = parsed.hostname.toLowerCase(); // Block localhost variants if (hostname === 'localhost' || hostname === '[::1]') { return false; } // Block private/reserved IPv4 ranges const ipv4Match = hostname.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/); if (ipv4Match) { const [, a, b] = ipv4Match.map(Number); if ( a === 127 || // 127.0.0.0/8 (loopback) a === 10 || // 10.0.0.0/8 (private) a === 0 || // 0.0.0.0/8 (unspecified) (a === 172 && b >= 16 && b <= 31) || // 172.16.0.0/12 (private) (a === 192 && b === 168) || // 192.168.0.0/16 (private) (a === 169 && b === 254) // 169.254.0.0/16 (link-local) ) { return false; } } return true; } // Intentional outbound requests: this function fetches remote images // referenced in HTML source files and embeds them as base64 data URIs to // produce self-contained HTML snapshots. URLs are validated by isSafeUrl() // to block SSRF against private/internal networks. [CodeQL js/file-access-to-http] function fetchAndEncode(url: string, timeout: number, redirectCount = 0): Promise<string> { if (imgCache.has(url)) return Promise.resolve(imgCache.get(url)!); if (!isImageUrl(url)) { imgCache.set(url, url); return Promise.resolve(url); } // Redirect-loop protection if (redirectCount >= MAX_REDIRECTS) { const fallback = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'; console.warn(` WARN: Too many redirects (${MAX_REDIRECTS}) <- ${url.slice(0, 70).replace(/\n|\r/g, '')}...`); imgCache.set(url, fallback); return Promise.resolve(fallback); } return new Promise((resolve) => { let parsedUrl: URL; try { parsedUrl = new URL(url); } catch { const fallback = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'; console.warn(` WARN: Invalid URL: ${url.slice(0, 70).replace(/\n|\r/g, '')}...`); imgCache.set(url, fallback); resolve(fallback); return; } // SSRF protection: block requests to private/internal networks if (!isSafeUrl(parsedUrl)) { const fallback = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'; console.warn(` WARN: Blocked request to non-public URL: ${url.slice(0, 70).replace(/\n|\r/g, '')}...`); imgCache.set(url, fallback); resolve(fallback); return; } const client = parsedUrl.protocol === 'https:' ? https : http; const req = client.get( url, { headers: { 'User-Agent': 'Mozilla/5.0 (compatible; SnapshotBot/2.0)' }, timeout, }, (resp) => { if ( resp.statusCode! >= 300 && resp.statusCode! < 400 && resp.headers.location ) { // Resolve relative redirect URLs let redirectUrl: string; try { redirectUrl = new URL(resp.headers.location, url).href; } catch { redirectUrl = resp.headers.location; } // Consume response body to free the socket resp.resume(); fetchAndEncode(redirectUrl, timeout, redirectCount + 1).then(resolve); return; } if (resp.statusCode! >= 400) { const fallback = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'; console.warn( ` WARN: HTTP ${resp.statusCode} <- ${url.slice(0, 70).replace(/\n|\r/g, '')}...`, ); resp.resume(); imgCache.set(url, fallback); resolve(fallback); return; } const chunks: Buffer[] = []; resp.on('data', (d: Buffer) => chunks.push(d)); resp.on('end', () => { const buf = Buffer.concat(chunks); const ct = resp.headers['content-type'] || 'image/jpeg'; const result = `data:${ct};base64,${buf.toString('base64')}`; imgCache.set(url, result); console.log( ` Embedded ${buf.length.toLocaleString()} bytes <- ${url.slice(0, 70).replace(/\n|\r/g, '')}...`, ); resolve(result); }); resp.on('error', (e: Error) => { const fallback = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'; console.warn(` WARN: Stream error: ${e.message.replace(/\n|\r/g, '')} <- ${url.slice(0, 70).replace(/\n|\r/g, '')}...`); imgCache.set(url, fallback); resolve(fallback); }); }, ); req.on('error', (e: Error) => { const fallback = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'; console.warn(` WARN: ${e.message.replace(/\n|\r/g, '')} <- ${url.slice(0, 70).replace(/\n|\r/g, '')}...`); imgCache.set(url, fallback); resolve(fallback); }); req.on('timeout', () => { req.destroy(); const fallback = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'; console.warn(` WARN: Timeout after ${timeout}ms <- ${url.slice(0, 70).replace(/\n|\r/g, '')}...`); imgCache.set(url, fallback); resolve(fallback); }); }); } // --------------------------------------------------------------------------- // Robust CSS url() parser — character-by-character (no regex) // --------------------------------------------------------------------------- function extractCssUrls(text: string): CssUrlRef[] { const results: CssUrlRef[] = []; let i = 0; const len = text.length; while (i < len) { // Look for 'url(' — case insensitive if ( i + 3 < len && text[i].toLowerCase() === 'u' && text[i + 1].toLowerCase() === 'r' && text[i + 2].toLowerCase() === 'l' && text[i + 3] === '(' ) { const urlStart = i; i += 4; // Skip whitespace while (i < len && (text[i] === ' ' || text[i] === '\t' || text[i] === '\n' || text[i] === '\r')) i++; // Check for quote let quote: string | null = null; if (i < len && (text[i] === '"' || text[i] === "'")) { quote = text[i]; i++; } // Read the URL value let url = ''; if (quote) { while (i < len && text[i] !== quote) { if (text[i] === '\\' && i + 1 < len) { i++; url += text[i]; } else { url += text[i]; } i++; } if (i < len) i++; // closing quote } else { while (i < len && text[i] !== ')' && text[i] !== ' ' && text[i] !== '\t' && text[i] !== '\n') { url += text[i]; i++; } } - plugins/stitch-design/skills/extract-static-html/scripts/post_process.ts (14295 bytes)
#!/usr/bin/env npx tsx /** * post_process.ts — Inline local images as base64 in extracted HTML files. * * Scans HTML files for local image references (src attributes and CSS url() * values) and replaces them with inline base64 data URIs. Uses a robust * character-by-character CSS url() parser instead of regex. * * Usage: * npx tsx post_process.ts .stitch/home.html --base-dir my-app * npx tsx post_process.ts .stitch/page1.html .stitch/page2.html --base-dir . * npx tsx post_process.ts .stitch/*.html --base-dir . --json * * Flags: * --base-dir Base directory for resolving relative paths * --json Output machine-readable JSON stats * --dry-run Report what would be inlined without modifying files * --max-size Max file size to inline in bytes (default: 5242880 / 5MB) */ import fs from 'node:fs'; import path from 'node:path'; // --------------------------------------------------------------------------- // MIME type mapping // --------------------------------------------------------------------------- const MIME_MAP: Record<string, string> = { '.svg': 'image/svg+xml', '.jpeg': 'image/jpeg', '.jpg': 'image/jpeg', '.png': 'image/png', '.gif': 'image/gif', '.webp': 'image/webp', '.ico': 'image/x-icon', '.bmp': 'image/bmp', '.avif': 'image/avif', '.tiff': 'image/tiff', '.tif': 'image/tiff', '.apng': 'image/apng', '.cur': 'image/x-icon', }; function getMime(filePath: string): string { return MIME_MAP[path.extname(filePath).toLowerCase()] || 'application/octet-stream'; } // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- interface Opts { files: string[]; baseDir: string; json: boolean; dryRun: boolean; maxSize: number; } interface CssUrlRef { url: string; fullMatch: string; start: number; end: number; } interface InlineStats { srcInlined: number; urlInlined: number; skippedTooLarge: Array<{ path: string; size: number }>; skippedNotFound: string[]; } interface FileStats { file: string; srcInlined: number; urlInlined: number; skippedNotFound: number; skippedTooLarge: number; sizeBytes: number; } interface AllStats { files: FileStats[]; totalSrcInlined: number; totalUrlInlined: number; totalSkippedNotFound: number; totalSkippedTooLarge: number; } // --------------------------------------------------------------------------- // Argument parsing & validation // --------------------------------------------------------------------------- function parseArgs(): Opts { const args = process.argv.slice(2); const opts: Opts = { files: [], baseDir: '', json: false, dryRun: false, maxSize: 5 * 1024 * 1024, // 5MB }; for (let i = 0; i < args.length; i++) { switch (args[i]) { case '--base-dir': opts.baseDir = args[++i]; break; case '--json': opts.json = true; break; case '--dry-run': opts.dryRun = true; break; case '--max-size': opts.maxSize = parseInt(args[++i], 10); break; case '--help': console.log(` Usage: npx tsx post_process.ts <html_file> [...] [options] Options: --base-dir Base directory for resolving relative paths --json Output machine-readable JSON stats --dry-run Report what would be inlined without modifying files --max-size Max file size to inline in bytes (default: 5242880 / 5MB) `); process.exit(0); default: opts.files.push(args[i]); } } return opts; } function validateOpts(opts: Opts): void { const errors: string[] = []; if (opts.files.length === 0) { errors.push('No HTML files specified'); } if (opts.baseDir && !fs.existsSync(opts.baseDir)) { errors.push(`Base directory not found: ${opts.baseDir}`); } if (isNaN(opts.maxSize) || opts.maxSize < 1) { errors.push('--max-size must be a positive integer'); } if (errors.length > 0) { console.error('❌ Validation errors:'); errors.forEach((e) => console.error(` • ${e}`)); process.exit(1); } } // --------------------------------------------------------------------------- // Robust CSS url() parser — character-by-character (no regex) // --------------------------------------------------------------------------- function extractCssUrls(text: string): CssUrlRef[] { const results: CssUrlRef[] = []; let i = 0; const len = text.length; while (i < len) { if ( i + 3 < len && text[i].toLowerCase() === 'u' && text[i + 1].toLowerCase() === 'r' && text[i + 2].toLowerCase() === 'l' && text[i + 3] === '(' ) { const urlStart = i; i += 4; // Skip whitespace while (i < len && (text[i] === ' ' || text[i] === '\t' || text[i] === '\n' || text[i] === '\r')) i++; let quote: string | null = null; if (i < len && (text[i] === '"' || text[i] === "'")) { quote = text[i]; i++; } let url = ''; if (quote) { while (i < len && text[i] !== quote) { if (text[i] === '\\' && i + 1 < len) { i++; url += text[i]; } else { url += text[i]; } i++; } if (i < len) i++; } else { while (i < len && text[i] !== ')' && text[i] !== ' ' && text[i] !== '\t' && text[i] !== '\n') { url += text[i]; i++; } } while (i < len && (text[i] === ' ' || text[i] === '\t' || text[i] === '\n' || text[i] === '\r')) i++; if (i < len && text[i] === ')') { const fullMatch = text.substring(urlStart, i + 1); results.push({ url: url.trim(), fullMatch, start: urlStart, end: i + 1 }); i++; } else { i = urlStart + 1; } } else { i++; } } return results; } // --------------------------------------------------------------------------- // Local path resolution // --------------------------------------------------------------------------- function resolveLocalFile(localPath: string, baseDir: string): string | null { const candidates = [localPath]; if (baseDir) { candidates.push(path.join(baseDir, localPath.replace(/^\//, ''))); } for (const candidate of candidates) { try { if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) { return candidate; } } catch { // Permission errors, etc. — skip } } return null; } /** * Atomically open, stat, and read a file using a file descriptor. * Eliminates TOCTOU race conditions by performing all operations on the * same fd, ensuring the file cannot change between the size check and read. * Returns null if the file cannot be opened (e.g., deleted between resolve and open). */ function readFileAtomic( filePath: string, maxSize: number, ): { size: number; mime: string; b64: string } | { size: number; tooLarge: true } | null { let fd: number; try { fd = fs.openSync(filePath, 'r'); } catch { // File was removed or became inaccessible between resolve and open return null; } try { const stat = fs.fstatSync(fd); if (stat.size > maxSize) { return { size: stat.size, tooLarge: true }; } const mime = getMime(filePath); const b64 = fs.readFileSync(fd).toString('base64'); return { size: stat.size, mime, b64 }; } finally { fs.closeSync(fd); } } /** * Check if a path is a local (non-remote, non-data) reference. */ function isLocalPath(url: string): boolean { return ( !!url && !url.startsWith('http://') && !url.startsWith('https://') && !url.startsWith('data:') && !url.startsWith('//') ); } // --------------------------------------------------------------------------- // Inline images in HTML // --------------------------------------------------------------------------- function inlineImages( html: string, baseDir: string, maxSize: number, dryRun: boolean, ): { html: string; stats: InlineStats } { const stats: InlineStats = { srcInlined: 0, urlInlined: 0, skippedTooLarge: [], skippedNotFound: [], }; // --- Inline src="<local_path>" attributes --- // Handle src, poster, data attributes const srcAttrs = ['src', 'poster', 'data']; for (const attr of srcAttrs) { const regex = new RegExp(`${attr}="((?!https?:\\/\\/|data:|\\/\\/)[^"]+)"`, 'g'); html = html.replace(regex, (match: string, localPath: string) => { const resolved = resolveLocalFile(localPath, baseDir); if (!resolved) { if (!localPath.endsWith('.js') && !localPath.endsWith('.css')) { stats.skippedNotFound.push(localPath); } return match; } const result = readFileAtomic(resolved, maxSize); if (!result) { stats.skippedNotFound.push(localPath); return match; } if ('tooLarge' in result) { stats.skippedTooLarge.push({ path: localPath, size: result.size }); return match; } if (dryRun) { stats.srcInlined++; return match; } stats.srcInlined++; return `${attr}="data:${result.mime};base64,${result.b64}"`; }); } // --- Inline CSS url() with local paths (using robust parser) --- const urlRefs = extractCssUrls(html); const localUrlRefs = urlRefs.filter((ref) => isLocalPath(ref.url)); // Process from end to preserve indices const sorted = [...localUrlRefs].sort((a, b) => b.start - a.start); for (const ref of sorted) { const resolved = resolveLocalFile(ref.url, baseDir); if (!resolved) { stats.skippedNotFound.push(ref.url); continue; } const result = readFileAtomic(resolved, maxSize); if (!result) { stats.skippedNotFound.push(ref.url); continue; } if ('tooLarge' in result) { stats.skippedTooLarge.push({ path: ref.url, size: result.size }); continue; } if (dryRun) { stats.urlInlined++; continue; } html = html.substring(0, ref.start) + `url('data:${result.mime};base64,${result.b64}')` + html.substring(ref.end); stats.urlInlined++; } // --- Inline SVG <image href="..."> and xlink:href --- const svgHrefRegex = /(href|xlink:href)="((?!https?:\/\/|data:|\/\/)[^"]+)"/g; html = html.replace(svgHrefRegex, (match: string, attrName: string, localPath: string) => { // Skip non-image hrefs (like <a href>) if (!localPath.match(/\.(svg|png|jpg|jpeg|gif|webp|avif|bmp|ico)$/i)) { return match; } const resolved = resolveLocalFile(localPath, baseDir); if (!resolved) { stats.skippedNotFound.push(localPath); return match; } const result = readFileAtomic(resolved, maxSize); if (!result) { stats.skippedNotFound.push(localPath); return match; } if ('tooLarge' in result) { stats.skippedTooLarge.push({ path: localPath, size: result.size }); return match; } if (dryRun) { stats.srcInlined++; return match; } stats.srcInlined++; return `${attrName}="data:${result.mime};base64,${result.b64}"`; }); return { html, stats }; } // --------------------------------------------------------------------------- // Main // --------------------------------------------------------------------------- function main(): void { const opts = parseArgs(); validateOpts(opts); const allStats: AllStats = { files: [], totalSrcInlined: 0, totalUrlInlined: 0, totalSkippedNotFound: 0, totalSkippedTooLarge: 0, }; if (opts.dryRun) { console.log('🔍 DRY RUN — no files will be modified\n'); } for (const file of opts.files) { // Open file once with r+ to eliminate TOCTOU race between read and write. // A single fd is used for both operations, so the file cannot be swapped // between the read and write phases. let fd: number; try { fd = fs.openSync(file, opts.dryRun ? 'r' : 'r+'); } catch { console.warn(`⚠️ File not found, skipping: ${file}`); continue; } let processed: string = ''; let stats: InlineStats = { srcInlined: 0, urlInlined: 0, skippedTooLarge: [], skippedNotFound: [] }; try { const html = fs.readFileSync(fd, 'utf-8'); const result = inlineImages(html, opts.baseDir, opts.maxSize, opts.dryRun); processed = result.html; stats = result.stats; if (!opts.dryRun) { // Truncate and rewrite using the same fd — no second path-based open fs.ftruncateSync(fd); fs.writeSync(fd, processed, 0, 'utf-8'); } } finally { fs.closeSync(fd); } const totalInlined = stats.srcInlined + stats.urlInlined; const label = opts.dryRun ? 'would inline' : 'inlined'; console.log( `${file}: ${label} ${totalInlined} resources ` + `(${stats.srcInlined} src, ${stats.urlInlined} url()) ` + `— ${processed.length.toLocaleString()} bytes`, ); if (stats.skippedTooLarge.length > 0) { for (const s of stats.skippedTooLarge) { console.log( ` ⚠️ Skipped (too large: ${(s.size / 1024).toFixed(1)} KB): ${s.path}`, ); } } allStats.files.push({ file, srcInlined: stats.srcInlined, urlInlined: stats.urlInlined, skippedNotFound: stats.skippedNotFound.length, skippedTooLarge: stats.skippedTooLarge.length, sizeBytes: processed.length, }); allStats.totalSrcInlined += stats.srcInlined; allStats.totalUrlInlined += stats.urlInlined; allStats.totalSkippedNotFound += stats.skippedNotFound.length; allStats.totalSkippedTooLarge += stats.skippedTooLarge.length; } const totalInlined = allStats.totalSrcInlined + allStats.totalUrlInlined; console.log(`\n✅ Total: ${totalInlined} resources inlined across ${allStats.files.length} file(s)`); if (allStats.totalSkippedTooLarge > 0) { console.log(` ⚠️ ${allStats.totalSkippedTooLarge} skipped (exceeded ${(opts.maxSize / 1024 / 1024).toFixed(1)} MB limit)`); } if (opts.json) { console.log('\n--- JSON Stats ---'); console.log(JSON.stringify(allStats, null, 2)); } } main(); - plugins/stitch-design/skills/extract-static-html/scripts/snapshot.ts (54743 bytes)
#!/usr/bin/env npx tsx /** * snapshot.ts — Production-grade Puppeteer-based full-page HTML snapshot * * Captures the fully rendered DOM from a running web application and produces * a self-contained HTML file with all CSS inlined and images converted to * base64 data URIs. Works with any framework (React, Vue, Svelte, Angular, * plain HTML, etc.) — no MockPage.jsx needed. * * Usage: * npx tsx snapshot.ts --url http://localhost:5173 --output .stitch/home.html * npx tsx snapshot.ts --url http://localhost:3000/pricing --output .stitch/pricing.html --html-class dark * npx tsx snapshot.ts --url http://localhost:5173 --output .stitch/page.html --wait 5000 --viewport 1440x900 * * Flags: * --url URL to capture (required) * --output Output file path (required) * --wait Extra wait time in ms after network idle (default: 1000) * --viewport Viewport size as WIDTHxHEIGHT (default: 1280x800) * --html-class Class(es) to add to <html> element (e.g., "dark") * --remove-fixed Remove fixed/sticky positioned elements (e.g., cookie banners) * --full-height Capture full scrollable content by resizing viewport to scrollHeight * --title Override the page title * --timeout Global timeout in ms (default: 60000) * --concurrency Max concurrent resource fetches (default: 6) * --json Output machine-readable JSON stats to stdout */ import puppeteer, { type Browser } from 'puppeteer'; import path from 'node:path'; import fs from 'node:fs'; // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- interface Opts { url: string | null; output: string | null; wait: number; viewport: string; htmlClass: string | null; removeFixed: boolean; fullHeight: boolean; title: string | null; authScript: string | null; inlineCanvas: boolean; timeout: number; concurrency: number; json: boolean; inlineFonts: boolean; removeSelectors: string | null; click: string | null; } interface Stats { url: string | null; output: string | null; sizeBytes: number; stylesheets: number; images: number; cssUrls: number; svgImages: number; videoPoster: number; favicons: number; scriptsRemoved: number; warnings: string[]; durationMs: number; error?: string; } // --------------------------------------------------------------------------- // Argument parsing // --------------------------------------------------------------------------- function parseArgs(): Opts { const args = process.argv.slice(2); const opts: Opts = { url: null, output: null, wait: 1000, viewport: '1280x800', htmlClass: null, removeFixed: false, fullHeight: false, title: null, authScript: null, inlineCanvas: false, timeout: 60000, concurrency: 6, json: false, inlineFonts: false, removeSelectors: null, click: null, }; for (let i = 0; i < args.length; i++) { switch (args[i]) { case '--url': opts.url = args[++i]; break; case '--output': opts.output = args[++i]; break; case '--wait': opts.wait = parseInt(args[++i], 10); break; case '--viewport': opts.viewport = args[++i]; break; case '--html-class': opts.htmlClass = args[++i]; break; case '--remove-fixed': opts.removeFixed = true; break; case '--full-height': opts.fullHeight = true; break; case '--title': opts.title = args[++i]; break; case '--auth-script': opts.authScript = args[++i]; break; case '--inline-canvas': opts.inlineCanvas = true; break; case '--timeout': opts.timeout = parseInt(args[++i], 10); break; case '--concurrency': opts.concurrency = parseInt(args[++i], 10); break; case '--json': opts.json = true; break; case '--inline-fonts': opts.inlineFonts = true; break; case '--remove-selectors': opts.removeSelectors = args[++i]; break; case '--click': opts.click = args[++i]; break; case '--help': console.log(` Usage: npx tsx snapshot.ts --url <URL> --output <FILE> [options] Options: --url URL to capture (required) --output Output file path (required) --wait Extra wait time in ms after network idle (default: 1000) --viewport Viewport size as WIDTHxHEIGHT (default: 1280x800) --html-class Class(es) to add to <html> element (e.g., "dark") --remove-fixed Remove fixed/sticky positioned elements (cookie banners, etc.) --full-height Resize viewport to capture full scrollable content --title Override the page title --auth-script Path to JS/TS script exporting an async function to authenticate before capture --inline-canvas Convert <canvas> elements (charts, graphs) to base64 images --timeout Global timeout in ms (default: 60000) --concurrency Max concurrent resource fetches (default: 6) --json Output machine-readable JSON stats `); process.exit(0); default: console.error(`Unknown argument: ${args[i]}`); process.exit(1); } } return opts; } // --------------------------------------------------------------------------- // Input validation // --------------------------------------------------------------------------- function validateOpts(opts: Opts): void { const errors: string[] = []; if (!opts.url) errors.push('--url is required'); if (!opts.output) errors.push('--output is required'); if (opts.url) { try { new URL(opts.url); } catch { errors.push( `Invalid URL: "${opts.url}". Must be a valid URL (e.g., http://localhost:5173)`, ); } } if (opts.viewport) { const vpMatch = opts.viewport.match(/^(\d+)x(\d+)$/); if (!vpMatch) { errors.push( `Invalid viewport: "${opts.viewport}". Must be WIDTHxHEIGHT (e.g., 1280x800)`, ); } else { const w = Number(vpMatch[1]); const h = Number(vpMatch[2]); if (w < 1 || h < 1) { errors.push('Viewport dimensions must be positive integers'); } if (w > 7680 || h > 4320) { errors.push('Viewport too large: max 7680x4320'); } } } if (isNaN(opts.wait) || opts.wait < 0) { errors.push('--wait must be a non-negative integer'); } if (isNaN(opts.timeout) || opts.timeout < 1000) { errors.push('--timeout must be at least 1000ms'); } if (isNaN(opts.concurrency) || opts.concurrency < 1 || opts.concurrency > 20) { errors.push('--concurrency must be between 1 and 20'); } if (opts.output) { const outputDir = path.dirname(path.resolve(opts.output)); try { fs.mkdirSync(outputDir, { recursive: true }); fs.accessSync(outputDir, fs.constants.W_OK); } catch (e: unknown) { errors.push(`Cannot write to output directory: ${(e as Error).message}`); } } if (errors.length > 0) { console.error('❌ Validation errors:'); errors.forEach((e) => console.error(` • ${e}`)); process.exit(1); } } // --------------------------------------------------------------------------- // Main snapshot logic // --------------------------------------------------------------------------- async function snapshot(opts: Opts): Promise<void> { const [, widthStr, heightStr] = opts.viewport.match(/^(\d+)x(\d+)$/)!; const width = Number(widthStr); const height = Number(heightStr); let browser: Browser | undefined; let globalTimer: ReturnType<typeof setTimeout> | undefined; // Stats tracking const stats: Stats = { url: opts.url, output: null, sizeBytes: 0, stylesheets: 0, images: 0, cssUrls: 0, svgImages: 0, videoPoster: 0, favicons: 0, scriptsRemoved: 0, warnings: [], durationMs: 0, }; const startTime = Date.now(); try { // Global timeout safety net — prevents zombie browser processes globalTimer = setTimeout(() => { const msg = `Global timeout of ${opts.timeout}ms exceeded — aborting`; console.error(`⏰ ${msg}`); stats.warnings.push(msg); if (browser) browser.close().catch(() => {}); if (opts.json) { stats.durationMs = Date.now() - startTime; stats.error = msg; console.log(JSON.stringify(stats, null, 2)); } process.exit(2); }, opts.timeout); // ----- Launch browser ----- console.log('🚀 Launching browser...'); browser = await puppeteer.launch({ headless: true, args: [ '--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', `--window-size=${width},${height}`, ], }); const page = await browser.newPage(); await page.setViewport({ width, height }); // Forward browser console logs to Node.js page.on('console', (msg) => { const type = msg.type().toString(); if (type === 'warning' || type === 'error') { console.log(` [Browser ${type.toUpperCase()}] ${msg.text()}`); } }); // ----- Navigate and wait for network idle ----- console.log(`📄 Navigating to ${opts.url}...`); try { await page.goto(opts.url!, { waitUntil: 'networkidle0', timeout: 10000, }); } catch { const msg = 'networkidle0 timed out, falling back to networkidle2'; console.warn(`⚠️ ${msg}...`); stats.warnings.push(msg); try { await page.goto(opts.url!, { waitUntil: 'networkidle2', timeout: 10000, }); } catch { const msg2 = 'networkidle2 timed out, falling back to domcontentloaded'; console.warn(`⚠️ ${msg2}...`); stats.warnings.push(msg2); await page.goto(opts.url!, { waitUntil: 'domcontentloaded', timeout: 15000, }); } } // Extra wait for JS-rendered content (animations, lazy loading, etc.) if (opts.wait > 0) { console.log(`⏳ Waiting ${opts.wait}ms for rendering to settle...`); await new Promise((r) => setTimeout(r, opts.wait)); } // Execute authentication script if provided if (opts.authScript) { console.log(`🔐 Running authentication script from ${opts.authScript}...`); try { const path = await import('path'); const authPath = path.resolve(process.cwd(), opts.authScript); const authModule = await import(authPath); const authFn = authModule.default || authModule; if (typeof authFn === 'function') { await authFn(page); console.log(' ✅ Auth script executed, re-navigating to target URL...'); await page.goto(opts.url!, { waitUntil: 'networkidle2', timeout: Math.min(30000, opts.timeout), }); if (opts.wait > 0) { await new Promise((r) => setTimeout(r, opts.wait)); } } else { console.warn(`⚠️ --auth-script (${opts.authScript}) did not export a function`); } } catch (err: any) { console.warn(`⚠️ Failed to execute --auth-script: ${err.message}`); stats.warnings.push(`auth-script error: ${err.message}`); } } // Perform click interaction if specified if (opts.click) { console.log(`🖱️ Clicking element "${opts.click}"...`); try { let element = await page.$(opts.click); if (!element) { // Search in child frames recursively! for (const frame of page.frames()) { const childElement = await frame.$(opts.click); if (childElement) { element = childElement; console.log(` Found element inside child frame: ${frame.url()}`); break; } } } if (element) { await element.click(); // wait an extra 2 seconds for animation or modal loading to settle console.log(` Click succeeded! Waiting 2000ms for click action to settle...`); await new Promise((r) => setTimeout(r, 2000)); } else { throw new Error(`Selector "${opts.click}" not found in main document or child frames.`); } } catch (clickErr: any) { console.error(`⚠️ Click action failed:`, clickErr); stats.warnings.push(`Click action failed: ${clickErr.message || clickErr}`); } } // ----- Pre-processing options ----- // Add class to <html> (e.g., dark mode) if (opts.htmlClass) { console.log(`🎨 Adding class "${opts.htmlClass}" to <html>...`); await page.evaluate((cls: string) => { document.documentElement.classList.add(...cls.split(/\s+/)); if (cls.includes('dark')) { document.documentElement.setAttribute('data-theme', 'dark'); } else if (cls.includes('light')) { document.documentElement.setAttribute('data-theme', 'light'); } }, opts.htmlClass); await new Promise((r) => setTimeout(r, 500)); } // Remove fixed/sticky elements if (opts.removeFixed) { console.log('🧹 Removing fixed/sticky positioned elements...'); await page.evaluate(() => { const all = document.querySelectorAll('*'); for (const el of all) { const style = getComputedStyle(el); if (style.position === 'fixed' || style.position === 'sticky') { const rect = el.getBoundingClientRect(); if (rect.top > 100 || rect.height < 50) { el.remove(); } } } }); } // Remove custom selectors if (opts.removeSelectors) { console.log(`🧹 Removing custom selectors: "${opts.removeSelectors}"...`); await page.evaluate((selectors: string) => { const items = selectors.split(',').map((s) => s.trim()).filter(Boolean); for (const selector of items) { try { document.querySelectorAll(selector).forEach((el) => el.remove()); } catch (e) { console.warn(`Invalid selector "${selector}":`, e); } } }, opts.removeSelectors); } // Override title if (opts.title) { await page.evaluate((t: string) => { document.title = t; }, opts.title); } // ----- Inject shared browser-side helpers (deduplication) ----- // Mock __name to prevent esbuild generated code from failing in browser await page.evaluate(() => { (window as any).__name = (fn: any, name: string) => fn; }); await page.evaluate((concurrency: number) => { (window as any).__snapshot = { CONCURRENCY: concurrency, toDataUri: async (url: string): Promise<string | null> => { try { const resp = await fetch(ur - plugins/stitch-design/skills/extract-static-html/SKILL.md (10774 bytes)
--- name: stitch::extract-static-html description: >- Extract self-contained static HTML from a built web application or React components by inlining CSS and images. Use this skill whenever you need to capture a specific UI state, share a static version of a page, or prepare assets for Stitch upload, even if the user just asks to 'save the HTML' or 'mock the view'. allowed-tools: - "stitch*:*" - "Bash" - "Read" - "Write" - "web_fetch" --- # Extract Static HTML Extract a self-contained static HTML file from any web application. ## Which Strategy to Use You MUST ask the user to choose which strategy to use before proceeding. Present the options clearly, **recommend Strategy A** as the preferred default, and **provide a brief pros/cons summary** for each option to help them make an informed decision. | | Strategy A (Puppeteer) | Strategy B (Browser Subagent) | | :--- | :--- | :--- | | **When** | App runs locally, no auth wall | Need to interact with page first (click, fill forms) | | **Fidelity** | **Highest — computed styles resolved** | High — rendered DOM | | **Setup** | **Zero — no mock needed** | Zero — no mock needed | | **Framework** | **Any** | Any | | **Output** | **Writes to file — no size limit** | May truncate in agent context | > [!WARNING] > **Checkpoint — User Confirmation Required.** > You **MUST** ask the user which strategy they prefer before proceeding. > Present the comparison table above, recommend Strategy A as the default, and > wait for explicit approval. Do **NOT** make the decision yourself or proceed > until the user confirms. *** ## Strategy A: Puppeteer Snapshot (Recommended) Launches headless Chrome, captures the fully rendered DOM, and produces a self-contained HTML file with all CSS inlined and images as base64. Works with **any framework** — no MockPage.jsx needed. ### Prerequisites - App running locally (e.g., `npm run dev`) - Node.js with `puppeteer` available (check: `node -e "require('puppeteer')"`) ### Workflow 1. **Start the App** and note the port. > [!WARNING] > **Checkpoint — User Confirmation Required.** > After starting the local server, you **MUST** pause and ask the user for > confirmation before running the snapshot script or launching a browser > subagent. Report the URL and port to the user so they can verify the app > is running and rendering correctly. Do **NOT** proceed to the snapshot > step until the user confirms. 2. **Run the Snapshot Script**: ```bash npx tsx <SKILL_DIR>/scripts/snapshot.ts \ --url http://localhost:5173 \ --output .stitch/home.html \ --wait 2000 ``` 3. **Multiple pages** — run once per route: ```bash npx tsx <SKILL_DIR>/scripts/snapshot.ts \ --url http://localhost:5173 --output .stitch/home.html --wait 2000 npx tsx <SKILL_DIR>/scripts/snapshot.ts \ --url http://localhost:5173/pricing --output .stitch/pricing.html --wait 2000 npx tsx <SKILL_DIR>/scripts/snapshot.ts \ --url http://localhost:5173/dashboard --output .stitch/dashboard.html --wait 2000 --html-class dark ``` 4. **Clean Up Dev Server**: If a local dev server was started specifically for snapshot extraction, make sure to stop the server process or terminate the background task once extraction is completed. ### Script Flags | Flag | Default | Description | | :--- | :--- | :--- | | `--url` | *(required)* | URL to capture | | `--output` | *(required)* | Output file path | | `--wait` | `1000` | Extra wait (ms) after network idle. Increase for lazy-loading apps. | | `--viewport` | `1280x800` | Viewport size as `WIDTHxHEIGHT` | | `--html-class` | — | Class(es) for `<html>` element (e.g., `dark`) | | `--remove-fixed` | `false` | Remove fixed/sticky elements (cookie banners, chat widgets) | | `--full-height` | `false` | Resize viewport to full scroll height | | `--title` | — | Override page title (set to the route path, e.g. `/dashboard` or `/settings/profile`) | | `--auth-script` | — | Path to a JS/TS module that exports a default `async (page) => void` function for authentication | | `--inline-canvas` | `false` | Convert `<canvas>` elements (ECharts, Chart.js, D3) to base64 `<img>` tags | ### What It Does Automatically - Captures all CSSOM rules from `document.styleSheets` (preserves dynamic Vite/Tailwind dev styles and CSS-in-JS) - Inlines all `<link rel="stylesheet">` → `<style>` blocks - Converts `<img>` `src` **and `srcset`** → base64 data URIs (skips external fonts) - Inlines same-origin and relative icon font files (`@font-face`) as base64 data URIs so ligatures never render as ASCII text - Inlines `<source srcset>` URLs as base64 - Removes failed/dead `srcset` entries so the browser falls back to the inlined `src` - Removes `<script>` tags, Vite HMR dev style blocks (`createHotContext`, `import.meta.hot`), and dev overlays - Resolves relative CSS `url()` paths before inlining ### Framework Notes | Framework | Notes | | :--- | :--- | | **React + Vite** | Works out of the box. `--wait 1000`. | | **Next.js** | `--wait 3000` for SSR hydration. URL: `http://localhost:3000`. `<img srcset>` from `/_next/image` is auto-inlined as base64. | | **Angular (@angular/cli / v17+)** | Works out of the box with `ng serve` (default URL: `http://localhost:4200`). `--wait 2000` for Angular Material / PrimeNG animation hydration and lazy-loaded routes. | | **Vue / Nuxt** | Works out of the box. | | **Svelte / SvelteKit** | Works out of the box. | | **Storybook** | Use story URL: `--url http://localhost:6006/?path=/story/...` | | **SSR (Webpack)** | May need longer `--wait`. | ### Troubleshooting | Issue | Solution | | :--- | :--- | | Images missing | Increase `--wait` | | Images show as broken after server stops | Verify `srcset` was inlined — check log for "Inlined N images". If `srcset` URLs failed, they are auto-removed so `src` (inlined) is used. | | Icons display as text / Serif unstyled font | Ensure `snapshot.ts` captures CSSOM from `document.styleSheets` (step 0) and same-origin icon fonts (`@font-face`) are inlined as base64 data URIs. | | Next.js `/_next/image` not inlined | Ensure the dev server is running when snapshot runs — the script fetches optimized images from the running server. | | Dark mode not applied | `--html-class dark` | | Cookie banner in output | `--remove-fixed` | | Page requires login | Use `--auth-script ./auth.ts` (see Auth-Gated Pages below) | | Charts/graphs show as blank boxes | Use `--inline-canvas` to serialize `<canvas>` to base64 `<img>` | | `Cannot find module 'puppeteer'` | `npm install -g puppeteer` | ### Auth-Gated Pages For apps with login guards (Vue Router `beforeEach`, React `ProtectedRoute`, etc.), create a small auth script that runs in the Puppeteer session: ```ts // auth-myapp.ts import type { Page } from 'puppeteer'; export default async function authenticate(page: Page) { // Example 1: Fill and submit a login form await page.type('#username', 'admin'); await page.type('#password', 'password123'); await page.click('#login-button'); await page.waitForNavigation({ waitUntil: 'networkidle2' }); // Example 2: Inject cookies/localStorage directly // await page.evaluate(() => { // localStorage.setItem('token', 'mock-jwt-token'); // }); // Example 3: Call the app's own login API via module injection (Vue/Vite) // await page.evaluate(() => { // return new Promise((resolve) => { // const script = document.createElement('script'); // script.type = 'module'; // script.textContent = ` // import { useUserStore } from '/src/store/modules/user.ts'; // import { fetchLogin } from '/src/api/auth.ts'; // const res = await fetchLogin({ userName: 'Admin', password: '123456' }); // useUserStore().setToken(res.token, res.refreshToken); // window.dispatchEvent(new CustomEvent('auth-done')); // `; // document.head.appendChild(script); // window.addEventListener('auth-done', () => resolve(true), { once: true }); // }); // }); } ``` Then use it: ```bash npx tsx <SKILL_DIR>/scripts/snapshot.ts \ --url http://localhost:5173/#/dashboard \ --output .stitch/dashboard.html \ --auth-script ./auth-myapp.ts \ --inline-canvas \ --wait 5000 ``` The script navigates to the `--url` first (which may redirect to login), runs your auth function, then **re-navigates** to the original `--url` with the authenticated session. *** ## Strategy B: Browser Subagent Capture Use when you need to **interact with the page** (click buttons, fill forms, navigate tabs) before capturing. The browser subagent gives you full control but output may truncate for large pages. ### Workflow 1. **Start the App** locally. 2. **Navigate** using a browser subagent. 3. **Interact** as needed (click, scroll, fill forms). 4. **Extract DOM**: `document.documentElement.outerHTML` > [!WARNING] > Large pages may truncate. To handle this: > - Remove `<style>` tags before extraction: `document.querySelectorAll('style').forEach(el => el.remove())` > - Re-add styles statically (Tailwind CDN link, source CSS) 5. **Save** to file. *** ## Appendix: Static Fallback (MockPage.jsx) > [!NOTE] > This method is a **last resort** for when the app cannot run locally (broken deps, missing backend, auth walls with no bypass). It requires manually flattening React components into a single JSX file. **Prefer Strategy A whenever possible.** ### When to Use - App can't run locally at all - Page requires auth with no mock/bypass - You need a specific UI state that's impossible to reach by navigation (error screens, empty states) ### Quick Reference ```bash npx tsx <SKILL_DIR>/scripts/extract_inline_html.ts \ --index-css src/css/App.css \ --extra-css index.html \ --outdir .stitch \ --page src/MockPage.jsx:Page.html:"Page Title" ``` **Key flags**: `--no-tailwind` (non-Tailwind apps), `--html-class dark` (dark mode), `--css-files` (extra CSS files). **Auto-detection**: Tailwind config is auto-detected. `@apply` directives automatically use `<style type="text/tailwindcss">`. ### MockPage.jsx Rules 1. **Include the full layout** — header, sidebar, footer (read `App.js` first) 2. **Flatten all conditionals** — pick one state, remove all ternaries and `&&` guards 3. **Hardcode all data** — replace `{variable}` with concrete values, unroll `.map()` loops 4. **Preserve logos** — use `<img>` with local paths (post-process will inline them) 5. **Remove floating elements** — cookie banners, chat widgets, feedback buttons ### Post-Processing Inline local images: ```bash npx tsx <SKILL_DIR>/scripts/post_process.ts \ .stitch/Page.html --base-dir <app-directory> ``` - plugins/stitch-design/skills/generate-design/examples/enhanced-prompt.md (1704 bytes)
# Example: Prompt Enhancement ## User Input (Vague) > "Make a landing page for my fitness app called 'Pulse'. It should have a > place for features and a hero section." --- ## Enhanced Prompt (Stitch-Optimized) > [!NOTE] > This prompt contains NO colors, fonts, or theme instructions — those are > handled by the project's design system. The prompt focuses exclusively on > layout, structure, and content. **Overall Purpose**: A high-energy, modern landing page for 'Pulse', a fitness tracking application. The page should feel powerful, motivating, and high-performance. **PLATFORM:** Web, Desktop-first **PAGE STRUCTURE:** 1. **Header**: Minimalist navigation with Pulse logo (left) and "Start Training" primary call-to-action button (right). 2. **Hero Section**: Large, emotive fitness photography background. Headline: "Elevate Every Beat." Sub-headline: "Track, analyze, and crush your fitness goals with Pulse." Primary CTA button: "Get Started". 3. **Feature Grid**: Three-column responsive card grid highlighting: - **Real-time Tracking**: Live stats from your wearable. - **AI Coaching**: Personalized workouts based on your performance. - **Community Challenges**: Compete with friends and stay motivated. 4. **Social Proof Section**: Horizontal slider showing "Trusted by 500,000+ athletes" with partner logos. 5. **Footer**: Quick links (Training, Pricing, Support), social icons, and legal text. --- 💡 **Tip**: Notice how the enhanced prompt describes **structure and content** without specifying hex codes, font families, or color roles. The design system (created via the manage-design-system skill) handles all visual theming at the project level. - plugins/stitch-design/skills/generate-design/references/design-mappings.md (2330 bytes)
# Design Mappings & Descriptors Use these mappings to transform vague user requests into precise, high-fidelity design instructions. ## UI/UX Keyword Refinement | Vague Term | Enhanced Professional Terminology | |:---|:---| | "menu at the top" | "sticky navigation bar with logo and list items" | | "big photo" | "high-impact hero section with full-width imagery" | | "list of things" | "responsive card grid with hover states and subtle elevations" | | "button" | "primary call-to-action button with micro-interactions" | | "form" | "clean form with labeled input fields, validation states, and submit button" | | "picture area" | "hero section with focal-point image or video background" | | "sidebar" | "collapsible side navigation with icon-label pairings" | | "popup" | "modal dialog with overlay and smooth entry animation" | ## Atmosphere & "Vibe" Descriptors Add these adjectives to set the mood and aesthetic philosophy: | Basic Vibe | Enhanced Design Description | |:---|:---| | "Modern" | "Clean, minimal, with generous whitespace and high-contrast typography." | | "Professional" | "Sophisticated, trustworthy, utilizing subtle shadows and a restricted, premium palette." | | "Fun / Playful" | "Vibrant, organic, with rounded corners, bold accent colors, and bouncy micro-animations." | | "Dark Mode" | "Electric, high-contrast accents on deep slate or near-black backgrounds." | | "Luxury" | "Elegant, spacious, with fine lines, serif headers, and a focus on high-fidelity photography." | | "Tech / Cyber" | "Futuristic, neon accents, glassmorphism effects, and technological monospaced typography." | ## Geometry & Shape Translation Convert technical values into physical descriptions for Stitch: - **Pill-shaped**: Used for `rounded-full` elements (buttons, tags). - **Softly rounded**: Used for `rounded-xl` (12px) or `rounded-2xl` (16px) containers. - **Sharp/Precise**: Used for `rounded-none` or `rounded-sm` elements. - **Glassmorphism**: Semi-transparent surfaces with background blur and thin borders. ## Depth & Elevation - **Flat**: No shadows, focus on color blocking and borders. - **Whisper-soft**: Diffused, light shadows for subtle lift. - **Floating**: High-offset, soft shadows for elements that appear high above the surface. - **Inset**: Inner shadows for pressable or nested elements.
- plugins/stitch-design/skills/generate-design/references/prompt-keywords.md (2798 bytes)
# UI/UX Keywords Reference Progressive disclosure reference for common UI terminology and adjective palettes. ## Component Keywords ### Navigation - navigation bar, nav menu, header - breadcrumbs, tabs, sidebar - hamburger menu, dropdown menu - back button, close button ### Content Containers - hero section, hero banner - card, card grid, tile - modal, dialog, popup - accordion, collapsible section - carousel, slider ### Forms - input field, text input - dropdown, select menu - checkbox, radio button - toggle switch - date picker, time picker - search bar, search input - submit button, form actions ### Calls to Action - primary button, secondary button - ghost button, text link - floating action button (FAB) - icon button ### Feedback - toast notification, snackbar - alert banner, warning message - loading spinner, skeleton loader - progress bar, step indicator ### Layout - grid layout, flexbox - sidebar layout, split view - sticky header, fixed footer - full-width, contained width - centered content, max-width container ## Adjective Palettes ### Minimal / Clean - minimal, clean, uncluttered - generous whitespace, breathing room - subtle, understated, refined - simple, focused, distraction-free ### Professional / Corporate - sophisticated, polished, trustworthy - corporate, business-like, formal - subtle shadows, clean lines - structured, organized, hierarchical ### Playful / Fun - vibrant, colorful, energetic - rounded corners, soft edges - bold, expressive, dynamic - friendly, approachable, warm ### Premium / Luxury - elegant, luxurious, high-end - dramatic, bold contrasts - sleek, modern, cutting-edge - exclusive, boutique, curated ### Dark Mode - dark theme, night mode - high-contrast accents - soft glows, subtle highlights - deep backgrounds, muted surfaces ### Organic / Natural - earthy tones, natural colors - warm, inviting, cozy - textured, tactile, handcrafted - flowing, organic shapes ## Interaction & Behavior Keywords ### Animations - smooth entry animation, slide-in - fade transition, cross-fade - micro-interaction, bounce effect - skeleton loader, shimmer effect ### Responsiveness - responsive layout, adaptive grid - mobile-first, desktop-first - breakpoint, viewport - stacked layout, side-by-side ### User Flows - progressive disclosure, step indicator - expandable section, collapsible panel - infinite scroll, pagination - drag and drop, swipe gesture ## Shape Descriptions | Technical | Natural Language | |-----------|------------------| | `rounded-none` | sharp, squared-off edges | | `rounded-sm` | slightly softened corners | | `rounded-md` | gently rounded corners | | `rounded-lg` | generously rounded corners | | `rounded-xl` | very rounded, pillow-like | | `rounded-full` | pill-shaped, circular |
- plugins/stitch-design/skills/generate-design/SKILL.md (10996 bytes)
--- name: stitch::generate-design description: >- Generate new screens from text prompts or images, edit existing screens with prompts and design system tokens, and generate design variants using Stitch MCP. Includes prompt enhancement pipeline, design mappings, professional UI/UX terminology, design tokens and theme system capabilities. allowed-tools: - "stitch*:*" - "Bash" - "Read" - "Write" - "web_fetch" --- # Generate Design Create new design screens from text descriptions, images, or mockups, edit existing screens with prompts and design system tokens, and generate design variants using Stitch MCP. > [!NOTE] > Refer to your system prompt for instruction on handling MCP tool prefixes for > all tools mentioned in this skill (e.g., `list_projects`, > `generate_screen_from_text`, `edit_screens`). ## 🎨 Prompt Enhancement Pipeline Before calling any Stitch generation or editing tool, you MUST enhance the user's prompt. ### 1. Analyze Context - **Project**: Use `list_projects` to find the correct `projectId`. If no suitable project exists, create one using `create_project`. - **Design System**: Check if a design system exists for the project via `list_design_systems`. If one exists, design tokens (colors, fonts, roundness) are already applied at the project level — do NOT include any color, font, or theme instructions in the generation prompt. If none exists, delegate to the **manage-design-system** skill first before generating screens. ### 2. Refine UI/UX Terminology Consult [Design Mappings](references/design-mappings.md) to replace vague terms. - Vague: "Make a nice header" - Professional: "Sticky navigation bar with glassmorphism effect and centered logo" Use [Prompting Keywords](references/prompt-keywords.md) for component names, adjective palettes, color roles, and shape descriptions. ### 3. Structure the Final Prompt Format the enhanced prompt for Stitch. Focus exclusively on **layout, content, and structure** — never include colors, fonts, or theme instructions (these are handled by the manage-design-system skill at the project level). For **new screens**, use this template: ```markdown [Overall purpose and user intent of the page] **PLATFORM:** [Web/Mobile], [Desktop/Mobile]-first **PAGE STRUCTURE:** 1. **Header:** [Description of navigation and branding] 2. **Hero Section:** [Headline, subtext, and primary CTA] 3. **Primary Content Area:** [Detailed component breakdown] 4. **Footer:** [Links and copyright information] ``` For **edits**, be specific about what to change: - **Location**: "Change the [primary button] in the [hero section]..." - **Visuals**: "...to a darker blue (#004080) and add a subtle shadow." - **Structure**: "Add a secondary button next to the primary one with the text 'Learn More'." > [!CAUTION] > Do NOT include hex codes, font names, color palettes, roundness values, or > any design system tokens in a **generation** prompt. These are applied at the > project level by the manage-design-system skill and will conflict if > duplicated. (For **edit** prompts, hex codes are acceptable for precise > color adjustments.) ### 4. Present AI Insights After any tool call, always surface the `outputComponents` (Text Description and Suggestions) to the user. See [examples/enhanced-prompt.md](examples/enhanced-prompt.md) for a full before/after prompt enhancement example. -------------------------------------------------------------------------------- ## Steps ### Determine the Mode Decide which flow to use based on the user's request: - User wants to create from a text description → **Generate from Text** flow - User provides an image, screenshot, or mockup → **Generate from Image** flow - User wants to modify an existing screen → **Edit** flow - User wants layout/color/content variations → **Generate Variants** flow --- ### Generate from Text Flow (New Screen) #### 1. Enhance the User Prompt Apply the Prompt Enhancement Pipeline above. #### 2. Identify the Project Use `list_projects` to find the correct `projectId` if it is not already known. #### 3. Generate the Screen Call the `generate_screen_from_text` tool with the enhanced prompt and the `designSystem` ID (if found in Step 1). ```json { "projectId": "...", "prompt": "[Your Enhanced Prompt]", "designSystem": "assets/...", // Optional: Pass if found in Step 1 "deviceType": "DESKTOP" // Options: MOBILE, DESKTOP, TABLET } ``` #### 4. Present AI Feedback Always show the text description and suggestions from `outputComponents` to the user. #### 5. Download Design Assets After generation, download the HTML and screenshot urls from `outputComponents` to the `.stitch/designs` directory. - **Naming**: Use the screen ID or a descriptive slug for the filename. - **Tools**: Use `curl -o` via `run_command` or similar. - **Directory**: Ensure `.stitch/designs` exists. #### 6. Review and Refine - If the result is not exactly as expected, continue with the **Edit** flow to make targeted adjustments. - Do NOT re-generate from scratch unless the fundamental layout is wrong. --- ### Generate from Image Flow (Image/Mockup → Design) Use this flow when the user provides an image, screenshot, or design mockup to recreate in Stitch. #### 1. Identify the Project Use `list_projects` to find the correct `projectId`. If no suitable project exists, create one using `create_project`. #### 2. Upload the Image Delegate to the **upload-to-stitch** skill to upload the image to the project. This creates a new screen with the image as its content. #### 3. Refine with Edit Once uploaded, use `list_screens` to find the newly created `screenId`, then call `edit_screens` with a descriptive prompt to refine the design: ```json { "projectId": "...", "selectedScreenIds": ["<uploaded-screen-id>"], "prompt": "[Describe what to adjust, enhance, or recreate from this mockup]" } ``` > [!TIP] > For best results, describe the intent behind the image rather than just saying > "make it look like this". For example: "This is a dashboard mockup — recreate > it with a proper data table, sidebar navigation, and chart widgets." #### 4. Present AI Feedback Always show the text description and suggestions from `outputComponents` to the user. #### 5. Download Design Assets Download the HTML and screenshot urls from `outputComponents` to the `.stitch/designs` directory. - **Naming**: Use the screen ID or a descriptive slug for the filename. - **Tools**: Use `curl -o` via `run_command` or similar. - **Directory**: Ensure `.stitch/designs` exists. --- ### Edit Flow (Modify Existing Screen) #### 1. Identify the Screen Use `list_screens` or `get_screen` to find the correct `projectId` and `screenId`. #### 2. Formulate the Edit Prompt Apply the Prompt Enhancement Pipeline, focusing on specificity: - **Location**: "Change the color of the [primary button] in the [hero section]..." - **Visuals**: "...to a darker blue (#004080) and add a subtle shadow." - **Structure**: "Add a secondary button next to the primary one with the text 'Learn More'." #### 3. Apply the Edit Call the `edit_screens` tool. ```json { "projectId": "...", "selectedScreenIds": ["..."], "prompt": "[Your targeted edit prompt]" } ``` #### 4. Present AI Feedback Always show the text description and suggestions from `outputComponents` to the user. #### 5. Download Design Assets After editing, download the updated HTML and screenshot urls from `outputComponents` to the `.stitch/designs` directory, overwriting previous versions to ensure the local files reflect the latest edits. - **Naming**: Use the screen ID or a descriptive slug for the filename. - **Tools**: Use `curl -o` via `run_command` or similar. - **Directory**: Ensure `.stitch/designs` exists. #### 6. Update Project Metadata After downloading assets, update `.stitch/metadata.json` to reflect any changes (e.g., updated screen titles or new screen IDs from the edit). The metadata file tracks all screens, their device types, and design system info. See the **manage-design-system** skill's `examples/metadata.json` for the format. #### 7. Verify and Repeat - Check the output screen to see if the changes were applied correctly. - If more polish is needed, repeat the edit flow with a new specific prompt. --- ### Generate Variants Flow (Explore Variations) Use this flow when the user wants to explore alternative layouts, color schemes, or content variations of an existing screen. #### 1. Identify the Screen Use `list_screens` or `get_screen` to find the correct `projectId` and `screenId`. #### 2. Configure Variant Options Call the `generate_variants` tool with the appropriate options: ```json { "projectId": "...", "selectedScreenIds": ["..."], "prompt": "[Describe the direction for variants]", "variantOptions": { "variantCount": 3, "creativeRange": "EXPLORE", "aspects": ["LAYOUT", "COLOR_SCHEME"] } } ``` **Variant Options:** - **`variantCount`**: 1–5 variants (default: 3) - **`creativeRange`**: `REFINE` (subtle), `EXPLORE` (balanced), or `REIMAGINE` (radical) - **`aspects`**: Focus on specific dimensions — `LAYOUT`, `COLOR_SCHEME`, `IMAGES`, `TEXT_FONT`, `TEXT_CONTENT`, or leave empty for all #### 3. Present AI Feedback Always show the text description and suggestions from `outputComponents` to the user. #### 4. Download Design Assets Download the variant HTML and screenshot urls from `outputComponents` to the `.stitch/designs` directory. - **Naming**: Use the screen ID or a descriptive slug for the filename. - **Tools**: Use `curl -o` via `run_command` or similar. - **Directory**: Ensure `.stitch/designs` exists. -------------------------------------------------------------------------------- ## 💡 Tips - **Be structural**: Break the page down into header, hero, features, and footer in your prompt. - **Content first**: Describe what each section contains (text, images, CTAs) rather than how it looks. - **Iterative Polish**: Prefer editing for targeted adjustments over full re-generation. - **No theme leakage**: Never put hex codes, font names, or color roles in a generation prompt — the design system handles all visual styling. - **Specify interactions**: Mention hover states, animations, and click behavior rather than visual styling. - **Keep edits focused**: One edit at a time is often better than a long list of changes. - **Reference components**: Use professional terms like "navigation bar", "hero section", "footer", "card grid". - **Precise colors in edits**: Use hex codes for exact color matching when editing existing screens. ## 📚 References - [Design Mappings](references/design-mappings.md) — UI/UX keywords and atmosphere descriptors. - [Prompting Keywords](references/prompt-keywords.md) — Technical terms Stitch understands best. - [Enhanced Prompt Example](examples/enhanced-prompt.md) — Before/after prompt enhancement. - plugins/stitch-design/skills/manage-design-system/examples/metadata.json (546 bytes)
{ "projectId": "4044680601076201931", "title": "Solace Mindfulness App", "screens": [ { "screenId": "98b50e2ddc9943efb387052637738f61", "title": "Landing Page", "deviceType": "DESKTOP" }, { "screenId": "98b50e2ddc9943efb387052637738f62", "title": "Breathing Exercise", "deviceType": "MOBILE" } ], "designSystem": { "assetId": "15996705518239280238", "primaryColor": "#1a365d", "secondaryColor": "#718096", "backgroundColor": "#f7fafc", "fontFamily": "INTER" } } - plugins/stitch-design/skills/manage-design-system/reference/tool-schema.md (6630 bytes)
# Design System Tool Schemas Use these examples to format your Stitch MCP design system tool calls correctly. --- ## Upload `DESIGN.md` (via `upload_to_stitch.py` script) Uploads a `DESIGN.md` file to a project via the `BatchCreateScreens` endpoint. This is the first step in creating a design system from a markdown file. > [!NOTE] > Use the `upload-to-stitch` skill's script instead of the `upload_design_md` > MCP tool. The script handles base64 encoding in-process, avoiding the model's > output token limit. ```bash python3 <SKILL_DIR>/scripts/upload_to_stitch.py \ --project-id <PROJECT_ID> \ --file-path /path/to/DESIGN.md \ --api-key <API_KEY> ``` --- ## `create_design_system_from_design_md` Creates a design system for a project using the uploaded `DESIGN.md` file. ```json { "projectId": "4044680601076201931", "selectedScreenInstance": { "id": "98b50e2ddc9943efb387052637738f61", "sourceScreen": "projects/4044680601076201931/screens/98b50e2ddc9943efb387052637738f61" }, "deviceType": "DESKTOP" } ``` > [!NOTE] > You must upload `DESIGN.md` via the script first to get the source screen ID, and then fetch the project details with `get_project` to find the corresponding screen instance ID to pass as `id` in `selectedScreenInstance`. --- ## `update_design_system` Updates an existing design system for a project. This is **required** immediately after calling `create_design_system` to set the theme and display the design system in the UI. > [!NOTE] > While `update_design_system` is mandatory after the basic `create_design_system` call, you do **not** need to call it after `create_design_system_from_design_md`. The latter automatically populates and updates all theme tokens directly from the parsed YAML frontmatter of the uploaded `DESIGN.md`. ```json { "name": "assets/15996705518239280238", "projectId": "4044680601076201931", "designSystem": { "displayName": "My Design System", // OPTIONAL. Display name of the design system "theme": { // REQUIRED. The design theme object "colorMode": "LIGHT", // REQUIRED. Options: LIGHT, DARK "headlineFont": "INTER", // REQUIRED. Options: INTER, ROBOTO, OPEN_SANS, LATO, MONTSERRAT, NOTO_SANS, NOTO_SERIF, etc. "bodyFont": "INTER", // REQUIRED. Same font options as headlineFont "labelFont": "INTER", // OPTIONAL. Same font options as headlineFont "roundness": "ROUND_EIGHT", // REQUIRED. Options: ROUND_FOUR, ROUND_EIGHT, ROUND_TWELVE, ROUND_FULL "customColor": "#0EA5E9", // REQUIRED. Primary brand color / seed color for dynamic color system (hex) "colorVariant": "FIDELITY", // OPTIONAL. Options: FIDELITY, TONAL, VIBRANT, EXPRESSIVE, CONTENT, MONOCHROME, FRUIT_SALAD, RAINBOW "overridePrimaryColor": "#996e47", // OPTIONAL. Override primary color (hex) "overrideSecondaryColor": "#0EA5E9", // OPTIONAL. Override secondary color (hex) "overrideTertiaryColor": "#c4956a", // OPTIONAL. Override tertiary color (hex) "overrideNeutralColor": "#0D0D0D", // OPTIONAL. Override neutral color (hex) "designMd": "# Design System..." // OPTIONAL. Markdown string with detailed design system spec } } } ``` ### Field Reference #### Required Fields | Field | Type | Description | |:------|:-----|:------------| | `colorMode` | enum | `LIGHT` or `DARK` | | `headlineFont` | enum | Font for headlines and display text. See font options below. | | `bodyFont` | enum | Font for body text. See font options below. | | `roundness` | enum | `ROUND_FOUR`, `ROUND_EIGHT`, `ROUND_TWELVE`, `ROUND_FULL` | | `customColor` | hex | Primary brand / seed color for the dynamic color system (e.g., `#E8732A`) | #### Optional Fields | Field | Type | Description | |:------|:-----|:------------| | `displayName` | string | Human-readable name for the design system | | `labelFont` | enum | Font for labels and captions. Defaults to `bodyFont` if omitted. | | `colorVariant` | enum | `FIDELITY`, `TONAL`, `VIBRANT`, `EXPRESSIVE`, `CONTENT`, `MONOCHROME`, `FRUIT_SALAD`, `RAINBOW` | | `overridePrimaryColor` | hex | Override primary color (e.g., `#E8732A`) | | `overrideSecondaryColor` | hex | Override secondary color (e.g., `#1B6B93`) | | `overrideTertiaryColor` | hex | Override tertiary color (e.g., `#F2A541`) | | `overrideNeutralColor` | hex | Override neutral color (e.g., `#FAF7F2`) | | `spacingScale` | integer | Spacing scale factor (observed value: `3`) | | `designMd` | string | Markdown string with detailed design system specifications | #### Font Options The following font enum values are confirmed to work (server-validated): | Value | Font Name | |:------|:----------| | `INTER` | Inter | | `ROBOTO` | Roboto | | `OPEN_SANS` | Open Sans | | `LATO` | Lato | | `MONTSERRAT` | Montserrat | | `NOTO_SANS` | Noto Sans | | `NOTO_SERIF` | Noto Serif | | `PLUS_JAKARTA_SANS` | Plus Jakarta Sans | | `BE_VIETNAM_PRO` | Be Vietnam Pro | > [!WARNING] > Omit the legacy `font` field when updating the design system to avoid "invalid argument" errors. > [!NOTE] > The `namedColors` object above is abbreviated. The full response contains 50+ > Material 3 color tokens including all container, fixed, and inverse variants. --- ## `apply_design_system` Applies a design system to one or more screens in a project. > [!IMPORTANT] > `selectedScreenInstances` must contain **only** `id` and `sourceScreen` — do NOT > include position/dimension fields (`x`, `y`, `width`, `height`) or the request > will fail with "invalid argument". Get the screen instance IDs from > `get_project`. ```json { "projectId": "4044680601076201931", "assetId": "c277fcdfc1e04baf91b92d975ff4c54a", "selectedScreenInstances": [ { "id": "98b50e2ddc9943efb387052637738f61", "sourceScreen": "projects/4044680601076201931/screens/98b50e2ddc9943efb387052637738f61" }, { "id": "ab12cd34ef56789012345678abcdef01", "sourceScreen": "projects/4044680601076201931/screens/ab12cd34ef56789012345678abcdef01" } ] } ``` **How to get the required IDs:** 1. Call `get_project` to retrieve `screenInstances` — each has an `id` and `sourceScreen`. 2. Call `list_design_systems` to retrieve the design system `name` (format: `assets/{assetId}`) — use the part after `assets/` as the `assetId`. 3. Filter out any instances with `type: "DESIGN_SYSTEM_INSTANCE"` — only pass real screens. - plugins/stitch-design/skills/manage-design-system/SKILL.md (5663 bytes)
--- name: stitch::manage-design-system description: >- Manage design systems in Stitch using MCP tools. Includes retrieval of assets, creating/updating design systems in Stitch, and applying them to screens. allowed-tools: - "stitch*:*" - "Bash" - "Read" - "Write" - "web_fetch" --- # Design-System Create a "source of truth" for your project's design language to ensure consistency across all future screens. > [!NOTE] > Refer to your system prompt for instruction on handling MCP tool prefixes for > all tools mentioned in this skill (e.g., `get_screen`, > `create_design_system_from_design_md`, `apply_design_system`). ## 📥 Retrieval To analyze a Stitch project, you must retrieve metadata and assets using the Stitch MCP tools: 1. **Project lookup**: Use `list_projects` to find the target `projectId`. 2. **Screen lookup**: Use `list_screens` for that `projectId` to find representative screens (e.g., "Home", "Main Dashboard"). 3. **Metadata fetch**: Call `get_screen` for the target screen to get `screenshot.downloadUrl` and `htmlCode.downloadUrl`. 4. **Asset download**: Use `read_url_content` to fetch the HTML code. ## 🧠 Synthesis from Description If you need to extract a design system from existing screens, use the `design-md` skill (in the `stitch-utilities` plugin). If there are no existing screens (new project), or the user provides a direct description (e.g., "dark theme, blue and purple, rounded, Inter font"): 1. Map the user's vague terms to precise values using the design mappings (see `design-md` skill in `stitch-utilities` or `generate-design` skill). 2. Select concrete hex codes, font families, and roundness values. 3. Generate the `DESIGN.md` file (refer to the `design-md` skill in `stitch-utilities` for structure). 4. Proceed to the "Create or Update Design System in Stitch" step below. ## 📝 Output Structure The `DESIGN.md` file should follow the structure defined in the `design-md` skill (in the `stitch-utilities` plugin). ## 🚀 Create or Update Design System in Stitch After generating `.stitch/DESIGN.md`, make sure to also create or update the design system in Stitch. **Two-step design system creation:** > [!WARNING] > **Checkpoint — User Confirmation Required.** > Before uploading, you **MUST** pause and ask the user for > confirmation. Present a summary of the design system you are about to create > (display name, key colors, fonts, and roundness) and wait for explicit approval > before proceeding. Do **NOT** upload until the user confirms. 1. **Upload `DESIGN.md`**: - **Option A (Recommended - Uploader Script)**: Use the modified `upload-to-stitch` Python script which natively handles `.md` files. It base64-encodes the markdown file in-process and sends it to the `/v1/projects/{projectId}/screens:batchCreate` endpoint, bypassing output token limits. ```bash python3 stitch-skills/plugins/stitch-design/skills/upload-to-stitch/scripts/upload_to_stitch.py \ --project-id <PROJECT_ID> \ --file-path /path/to/DESIGN.md \ --api-key <API_KEY> \ --generated-by <GENERATED_BY> ``` Set `<GENERATED_BY>` to identify the skill or tool that produced the `DESIGN.md`. Use the calling skill name when invoked from another skill (e.g. `stitch::code-to-design`), or the agent/tool name for standalone use (e.g. `Gemini`, `Claude Code`). If omitted, the script defaults to `UserUploadedDesignMd`. This returns the `sourceScreen` ID and the `screenInstance` ID. - **Option B (Direct MCP Tool)**: If the `DESIGN.md` is small (under ~5KB), you can call the `upload_design_md` MCP tool directly, passing the base64-encoded design markdown content as `designMdBase64`. 2. **Create Design System**: Call the `create_design_system_from_design_md` tool immediately after the upload, passing the `projectId` and the `selectedScreenInstance` (containing the `id` and `sourceScreen` returned from the upload step). Once the upload script and `create_design_system_from_design_md` have both completed, Stitch holds the design tokens at the project level — you do NOT need to repeat them in generation prompts. ## 🎨 Apply Design System to Screens Use `apply_design_system` to apply a design system to existing screens. > [!IMPORTANT] > `selectedScreenInstances` must contain **only** `id` and `sourceScreen` — do > NOT include position/dimension fields (`x`, `y`, `width`, `height`) or the > request will fail with "invalid argument". Get the screen instance IDs from > `get_project`. ```json { "projectId": "...", "assetId": "...", "selectedScreenInstances": [ { "id": "...", "sourceScreen": "projects/.../screens/..." } ] } ``` **How to get the required IDs:** 1. Call `get_project` to retrieve `screenInstances` — each has an `id` and `sourceScreen`. 2. Call `list_design_systems` to retrieve the design system `name` (format: `assets/{assetId}`) — use the part after `assets/` as the `assetId`. 3. Filter out any instances with `type: "DESIGN_SYSTEM_INSTANCE"` — only pass real screens. ## 📋 Update Project Metadata After writing `.stitch/DESIGN.md`, also create or update `.stitch/metadata.json` to track the `projectId`, `title`, all known screens, and design system summary. See [examples/metadata.json](examples/metadata.json) for the format. ## Schema Reference See [reference/tool-schema.md](reference/tool-schema.md) for the full `designSystem` object schema with all available options. ## 💡 Best Practices Refer to the `design-md` skill (in the `stitch-utilities` plugin) for best practices on describing design elements. - plugins/stitch-design/skills/upload-to-stitch/scripts/upload_to_stitch.py (7417 bytes)
#!/usr/bin/env python3 r"""Upload an image, HTML, or Markdown file to a Stitch project via BatchCreateScreens. WHY THIS SCRIPT EXISTS: The AI model cannot upload files via the MCP tool directly because MCP tool call arguments are part of the model's *output*. The model must re-emit the entire base64-encoded file as generated text, but its output token limit (~16K tokens) is far smaller than a typical file's base64 encoding (e.g. a 53KB PNG becomes ~71K chars of base64). The output gets truncated mid-string, producing a corrupted payload that the API rejects. This script bypasses the model entirely — it reads the file, encodes it in-process, and sends the full payload directly over HTTP with no token limits. SUPPORTED FILE TYPES: - Images: .png, .jpg, .jpeg, .webp - HTML: .html, .htm - Markdown: .md Usage: python3 upload_to_stitch.py \ --project-id <PROJECT_ID> \ --file-path <PATH_TO_FILE> \ [--api-url <STITCH_API_BASE_URL>] \ [--api-key <API_KEY>] \ [--title <SCREEN_TITLE>] \ [--generated-by <GENERATED_BY>] \ [--create-screen-instances] """ import argparse import base64 import json import pathlib import sys from typing import Any import urllib.request try: import ssl import certifi _SSL_CONTEXT = ssl.create_default_context(cafile=certifi.where()) except ImportError: _SSL_CONTEXT = None # Maps file extensions to MIME types. _MIME_TYPES = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".html": "text/html", ".htm": "text/html", ".md": "text/markdown", } def encode_file(path: pathlib.Path) -> str: """Read and base64-encode a file.""" with open(path, "rb") as f: return base64.b64encode(f.read()).decode("utf-8") def call_batch_create_screens( api_url: str, api_key: str, project_id: str, requests: list[dict[str, Any]], create_screen_instances: bool = False, urlopen: Any = urllib.request.urlopen, ) -> dict[str, Any]: """Call BatchCreateScreens REST API directly. Endpoint: POST /v1/{parent=projects/*}/screens:batchCreate Args: api_url: Base URL of the Stitch API (e.g. https://stitch.googleapis.com). api_key: API key for authentication. project_id: The Stitch project ID. requests: List of CreateScreenRequest dicts, each containing a screen. create_screen_instances: Whether to create screen instances for display. urlopen: The urlopen function to use (for testing). Returns: Parsed JSON response dict. """ url = f"{api_url.rstrip('/')}/v1/projects/{project_id}/screens:batchCreate" payload = { "parent": f"projects/{project_id}", "requests": requests, "createScreenInstances": create_screen_instances, } data = json.dumps(payload).encode("utf-8") req = urllib.request.Request( url, data=data, headers={ "Content-Type": "application/json", "X-Goog-Api-Key": api_key, }, method="POST", ) try: print("Calling urlopen...") urlopen_kwargs = {"timeout": 120} if _SSL_CONTEXT is not None: urlopen_kwargs["context"] = _SSL_CONTEXT with urlopen(req, **urlopen_kwargs) as resp: print(f"urlopen returned. Status: {resp.getcode()}") body = resp.read().decode("utf-8") print(f"Response status: {resp.getcode()}") print(f"Response body (first 1000 chars): {body[:1000]}") if not body: print("Error: Empty response body") sys.exit(1) return json.loads(body) except urllib.error.HTTPError as e: error_body = e.read().decode("utf-8") print(f"HTTP Error {e.code}: {e.reason}") print(f"Response: {error_body}") sys.exit(1) def build_screen_request( mime_type: str, b64_data: str, title: str | None = None, generated_by: str | None = None, ) -> dict[str, Any]: """Build a CreateScreenRequest dict from a file. For images, the file is set as the screenshot. For HTML, the file is set as the html_code. Args: mime_type: The MIME type of the file. b64_data: Base64-encoded file content. title: Optional title for the screen. generated_by: Optional value for the generatedBy field (HTML/markdown only). Returns: A CreateScreenRequest-shaped dict. """ file_obj = { "fileContentBase64": b64_data, "mimeType": mime_type, } if mime_type in ("text/html", "text/markdown"): screen = { "htmlCode": file_obj, "screenType": "DOCUMENT", "isCreatedByClient": True, } if not generated_by: if mime_type == "text/markdown": generated_by = "UserUploadedDesignMd" elif mime_type == "text/html": generated_by = "UserUploadedHtml" if generated_by: screen["generatedBy"] = generated_by else: screen = { "screenshot": file_obj, "screenType": "IMAGE", "isCreatedByClient": True, } if title: screen["title"] = title return {"screen": screen} def parse_args(): """Parse command-line arguments.""" parser = argparse.ArgumentParser( description="Upload a file to a Stitch project via BatchCreateScreens." ) parser.add_argument("--project-id", required=True, help="Stitch project ID") parser.add_argument( "--file-path", required=True, type=pathlib.Path, help=( "Path to the file to upload. Supported types:" f" {', '.join(sorted(_MIME_TYPES.keys()))}" ), ) parser.add_argument( "--api-url", default="https://stitch.googleapis.com", help="Stitch API base URL. Defaults to https://stitch.googleapis.com.", ) parser.add_argument( "--api-key", required=True, help="API key for the Stitch API.", ) parser.add_argument( "--title", default=None, help="Optional title for the created screen", ) parser.add_argument( "--generated-by", default=None, help=( "Value for the generatedBy field in the screen proto" " (HTML/markdown uploads only)." ), ) return parser.parse_args() def main(): args = parse_args() file_path = args.file_path file_suffix = file_path.suffix.lower() mime_type = _MIME_TYPES.get(file_suffix) if mime_type is None: print( f"Error: Unsupported file type '{file_suffix}'. Supported types:" f" {', '.join(sorted(_MIME_TYPES.keys()))}" ) sys.exit(1) if not file_path.exists(): print(f"Error: File not found: {file_path}") sys.exit(1) if args.generated_by and mime_type not in ("text/html", "text/markdown"): print("Warning: --generated-by is ignored for image uploads.") print(f"File: {file_path}") print(f"MIME type: {mime_type}") b64_data = encode_file(file_path) print(f"Base64: {len(b64_data)} chars") screen_request = build_screen_request( mime_type, b64_data, title=args.title, generated_by=args.generated_by, ) print(f"\nUploading to project: {args.project_id}") print(f"API URL: {args.api_url}") result = call_batch_create_screens( api_url=args.api_url, api_key=args.api_key, project_id=args.project_id, requests=[screen_request], create_screen_instances=True, ) print("\nResponse:") print(json.dumps(result, indent=2)) if __name__ == "__main__": main() - plugins/stitch-design/skills/upload-to-stitch/SKILL.md (4200 bytes)
--- name: stitch::upload-to-stitch description: >- Upload local assets (images, mockups, extracted HTML, design markdown) to a Stitch project. ALWAYS use this skill when you need to upload visual assets, HTML pages, or design docs to Stitch, particularly when direct MCP tool calls fail or truncate due to base64 token limits. allowed-tools: - "stitch*:*" - "Bash" - "Read" - "Write" - "web_fetch" --- # Upload-to-Stitch Upload local assets (images, mockups, HTML, and markdown files) to a Stitch project using the provided upload script, which bypasses the MCP tool's base64 output token limits. > [!NOTE] > The AI model cannot upload files via MCP tools directly because the base64 > encoding of even a small file exceeds the model's output token limit (~16K > tokens). This script reads the file and sends it directly over HTTP. ## Steps ### 1. Identify Target Project Use `list_projects` to find the correct `projectId`. ### 2. Get the API Key Locate your active MCP server configuration file and extract the API key: - **Antigravity**: `.gemini/antigravity/mcp_config.json` or `.gemini/jetski/mcp_config.json` - **Gemini CLI**: `~/.gemini/settings.json` or `~/.gemini/extensions/Stitch/gemini-extension.json` - **Claude Code**: `~/.claude.json` Extract: - **API Key**: From the `X-Goog-Api-Key` header or auth argument - **MCP URL** (optional): From the `httpUrl` or endpoint argument (defaults to `https://stitch.googleapis.com`) > [!IMPORTANT] > If you cannot find the API key in any of these locations, or if you cannot access these files, you MUST ask the user to provide the Stitch API key. Do not proceed without a valid API key. ### 3. Run Upload Script > [!WARNING] > **Checkpoint — User Confirmation Required.** > Before running the upload script, you **MUST** pause and present the file(s) > to be uploaded (paths, sizes, and types) to the user and wait for explicit > approval. Do **NOT** execute the upload script until the user confirms. Use `run_command` to execute the Python script: ```bash python3 <SKILL_DIR>/scripts/upload_to_stitch.py \ --project-id <PROJECT_ID> \ --file-path <PATH_TO_FILE> \ --api-key <API_KEY> \ [--api-url <STITCH_API_URL>] \ [--title <SCREEN_TITLE>] \ [--generated-by <GENERATED_BY>] ``` > [!TIP] > **macOS / SSL Certificate Troubleshooting:** > If the upload fails with `ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] unable to get local issuer certificate`, this means your Python installation does not have root certificate authorities configured. > > The script automatically attempts to use the `certifi` package to load the CA bundle if it is installed in your python environment. If `certifi` is not installed, you can either install it (`pip install certifi`) or manually supply the `SSL_CERT_FILE` environment variable when running the script: > ```bash > SSL_CERT_FILE=$(python3 -c "import certifi; print(certifi.where())") python3 <SKILL_DIR>/scripts/upload_to_stitch.py \ > --project-id <PROJECT_ID> \ > --file-path <PATH_TO_FILE> \ > --api-key <API_KEY> \ > [--api-url <STITCH_API_URL>] \ > [--title <SCREEN_TITLE>] \ > [--generated-by <GENERATED_BY>] > ``` ### Supported File Types | Extension | MIME Type | |:---|:---| | `.png` | `image/png` | | `.jpg`, `.jpeg` | `image/jpeg` | | `.webp` | `image/webp` | | `.html`, `.htm` | `text/html` | | `.md` | `text/markdown` | The script auto-detects MIME type from the file extension. ### Script Options - `--project-id`: **Required**. The Stitch project ID. - `--file-path`: **Required**. Path to the local file to upload. - `--api-key`: **Required**. API key for Stitch authorization. - `--api-url`: Optional. Base URL of the Stitch API. Defaults to `https://stitch.googleapis.com`. - `--title`: Optional. Title for the uploaded screen. When uploading extracted HTML from a web app, set this to the **route path** of the page (e.g., `'/dashboard'`, `'/settings/profile'`, `'/inbox'`) so that the screen name/title in Stitch clearly identifies the route. - `--generated-by`: Optional. Specify how the uploaded file was generated (e.g., 'stitch::extract-static-html' skill, 'Claude Code', 'Codex', 'Gemini' etc.).
- plugins/stitch-utilities/skills/design-md/README.md (1273 bytes)
# Stitch Design System Documentation Skill ## Install ```bash npx skills add google-labs-code/stitch-skills --skill design-md --global ``` ## Example Prompt ```text Analyze my Furniture Collection project's Home screen and generate a comprehensive DESIGN.md file documenting the design system. ``` ## Skill Structure This repository follows the **Agent Skills** open standard. Each skill is self-contained with its own logic, workflow, and reference materials. ```text design-md/ ├── SKILL.md — Core instructions & workflow ├── examples/ — Sample DESIGN.md outputs └── README.md — This file ``` ## How it Works When activated, the agent follows a structured design analysis pipeline: 1. **Retrieval**: Uses the Stitch MCP Server to fetch project screens, HTML code, and design metadata. 2. **Extraction**: Identifies design tokens including colors, typography, spacing, and component patterns. 3. **Translation**: Converts technical CSS/Tailwind values into descriptive, natural design language. 4. **Synthesis**: Generates a comprehensive DESIGN.md following the semantic design system format. 5. **Alignment**: Ensures output follows Stitch Effective Prompting Guide principles for optimal screen generation.
- plugins/stitch-utilities/skills/design-md/SKILL.md (7654 bytes)
--- name: design-md description: Analyze Stitch projects and synthesize a semantic design system into DESIGN.md files allowed-tools: - "stitch*:*" - "Read" - "Write" - "web_fetch" --- # Stitch DESIGN.md Skill You are an expert Design Systems Lead. Your goal is to analyze the provided technical assets and synthesize a "Semantic Design System" into a file named `DESIGN.md`. ## Overview This skill helps you create `DESIGN.md` files that serve as the "source of truth" for prompting Stitch to generate new screens that align perfectly with existing design language. Stitch interprets design through "Visual Descriptions" supported by specific color values. ## Prerequisites - Access to the Stitch MCP Server - A Stitch project with at least one designed screen - Access to the Stitch Effective Prompting Guide: https://stitch.withgoogle.com/docs/learn/prompting/ ## The Goal The `DESIGN.md` file will serve as the "source of truth" for prompting Stitch to generate new screens that align perfectly with the existing design language. Stitch interprets design through "Visual Descriptions" supported by specific color values. ## Retrieval and Networking To analyze a Stitch project, you must retrieve screen metadata and design assets using the Stitch MCP Server tools: 1. **Namespace discovery**: Run `list_tools` to find the Stitch MCP prefix. Use this prefix (e.g., `mcp_stitch:`) for all subsequent calls. 2. **Project lookup** (if Project ID is not provided): - Call `[prefix]:list_projects` with `filter: "view=owned"` to retrieve all user projects - Identify the target project by title or URL pattern - Extract the Project ID from the `name` field (e.g., `projects/13534454087919359824`) 3. **Screen lookup** (if Screen ID is not provided): - Call `[prefix]:list_screens` with the `projectId` (just the numeric ID, not the full path) - Review screen titles to identify the target screen (e.g., "Home", "Landing Page") - Extract the Screen ID from the screen's `name` field 4. **Metadata fetch**: - Call `[prefix]:get_screen` with both `projectId` and `screenId` (both as numeric IDs only) - This returns the complete screen object including: - `screenshot.downloadUrl` - Visual reference of the design - `htmlCode.downloadUrl` - Full HTML/CSS source code - `width`, `height`, `deviceType` - Screen dimensions and target platform - Project metadata including `designTheme` with color and style information 5. **Asset download**: - Use `web_fetch` or `read_url_content` to download the HTML code from `htmlCode.downloadUrl` - Optionally download the screenshot from `screenshot.downloadUrl` for visual reference - Parse the HTML to extract Tailwind classes, custom CSS, and component patterns 6. **Project metadata extraction**: - Call `[prefix]:get_project` with the project `name` (full path: `projects/{id}`) to get: - `designTheme` object with color mode, fonts, roundness, custom colors - Project-level design guidelines and descriptions - Device type preferences and layout principles ## Analysis & Synthesis Instructions ### 1. Extract Project Identity (JSON) - Locate the Project Title - Locate the specific Project ID (e.g., from the `name` field in the JSON) ### 2. Define the Atmosphere (Image/HTML) Evaluate the screenshot and HTML structure to capture the overall "vibe." Use evocative adjectives to describe the mood (e.g., "Airy," "Dense," "Minimalist," "Utilitarian"). ### 3. Map the Color Palette (Tailwind Config/JSON) Identify the key colors in the system. For each color, provide: - A descriptive, natural language name that conveys its character (e.g., "Deep Muted Teal-Navy") - The specific hex code in parentheses for precision (e.g., "#294056") - Its specific functional role (e.g., "Used for primary actions") ### 4. Translate Geometry & Shape (CSS/Tailwind) Convert technical `border-radius` and layout values into physical descriptions: - Describe `rounded-full` as "Pill-shaped" - Describe `rounded-lg` as "Subtly rounded corners" - Describe `rounded-none` as "Sharp, squared-off edges" ### 5. Describe Depth & Elevation Explain how the UI handles layers. Describe the presence and quality of shadows (e.g., "Flat," "Whisper-soft diffused shadows," or "Heavy, high-contrast drop shadows"). ## Output Guidelines - **Language:** Use descriptive design terminology and natural language exclusively - **Format:** Generate a clean Markdown file following the structure below - **Precision:** Include exact hex codes for colors while using descriptive names - **Context:** Explain the "why" behind design decisions, not just the "what" ## Output Format (DESIGN.md Structure) ```markdown # Design System: [Project Title] **Project ID:** [Insert Project ID Here] ## 1. Visual Theme & Atmosphere (Description of the mood, density, and aesthetic philosophy.) ## 2. Color Palette & Roles (List colors by Descriptive Name + Hex Code + Functional Role.) ## 3. Typography Rules (Description of font family, weight usage for headers vs. body, and letter-spacing character.) ## 4. Component Stylings * **Buttons:** (Shape description, color assignment, behavior). * **Cards/Containers:** (Corner roundness description, background color, shadow depth). * **Inputs/Forms:** (Stroke style, background). ## 5. Layout Principles (Description of whitespace strategy, margins, and grid alignment.) ``` ## Usage Example To use this skill for the Furniture Collection project: 1. **Retrieve project information:** ``` Use the Stitch MCP Server to get the Furniture Collection project ``` 2. **Get the Home page screen details:** ``` Retrieve the Home page screen's code, image, and screen object information ``` 3. **Reference best practices:** ``` Review the Stitch Effective Prompting Guide at: https://stitch.withgoogle.com/docs/learn/prompting/ ``` 4. **Analyze and synthesize:** - Extract all relevant design tokens from the screen - Translate technical values into descriptive language - Organize information according to the DESIGN.md structure 5. **Generate the file:** - Create `DESIGN.md` in the project directory - Follow the prescribed format exactly - Ensure all color codes are accurate - Use evocative, designer-friendly language ## Best Practices - **Be Descriptive:** Avoid generic terms like "blue" or "rounded." Use "Ocean-deep Cerulean (#0077B6)" or "Gently curved edges" - **Be Functional:** Always explain what each design element is used for - **Be Consistent:** Use the same terminology throughout the document - **Be Visual:** Help readers visualize the design through your descriptions - **Be Precise:** Include exact values (hex codes, pixel values) in parentheses after natural language descriptions ## Tips for Success 1. **Start with the big picture:** Understand the overall aesthetic before diving into details 2. **Look for patterns:** Identify consistent spacing, sizing, and styling patterns 3. **Think semantically:** Name colors by their purpose, not just their appearance 4. **Consider hierarchy:** Document how visual weight and importance are communicated 5. **Reference the guide:** Use language and patterns from the Stitch Effective Prompting Guide ## Common Pitfalls to Avoid - ❌ Using technical jargon without translation (e.g., "rounded-xl" instead of "generously rounded corners") - ❌ Omitting color codes or using only descriptive names - ❌ Forgetting to explain functional roles of design elements - ❌ Being too vague in atmosphere descriptions - ❌ Ignoring subtle design details like shadows or spacing patterns - plugins/stitch-utilities/skills/enhance-prompt/SKILL.md (6640 bytes)
--- name: enhance-prompt description: Transforms vague UI ideas into polished, Stitch-optimized prompts. Enhances specificity, adds UI/UX keywords, injects design system context, and structures output for better generation results. allowed-tools: - "Read" - "Write" --- # Enhance Prompt for Stitch You are a **Stitch Prompt Engineer**. Your job is to transform rough or vague UI generation ideas into polished, optimized prompts that produce better results from Stitch. ## Prerequisites Before enhancing prompts, consult the official Stitch documentation for the latest best practices: - **Stitch Effective Prompting Guide**: https://stitch.withgoogle.com/docs/learn/prompting/ This guide contains up-to-date recommendations that may supersede or complement the patterns in this skill. ## When to Use This Skill Activate when a user wants to: - Polish a UI prompt before sending to Stitch - Improve a prompt that produced poor results - Add design system consistency to a simple idea - Structure a vague concept into an actionable prompt ## Enhancement Pipeline Follow these steps to enhance any prompt: ### Step 1: Assess the Input Evaluate what's missing from the user's prompt: | Element | Check for | If missing... | |---------|-----------|---------------| | **Platform** | "web", "mobile", "desktop" | Add based on context or ask | | **Page type** | "landing page", "dashboard", "form" | Infer from description | | **Structure** | Numbered sections/components | Create logical page structure | | **Visual style** | Adjectives, mood, vibe | Add appropriate descriptors | | **Colors** | Specific values or roles | Add design system or suggest | | **Components** | UI-specific terms | Translate to proper keywords | ### Step 2: Check for DESIGN.md Look for a `DESIGN.md` file in the current project: **If DESIGN.md exists:** 1. Read the file to extract the design system block 2. Include the color palette, typography, and component styles 3. Format as a "DESIGN SYSTEM (REQUIRED)" section in the output **If DESIGN.md does not exist:** 1. Add this note at the end of the enhanced prompt: ``` --- 💡 **Tip:** For consistent designs across multiple screens, create a DESIGN.md file using the `design-md` skill. This ensures all generated pages share the same visual language. ``` ### Step 3: Apply Enhancements Transform the input using these techniques: #### A. Add UI/UX Keywords Replace vague terms with specific component names: | Vague | Enhanced | |-------|----------| | "menu at the top" | "navigation bar with logo and menu items" | | "button" | "primary call-to-action button" | | "list of items" | "card grid layout" or "vertical list with thumbnails" | | "form" | "form with labeled input fields and submit button" | | "picture area" | "hero section with full-width image" | #### B. Amplify the Vibe Add descriptive adjectives to set the mood: | Basic | Enhanced | |-------|----------| | "modern" | "clean, minimal, with generous whitespace" | | "professional" | "sophisticated, trustworthy, with subtle shadows" | | "fun" | "vibrant, playful, with rounded corners and bold colors" | | "dark mode" | "dark theme with high-contrast accents on deep backgrounds" | #### C. Structure the Page Organize content into numbered sections: ```markdown **Page Structure:** 1. **Header:** Navigation with logo and menu items 2. **Hero Section:** Headline, subtext, and primary CTA 3. **Content Area:** [Describe the main content] 4. **Footer:** Links, social icons, copyright ``` #### D. Format Colors Properly When colors are mentioned, format them as: ``` Descriptive Name (#hexcode) for functional role ``` Examples: - "Deep Ocean Blue (#1a365d) for primary buttons and links" - "Warm Cream (#faf5f0) for page background" - "Soft Gray (#6b7280) for secondary text" ### Step 4: Format the Output Structure the enhanced prompt in this order: ```markdown [One-line description of the page purpose and vibe] **DESIGN SYSTEM (REQUIRED):** - Platform: [Web/Mobile], [Desktop/Mobile]-first - Theme: [Light/Dark], [style descriptors] - Background: [Color description] (#hex) - Primary Accent: [Color description] (#hex) for [role] - Text Primary: [Color description] (#hex) - [Additional design tokens...] **Page Structure:** 1. **[Section]:** [Description] 2. **[Section]:** [Description] ... ``` ## Output Options **Default:** Return the enhanced prompt as text for the user to copy. **Optional file output:** If the user requests, write to a file: - `next-prompt.md` — for use with the `stitch-loop` skill - Custom filename specified by user ## Examples ### Example 1: Vague Input → Structured Prompt **User input:** > "make me a login page" **Enhanced output:** ```markdown A clean, trustworthy login page with a centered form and subtle branding. **DESIGN SYSTEM (REQUIRED):** - Platform: Web, Desktop-first - Theme: Light, minimal, professional - Background: Clean White (#ffffff) - Surface: Soft Gray (#f9fafb) for form card - Primary Accent: Deep Blue (#2563eb) for submit button and links - Text Primary: Near Black (#111827) for headings - Text Secondary: Medium Gray (#6b7280) for labels - Buttons: Subtly rounded (8px), full-width on form - Cards: Gently rounded (12px), soft shadow for elevation **Page Structure:** 1. **Header:** Minimal logo, centered 2. **Login Card:** Centered form with email, password fields, "Forgot password?" link 3. **Submit Button:** Primary blue "Sign In" button 4. **Footer:** "Don't have an account? Sign up" link --- 💡 **Tip:** For consistent designs across multiple screens, create a DESIGN.md file using the `design-md` skill. ``` ### Example 2: Feature Request → Targeted Edit **User input:** > "add a search bar" **Enhanced output:** ```markdown Add a search bar to the header navigation. **Specific changes:** - Location: Header, right side before user avatar - Style: Pill-shaped input with subtle gray background (#f3f4f6) - Icon: Magnifying glass icon on the left, inside the input - Placeholder: "Search..." in light gray (#9ca3af) - Behavior: Expands on focus with subtle shadow - Width: 240px default, 320px on focus **Context:** This is a targeted edit. Make only this change while preserving all existing elements. ``` ## Tips for Best Results 1. **Be specific early** — Vague inputs need more enhancement 2. **Match the user's intent** — Don't over-design if they want simple 3. **Keep it structured** — Numbered sections help Stitch understand hierarchy 4. **Include the design system** — Consistency is key for multi-page projects 5. **One change at a time for edits** — Don't bundle unrelated changes
- plugins/stitch-utilities/skills/site-md/SKILL.md (3133 bytes)
--- name: site-md description: Analyze a project description or site requirements and synthesize a project constitution into SITE.md for the Stitch Build Loop allowed-tools: - "Read" - "Write" - "web_fetch" --- # Stitch SITE.md Skill You are a Lead Product Owner and Architect. Your goal is to analyze project descriptions, requirement briefs, or existing site content and synthesize a project constitution file named `.stitch/SITE.md`. ## Overview This skill helps you initialize and structure `.stitch/SITE.md` files, which act as the "Long-Term Memory" and constitution for the Stitch Build Loop. A properly structured `SITE.md` ensures that coding agents stay aligned on project scope, visual vibes, and navigation flow across successive build iterations. ## Prerequisites - Access to a project requirements brief or description document. - Optionally, the Stitch Project ID if a project has already been initialized in Google Stitch. ## The Goal Generate a `.stitch/SITE.md` file at the root of the project that complies with the official schema. It must cover: 1. Core Identity (Name, Mission, Voice). 2. Visual Language Vibe. 3. Architecture & File Structure. 4. Sitemap (Current and target pages). 5. Roadmap Backlog (High, Medium, Low priority tasks). 6. Creative Freedom Guidelines. ## Guidelines and Structure Analyze the input brief and translate it into the following sections: ### 1. Core Identity - **Project Name**: Extracted from requirements. - **Stitch Project ID**: Use a placeholder `[Stitch Project ID]` or the active ID if provided. - **Mission**: A 1-2 sentence description of what the application/site does. - **Target Audience**: Who the main users are. - **Voice**: Tone adjectives (e.g. professional, playful, clean). ### 2. Visual Language - **Vibe (Adjectives)**: Define a primary, secondary, and tertiary aesthetic keyword matching the project's visual direction. ### 3. Architecture & File Structure - Map out the directory structure. Default to: * Root: `site/public/` * Asset Flow: Stitch generates to `queue/` → Validate → Move to `site/public/` * Navigation Strategy: (e.g., standard header links, shared navigation bar). ### 4. Live Sitemap - Map out the files requested in the brief. Mark completed files as `[x]` and pending/target files as `[ ]`. At initialization, at least `index.html` should be listed. ### 5. The Roadmap (Backlog) - Parse the requirements into concrete development tasks, grouped by priority: - **High Priority**: Core pages, basic layouts, primary user flows. - **Medium Priority**: Interactive features, forms, secondary pages. - **Low Priority**: Enhancements, visual assets, optional states. --- ## Action Plan 1. **Read input requirements**: Locate and read the project description document or text input. 2. **Draft the structure**: Map the project details directly into the `SITE.md` format. 3. **Write the file**: Write the output to `.stitch/SITE.md`. If the `.stitch/` directory does not exist, create it first. 4. **Validate**: Verify that all seven sections of the `SITE.md` template are present and properly formatted.
- plugins/stitch-utilities/skills/stitch-loop/SKILL.md (10328 bytes)
--- name: stitch-loop description: Teaches agents to iteratively build websites using Stitch with an autonomous baton-passing loop pattern allowed-tools: - "stitch*:*" - "chrome*:*" - "Read" - "Write" - "Bash" --- # Stitch Build Loop You are an **autonomous frontend builder** participating in an iterative site-building loop. Your goal is to generate a page using Stitch, integrate it into the site, and prepare instructions for the next iteration. ## Overview The Build Loop pattern enables continuous, autonomous website development through a "baton" system. Each iteration: 1. Reads the current task from a baton file (`.stitch/next-prompt.md`) 2. Generates a page using Stitch MCP tools 3. Integrates the page into the site structure 4. Writes the next task to the baton file for the next iteration ## Prerequisites **Required:** - Access to the Stitch MCP Server - A Stitch project (existing or will be created) - A `.stitch/DESIGN.md` file (generate one using the `design-md` skill if needed) - A `.stitch/SITE.md` file documenting the site vision and roadmap **Optional:** - Chrome DevTools MCP Server — enables visual verification of generated pages ## The Baton System The `.stitch/next-prompt.md` file acts as a relay baton between iterations: ```markdown --- page: about --- A page describing how jules.top tracking works. **DESIGN SYSTEM (REQUIRED):** [Copy from .stitch/DESIGN.md Section 6] **Page Structure:** 1. Header with navigation 2. Explanation of tracking methodology 3. Footer with links ``` **Critical rules:** - The `page` field in YAML frontmatter determines the output filename - The prompt content must include the design system block from `.stitch/DESIGN.md` - You MUST update this file before completing your work to continue the loop ## Execution Protocol ### Step 1: Read the Baton Parse `.stitch/next-prompt.md` to extract: - **Page name** from the `page` frontmatter field - **Prompt content** from the markdown body ### Step 2: Consult Context Files Before generating, read these files: | File | Purpose | |------|---------| | `.stitch/SITE.md` | Site vision, **Stitch Project ID**, existing pages (sitemap), roadmap | | `.stitch/DESIGN.md` | Required visual style for Stitch prompts | **Important checks:** - Section 4 (Sitemap) — Do NOT recreate pages that already exist - Section 5 (Roadmap) — Pick tasks from here if backlog exists - Section 6 (Creative Freedom) — Ideas for new pages if roadmap is empty ### Step 3: Generate with Stitch Use the Stitch MCP tools to generate the page: 1. **Discover namespace**: Run `list_tools` to find the Stitch MCP prefix 2. **Get or create project**: - If `.stitch/metadata.json` exists, use the `projectId` from it - Otherwise, call `[prefix]:create_project`, then call `[prefix]:get_project` to retrieve full project details, and save them to `.stitch/metadata.json` (see schema below) - After generating each screen, call `[prefix]:get_project` again and update the `screens` map in `.stitch/metadata.json` with each screen's full metadata (id, sourceScreen, dimensions, canvas position) 3. **Generate screen**: Call `[prefix]:generate_screen_from_text` with: - `projectId`: The project ID - `prompt`: The full prompt from the baton (including design system block) - `deviceType`: `DESKTOP` (or as specified) 4. **Retrieve assets**: Before downloading, check if `.stitch/designs/{page}.html` and `.stitch/designs/{page}.png` already exist: - **If files exist**: Ask the user whether to refresh the designs from the Stitch project or reuse the existing local files. Only re-download if the user confirms. - **If files do not exist**: Proceed with download: - `htmlCode.downloadUrl` — Download and save as `.stitch/designs/{page}.html` - `screenshot.downloadUrl` — Append `=w{width}` to the URL before downloading, where `{width}` is the `width` value from the screen metadata (Google CDN serves low-res thumbnails by default). Save as `.stitch/designs/{page}.png` ### Step 4: Integrate into Site 1. Move generated HTML from `.stitch/designs/{page}.html` to `site/public/{page}.html` 2. Fix any asset paths to be relative to the public folder 3. Update navigation: - Find existing placeholder links (e.g., `href="#"`) and wire them to the new page - Add the new page to the global navigation if appropriate 4. Ensure consistent headers/footers across all pages ### Step 4.5: Visual Verification (Optional) If the **Chrome DevTools MCP Server** is available, verify the generated page: 1. **Check availability**: Run `list_tools` to see if `chrome*` tools are present 2. **Start dev server**: Use Bash to start a local server (e.g., `npx serve site/public`) 3. **Navigate to page**: Call `[chrome_prefix]:navigate` to open `http://localhost:3000/{page}.html` 4. **Capture screenshot**: Call `[chrome_prefix]:screenshot` to capture the rendered page 5. **Visual comparison**: Compare against the Stitch screenshot (`.stitch/designs/{page}.png`) for fidelity 6. **Stop server**: Terminate the dev server process > **Note:** This step is optional. If Chrome DevTools MCP is not installed, skip to Step 5. ### Step 5: Update Site Documentation Modify `.stitch/SITE.md`: - Add the new page to Section 4 (Sitemap) with `[x]` - Remove any idea you consumed from Section 6 (Creative Freedom) - Update Section 5 (Roadmap) if you completed a backlog item ### Step 6: Prepare the Next Baton (Critical) **You MUST update `.stitch/next-prompt.md` before completing.** This keeps the loop alive. 1. **Decide the next page**: - Check `.stitch/SITE.md` Section 5 (Roadmap) for pending items - If empty, pick from Section 6 (Creative Freedom) - Or invent something new that fits the site vision 2. **Write the baton** with proper YAML frontmatter: ```markdown --- page: achievements --- A competitive achievements page showing developer badges and milestones. **DESIGN SYSTEM (REQUIRED):** [Copy the entire design system block from .stitch/DESIGN.md] **Page Structure:** 1. Header with title and navigation 2. Badge grid showing unlocked/locked states 3. Progress bars for milestone tracking ``` ## File Structure Reference ``` project/ ├── .stitch/ │ ├── metadata.json # Stitch project & screen IDs (persist this!) │ ├── DESIGN.md # Visual design system (from design-md skill) │ ├── SITE.md # Site vision, sitemap, roadmap │ ├── next-prompt.md # The baton — current task │ └── designs/ # Staging area for Stitch output │ ├── {page}.html │ └── {page}.png └── site/public/ # Production pages ├── index.html └── {page}.html ``` ### `.stitch/metadata.json` Schema This file persists all Stitch identifiers so future iterations can reference them for edits or variants. Populate it by calling `[prefix]:get_project` after creating a project or generating screens. ```json { "name": "projects/6139132077804554844", "projectId": "6139132077804554844", "title": "My App", "visibility": "PRIVATE", "createTime": "2026-03-04T23:11:25.514932Z", "updateTime": "2026-03-04T23:34:40.400007Z", "projectType": "PROJECT_DESIGN", "origin": "STITCH", "deviceType": "MOBILE", "designTheme": { "colorMode": "DARK", "font": "INTER", "roundness": "ROUND_EIGHT", "customColor": "#40baf7", "saturation": 3 }, "screens": { "index": { "id": "d7237c7d78f44befa4f60afb17c818c1", "sourceScreen": "projects/6139132077804554844/screens/d7237c7d78f44befa4f60afb17c818c1", "x": 0, "y": 0, "width": 390, "height": 1249 }, "about": { "id": "bf6a3fe5c75348e58cf21fc7a9ddeafb", "sourceScreen": "projects/6139132077804554844/screens/bf6a3fe5c75348e58cf21fc7a9ddeafb", "x": 549, "y": 0, "width": 390, "height": 1159 } }, "metadata": { "userRole": "OWNER" } } ``` | Field | Description | |-------|-------------| | `name` | Full resource name (`projects/{id}`) | | `projectId` | Stitch project ID (from `create_project` or `get_project`) | | `title` | Human-readable project title | | `designTheme` | Design system tokens: color mode, font, roundness, custom color, saturation | | `deviceType` | Target device: `MOBILE`, `DESKTOP`, `TABLET` | | `screens` | Map of page name → screen object. Each screen includes `id`, `sourceScreen` (resource path for MCP calls), canvas position (`x`, `y`), and dimensions (`width`, `height`) | | `metadata.userRole` | User's role on the project (`OWNER`, `EDITOR`, `VIEWER`) | ## Orchestration Options The loop can be driven by different orchestration layers: | Method | How it works | |--------|--------------| | **CI/CD** | GitHub Actions triggers on `.stitch/next-prompt.md` changes | | **Human-in-loop** | Developer reviews each iteration before continuing | | **Agent chains** | One agent dispatches to another (e.g., Jules API) | | **Manual** | Developer runs the agent repeatedly with the same repo | The skill is orchestration-agnostic — focus on the pattern, not the trigger mechanism. ## Design System Integration This skill works best with the `design-md` skill: 1. **First time setup**: Generate `.stitch/DESIGN.md` using the `design-md` skill from an existing Stitch screen 2. **Every iteration**: Copy Section 6 ("Design System Notes for Stitch Generation") into your baton prompt 3. **Consistency**: All generated pages will share the same visual language ## Common Pitfalls - ❌ Forgetting to update `.stitch/next-prompt.md` (breaks the loop) - ❌ Recreating a page that already exists in the sitemap - ❌ Not including the design system block from `.stitch/DESIGN.md` in the prompt - ❌ Leaving placeholder links (`href="#"`) instead of wiring real navigation - ❌ Forgetting to persist `.stitch/metadata.json` after creating a new project ## Troubleshooting | Issue | Solution | |-------|----------| | Stitch generation fails | Check that the prompt includes the design system block | | Inconsistent styles | Ensure `.stitch/DESIGN.md` is up-to-date and copied correctly | | Loop stalls | Verify `.stitch/next-prompt.md` was updated with valid frontmatter | | Navigation broken | Check all internal links use correct relative paths | - plugins/stitch-utilities/skills/taste-design/SKILL.md (12568 bytes)
--- name: taste-design description: Semantic Design System Skill for Google Stitch. Generates agent-friendly DESIGN.md files that enforce premium, anti-generic UI standards — strict typography, calibrated color, asymmetric layouts, perpetual micro-motion, and hardware-accelerated performance. allowed-tools: - "StitchMCP" - "Read" - "Write" --- # Stitch Design Taste — Semantic Design System Skill ## Overview This skill generates `DESIGN.md` files optimized for Google Stitch screen generation. It translates the battle-tested anti-slop frontend engineering directives into Stitch's native semantic design language — descriptive, natural-language rules paired with precise values that Stitch's AI agent can interpret to produce premium, non-generic interfaces. The generated `DESIGN.md` serves as the **single source of truth** for prompting Stitch to generate new screens that align with a curated, high-agency design language. Stitch interprets design through **"Visual Descriptions"** supported by specific color values, typography specs, and component behaviors. ## Prerequisites - Access to Google Stitch via [labs.google.com/stitch](https://labs.google.com/stitch) - Optionally: Stitch MCP Server for programmatic integration with Cursor, Antigravity, or Gemini CLI ## The Goal Generate a `DESIGN.md` file that encodes: 1. **Visual atmosphere** — the mood, density, and design philosophy 2. **Color calibration** — neutrals, accents, and banned patterns with hex codes 3. **Typographic architecture** — font stacks, scale hierarchy, and anti-patterns 4. **Component behaviors** — buttons, cards, inputs with interaction states 5. **Layout principles** — grid systems, spacing philosophy, responsive strategy 6. **Motion philosophy** — animation engine specs, spring physics, perpetual micro-interactions 7. **Anti-patterns** — explicit list of banned AI design clichés ## Analysis & Synthesis Instructions ### 1. Define the Atmosphere Evaluate the target project's intent. Use evocative adjectives from the taste spectrum: - **Density:** "Art Gallery Airy" (1–3) → "Daily App Balanced" (4–7) → "Cockpit Dense" (8–10) - **Variance:** "Predictable Symmetric" (1–3) → "Offset Asymmetric" (4–7) → "Artsy Chaotic" (8–10) - **Motion:** "Static Restrained" (1–3) → "Fluid CSS" (4–7) → "Cinematic Choreography" (8–10) Default baseline: Creativity 9, Variance 8, Motion 6, Density 5. Adapt dynamically based on user's vibe description. ### 2. Map the Color Palette For each color provide: **Descriptive Name** + **Hex Code** + **Functional Role**. **Mandatory constraints:** - Maximum 1 accent color. Saturation below 80% - The "AI Purple/Blue Neon" aesthetic is strictly BANNED — no purple button glows, no neon gradients - Use absolute neutral bases (Zinc/Slate) with high-contrast singular accents - Stick to one palette for the entire output — no warm/cool gray fluctuation - Never use pure black (`#000000`) — use Off-Black, Zinc-950, or Charcoal ### 3. Establish Typography Rules - **Display/Headlines:** Track-tight, controlled scale. Not screaming. Hierarchy through weight and color, not just massive size - **Body:** Relaxed leading, max 65 characters per line - **Font Selection:** `Inter` is BANNED for premium/creative contexts. Force unique character: `Geist`, `Outfit`, `Cabinet Grotesk`, or `Satoshi` - **Serif Ban:** Generic serif fonts (`Times New Roman`, `Georgia`, `Garamond`, `Palatino`) are BANNED. If serif is needed for editorial/creative contexts, use only distinctive modern serifs: `Fraunces`, `Gambarino`, `Editorial New`, or `Instrument Serif`. Serif is always BANNED in dashboards or software UIs - **Dashboard Constraint:** Use Sans-Serif pairings exclusively (`Geist` + `Geist Mono` or `Satoshi` + `JetBrains Mono`) - **High-Density Override:** When density exceeds 7, all numbers must use Monospace ### 4. Define the Hero Section The Hero is the first impression and must be creative, striking, and never generic: - **Inline Image Typography:** Embed small, contextual photos or visuals directly between words or letters in the headline. Images sit inline at type-height, rounded, acting as visual punctuation. This is the signature creative technique - **No Overlapping:** Text must never overlap images or other text. Every element occupies its own clean spatial zone - **No Filler Text:** "Scroll to explore", "Swipe down", scroll arrow icons, bouncing chevrons are BANNED. The content should pull users in naturally - **Asymmetric Structure:** Centered Hero layouts BANNED when variance exceeds 4 - **CTA Restraint:** Maximum one primary CTA. No secondary "Learn more" links ### 5. Describe Component Stylings For each component type, describe shape, color, shadow depth, and interaction behavior: - **Buttons:** Tactile push feedback on active state. No neon outer glows. No custom mouse cursors - **Cards:** Use ONLY when elevation communicates hierarchy. Tint shadows to background hue. For high-density layouts, replace cards with border-top dividers or negative space - **Inputs/Forms:** Label above input, helper text optional, error text below. Standard gap spacing - **Loading States:** Skeletal loaders matching layout dimensions — no generic circular spinners - **Empty States:** Composed compositions indicating how to populate data - **Error States:** Clear, inline error reporting ### 6. Define Layout Principles - No overlapping elements — every element occupies its own clear spatial zone. No absolute-positioned content stacking - Centered Hero sections are BANNED when variance exceeds 4 — force Split Screen, Left-Aligned, or Asymmetric Whitespace - The generic "3 equal cards horizontally" feature row is BANNED — use 2-column Zig-Zag, asymmetric grid, or horizontal scroll - CSS Grid over Flexbox math — never use `calc()` percentage hacks - Contain layouts using max-width constraints (e.g., 1400px centered) - Full-height sections must use `min-h-[100dvh]` — never `h-screen` (iOS Safari catastrophic jump) ### 7. Define Responsive Rules Every design must work across all viewports: - **Mobile-First Collapse (< 768px):** All multi-column layouts collapse to single column. No exceptions - **No Horizontal Scroll:** Horizontal overflow on mobile is a critical failure - **Typography Scaling:** Headlines scale via `clamp()`. Body text minimum `1rem`/`14px` - **Touch Targets:** All interactive elements minimum `44px` tap target - **Image Behavior:** Inline typography images (photos between words) stack below headline on mobile - **Navigation:** Desktop horizontal nav collapses to clean mobile menu - **Spacing:** Vertical section gaps reduce proportionally (`clamp(3rem, 8vw, 6rem)`) ### 8. Encode Motion Philosophy - **Spring Physics default:** `stiffness: 100, damping: 20` — premium, weighty feel. No linear easing - **Perpetual Micro-Interactions:** Every active component should have an infinite loop state (Pulse, Typewriter, Float, Shimmer) - **Staggered Orchestration:** Never mount lists instantly — use cascade delays for waterfall reveals - **Performance:** Animate exclusively via `transform` and `opacity`. Never animate `top`, `left`, `width`, `height`. Grain/noise filters on fixed pseudo-elements only ### 9. List Anti-Patterns (AI Tells) Encode these as explicit "NEVER DO" rules in the DESIGN.md: - No emojis anywhere - No `Inter` font - No generic serif fonts (`Times New Roman`, `Georgia`, `Garamond`) — distinctive modern serifs only if needed - No pure black (`#000000`) - No neon/outer glow shadows - No oversaturated accents - No excessive gradient text on large headers - No custom mouse cursors - No overlapping elements — clean spatial separation always - No 3-column equal card layouts - No generic names ("John Doe", "Acme", "Nexus") - No fake round numbers (`99.99%`, `50%`) - No fabricated data or statistics — never generate metrics, performance numbers, uptime percentages, response times, or any data that the user did not explicitly provide. "99.98% UPTIME SLA", "124ms AVG. RESPONSE", "18.5k DEPLOY CYCLES" are invented AI filler. If real data is not available, use clear placeholder labels like `[metric]` instead of making up numbers - No fake system/metric sections — "SYSTEM PERFORMANCE METRICS", "KEY STATISTICS", "BY THE NUMBERS" dashboard cards filled with invented data are BANNED - No `LABEL // YEAR` formatting — "SYSTEM // 2024", "METRICS // 2025" is a lazy AI convention, not real design typography - No AI copywriting clichés ("Elevate", "Seamless", "Unleash", "Next-Gen") - No filler UI text: "Scroll to explore", "Swipe down", scroll arrows, bouncing chevrons - No broken Unsplash links — use `picsum.photos` or SVG avatars - No centered Hero sections (for high-variance projects) ## Output Format (DESIGN.md Structure) ```markdown # Design System: [Project Title] ## 1. Visual Theme & Atmosphere (Evocative description of the mood, density, variance, and motion intensity. Example: "A restrained, gallery-airy interface with confident asymmetric layouts and fluid spring-physics motion. The atmosphere is clinical yet warm — like a well-lit architecture studio.") ## 2. Color Palette & Roles - **Canvas White** (#F9FAFB) — Primary background surface - **Pure Surface** (#FFFFFF) — Card and container fill - **Charcoal Ink** (#18181B) — Primary text, Zinc-950 depth - **Muted Steel** (#71717A) — Secondary text, descriptions, metadata - **Whisper Border** (rgba(226,232,240,0.5)) — Card borders, 1px structural lines - **[Accent Name]** (#XXXXXX) — Single accent for CTAs, active states, focus rings (Max 1 accent. Saturation < 80%. No purple/neon.) ## 3. Typography Rules - **Display:** [Font Name] — Track-tight, controlled scale, weight-driven hierarchy - **Body:** [Font Name] — Relaxed leading, 65ch max-width, neutral secondary color - **Mono:** [Font Name] — For code, metadata, timestamps, high-density numbers - **Banned:** Inter, generic system fonts for premium contexts. Serif fonts banned in dashboards. ## 4. Component Stylings * **Buttons:** Flat, no outer glow. Tactile -1px translate on active. Accent fill for primary, ghost/outline for secondary. * **Cards:** Generously rounded corners (2.5rem). Diffused whisper shadow. Used only when elevation serves hierarchy. High-density: replace with border-top dividers. * **Inputs:** Label above, error below. Focus ring in accent color. No floating labels. * **Loaders:** Skeletal shimmer matching exact layout dimensions. No circular spinners. * **Empty States:** Composed, illustrated compositions — not just "No data" text. ## 5. Layout Principles (Grid-first responsive architecture. Asymmetric splits for Hero sections. Strict single-column collapse below 768px. Max-width containment. No flexbox percentage math. Generous internal padding.) ## 6. Motion & Interaction (Spring physics for all interactive elements. Staggered cascade reveals. Perpetual micro-loops on active dashboard components. Hardware-accelerated transforms only. Isolated Client Components for CPU-heavy animations.) ## 7. Anti-Patterns (Banned) (Explicit list of forbidden patterns: no emojis, no Inter, no pure black, no neon glows, no 3-column equal grids, no AI copywriting clichés, no generic placeholder names, no broken image links.) ``` ## Best Practices - **Be Descriptive:** "Deep Charcoal Ink (#18181B)" — not just "dark text" - **Be Functional:** Explain what each element is used for - **Be Consistent:** Same terminology throughout the document - **Be Precise:** Include exact hex codes, rem values, pixel values in parentheses - **Be Opinionated:** This is not a neutral template — it enforces a specific, premium aesthetic ## Tips for Success 1. Start with the atmosphere — understand the vibe before detailing tokens 2. Look for patterns — identify consistent spacing, sizing, and styling 3. Think semantically — name colors by purpose, not just appearance 4. Consider hierarchy — document how visual weight communicates importance 5. Encode the bans — anti-patterns are as important as the rules themselves ## Common Pitfalls to Avoid - Using technical jargon without translation ("rounded-xl" instead of "generously rounded corners") - Omitting hex codes or using only descriptive names - Forgetting functional roles of design elements - Being too vague in atmosphere descriptions - Ignoring the anti-pattern list — these are what make the output premium - Defaulting to generic "safe" designs instead of enforcing the curated aesthetic - README.md (11076 bytes)
# Stitch Design Skills A collection of agent skills and plugins for [Google Stitch](https://stitch.withgoogle.com), following the [Agent Skills](https://agentskills.io) open standard. Compatible with coding agents such as Codex, Antigravity, Gemini CLI, Claude Code, Cursor, and OpenCode (manual install). ## Quick Start ### 1. Install Plugins (Recommended) The fastest way to set up the full Stitch plugin suite globally. #### Codex Add the Stitch Skills marketplace, then install the plugins you need. <details open> <summary><strong>Via CLI</strong> (recommended)</summary> ```bash codex plugin marketplace add google-labs-code/stitch-skills --ref main \ --sparse .agents/plugins \ --sparse plugins/stitch-design \ --sparse plugins/stitch-build \ --sparse plugins/stitch-utilities ``` > [!TIP] > The `--sparse` flags are optional — they limit the checkout to only the > listed paths for a faster clone. Omit them to pull the entire repository. </details> <details> <summary><strong>Via the Codex UI</strong></summary> Navigate to **Settings → Plugin Marketplaces → Add** and fill in: | Field | Value | |---|---| | **Source** | `https://github.com/google-labs-code/stitch-skills` | | **Git ref** | `main` | | **Sparse paths** | *(optional)* `.agents/plugins`, `plugins/stitch-design`, `plugins/stitch-build`, `plugins/stitch-utilities` | </details> Once the marketplace is registered, install any combination of: - **`stitch-design`** — design-focused skills - **`stitch-build`** — build and component skills - **`stitch-utilities`** — utility and helper skills #### Claude Code & Cursor ```bash # Claude Code — installs into the current project npx plugins add google-labs-code/stitch-skills --scope project --target claude-code ``` ```bash # Cursor — installs into the current workspace npx plugins add google-labs-code/stitch-skills --scope workspace --target cursor ``` #### OpenCode OpenCode does **not** use `npx plugins` / `npx skills` or the Codex/Claude marketplace layout. Install skills and the Stitch MCP server manually: **1. Skills** — copy the skill folders you need into a discoverable path: ```bash # Project-local (recommended) mkdir -p .opencode/skills cp -R plugins/stitch-design/skills/generate-design .opencode/skills/generate-design # repeat for other skills under plugins/*/skills/ ``` OpenCode also discovers `.claude/skills/` and `.agents/skills/` (see [OpenCode skills docs](https://opencode.ai/docs/skills/)). > **Naming:** OpenCode requires skill `name` frontmatter to be lowercase kebab-case and match the directory name. Skills that use `stitch::…` names (or other non-kebab forms) need the `name` field and folder renamed before OpenCode will load them. Extra frontmatter such as `allowed-tools` is ignored. **2. Stitch MCP** — add a remote MCP entry in project `opencode.json` or `~/.config/opencode/opencode.json` after completing the [Stitch MCP setup](https://stitch.withgoogle.com/docs/mcp/setup/): ```json { "$schema": "https://opencode.ai/config.json", "mcp": { "stitch": { "type": "remote", "url": "YOUR_STITCH_MCP_URL", "enabled": true } } } ``` Replace `YOUR_STITCH_MCP_URL` with the endpoint from the Stitch MCP setup flow (credentials/env vars from that guide still apply). Tool names inside skill instructions may differ from OpenCode builtins (`webfetch` / `bash` instead of `web_fetch` / `run_command`). Prefer the OpenCode tool names when adapting a skill for OpenCode. ### 2. Install Skills Selectively Choose only the specific skills you need. > [!IMPORTANT] > Stitch Design Skills often have inter-dependencies. If you choose to install skills selectively, ensure you include all required dependencies. ```bash npx skills add google-labs-code/stitch-skills ``` You can run the following commands to see the help documentation for plugins and skills: ```bash npx plugins --help npx skills --help ``` ## Prerequisites These skills require the **Stitch MCP** server to be configured and running in your agent's environment. Make sure you have followed the [Stitch MCP Setup Instructions](https://stitch.withgoogle.com/docs/mcp/setup/) to register the server and set up appropriate environment variables and credentials. > **Docs navigation:** If a link on [stitch.withgoogle.com/docs](https://stitch.withgoogle.com/docs/) redirects incorrectly, open the target path under the same host (e.g. `https://stitch.withgoogle.com/docs/learn/device-types/`). ## Available Plugins ### Design (`stitch-design`) Core design workflows for creating, managing, and optimizing designs within Stitch. | Skill | Description | Prompt Example | |---|---|---| | [stitch::code-to-design](plugins/stitch-design/skills/code-to-design/) | Convert frontend code (React, Vue, etc.) to a Stitch Design via HTML extraction + design system + upload | *"Upload the frontend code at `/path/to/dashboard` into a Stitch project named 'Dashboard-Migration-2026'."* | | [stitch::generate-design](plugins/stitch-design/skills/generate-design/) | Generate new screens from text or images, edit existing screens, and create design variants | · *"Make a browse tab for a mobile app for romance and date night ideas."*<br>· *"Edit the login screen to add a 'Remember Me' checkbox and change the button color to blue."*<br>· *"Generate 3 design variants of the home screen with dark mode and high-density layouts."* | | [stitch::manage-design-system](plugins/stitch-design/skills/manage-design-system/) | Manage design systems in Stitch — upload DESIGN.md and apply themes to screens | *"Upload our design system from `.stitch/DESIGN.md` and apply it to all screens."* | | [stitch::extract-design-md](plugins/stitch-design/skills/extract-design-md/) | Extract a comprehensive DESIGN.md directly from frontend source code | *"Scan `/src` and extract the design system into `.stitch/DESIGN.md`."* | | [stitch::extract-static-html](plugins/stitch-design/skills/extract-static-html/) | Extract self-contained static HTML from running web apps, inlining CSS and images | *"Extract a static HTML snapshot of `http://localhost:3000/profile`."* | | [stitch::upload-to-stitch](plugins/stitch-design/skills/upload-to-stitch/) | Upload local assets (images, mockups, HTML) to a Stitch project | *"Upload `.stitch/landing_page.html` to Stitch project `projects/987654321`."* | --- ### Build (`stitch-build`) Code generation, framework integration, and asset compilation from Stitch designs. | Skill | Description | Prompt Example | |---|---|---| | [stitch::react-components](plugins/stitch-build/skills/react-components/) | Convert Stitch screens to React component systems with automated validation and design token consistency | · *"Convert all screens in Stitch project `projects/123` to React components."*<br>· *"Sync the app to the last updates of the Stitch project `13039335308618232534`."* | | [stitch::react-native](plugins/stitch-build/skills/react-native/) | Convert Stitch HTML designs to production-ready React Native components with StyleSheet and platform-specific code | · *"Convert the Stitch design to React Native components with proper theme and navigation."*<br>· *"Sync the app to the last updates of the Stitch project `13039335308618232534`."* | | [remotion](plugins/stitch-build/skills/remotion/) | Generate walkthrough videos from Stitch projects using Remotion with smooth transitions and zooming | *"Generate a walkthrough video of the Stitch project `projects/456`."* | | [shadcn-ui](plugins/stitch-build/skills/shadcn-ui/) | Expert guidance for integrating and building applications with shadcn/ui components | *"Set up shadcn/ui and build a data table with sorting and filtering."* | | [react-vite-dashboard](plugins/stitch-build/skills/react-vite-dashboard/) | Convert Stitch screens to React + Vite dashboards with TanStack Query, DESIGN.md tokens, and Web3 read patterns | *"Build a DeFi portfolio dashboard from this Stitch screen using our DESIGN.md."* | --- ### Utilities (`stitch-utilities`) Supporting tools for enhancing prompts, generating design specs, and enforcing design standards. | Skill | Description | Prompt Example | |---|---|---| | [design-md](plugins/stitch-utilities/skills/design-md/) | Analyze Stitch projects and generate comprehensive DESIGN.md files in semantic language | *"Analyze Stitch project `projects/123` and generate a DESIGN.md."* | | [enhance-prompt](plugins/stitch-utilities/skills/enhance-prompt/) | Transform vague UI ideas into polished, Stitch-optimized prompts with UI/UX keywords | *"Enhance this prompt: 'make a settings page'."* | | [stitch-loop](plugins/stitch-utilities/skills/stitch-loop/) | Generate complete multi-page websites from a single prompt with automated validation | *"Build a 5-page portfolio website with Stitch."* | | [taste-design](plugins/stitch-utilities/skills/taste-design/) | Generate DESIGN.md files enforcing premium, anti-generic UI standards | *"Generate a premium DESIGN.md with strict typography and calibrated colors."* | ## Repository Structure ```text plugins/ ├── stitch-design/ — Core design workflow plugin │ ├── plugin.json │ └── skills/ │ ├── code-to-design/ │ ├── generate-design/ │ ├── manage-design-system/ │ ├── extract-design-md/ │ ├── extract-static-html/ │ └── upload-to-stitch/ ├── stitch-build/ — Code generation & build plugin │ ├── plugin.json │ └── skills/ │ ├── react-components/ — stitch::react-components │ ├── react-native/ │ ├── react-vite-dashboard/ │ ├── remotion/ │ └── shadcn-ui/ └── stitch-utilities/ — Design utilities & assistants plugin ├── plugin.json └── skills/ ├── design-md/ ├── enhance-prompt/ ├── stitch-loop/ └── taste-design/ ``` Each skill follows the Agent Skills standard: ```text skills/<skill-name>/ ├── SKILL.md — The "Mission Control" for the agent ├── scripts/ — Executable enforcers (Validation & Networking) ├── resources/ — The knowledge base (Checklists & Style Guides) └── examples/ — The "Gold Standard" syntactically valid references ``` ## Adding New Skills All new skills need to follow the file structure above to implement the Agent Skills open standard. ### Great candidates for new skills * **Validation**: Skills that convert Stitch HTML to other UI frameworks and validate the syntax. * **Decoupling Data**: Skills that convert static design content into external mock data files. * **Generate Designs**: Skills that generate new design screens in Stitch from a given set of data. This is not an officially supported Google product. This project is not eligible for the [Google Open Source Software Vulnerability Rewards Program](https://bughunters.google.com/open-source-security). - SKILL.md (8769 bytes)
--- name: stitch::react-components description: >- Converts Stitch designs into modular Vite and React components, or syncs/updates existing React components to align with the latest Stitch designs, using system-level networking and AST-based validation. allowed-tools: - "stitch*:*" - "Bash" - "Read" - "Write" - "web_fetch" --- # Stitch to React Components You are a frontend engineer focused on transforming designs into clean React code or syncing/updating existing React components to align with the latest Stitch designs. You follow a modular approach and use automated tools to ensure code quality. > **CRITICAL: Every step in this skill is MANDATORY. Do NOT skip any step or take shortcuts. Each section contains a GATE that must be satisfied before proceeding.** ## Phase 1: Retrieval and networking > **GATE: Phase 1 is complete ONLY when all screens have been downloaded via `scripts/fetch-stitch.sh` AND visually audited. Reading local files directly without going through this phase is PROHIBITED.** 1. **Namespace discovery**: Run `list_tools` to find the Stitch MCP prefix. Use this prefix (e.g., `stitch:`) for all subsequent calls. 2. **Metadata fetch**: Call `[prefix]:get_screen` for **EVERY screen** in the project to retrieve the design JSON with download URLs. Do NOT skip any screen. 3. **Check for existing designs**: Before downloading, check if `.stitch/designs/{page}.html` and `.stitch/designs/{page}.png` already exist: - **If files exist**: Ask the user whether to refresh the designs from the Stitch project using the MCP, or reuse the existing local files. **You MUST ask — do not assume.** Only re-download if the user confirms. - **If files do not exist**: Proceed to step 4. 4. **High-reliability download**: Internal AI fetch tools can fail on Google Cloud Storage domains. You MUST use the provided script. - **HTML**: `bash scripts/fetch-stitch.sh "[htmlCode.downloadUrl]" ".stitch/designs/{page}.html"` - **Screenshot**: Append `=w{width}` to the screenshot URL first, where `{width}` is the `width` value from the screen metadata (Google CDN serves low-res thumbnails by default). Then run: `bash scripts/fetch-stitch.sh "[screenshot.downloadUrl]=w{width}" ".stitch/designs/{page}.png"` - This script handles the necessary redirects and security handshakes. 5. **Visual audit**: Review the downloaded screenshot (`.stitch/designs/{page}.png`) to confirm design intent and layout details. **You MUST view each screenshot** — do not proceed based on assumptions about the design. 6. **Project metadata tracking**: Retrieve project configuration using `[prefix]:get_project` and save it to `.stitch/metadata.json` (inside the app folder, and mirrored in the workspace root). Ensure it has: - `projectId`, `title`, `deviceType` - A `Last Sync Time` field matching the current sync ISO execution time - A `screens` map detailing each screen's ID, label, sourceScreen reference, dimensions, and canvasPosition. ### Anti-patterns for Phase 1 - ❌ Reading `.stitch/designs/*.html` directly without calling MCP `get_screen` first. - ❌ Skipping the `fetch-stitch.sh` download script. - ❌ Not asking the user when existing files are found. - ❌ Skipping the visual audit of `.png` screenshots. - ❌ Failing to generate or update `.stitch/metadata.json` and its `Last Sync Time` field upon syncing. ## Phase 2: Style extraction > **GATE: Phase 2 is complete ONLY when `resources/style-guide.json` has been updated with tokens extracted from the current project's HTML `<head>`. Tokens from a previous project are NOT acceptable.** 1. **Extract `tailwind.config`**: Open each downloaded HTML file and locate the `tailwind.config` object in the `<head>` `<script>` block. Extract: - All color tokens - Font families - Spacing values - Border radius values - Font size/typography tokens 2. **Sync `resources/style-guide.json`**: Overwrite the file with the extracted tokens from THIS project. The style guide MUST match the Stitch project being converted. 3. **Verify sync**: Confirm the primary color, font families, and spacing in the updated `style-guide.json` match what you extracted. ### Anti-patterns for Phase 2 - ❌ Using `style-guide.json` as-is without verifying it matches the current project. - ❌ Using hardcoded hex values in components instead of theme-mapped classes. ## Phase 3: Architectural rules > **GATE: Every component MUST satisfy ALL of the following rules. Violations will cause `npm run validate` to fail.** * **Modular components**: Break the design into independent files. **Each reusable UI pattern** (cards, badges, pagination, search bars) MUST be extracted into its own component in `src/components/`. Monolithic page files that contain everything are PROHIBITED. * **Logic isolation**: Move event handlers and business logic into custom hooks in `src/hooks/`. Examples: pagination logic → `usePagination`, filtering → `useFilter`. * **Data decoupling**: Move ALL static text, image URLs, and lists into `src/data/mockData.ts`. No hardcoded content in components. * **Type safety**: EVERY component file (including pages) MUST include a `Readonly` TypeScript interface named `[ComponentName]Props`. The validator checks for this — files without a Props interface will FAIL validation. * **Project specific**: Focus on the target project's needs and constraints. Leave Google license headers out of the generated React components. * **Navigation wiring**: Stitch screens are standalone pages with `href="#"` placeholder links. When building a multi-page React app: * Replace ALL `href="#"` anchors with React Router `<Link>` components pointing to the correct routes. * **Always make the app logo/title in the TopAppBar a `<Link to="/">`** so users can navigate home from any page. This is critical because Stitch bottom nav bars use `md:hidden` and are invisible on desktop — without a clickable logo, desktop users have no way to return to the home page. * Wire the bottom nav items and sidebar nav items to their corresponding routes using `<Link>` with active-state highlighting based on `useLocation()`. * **Style mapping**: Use theme-mapped Tailwind classes from the synced `style-guide.json`. No arbitrary hex codes. * **Dark mode**: Apply `dark:` variants to ALL color classes throughout every component. ### Anti-patterns for Phase 3 - ❌ Putting all UI in a single monolithic page file. - ❌ Inline event handlers or business logic without hooks. - ❌ Hardcoding text, URLs, or data in component files. - ❌ Components without a `[Name]Props` interface. - ❌ Using hex color values instead of theme tokens. - ❌ Leaving `href="#"` links unconverted. ## Phase 4: Execution steps > **GATE: Phase 4 verification, audits, and validation checks are optional. You MUST ask the user's permission to proceed with validation scripts, running local dev servers, or automated browser testing.** 1. **Environment setup**: If `node_modules` is missing, run `npm install` to enable the validation tools. 2. **Data layer**: Create `src/data/mockData.ts` based on the design content. 3. **Component drafting**: Use `resources/component-template.tsx` as a base. Find and replace ALL instances of `StitchComponent` with the actual name of the component you are creating. 4. **Application wiring**: Update the project entry point (like `App.tsx`) to render the new components. 5. **Quality check (Optional - Ask User first)**: * Run `npm run validate <file_path>` for **EVERY** `.tsx` file in `src/components/` and `src/pages/` to report component validity. * Run `tsc --noEmit` to verify TypeScript compile status. * Check output against `resources/architecture-checklist.md`. * Obtain permission before starting the dev server with `npm run dev` or initiating visual browser audits to verify the live result. ### Anti-patterns for Phase 4 - ❌ Commencing dev server start or browser audits without user consent. - ❌ Declaring task "done" without verifying code compiles. ## Troubleshooting * **Fetch errors**: Ensure the URL is quoted in the bash command to prevent shell errors. * **Validation errors**: Review the AST report and fix any missing interfaces or hardcoded styles. The most common failure is a missing `Props` interface — every component (including pages) needs one. * **Dead navigation links**: Stitch HTML uses `href="#"` placeholders everywhere. Every `<a href="#">` must be converted to a `<Link to="/route">` with a real route. Verify all nav items are clickable and lead to the correct page. * **Stale style-guide.json**: If colors or fonts look wrong, the `style-guide.json` likely has tokens from a different project. Re-extract from the current HTML `<head>`.