(
+ Mouse position: {x}, {y}
+ )}
+/>
+```
+
+### Higher-Order Components (HOC)
+
+Use HOCs for cross-cutting concerns like authentication or logging.
+
+```tsx
+function withAuth(WrappedComponent: React.ComponentType
) {
+ return function AuthenticatedComponent(props: P) {
+ const { user, isLoading } = useAuth();
+
+ if (isLoading) return ;
+ if (!user) return ;
+
+ return ;
+ };
+}
+
+// Usage
+const ProtectedDashboard = withAuth(Dashboard);
+```
+
+---
+
+## Custom Hooks
+
+### useAsync - Handle async operations
+
+```tsx
+interface AsyncState {
+ data: T | null;
+ error: Error | null;
+ status: 'idle' | 'loading' | 'success' | 'error';
+}
+
+function useAsync(asyncFn: () => Promise, deps: any[] = []) {
+ const [state, setState] = useState>({
+ data: null,
+ error: null,
+ status: 'idle',
+ });
+
+ const execute = useCallback(async () => {
+ setState({ data: null, error: null, status: 'loading' });
+ try {
+ const data = await asyncFn();
+ setState({ data, error: null, status: 'success' });
+ } catch (error) {
+ setState({ data: null, error: error as Error, status: 'error' });
+ }
+ }, deps);
+
+ useEffect(() => {
+ execute();
+ }, [execute]);
+
+ return { ...state, refetch: execute };
+}
+
+// Usage
+function UserProfile({ userId }: { userId: string }) {
+ const { data: user, status, error, refetch } = useAsync(
+ () => fetchUser(userId),
+ [userId]
+ );
+
+ if (status === 'loading') return ;
+ if (status === 'error') return ;
+ if (!user) return null;
+
+ return ;
+}
+```
+
+### useDebounce - Debounce values
+
+```tsx
+function useDebounce(value: T, delay: number): T {
+ const [debouncedValue, setDebouncedValue] = useState(value);
+
+ useEffect(() => {
+ const timer = setTimeout(() => setDebouncedValue(value), delay);
+ return () => clearTimeout(timer);
+ }, [value, delay]);
+
+ return debouncedValue;
+}
+
+// Usage
+function SearchInput() {
+ const [query, setQuery] = useState('');
+ const debouncedQuery = useDebounce(query, 300);
+
+ useEffect(() => {
+ if (debouncedQuery) {
+ searchAPI(debouncedQuery);
+ }
+ }, [debouncedQuery]);
+
+ return setQuery(e.target.value)} />;
+}
+```
+
+### useLocalStorage - Persist state
+
+```tsx
+function useLocalStorage(key: string, initialValue: T) {
+ const [storedValue, setStoredValue] = useState(() => {
+ if (typeof window === 'undefined') return initialValue;
+ try {
+ const item = window.localStorage.getItem(key);
+ return item ? JSON.parse(item) : initialValue;
+ } catch {
+ return initialValue;
+ }
+ });
+
+ const setValue = useCallback((value: T | ((val: T) => T)) => {
+ try {
+ const valueToStore = value instanceof Function ? value(storedValue) : value;
+ setStoredValue(valueToStore);
+ if (typeof window !== 'undefined') {
+ window.localStorage.setItem(key, JSON.stringify(valueToStore));
+ }
+ } catch (error) {
+ console.error('Error saving to localStorage:', error);
+ }
+ }, [key, storedValue]);
+
+ return [storedValue, setValue] as const;
+}
+
+// Usage
+const [theme, setTheme] = useLocalStorage('theme', 'light');
+```
+
+### useMediaQuery - Responsive design
+
+```tsx
+function useMediaQuery(query: string): boolean {
+ const [matches, setMatches] = useState(false);
+
+ useEffect(() => {
+ const media = window.matchMedia(query);
+ setMatches(media.matches);
+
+ const listener = (e: MediaQueryListEvent) => setMatches(e.matches);
+ media.addEventListener('change', listener);
+ return () => media.removeEventListener('change', listener);
+ }, [query]);
+
+ return matches;
+}
+
+// Usage
+function ResponsiveNav() {
+ const isMobile = useMediaQuery('(max-width: 768px)');
+ return isMobile ? : ;
+}
+```
+
+### usePrevious - Track previous values
+
+```tsx
+function usePrevious(value: T): T | undefined {
+ const ref = useRef();
+
+ useEffect(() => {
+ ref.current = value;
+ }, [value]);
+
+ return ref.current;
+}
+
+// Usage
+function Counter() {
+ const [count, setCount] = useState(0);
+ const prevCount = usePrevious(count);
+
+ return (
+
+ Current: {count}, Previous: {prevCount}
+
+ );
+}
+```
+
+---
+
+## State Management
+
+### Context with Reducer
+
+For complex state that multiple components need to access.
+
+```tsx
+// types.ts
+interface CartItem {
+ id: string;
+ name: string;
+ price: number;
+ quantity: number;
+}
+
+interface CartState {
+ items: CartItem[];
+ total: number;
+}
+
+type CartAction =
+ | { type: 'ADD_ITEM'; payload: CartItem }
+ | { type: 'REMOVE_ITEM'; payload: string }
+ | { type: 'UPDATE_QUANTITY'; payload: { id: string; quantity: number } }
+ | { type: 'CLEAR_CART' };
+
+// reducer.ts
+function cartReducer(state: CartState, action: CartAction): CartState {
+ switch (action.type) {
+ case 'ADD_ITEM': {
+ const existingItem = state.items.find(i => i.id === action.payload.id);
+ if (existingItem) {
+ return {
+ ...state,
+ items: state.items.map(item =>
+ item.id === action.payload.id
+ ? { ...item, quantity: item.quantity + 1 }
+ : item
+ ),
+ };
+ }
+ return {
+ ...state,
+ items: [...state.items, { ...action.payload, quantity: 1 }],
+ };
+ }
+ case 'REMOVE_ITEM':
+ return {
+ ...state,
+ items: state.items.filter(i => i.id !== action.payload),
+ };
+ case 'UPDATE_QUANTITY':
+ return {
+ ...state,
+ items: state.items.map(item =>
+ item.id === action.payload.id
+ ? { ...item, quantity: action.payload.quantity }
+ : item
+ ),
+ };
+ case 'CLEAR_CART':
+ return { items: [], total: 0 };
+ default:
+ return state;
+ }
+}
+
+// context.tsx
+const CartContext = createContext<{
+ state: CartState;
+ dispatch: React.Dispatch;
+} | null>(null);
+
+function CartProvider({ children }: { children: React.ReactNode }) {
+ const [state, dispatch] = useReducer(cartReducer, { items: [], total: 0 });
+
+ // Compute total whenever items change
+ const stateWithTotal = useMemo(() => ({
+ ...state,
+ total: state.items.reduce((sum, item) => sum + item.price * item.quantity, 0),
+ }), [state.items]);
+
+ return (
+
+ {children}
+
+ );
+}
+
+function useCart() {
+ const context = useContext(CartContext);
+ if (!context) throw new Error('useCart must be used within CartProvider');
+ return context;
+}
+```
+
+### Zustand (Lightweight Alternative)
+
+```tsx
+import { create } from 'zustand';
+import { persist } from 'zustand/middleware';
+
+interface AuthStore {
+ user: User | null;
+ token: string | null;
+ login: (email: string, password: string) => Promise;
+ logout: () => void;
+}
+
+const useAuthStore = create()(
+ persist(
+ (set) => ({
+ user: null,
+ token: null,
+ login: async (email, password) => {
+ const { user, token } = await authAPI.login(email, password);
+ set({ user, token });
+ },
+ logout: () => set({ user: null, token: null }),
+ }),
+ { name: 'auth-storage' }
+ )
+);
+
+// Usage
+function Profile() {
+ const { user, logout } = useAuthStore();
+ return user ? {user.name}
: null;
+}
+```
+
+---
+
+## Performance Patterns
+
+### React.memo with Custom Comparison
+
+```tsx
+interface ListItemProps {
+ item: { id: string; name: string; count: number };
+ onSelect: (id: string) => void;
+}
+
+const ListItem = React.memo(
+ function ListItem({ item, onSelect }: ListItemProps) {
+ return (
+ onSelect(item.id)}>
+ {item.name} ({item.count})
+
+ );
+ },
+ (prevProps, nextProps) => {
+ // Only re-render if item data changed
+ return (
+ prevProps.item.id === nextProps.item.id &&
+ prevProps.item.name === nextProps.item.name &&
+ prevProps.item.count === nextProps.item.count
+ );
+ }
+);
+```
+
+### useMemo for Expensive Calculations
+
+```tsx
+function DataTable({ data, sortColumn, filterText }: {
+ data: Item[];
+ sortColumn: string;
+ filterText: string;
+}) {
+ const processedData = useMemo(() => {
+ // Filter
+ let result = data.filter(item =>
+ item.name.toLowerCase().includes(filterText.toLowerCase())
+ );
+
+ // Sort
+ result = [...result].sort((a, b) => {
+ const aVal = a[sortColumn as keyof Item];
+ const bVal = b[sortColumn as keyof Item];
+ return aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
+ });
+
+ return result;
+ }, [data, sortColumn, filterText]);
+
+ return (
+
+ {processedData.map(item => (
+ {/* ... */}
+ ))}
+
+ );
+}
+```
+
+### useCallback for Stable References
+
+```tsx
+function ParentComponent() {
+ const [items, setItems] = useState- ([]);
+
+ // Stable reference - won't cause child re-renders
+ const handleItemClick = useCallback((id: string) => {
+ setItems(prev => prev.map(item =>
+ item.id === id ? { ...item, selected: !item.selected } : item
+ ));
+ }, []);
+
+ const handleAddItem = useCallback((newItem: Item) => {
+ setItems(prev => [...prev, newItem]);
+ }, []);
+
+ return (
+ <>
+
+
+ >
+ );
+}
+```
+
+### Virtualization for Long Lists
+
+```tsx
+import { useVirtualizer } from '@tanstack/react-virtual';
+
+function VirtualList({ items }: { items: Item[] }) {
+ const parentRef = useRef(null);
+
+ const virtualizer = useVirtualizer({
+ count: items.length,
+ getScrollElement: () => parentRef.current,
+ estimateSize: () => 50, // estimated row height
+ overscan: 5,
+ });
+
+ return (
+
+
+ {virtualizer.getVirtualItems().map(virtualRow => (
+
+ {items[virtualRow.index].name}
+
+ ))}
+
+
+ );
+}
+```
+
+---
+
+## Error Boundaries
+
+### Class-Based Error Boundary
+
+```tsx
+interface ErrorBoundaryProps {
+ children: React.ReactNode;
+ fallback?: React.ReactNode;
+ onError?: (error: Error, errorInfo: React.ErrorInfo) => void;
+}
+
+interface ErrorBoundaryState {
+ hasError: boolean;
+ error: Error | null;
+}
+
+class ErrorBoundary extends React.Component {
+ state: ErrorBoundaryState = { hasError: false, error: null };
+
+ static getDerivedStateFromError(error: Error): ErrorBoundaryState {
+ return { hasError: true, error };
+ }
+
+ componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
+ this.props.onError?.(error, errorInfo);
+ // Log to error reporting service
+ console.error('Error caught:', error, errorInfo);
+ }
+
+ render() {
+ if (this.state.hasError) {
+ return this.props.fallback || (
+
+
Something went wrong
+
{this.state.error?.message}
+
+
+ );
+ }
+
+ return this.props.children;
+ }
+}
+
+// Usage
+}
+ onError={(error) => trackError(error)}
+>
+
+
+```
+
+### Suspense with Error Boundary
+
+```tsx
+function DataComponent() {
+ return (
+ }>
+ }>
+
+
+
+ );
+}
+```
+
+---
+
+## Anti-Patterns
+
+### Avoid: Inline Object/Array Creation in JSX
+
+```tsx
+// BAD - Creates new object every render, causes re-renders
+
+
+// GOOD - Define outside or use useMemo
+const style = { color: 'red' };
+const items = [1, 2, 3];
+
+
+// Or with useMemo for dynamic values
+const style = useMemo(() => ({ color: theme.primary }), [theme.primary]);
+```
+
+### Avoid: Index as Key for Dynamic Lists
+
+```tsx
+// BAD - Index keys break with reordering/filtering
+{items.map((item, index) => (
+
+))}
+
+// GOOD - Use stable unique ID
+{items.map(item => (
+
+))}
+```
+
+### Avoid: Prop Drilling
+
+```tsx
+// BAD - Passing props through many levels
+
+
+
+
+
+
+
+
+// GOOD - Use Context
+const UserContext = createContext(null);
+
+function App() {
+ return (
+
+
+
+
+
+
+
+ );
+}
+
+function UserInfo() {
+ const user = useContext(UserContext);
+ return {user?.name}
;
+}
+```
+
+### Avoid: Mutating State Directly
+
+```tsx
+// BAD - Mutates state directly
+const addItem = (item: Item) => {
+ items.push(item); // WRONG
+ setItems(items); // Won't trigger re-render
+};
+
+// GOOD - Create new array
+const addItem = (item: Item) => {
+ setItems(prev => [...prev, item]);
+};
+
+// GOOD - For objects
+const updateUser = (field: string, value: string) => {
+ setUser(prev => ({ ...prev, [field]: value }));
+};
+```
+
+### Avoid: useEffect for Derived State
+
+```tsx
+// BAD - Unnecessary effect and extra render
+const [items, setItems] = useState- ([]);
+const [total, setTotal] = useState(0);
+
+useEffect(() => {
+ setTotal(items.reduce((sum, item) => sum + item.price, 0));
+}, [items]);
+
+// GOOD - Compute during render
+const [items, setItems] = useState
- ([]);
+const total = items.reduce((sum, item) => sum + item.price, 0);
+
+// Or useMemo for expensive calculations
+const total = useMemo(
+ () => items.reduce((sum, item) => sum + item.price, 0),
+ [items]
+);
+```
diff --git a/skills/senior-frontend/scripts/bundle_analyzer.py b/skills/senior-frontend/scripts/bundle_analyzer.py
new file mode 100644
index 00000000..fc364888
--- /dev/null
+++ b/skills/senior-frontend/scripts/bundle_analyzer.py
@@ -0,0 +1,407 @@
+#!/usr/bin/env python3
+"""
+Frontend Bundle Analyzer
+
+Analyzes package.json and project structure for bundle optimization opportunities,
+heavy dependencies, and best practice recommendations.
+
+Usage:
+ python bundle_analyzer.py
+ python bundle_analyzer.py . --json
+ python bundle_analyzer.py /path/to/project --verbose
+"""
+
+import argparse
+import json
+import os
+import re
+import sys
+from pathlib import Path
+from typing import Dict, List, Optional, Any, Tuple
+
+
+# Known heavy packages and their lighter alternatives
+HEAVY_PACKAGES = {
+ "moment": {
+ "size": "290KB",
+ "alternative": "date-fns (12KB) or dayjs (2KB)",
+ "reason": "Large locale files bundled by default"
+ },
+ "lodash": {
+ "size": "71KB",
+ "alternative": "lodash-es with tree-shaking or individual imports (lodash/get)",
+ "reason": "Full library often imported when only few functions needed"
+ },
+ "jquery": {
+ "size": "87KB",
+ "alternative": "Native DOM APIs or React/Vue patterns",
+ "reason": "Rarely needed in modern frameworks"
+ },
+ "axios": {
+ "size": "14KB",
+ "alternative": "Native fetch API (0KB) or ky (3KB)",
+ "reason": "Fetch API covers most use cases"
+ },
+ "underscore": {
+ "size": "17KB",
+ "alternative": "Native ES6+ methods or lodash-es",
+ "reason": "Most utilities now in standard JavaScript"
+ },
+ "chart.js": {
+ "size": "180KB",
+ "alternative": "recharts (bundled with React) or lightweight-charts",
+ "reason": "Consider if you need all chart types"
+ },
+ "three": {
+ "size": "600KB",
+ "alternative": "None - use dynamic import for 3D features",
+ "reason": "Very large, should be lazy-loaded"
+ },
+ "firebase": {
+ "size": "400KB+",
+ "alternative": "Import specific modules (firebase/auth, firebase/firestore)",
+ "reason": "Modular imports significantly reduce size"
+ },
+ "material-ui": {
+ "size": "Large",
+ "alternative": "shadcn/ui (copy-paste components) or Tailwind",
+ "reason": "Heavy runtime, consider headless alternatives"
+ },
+ "@mui/material": {
+ "size": "Large",
+ "alternative": "shadcn/ui or Radix UI + Tailwind",
+ "reason": "Heavy runtime, consider headless alternatives"
+ },
+ "antd": {
+ "size": "Large",
+ "alternative": "shadcn/ui or Radix UI + Tailwind",
+ "reason": "Heavy runtime, consider headless alternatives"
+ }
+}
+
+# Recommended optimizations by package
+PACKAGE_OPTIMIZATIONS = {
+ "react-icons": "Import individual icons: import { FaHome } from 'react-icons/fa'",
+ "date-fns": "Use tree-shaking: import { format } from 'date-fns'",
+ "@heroicons/react": "Already tree-shakeable, good choice",
+ "lucide-react": "Already tree-shakeable, add to optimizePackageImports in next.config.js",
+ "framer-motion": "Use dynamic import for non-critical animations",
+ "recharts": "Consider lazy loading for dashboard charts",
+}
+
+# Development dependencies that should not be in dependencies
+DEV_ONLY_PACKAGES = [
+ "typescript", "@types/", "eslint", "prettier", "jest", "vitest",
+ "@testing-library", "cypress", "playwright", "storybook", "@storybook",
+ "webpack", "vite", "rollup", "esbuild", "tailwindcss", "postcss",
+ "autoprefixer", "sass", "less", "husky", "lint-staged"
+]
+
+
+def load_package_json(project_dir: Path) -> Optional[Dict]:
+ """Load and parse package.json."""
+ package_path = project_dir / "package.json"
+ if not package_path.exists():
+ return None
+
+ try:
+ with open(package_path) as f:
+ return json.load(f)
+ except json.JSONDecodeError:
+ return None
+
+
+def analyze_dependencies(package_json: Dict) -> Dict:
+ """Analyze dependencies for issues."""
+ deps = package_json.get("dependencies", {})
+ dev_deps = package_json.get("devDependencies", {})
+
+ issues = []
+ warnings = []
+ optimizations = []
+
+ # Check for heavy packages
+ for pkg, info in HEAVY_PACKAGES.items():
+ if pkg in deps:
+ issues.append({
+ "package": pkg,
+ "type": "heavy_dependency",
+ "size": info["size"],
+ "alternative": info["alternative"],
+ "reason": info["reason"]
+ })
+
+ # Check for dev dependencies in production
+ for pkg in deps.keys():
+ for dev_pattern in DEV_ONLY_PACKAGES:
+ if dev_pattern in pkg:
+ warnings.append({
+ "package": pkg,
+ "type": "dev_in_production",
+ "message": f"{pkg} should be in devDependencies, not dependencies"
+ })
+
+ # Check for optimization opportunities
+ for pkg in deps.keys():
+ for opt_pkg, opt_tip in PACKAGE_OPTIMIZATIONS.items():
+ if opt_pkg in pkg:
+ optimizations.append({
+ "package": pkg,
+ "tip": opt_tip
+ })
+
+ # Check for outdated React patterns
+ if "prop-types" in deps and ("typescript" in dev_deps or "@types/react" in dev_deps):
+ warnings.append({
+ "package": "prop-types",
+ "type": "redundant",
+ "message": "prop-types is redundant when using TypeScript"
+ })
+
+ # Check for multiple state management libraries
+ state_libs = ["redux", "@reduxjs/toolkit", "mobx", "zustand", "jotai", "recoil", "valtio"]
+ found_state_libs = [lib for lib in state_libs if lib in deps]
+ if len(found_state_libs) > 1:
+ warnings.append({
+ "packages": found_state_libs,
+ "type": "multiple_state_libs",
+ "message": f"Multiple state management libraries found: {', '.join(found_state_libs)}"
+ })
+
+ return {
+ "total_dependencies": len(deps),
+ "total_dev_dependencies": len(dev_deps),
+ "issues": issues,
+ "warnings": warnings,
+ "optimizations": optimizations
+ }
+
+
+def check_nextjs_config(project_dir: Path) -> Dict:
+ """Check Next.js configuration for optimizations."""
+ config_paths = [
+ project_dir / "next.config.js",
+ project_dir / "next.config.mjs",
+ project_dir / "next.config.ts"
+ ]
+
+ for config_path in config_paths:
+ if config_path.exists():
+ try:
+ content = config_path.read_text()
+ suggestions = []
+
+ # Check for image optimization
+ if "images" not in content:
+ suggestions.append("Configure images.remotePatterns for optimized image loading")
+
+ # Check for package optimization
+ if "optimizePackageImports" not in content:
+ suggestions.append("Add experimental.optimizePackageImports for lucide-react, @heroicons/react")
+
+ # Check for transpilePackages
+ if "transpilePackages" not in content and "swc" not in content:
+ suggestions.append("Consider transpilePackages for monorepo packages")
+
+ return {
+ "found": True,
+ "path": str(config_path),
+ "suggestions": suggestions
+ }
+ except Exception:
+ pass
+
+ return {
+ "found": False,
+ "suggestions": ["Create next.config.js with image and bundle optimizations"]
+ }
+
+
+def analyze_imports(project_dir: Path) -> Dict:
+ """Analyze import patterns in source files."""
+ issues = []
+ src_dirs = [project_dir / "src", project_dir / "app", project_dir / "pages"]
+
+ patterns_to_check = [
+ (r"import\s+\*\s+as\s+\w+\s+from\s+['\"]lodash['\"]", "Avoid import * from lodash, use individual imports"),
+ (r"import\s+moment\s+from\s+['\"]moment['\"]", "Consider replacing moment with date-fns or dayjs"),
+ (r"import\s+\{\s*\w+(?:,\s*\w+){5,}\s*\}\s+from\s+['\"]react-icons", "Import icons from specific icon sets (react-icons/fa)"),
+ ]
+
+ files_checked = 0
+ for src_dir in src_dirs:
+ if not src_dir.exists():
+ continue
+
+ for ext in ["*.ts", "*.tsx", "*.js", "*.jsx"]:
+ for file_path in src_dir.glob(f"**/{ext}"):
+ if "node_modules" in str(file_path):
+ continue
+
+ files_checked += 1
+ try:
+ content = file_path.read_text()
+ for pattern, message in patterns_to_check:
+ if re.search(pattern, content):
+ issues.append({
+ "file": str(file_path.relative_to(project_dir)),
+ "issue": message
+ })
+ except Exception:
+ continue
+
+ return {
+ "files_checked": files_checked,
+ "issues": issues
+ }
+
+
+def calculate_score(analysis: Dict) -> Tuple[int, str]:
+ """Calculate bundle health score."""
+ score = 100
+
+ # Deduct for heavy dependencies
+ score -= len(analysis["dependencies"]["issues"]) * 10
+
+ # Deduct for dev deps in production
+ score -= len([w for w in analysis["dependencies"]["warnings"]
+ if w.get("type") == "dev_in_production"]) * 5
+
+ # Deduct for import issues
+ score -= len(analysis.get("imports", {}).get("issues", [])) * 3
+
+ # Deduct for missing Next.js optimizations
+ if not analysis.get("nextjs", {}).get("found", True):
+ score -= 10
+
+ score = max(0, min(100, score))
+
+ if score >= 90:
+ grade = "A"
+ elif score >= 80:
+ grade = "B"
+ elif score >= 70:
+ grade = "C"
+ elif score >= 60:
+ grade = "D"
+ else:
+ grade = "F"
+
+ return score, grade
+
+
+def print_report(analysis: Dict) -> None:
+ """Print human-readable report."""
+ score, grade = calculate_score(analysis)
+
+ print("=" * 60)
+ print("FRONTEND BUNDLE ANALYSIS REPORT")
+ print("=" * 60)
+ print(f"\nBundle Health Score: {score}/100 ({grade})")
+
+ deps = analysis["dependencies"]
+ print(f"\nDependencies: {deps['total_dependencies']} production, {deps['total_dev_dependencies']} dev")
+
+ # Heavy dependencies
+ if deps["issues"]:
+ print("\n--- HEAVY DEPENDENCIES ---")
+ for issue in deps["issues"]:
+ print(f"\n {issue['package']} ({issue['size']})")
+ print(f" Reason: {issue['reason']}")
+ print(f" Alternative: {issue['alternative']}")
+
+ # Warnings
+ if deps["warnings"]:
+ print("\n--- WARNINGS ---")
+ for warning in deps["warnings"]:
+ if "package" in warning:
+ print(f" - {warning['package']}: {warning['message']}")
+ else:
+ print(f" - {warning['message']}")
+
+ # Optimizations
+ if deps["optimizations"]:
+ print("\n--- OPTIMIZATION TIPS ---")
+ for opt in deps["optimizations"]:
+ print(f" - {opt['package']}: {opt['tip']}")
+
+ # Next.js config
+ if "nextjs" in analysis:
+ nextjs = analysis["nextjs"]
+ if nextjs.get("suggestions"):
+ print("\n--- NEXT.JS CONFIG ---")
+ for suggestion in nextjs["suggestions"]:
+ print(f" - {suggestion}")
+
+ # Import issues
+ if analysis.get("imports", {}).get("issues"):
+ print("\n--- IMPORT ISSUES ---")
+ for issue in analysis["imports"]["issues"][:10]: # Limit to 10
+ print(f" - {issue['file']}: {issue['issue']}")
+
+ # Summary
+ print("\n--- RECOMMENDATIONS ---")
+ if score >= 90:
+ print(" Bundle is well-optimized!")
+ elif deps["issues"]:
+ print(" 1. Replace heavy dependencies with lighter alternatives")
+ if deps["warnings"]:
+ print(" 2. Move dev-only packages to devDependencies")
+ if deps["optimizations"]:
+ print(" 3. Apply import optimizations for tree-shaking")
+
+ print("\n" + "=" * 60)
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="Analyze frontend project for bundle optimization opportunities"
+ )
+ parser.add_argument(
+ "project_dir",
+ nargs="?",
+ default=".",
+ help="Project directory to analyze (default: current directory)"
+ )
+ parser.add_argument(
+ "--json",
+ action="store_true",
+ help="Output in JSON format"
+ )
+ parser.add_argument(
+ "--verbose", "-v",
+ action="store_true",
+ help="Include detailed import analysis"
+ )
+
+ args = parser.parse_args()
+ project_dir = Path(args.project_dir).resolve()
+
+ if not project_dir.exists():
+ print(f"Error: Directory not found: {project_dir}", file=sys.stderr)
+ sys.exit(1)
+
+ package_json = load_package_json(project_dir)
+ if not package_json:
+ print("Error: No valid package.json found", file=sys.stderr)
+ sys.exit(1)
+
+ analysis = {
+ "project": str(project_dir),
+ "dependencies": analyze_dependencies(package_json),
+ "nextjs": check_nextjs_config(project_dir)
+ }
+
+ if args.verbose:
+ analysis["imports"] = analyze_imports(project_dir)
+
+ analysis["score"], analysis["grade"] = calculate_score(analysis)
+
+ if args.json:
+ print(json.dumps(analysis, indent=2))
+ else:
+ print_report(analysis)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/senior-frontend/scripts/component_generator.py b/skills/senior-frontend/scripts/component_generator.py
new file mode 100644
index 00000000..fda723a0
--- /dev/null
+++ b/skills/senior-frontend/scripts/component_generator.py
@@ -0,0 +1,329 @@
+#!/usr/bin/env python3
+"""
+React Component Generator
+
+Generates React/Next.js component files with TypeScript, Tailwind CSS,
+and optional test files following best practices.
+
+Usage:
+ python component_generator.py Button --dir src/components/ui
+ python component_generator.py ProductCard --type client --with-test
+ python component_generator.py UserProfile --type server --with-story
+"""
+
+import argparse
+import os
+import sys
+from pathlib import Path
+from datetime import datetime
+
+
+# Component templates
+TEMPLATES = {
+ "client": '''\'use client\';
+
+import {{ useState }} from 'react';
+import {{ cn }} from '@/lib/utils';
+
+interface {name}Props {{
+ className?: string;
+ children?: React.ReactNode;
+}}
+
+export function {name}({{ className, children }}: {name}Props) {{
+ return (
+
+ {{children}}
+
+ );
+}}
+''',
+
+ "server": '''import {{ cn }} from '@/lib/utils';
+
+interface {name}Props {{
+ className?: string;
+ children?: React.ReactNode;
+}}
+
+export async function {name}({{ className, children }}: {name}Props) {{
+ return (
+
+ {{children}}
+
+ );
+}}
+''',
+
+ "hook": '''import {{ useState, useEffect, useCallback }} from 'react';
+
+interface Use{name}Options {{
+ // Add options here
+}}
+
+interface Use{name}Return {{
+ // Add return type here
+ isLoading: boolean;
+ error: Error | null;
+}}
+
+export function use{name}(options: Use{name}Options = {{}}): Use{name}Return {{
+ const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState(null);
+
+ useEffect(() => {{
+ // Effect logic here
+ }}, []);
+
+ return {{
+ isLoading,
+ error,
+ }};
+}}
+''',
+
+ "test": '''import {{ render, screen }} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {{ {name} }} from './{name}';
+
+describe('{name}', () => {{
+ it('renders correctly', () => {{
+ render(<{name}>Test content{name}>);
+ expect(screen.getByText('Test content')).toBeInTheDocument();
+ }});
+
+ it('applies custom className', () => {{
+ render(<{name} className="custom-class">Content{name}>);
+ expect(screen.getByText('Content').parentElement).toHaveClass('custom-class');
+ }});
+
+ // Add more tests here
+}});
+''',
+
+ "story": '''import type {{ Meta, StoryObj }} from '@storybook/react';
+import {{ {name} }} from './{name}';
+
+const meta: Meta = {{
+ title: 'Components/{name}',
+ component: {name},
+ tags: ['autodocs'],
+ argTypes: {{
+ className: {{
+ control: 'text',
+ description: 'Additional CSS classes',
+ }},
+ }},
+}};
+
+export default meta;
+type Story = StoryObj;
+
+export const Default: Story = {{
+ args: {{
+ children: 'Default content',
+ }},
+}};
+
+export const WithCustomClass: Story = {{
+ args: {{
+ className: 'bg-blue-100 p-4',
+ children: 'Styled content',
+ }},
+}};
+''',
+
+ "index": '''export {{ {name} }} from './{name}';
+export type {{ {name}Props }} from './{name}';
+''',
+}
+
+
+def to_pascal_case(name: str) -> str:
+ """Convert string to PascalCase."""
+ # Handle kebab-case and snake_case
+ words = name.replace('-', '_').split('_')
+ return ''.join(word.capitalize() for word in words)
+
+
+def to_kebab_case(name: str) -> str:
+ """Convert PascalCase to kebab-case."""
+ result = []
+ for i, char in enumerate(name):
+ if char.isupper() and i > 0:
+ result.append('-')
+ result.append(char.lower())
+ return ''.join(result)
+
+
+def generate_component(
+ name: str,
+ output_dir: Path,
+ component_type: str = "client",
+ with_test: bool = False,
+ with_story: bool = False,
+ with_index: bool = True,
+ flat: bool = False,
+) -> dict:
+ """Generate component files."""
+ pascal_name = to_pascal_case(name)
+ kebab_name = to_kebab_case(pascal_name)
+
+ # Determine output path
+ if flat:
+ component_dir = output_dir
+ else:
+ component_dir = output_dir / pascal_name
+
+ files_created = []
+
+ # Create directory
+ component_dir.mkdir(parents=True, exist_ok=True)
+
+ # Generate main component file
+ if component_type == "hook":
+ main_file = component_dir / f"use{pascal_name}.ts"
+ template = TEMPLATES["hook"]
+ else:
+ main_file = component_dir / f"{pascal_name}.tsx"
+ template = TEMPLATES[component_type]
+
+ content = template.format(name=pascal_name)
+ main_file.write_text(content)
+ files_created.append(str(main_file))
+
+ # Generate test file
+ if with_test and component_type != "hook":
+ test_file = component_dir / f"{pascal_name}.test.tsx"
+ test_content = TEMPLATES["test"].format(name=pascal_name)
+ test_file.write_text(test_content)
+ files_created.append(str(test_file))
+
+ # Generate story file
+ if with_story and component_type != "hook":
+ story_file = component_dir / f"{pascal_name}.stories.tsx"
+ story_content = TEMPLATES["story"].format(name=pascal_name)
+ story_file.write_text(story_content)
+ files_created.append(str(story_file))
+
+ # Generate index file
+ if with_index and not flat:
+ index_file = component_dir / "index.ts"
+ index_content = TEMPLATES["index"].format(name=pascal_name)
+ index_file.write_text(index_content)
+ files_created.append(str(index_file))
+
+ return {
+ "name": pascal_name,
+ "type": component_type,
+ "directory": str(component_dir),
+ "files": files_created,
+ }
+
+
+def print_result(result: dict, verbose: bool = False) -> None:
+ """Print generation result."""
+ print(f"\n{'='*50}")
+ print(f"Component Generated: {result['name']}")
+ print(f"{'='*50}")
+ print(f"Type: {result['type']}")
+ print(f"Directory: {result['directory']}")
+ print(f"\nFiles created:")
+ for file in result['files']:
+ print(f" - {file}")
+ print(f"{'='*50}\n")
+
+ # Print usage hint
+ if result['type'] != 'hook':
+ print("Usage:")
+ print(f" import {{ {result['name']} }} from '@/components/{result['name']}';")
+ print(f"\n <{result['name']}>Content{result['name']}>")
+ else:
+ print("Usage:")
+ print(f" import {{ use{result['name']} }} from '@/hooks/use{result['name']}';")
+ print(f"\n const {{ isLoading, error }} = use{result['name']}();")
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="Generate React/Next.js components with TypeScript and Tailwind CSS"
+ )
+ parser.add_argument(
+ "name",
+ help="Component name (PascalCase or kebab-case)"
+ )
+ parser.add_argument(
+ "--dir", "-d",
+ default="src/components",
+ help="Output directory (default: src/components)"
+ )
+ parser.add_argument(
+ "--type", "-t",
+ choices=["client", "server", "hook"],
+ default="client",
+ help="Component type (default: client)"
+ )
+ parser.add_argument(
+ "--with-test",
+ action="store_true",
+ help="Generate test file"
+ )
+ parser.add_argument(
+ "--with-story",
+ action="store_true",
+ help="Generate Storybook story file"
+ )
+ parser.add_argument(
+ "--no-index",
+ action="store_true",
+ help="Skip generating index.ts file"
+ )
+ parser.add_argument(
+ "--flat",
+ action="store_true",
+ help="Create files directly in output dir without subdirectory"
+ )
+ parser.add_argument(
+ "--dry-run",
+ action="store_true",
+ help="Show what would be generated without creating files"
+ )
+ parser.add_argument(
+ "--verbose", "-v",
+ action="store_true",
+ help="Enable verbose output"
+ )
+
+ args = parser.parse_args()
+
+ output_dir = Path(args.dir)
+ pascal_name = to_pascal_case(args.name)
+
+ if args.dry_run:
+ print(f"\nDry run - would generate:")
+ print(f" Component: {pascal_name}")
+ print(f" Type: {args.type}")
+ print(f" Directory: {output_dir / pascal_name if not args.flat else output_dir}")
+ print(f" Test: {'Yes' if args.with_test else 'No'}")
+ print(f" Story: {'Yes' if args.with_story else 'No'}")
+ return
+
+ try:
+ result = generate_component(
+ name=args.name,
+ output_dir=output_dir,
+ component_type=args.type,
+ with_test=args.with_test,
+ with_story=args.with_story,
+ with_index=not args.no_index,
+ flat=args.flat,
+ )
+ print_result(result, args.verbose)
+
+ except Exception as e:
+ print(f"Error: {e}", file=sys.stderr)
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/senior-frontend/scripts/frontend_scaffolder.py b/skills/senior-frontend/scripts/frontend_scaffolder.py
new file mode 100644
index 00000000..ecc826c8
--- /dev/null
+++ b/skills/senior-frontend/scripts/frontend_scaffolder.py
@@ -0,0 +1,1005 @@
+#!/usr/bin/env python3
+"""
+Frontend Project Scaffolder
+
+Generates a complete Next.js/React project structure with TypeScript,
+Tailwind CSS, and best practice configurations.
+
+Usage:
+ python frontend_scaffolder.py my-app --template nextjs
+ python frontend_scaffolder.py dashboard --template react --features auth,api
+ python frontend_scaffolder.py landing --template nextjs --dry-run
+"""
+
+import argparse
+import json
+import os
+import sys
+from pathlib import Path
+from typing import Dict, List, Optional
+
+
+# Project templates
+TEMPLATES = {
+ "nextjs": {
+ "name": "Next.js 14+ App Router",
+ "description": "Modern Next.js with App Router, Server Components, and TypeScript",
+ "structure": {
+ "app": {
+ "layout.tsx": "ROOT_LAYOUT",
+ "page.tsx": "HOME_PAGE",
+ "globals.css": "GLOBALS_CSS",
+ "(auth)": {
+ "login": {"page.tsx": "AUTH_PAGE"},
+ "register": {"page.tsx": "AUTH_PAGE"},
+ },
+ "api": {
+ "health": {"route.ts": "HEALTH_ROUTE"},
+ },
+ },
+ "components": {
+ "ui": {
+ "button.tsx": "UI_BUTTON",
+ "input.tsx": "UI_INPUT",
+ "card.tsx": "UI_CARD",
+ "index.ts": "UI_INDEX",
+ },
+ "layout": {
+ "header.tsx": "LAYOUT_HEADER",
+ "footer.tsx": "LAYOUT_FOOTER",
+ "sidebar.tsx": "LAYOUT_SIDEBAR",
+ },
+ },
+ "lib": {
+ "utils.ts": "UTILS",
+ "constants.ts": "CONSTANTS",
+ },
+ "hooks": {
+ "use-debounce.ts": "HOOK_DEBOUNCE",
+ "use-local-storage.ts": "HOOK_LOCAL_STORAGE",
+ },
+ "types": {
+ "index.ts": "TYPES_INDEX",
+ },
+ "public": {
+ ".gitkeep": "EMPTY",
+ },
+ },
+ "config_files": [
+ "next.config.js",
+ "tailwind.config.ts",
+ "tsconfig.json",
+ "postcss.config.js",
+ ".eslintrc.json",
+ ".prettierrc",
+ ".gitignore",
+ "package.json",
+ ],
+ },
+ "react": {
+ "name": "React + Vite",
+ "description": "Modern React with Vite, TypeScript, and Tailwind CSS",
+ "structure": {
+ "src": {
+ "App.tsx": "REACT_APP",
+ "main.tsx": "REACT_MAIN",
+ "index.css": "GLOBALS_CSS",
+ "components": {
+ "ui": {
+ "button.tsx": "UI_BUTTON",
+ "input.tsx": "UI_INPUT",
+ "card.tsx": "UI_CARD",
+ "index.ts": "UI_INDEX",
+ },
+ },
+ "hooks": {
+ "use-debounce.ts": "HOOK_DEBOUNCE",
+ "use-local-storage.ts": "HOOK_LOCAL_STORAGE",
+ },
+ "lib": {
+ "utils.ts": "UTILS",
+ },
+ "types": {
+ "index.ts": "TYPES_INDEX",
+ },
+ },
+ "public": {
+ ".gitkeep": "EMPTY",
+ },
+ },
+ "config_files": [
+ "vite.config.ts",
+ "tailwind.config.ts",
+ "tsconfig.json",
+ "postcss.config.js",
+ ".eslintrc.json",
+ ".prettierrc",
+ ".gitignore",
+ "package.json",
+ "index.html",
+ ],
+ },
+}
+
+# Feature modules that can be added
+FEATURES = {
+ "auth": {
+ "description": "Authentication with session management",
+ "files": {
+ "lib/auth.ts": "AUTH_LIB",
+ "middleware.ts": "AUTH_MIDDLEWARE",
+ "components/auth/login-form.tsx": "LOGIN_FORM",
+ "components/auth/register-form.tsx": "REGISTER_FORM",
+ },
+ "dependencies": ["next-auth", "@auth/core"],
+ },
+ "api": {
+ "description": "API client with React Query",
+ "files": {
+ "lib/api-client.ts": "API_CLIENT",
+ "lib/query-client.ts": "QUERY_CLIENT",
+ "providers/query-provider.tsx": "QUERY_PROVIDER",
+ },
+ "dependencies": ["@tanstack/react-query", "axios"],
+ },
+ "forms": {
+ "description": "Form handling with React Hook Form + Zod",
+ "files": {
+ "lib/form-utils.ts": "FORM_UTILS",
+ "components/forms/form-field.tsx": "FORM_FIELD",
+ },
+ "dependencies": ["react-hook-form", "@hookform/resolvers", "zod"],
+ },
+ "testing": {
+ "description": "Testing setup with Vitest and Testing Library",
+ "files": {
+ "vitest.config.ts": "VITEST_CONFIG",
+ "src/test/setup.ts": "TEST_SETUP",
+ "src/test/utils.tsx": "TEST_UTILS",
+ },
+ "dependencies": ["vitest", "@testing-library/react", "@testing-library/jest-dom"],
+ },
+ "storybook": {
+ "description": "Component documentation with Storybook",
+ "files": {
+ ".storybook/main.ts": "STORYBOOK_MAIN",
+ ".storybook/preview.ts": "STORYBOOK_PREVIEW",
+ },
+ "dependencies": ["@storybook/react-vite", "@storybook/addon-essentials"],
+ },
+}
+
+# File content templates
+FILE_CONTENTS = {
+ "ROOT_LAYOUT": '''import type { Metadata } from 'next';
+import { Inter } from 'next/font/google';
+import './globals.css';
+
+const inter = Inter({ subsets: ['latin'], variable: '--font-inter' });
+
+export const metadata: Metadata = {
+ title: 'My App',
+ description: 'Built with Next.js',
+};
+
+export default function RootLayout({
+ children,
+}: {
+ children: React.ReactNode;
+}) {
+ return (
+
+
+ {children}
+
+
+ );
+}
+''',
+ "HOME_PAGE": '''export default function Home() {
+ return (
+
+ Welcome
+
+ Get started by editing app/page.tsx
+
+
+ );
+}
+''',
+ "GLOBALS_CSS": '''@tailwind base;
+@tailwind components;
+@tailwind utilities;
+
+@layer base {
+ :root {
+ --background: 0 0% 100%;
+ --foreground: 222.2 84% 4.9%;
+ --primary: 222.2 47.4% 11.2%;
+ --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%;
+ --ring: 222.2 84% 4.9%;
+ --radius: 0.5rem;
+ }
+
+ .dark {
+ --background: 222.2 84% 4.9%;
+ --foreground: 210 40% 98%;
+ }
+}
+
+@layer base {
+ * {
+ @apply border-border;
+ }
+ body {
+ @apply bg-background text-foreground;
+ }
+}
+''',
+ "UI_BUTTON": '''import { forwardRef } from 'react';
+import { cn } from '@/lib/utils';
+
+interface ButtonProps extends React.ButtonHTMLAttributes {
+ variant?: 'default' | 'destructive' | 'outline' | 'ghost';
+ size?: 'default' | 'sm' | 'lg';
+}
+
+const Button = forwardRef(
+ ({ className, variant = 'default', size = 'default', ...props }, ref) => {
+ return (
+
+ );
+ }
+);
+
+Button.displayName = 'Button';
+
+export { Button, type ButtonProps };
+''',
+ "UI_INPUT": '''import { forwardRef } from 'react';
+import { cn } from '@/lib/utils';
+
+interface InputProps extends React.InputHTMLAttributes {
+ error?: string;
+}
+
+const Input = forwardRef(
+ ({ className, error, ...props }, ref) => {
+ return (
+
+ );
+ }
+);
+
+Input.displayName = 'Input';
+
+export { Input, type InputProps };
+''',
+ "UI_CARD": '''import { cn } from '@/lib/utils';
+
+interface CardProps extends React.HTMLAttributes {}
+
+function Card({ className, ...props }: CardProps) {
+ return (
+
+ );
+}
+
+function CardHeader({ className, ...props }: CardProps) {
+ return ;
+}
+
+function CardTitle({ className, ...props }: React.HTMLAttributes) {
+ return ;
+}
+
+function CardContent({ className, ...props }: CardProps) {
+ return ;
+}
+
+function CardFooter({ className, ...props }: CardProps) {
+ return ;
+}
+
+export { Card, CardHeader, CardTitle, CardContent, CardFooter };
+''',
+ "UI_INDEX": '''export { Button } from './button';
+export { Input } from './input';
+export { Card, CardHeader, CardTitle, CardContent, CardFooter } from './card';
+''',
+ "UTILS": '''import { type ClassValue, clsx } from 'clsx';
+import { twMerge } from 'tailwind-merge';
+
+export function cn(...inputs: ClassValue[]) {
+ return twMerge(clsx(inputs));
+}
+
+export function formatDate(date: Date | string): string {
+ return new Intl.DateTimeFormat('en-US', {
+ month: 'short',
+ day: 'numeric',
+ year: 'numeric',
+ }).format(new Date(date));
+}
+
+export function sleep(ms: number): Promise {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+''',
+ "CONSTANTS": '''export const APP_NAME = 'My App';
+export const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api';
+
+export const ROUTES = {
+ home: '/',
+ login: '/login',
+ register: '/register',
+ dashboard: '/dashboard',
+} as const;
+
+export const QUERY_KEYS = {
+ user: ['user'],
+ products: ['products'],
+} as const;
+''',
+ "HOOK_DEBOUNCE": '''import { useState, useEffect } from 'react';
+
+export function useDebounce(value: T, delay: number = 500): T {
+ const [debouncedValue, setDebouncedValue] = useState(value);
+
+ useEffect(() => {
+ const timer = setTimeout(() => setDebouncedValue(value), delay);
+ return () => clearTimeout(timer);
+ }, [value, delay]);
+
+ return debouncedValue;
+}
+''',
+ "HOOK_LOCAL_STORAGE": '''import { useState, useEffect } from 'react';
+
+export function useLocalStorage(
+ key: string,
+ initialValue: T
+): [T, (value: T | ((prev: T) => T)) => void] {
+ const [storedValue, setStoredValue] = useState(() => {
+ if (typeof window === 'undefined') return initialValue;
+
+ try {
+ const item = window.localStorage.getItem(key);
+ return item ? JSON.parse(item) : initialValue;
+ } catch {
+ return initialValue;
+ }
+ });
+
+ useEffect(() => {
+ if (typeof window !== 'undefined') {
+ window.localStorage.setItem(key, JSON.stringify(storedValue));
+ }
+ }, [key, storedValue]);
+
+ return [storedValue, setStoredValue];
+}
+''',
+ "TYPES_INDEX": '''export interface User {
+ id: string;
+ email: string;
+ name: string;
+ createdAt: Date;
+}
+
+export interface ApiResponse {
+ data: T;
+ message?: string;
+ error?: string;
+}
+
+export interface PaginatedResponse {
+ data: T[];
+ total: number;
+ page: number;
+ pageSize: number;
+ totalPages: number;
+}
+''',
+ "HEALTH_ROUTE": '''import { NextResponse } from 'next/server';
+
+export async function GET() {
+ return NextResponse.json({
+ status: 'ok',
+ timestamp: new Date().toISOString(),
+ });
+}
+''',
+ "AUTH_PAGE": ''''use client';
+
+export default function AuthPage() {
+ return (
+
+ );
+}
+''',
+ "LAYOUT_HEADER": '''import Link from 'next/link';
+
+export function Header() {
+ return (
+
+ );
+}
+''',
+ "LAYOUT_FOOTER": '''export function Footer() {
+ return (
+
+ );
+}
+''',
+ "LAYOUT_SIDEBAR": '''interface SidebarProps {
+ children?: React.ReactNode;
+}
+
+export function Sidebar({ children }: SidebarProps) {
+ return (
+
+ );
+}
+''',
+ "REACT_APP": '''import { Button } from './components/ui';
+
+function App() {
+ return (
+
+ Welcome
+
+ Get started by editing src/App.tsx
+
+
+
+ );
+}
+
+export default App;
+''',
+ "REACT_MAIN": '''import React from 'react';
+import ReactDOM from 'react-dom/client';
+import App from './App';
+import './index.css';
+
+ReactDOM.createRoot(document.getElementById('root')!).render(
+
+
+
+);
+''',
+ "EMPTY": "",
+}
+
+
+def generate_structure(
+ base_path: Path,
+ structure: Dict,
+ dry_run: bool = False
+) -> List[str]:
+ """Generate directory structure recursively."""
+ created_files = []
+
+ for name, content in structure.items():
+ current_path = base_path / name
+
+ if isinstance(content, dict):
+ # It's a directory
+ if not dry_run:
+ current_path.mkdir(parents=True, exist_ok=True)
+ created_files.extend(generate_structure(current_path, content, dry_run))
+ else:
+ # It's a file
+ if not dry_run:
+ current_path.parent.mkdir(parents=True, exist_ok=True)
+ file_content = FILE_CONTENTS.get(content, "")
+ current_path.write_text(file_content)
+ created_files.append(str(current_path))
+
+ return created_files
+
+
+def generate_config_files(
+ project_path: Path,
+ template: str,
+ project_name: str,
+ features: List[str],
+ dry_run: bool = False
+) -> List[str]:
+ """Generate configuration files."""
+ created_files = []
+ config_templates = get_config_templates(project_name, template, features)
+
+ template_config = TEMPLATES[template]
+ for config_file in template_config["config_files"]:
+ file_path = project_path / config_file
+ if config_file in config_templates:
+ if not dry_run:
+ file_path.write_text(config_templates[config_file])
+ created_files.append(str(file_path))
+
+ return created_files
+
+
+def get_config_templates(name: str, template: str, features: List[str]) -> Dict[str, str]:
+ """Get configuration file contents."""
+ deps = {
+ "nextjs": {
+ "dependencies": {
+ "next": "^14.0.0",
+ "react": "^18.2.0",
+ "react-dom": "^18.2.0",
+ "clsx": "^2.0.0",
+ "tailwind-merge": "^2.0.0",
+ },
+ "devDependencies": {
+ "@types/node": "^20.0.0",
+ "@types/react": "^18.2.0",
+ "@types/react-dom": "^18.2.0",
+ "autoprefixer": "^10.0.0",
+ "eslint": "^8.0.0",
+ "eslint-config-next": "^14.0.0",
+ "postcss": "^8.0.0",
+ "prettier": "^3.0.0",
+ "tailwindcss": "^3.4.0",
+ "typescript": "^5.0.0",
+ },
+ },
+ "react": {
+ "dependencies": {
+ "react": "^18.2.0",
+ "react-dom": "^18.2.0",
+ "clsx": "^2.0.0",
+ "tailwind-merge": "^2.0.0",
+ },
+ "devDependencies": {
+ "@types/react": "^18.2.0",
+ "@types/react-dom": "^18.2.0",
+ "@vitejs/plugin-react": "^4.0.0",
+ "autoprefixer": "^10.0.0",
+ "eslint": "^8.0.0",
+ "postcss": "^8.0.0",
+ "prettier": "^3.0.0",
+ "tailwindcss": "^3.4.0",
+ "typescript": "^5.0.0",
+ "vite": "^5.0.0",
+ },
+ },
+ }
+
+ # Add feature dependencies
+ for feature in features:
+ if feature in FEATURES:
+ for dep in FEATURES[feature].get("dependencies", []):
+ deps[template]["dependencies"][dep] = "latest"
+
+ package_json = {
+ "name": name,
+ "version": "0.1.0",
+ "private": True,
+ "scripts": {
+ "dev": "next dev" if template == "nextjs" else "vite",
+ "build": "next build" if template == "nextjs" else "vite build",
+ "start": "next start" if template == "nextjs" else "vite preview",
+ "lint": "eslint . --ext .ts,.tsx",
+ "format": "prettier --write .",
+ },
+ "dependencies": deps[template]["dependencies"],
+ "devDependencies": deps[template]["devDependencies"],
+ }
+
+ return {
+ "package.json": json.dumps(package_json, indent=2),
+ "tsconfig.json": '''{
+ "compilerOptions": {
+ "target": "ES2020",
+ "lib": ["dom", "dom.iterable", "esnext"],
+ "allowJs": true,
+ "skipLibCheck": true,
+ "strict": true,
+ "noEmit": true,
+ "esModuleInterop": true,
+ "module": "esnext",
+ "moduleResolution": "bundler",
+ "resolveJsonModule": true,
+ "isolatedModules": true,
+ "jsx": "preserve",
+ "incremental": true,
+ "plugins": [{ "name": "next" }],
+ "paths": {
+ "@/*": ["./*"]
+ }
+ },
+ "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
+ "exclude": ["node_modules"]
+}
+''',
+ "tailwind.config.ts": '''import type { Config } from 'tailwindcss';
+
+const config: Config = {
+ content: [
+ './pages/**/*.{js,ts,jsx,tsx,mdx}',
+ './components/**/*.{js,ts,jsx,tsx,mdx}',
+ './app/**/*.{js,ts,jsx,tsx,mdx}',
+ './src/**/*.{js,ts,jsx,tsx,mdx}',
+ ],
+ theme: {
+ extend: {
+ colors: {
+ background: 'hsl(var(--background))',
+ foreground: 'hsl(var(--foreground))',
+ primary: {
+ DEFAULT: 'hsl(var(--primary))',
+ foreground: 'hsl(var(--primary-foreground))',
+ },
+ secondary: {
+ DEFAULT: 'hsl(var(--secondary))',
+ foreground: 'hsl(var(--secondary-foreground))',
+ },
+ destructive: {
+ DEFAULT: 'hsl(var(--destructive))',
+ foreground: 'hsl(var(--destructive-foreground))',
+ },
+ muted: {
+ DEFAULT: 'hsl(var(--muted))',
+ foreground: 'hsl(var(--muted-foreground))',
+ },
+ accent: {
+ DEFAULT: 'hsl(var(--accent))',
+ foreground: 'hsl(var(--accent-foreground))',
+ },
+ border: 'hsl(var(--border))',
+ ring: 'hsl(var(--ring))',
+ },
+ borderRadius: {
+ lg: 'var(--radius)',
+ md: 'calc(var(--radius) - 2px)',
+ sm: 'calc(var(--radius) - 4px)',
+ },
+ },
+ },
+ plugins: [],
+};
+
+export default config;
+''',
+ "postcss.config.js": '''module.exports = {
+ plugins: {
+ tailwindcss: {},
+ autoprefixer: {},
+ },
+};
+''',
+ "next.config.js": '''/** @type {import('next').NextConfig} */
+const nextConfig = {
+ images: {
+ remotePatterns: [],
+ formats: ['image/avif', 'image/webp'],
+ },
+ experimental: {
+ optimizePackageImports: ['lucide-react'],
+ },
+};
+
+module.exports = nextConfig;
+''',
+ "vite.config.ts": '''import { defineConfig } from 'vite';
+import react from '@vitejs/plugin-react';
+import path from 'path';
+
+export default defineConfig({
+ plugins: [react()],
+ resolve: {
+ alias: {
+ '@': path.resolve(__dirname, './src'),
+ },
+ },
+});
+''',
+ ".eslintrc.json": '''{
+ "extends": ["next/core-web-vitals", "prettier"],
+ "rules": {
+ "react/no-unescaped-entities": "off"
+ }
+}
+''',
+ ".prettierrc": '''{
+ "semi": true,
+ "singleQuote": true,
+ "tabWidth": 2,
+ "trailingComma": "es5",
+ "printWidth": 100
+}
+''',
+ ".gitignore": '''# Dependencies
+node_modules/
+.pnp
+.pnp.js
+
+# Build
+.next/
+out/
+dist/
+build/
+
+# Environment
+.env
+.env.local
+.env.*.local
+
+# IDE
+.vscode/
+.idea/
+
+# Debug
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+
+# OS
+.DS_Store
+Thumbs.db
+
+# Testing
+coverage/
+''',
+ "index.html": '''
+
+
+
+
+
+ ''' + name + '''
+
+
+
+
+
+
+''',
+ }
+
+
+def scaffold_project(
+ name: str,
+ output_dir: Path,
+ template: str = "nextjs",
+ features: Optional[List[str]] = None,
+ dry_run: bool = False,
+) -> Dict:
+ """Scaffold a complete frontend project."""
+ features = features or []
+ project_path = output_dir / name
+
+ if project_path.exists() and not dry_run:
+ return {"error": f"Directory already exists: {project_path}"}
+
+ template_config = TEMPLATES.get(template)
+ if not template_config:
+ return {"error": f"Unknown template: {template}"}
+
+ created_files = []
+
+ # Create project directory
+ if not dry_run:
+ project_path.mkdir(parents=True, exist_ok=True)
+
+ # Generate base structure
+ created_files.extend(
+ generate_structure(project_path, template_config["structure"], dry_run)
+ )
+
+ # Generate config files
+ created_files.extend(
+ generate_config_files(project_path, template, name, features, dry_run)
+ )
+
+ # Add feature files
+ for feature in features:
+ if feature in FEATURES:
+ for file_path, content_key in FEATURES[feature]["files"].items():
+ full_path = project_path / file_path
+ if not dry_run:
+ full_path.parent.mkdir(parents=True, exist_ok=True)
+ content = FILE_CONTENTS.get(content_key, f"// TODO: Implement {content_key}")
+ full_path.write_text(content)
+ created_files.append(str(full_path))
+
+ return {
+ "name": name,
+ "template": template,
+ "template_name": template_config["name"],
+ "features": features,
+ "path": str(project_path),
+ "files_created": len(created_files),
+ "files": created_files,
+ "next_steps": [
+ f"cd {name}",
+ "npm install",
+ "npm run dev",
+ ],
+ }
+
+
+def print_result(result: Dict) -> None:
+ """Print scaffolding result."""
+ if "error" in result:
+ print(f"Error: {result['error']}", file=sys.stderr)
+ return
+
+ print(f"\n{'='*60}")
+ print(f"Project Scaffolded: {result['name']}")
+ print(f"{'='*60}")
+ print(f"Template: {result['template_name']}")
+ print(f"Location: {result['path']}")
+ print(f"Files Created: {result['files_created']}")
+
+ if result["features"]:
+ print(f"Features: {', '.join(result['features'])}")
+
+ print(f"\nNext Steps:")
+ for step in result["next_steps"]:
+ print(f" $ {step}")
+
+ print(f"{'='*60}\n")
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="Scaffold a frontend project with best practices"
+ )
+ parser.add_argument(
+ "name",
+ help="Project name (kebab-case recommended)"
+ )
+ parser.add_argument(
+ "--dir", "-d",
+ default=".",
+ help="Output directory (default: current directory)"
+ )
+ parser.add_argument(
+ "--template", "-t",
+ choices=list(TEMPLATES.keys()),
+ default="nextjs",
+ help="Project template (default: nextjs)"
+ )
+ parser.add_argument(
+ "--features", "-f",
+ help="Comma-separated features to add (auth,api,forms,testing,storybook)"
+ )
+ parser.add_argument(
+ "--list-templates",
+ action="store_true",
+ help="List available templates"
+ )
+ parser.add_argument(
+ "--list-features",
+ action="store_true",
+ help="List available features"
+ )
+ parser.add_argument(
+ "--dry-run",
+ action="store_true",
+ help="Show what would be created without creating files"
+ )
+ parser.add_argument(
+ "--json",
+ action="store_true",
+ help="Output in JSON format"
+ )
+
+ args = parser.parse_args()
+
+ if args.list_templates:
+ print("\nAvailable Templates:")
+ for key, template in TEMPLATES.items():
+ print(f" {key}: {template['name']}")
+ print(f" {template['description']}")
+ return
+
+ if args.list_features:
+ print("\nAvailable Features:")
+ for key, feature in FEATURES.items():
+ print(f" {key}: {feature['description']}")
+ deps = ", ".join(feature.get("dependencies", []))
+ if deps:
+ print(f" Adds: {deps}")
+ return
+
+ features = []
+ if args.features:
+ features = [f.strip() for f in args.features.split(",")]
+ invalid = [f for f in features if f not in FEATURES]
+ if invalid:
+ print(f"Unknown features: {', '.join(invalid)}", file=sys.stderr)
+ print(f"Valid features: {', '.join(FEATURES.keys())}")
+ sys.exit(1)
+
+ result = scaffold_project(
+ name=args.name,
+ output_dir=Path(args.dir),
+ template=args.template,
+ features=features,
+ dry_run=args.dry_run,
+ )
+
+ if args.json:
+ print(json.dumps(result, indent=2))
+ else:
+ print_result(result)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/shadcn/SKILL.md b/skills/shadcn/SKILL.md
new file mode 100644
index 00000000..6d5c2f17
--- /dev/null
+++ b/skills/shadcn/SKILL.md
@@ -0,0 +1,250 @@
+---
+name: shadcn
+description: Manages shadcn/ui components and projects, providing context, documentation, and usage patterns for building modern design systems.
+user-invocable: false
+risk: safe
+source: https://github.com/shadcn-ui/ui/tree/main/skills/shadcn
+date_added: "2026-03-07"
+---
+
+# shadcn/ui
+
+A framework for building ui, components and design systems. Components are added as source code to the user's project via the CLI.
+
+> **IMPORTANT:** Run all CLI commands using the project's package runner: `npx shadcn@latest`, `pnpm dlx shadcn@latest`, or `bunx --bun shadcn@latest` — based on the project's `packageManager`. Examples below use `npx shadcn@latest` but substitute the correct runner for the project.
+
+## When to Use
+
+- Use when adding new components from shadcn/ui or community registries.
+- Use when styling, composing, or debugging existing shadcn/ui components.
+- Use when initializing a new project or switching design system presets.
+- Use to retrieve component documentation, examples, and API references.
+
+## Current Project Context
+
+```json
+!`npx shadcn@latest info --json 2>/dev/null || echo '{"error": "No shadcn project found. Run shadcn init first."}'`
+```
+
+The JSON above contains the project config and installed components. Use `npx shadcn@latest docs ` to get documentation and example URLs for any component.
+
+## Principles
+
+1. **Use existing components first.** Use `npx shadcn@latest search` to check registries before writing custom UI. Check community registries too.
+2. **Compose, don't reinvent.** Settings page = Tabs + Card + form controls. Dashboard = Sidebar + Card + Chart + Table.
+3. **Use built-in variants before custom styles.** `variant="outline"`, `size="sm"`, etc.
+4. **Use semantic colors.** `bg-primary`, `text-muted-foreground` — never raw values like `bg-blue-500`.
+
+## Critical Rules
+
+These rules are **always enforced**. Each links to a file with Incorrect/Correct code pairs.
+
+### Styling & Tailwind → [styling.md](./rules/styling.md)
+
+- **`className` for layout, not styling.** Never override component colors or typography.
+- **No `space-x-*` or `space-y-*`.** Use `flex` with `gap-*`. For vertical stacks, `flex flex-col gap-*`.
+- **Use `size-*` when width and height are equal.** `size-10` not `w-10 h-10`.
+- **Use `truncate` shorthand.** Not `overflow-hidden text-ellipsis whitespace-nowrap`.
+- **No manual `dark:` color overrides.** Use semantic tokens (`bg-background`, `text-muted-foreground`).
+- **Use `cn()` for conditional classes.** Don't write manual template literal ternaries.
+- **No manual `z-index` on overlay components.** Dialog, Sheet, Popover, etc. handle their own stacking.
+
+### Forms & Inputs → [forms.md](./rules/forms.md)
+
+- **Forms use `FieldGroup` + `Field`.** Never use raw `div` with `space-y-*` or `grid gap-*` for form layout.
+- **`InputGroup` uses `InputGroupInput`/`InputGroupTextarea`.** Never raw `Input`/`Textarea` inside `InputGroup`.
+- **Buttons inside inputs use `InputGroup` + `InputGroupAddon`.**
+- **Option sets (2–7 choices) use `ToggleGroup`.** Don't loop `Button` with manual active state.
+- **`FieldSet` + `FieldLegend` for grouping related checkboxes/radios.** Don't use a `div` with a heading.
+- **Field validation uses `data-invalid` + `aria-invalid`.** `data-invalid` on `Field`, `aria-invalid` on the control. For disabled: `data-disabled` on `Field`, `disabled` on the control.
+
+### Component Structure → [composition.md](./rules/composition.md)
+
+- **Items always inside their Group.** `SelectItem` → `SelectGroup`. `DropdownMenuItem` → `DropdownMenuGroup`. `CommandItem` → `CommandGroup`.
+- **Use `asChild` (radix) or `render` (base) for custom triggers.** Check `base` field from `npx shadcn@latest info`. → [base-vs-radix.md](./rules/base-vs-radix.md)
+- **Dialog, Sheet, and Drawer always need a Title.** `DialogTitle`, `SheetTitle`, `DrawerTitle` required for accessibility. Use `className="sr-only"` if visually hidden.
+- **Use full Card composition.** `CardHeader`/`CardTitle`/`CardDescription`/`CardContent`/`CardFooter`. Don't dump everything in `CardContent`.
+- **Button has no `isPending`/`isLoading`.** Compose with `Spinner` + `data-icon` + `disabled`.
+- **`TabsTrigger` must be inside `TabsList`.** Never render triggers directly in `Tabs`.
+- **`Avatar` always needs `AvatarFallback`.** For when the image fails to load.
+
+### Use Components, Not Custom Markup → [composition.md](./rules/composition.md)
+
+- **Use existing components before custom markup.** Check if a component exists before writing a styled `div`.
+- **Callouts use `Alert`.** Don't build custom styled divs.
+- **Empty states use `Empty`.** Don't build custom empty state markup.
+- **Toast via `sonner`.** Use `toast()` from `sonner`.
+- **Use `Separator`** instead of `
` or ``.
+- **Use `Skeleton`** for loading placeholders. No custom `animate-pulse` divs.
+- **Use `Badge`** instead of custom styled spans.
+
+### Icons → [icons.md](./rules/icons.md)
+
+- **Icons in `Button` use `data-icon`.** `data-icon="inline-start"` or `data-icon="inline-end"` on the icon.
+- **No sizing classes on icons inside components.** Components handle icon sizing via CSS. No `size-4` or `w-4 h-4`.
+- **Pass icons as objects, not string keys.** `icon={CheckIcon}`, not a string lookup.
+
+### CLI
+
+- **Never decode or fetch preset codes manually.** Pass them directly to `npx shadcn@latest init --preset
`.
+
+## Key Patterns
+
+These are the most common patterns that differentiate correct shadcn/ui code. For edge cases, see the linked rule files above.
+
+```tsx
+// Form layout: FieldGroup + Field, not div + Label.
+
+
+ Email
+
+
+
+
+// Validation: data-invalid on Field, aria-invalid on the control.
+
+ Email
+
+ Invalid email.
+
+
+// Icons in buttons: data-icon, no sizing classes.
+
+
+// Spacing: gap-*, not space-y-*.
+ // correct
+
// wrong
+
+// Equal dimensions: size-*, not w-* h-*.
+
// correct
+ // wrong
+
+// Status colors: Badge variants or semantic tokens, not raw colors.
++20.1% // correct
++20.1% // wrong
+```
+
+## Component Selection
+
+| Need | Use |
+| -------------------------- | --------------------------------------------------------------------------------------------------- |
+| Button/action | `Button` with appropriate variant |
+| Form inputs | `Input`, `Select`, `Combobox`, `Switch`, `Checkbox`, `RadioGroup`, `Textarea`, `InputOTP`, `Slider` |
+| Toggle between 2–5 options | `ToggleGroup` + `ToggleGroupItem` |
+| Data display | `Table`, `Card`, `Badge`, `Avatar` |
+| Navigation | `Sidebar`, `NavigationMenu`, `Breadcrumb`, `Tabs`, `Pagination` |
+| Overlays | `Dialog` (modal), `Sheet` (side panel), `Drawer` (bottom sheet), `AlertDialog` (confirmation) |
+| Feedback | `sonner` (toast), `Alert`, `Progress`, `Skeleton`, `Spinner` |
+| Command palette | `Command` inside `Dialog` |
+| Charts | `Chart` (wraps Recharts) |
+| Layout | `Card`, `Separator`, `Resizable`, `ScrollArea`, `Accordion`, `Collapsible` |
+| Empty states | `Empty` |
+| Menus | `DropdownMenu`, `ContextMenu`, `Menubar` |
+| Tooltips/info | `Tooltip`, `HoverCard`, `Popover` |
+
+## Key Fields
+
+The injected project context contains these key fields:
+
+- **`aliases`** → use the actual alias prefix for imports (e.g. `@/`, `~/`), never hardcode.
+- **`isRSC`** → when `true`, components using `useState`, `useEffect`, event handlers, or browser APIs need `"use client"` at the top of the file. Always reference this field when advising on the directive.
+- **`tailwindVersion`** → `"v4"` uses `@theme inline` blocks; `"v3"` uses `tailwind.config.js`.
+- **`tailwindCssFile`** → the global CSS file where custom CSS variables are defined. Always edit this file, never create a new one.
+- **`style`** → component visual treatment (e.g. `nova`, `vega`).
+- **`base`** → primitive library (`radix` or `base`). Affects component APIs and available props.
+- **`iconLibrary`** → determines icon imports. Use `lucide-react` for `lucide`, `@tabler/icons-react` for `tabler`, etc. Never assume `lucide-react`.
+- **`resolvedPaths`** → exact file-system destinations for components, utils, hooks, etc.
+- **`framework`** → routing and file conventions (e.g. Next.js App Router vs Vite SPA).
+- **`packageManager`** → use this for any non-shadcn dependency installs (e.g. `pnpm add date-fns` vs `npm install date-fns`).
+
+See [cli.md — `info` command](./cli.md) for the full field reference.
+
+## Component Docs, Examples, and Usage
+
+Run `npx shadcn@latest docs ` to get the URLs for a component's documentation, examples, and API reference. Fetch these URLs to get the actual content.
+
+```bash
+npx shadcn@latest docs button dialog select
+```
+
+**When creating, fixing, debugging, or using a component, always run `npx shadcn@latest docs` and fetch the URLs first.** This ensures you're working with the correct API and usage patterns rather than guessing.
+
+## Workflow
+
+1. **Get project context** — already injected above. Run `npx shadcn@latest info` again if you need to refresh.
+2. **Check installed components first** — before running `add`, always check the `components` list from project context or list the `resolvedPaths.ui` directory. Don't import components that haven't been added, and don't re-add ones already installed.
+3. **Find components** — `npx shadcn@latest search`.
+4. **Get docs and examples** — run `npx shadcn@latest docs ` to get URLs, then fetch them. Use `npx shadcn@latest view` to browse registry items you haven't installed. To preview changes to installed components, use `npx shadcn@latest add --diff`.
+5. **Install or update** — `npx shadcn@latest add`. When updating existing components, use `--dry-run` and `--diff` to preview changes first (see [Updating Components](#updating-components) below).
+6. **Fix imports in third-party components** — After adding components from community registries (e.g. `@bundui`, `@magicui`), check the added non-UI files for hardcoded import paths like `@/components/ui/...`. These won't match the project's actual aliases. Use `npx shadcn@latest info` to get the correct `ui` alias (e.g. `@workspace/ui/components`) and rewrite the imports accordingly. The CLI rewrites imports for its own UI files, but third-party registry components may use default paths that don't match the project.
+7. **Review added components** — After adding a component or block from any registry, **always read the added files and verify they are correct**. Check for missing sub-components (e.g. `SelectItem` without `SelectGroup`), missing imports, incorrect composition, or violations of the [Critical Rules](#critical-rules). Also replace any icon imports with the project's `iconLibrary` from the project context (e.g. if the registry item uses `lucide-react` but the project uses `hugeicons`, swap the imports and icon names accordingly). Fix all issues before moving on.
+8. **Registry must be explicit** — When the user asks to add a block or component, **do not guess the registry**. If no registry is specified (e.g. user says "add a login block" without specifying `@shadcn`, `@tailark`, etc.), ask which registry to use. Never default to a registry on behalf of the user.
+9. **Switching presets** — Ask the user first: **reinstall**, **merge**, or **skip**?
+ - **Reinstall**: `npx shadcn@latest init --preset --force --reinstall`. Overwrites all components.
+ - **Merge**: `npx shadcn@latest init --preset --force --no-reinstall`, then run `npx shadcn@latest info` to list installed components, then for each installed component use `--dry-run` and `--diff` to [smart merge](#updating-components) it individually.
+ - **Skip**: `npx shadcn@latest init --preset --force --no-reinstall`. Only updates config and CSS, leaves components as-is.
+
+## Updating Components
+
+When the user asks to update a component from upstream while keeping their local changes, use `--dry-run` and `--diff` to intelligently merge. **NEVER fetch raw files from GitHub manually — always use the CLI.**
+
+1. Run `npx shadcn@latest add --dry-run` to see all files that would be affected.
+2. For each file, run `npx shadcn@latest add --diff ` to see what changed upstream vs local.
+3. Decide per file based on the diff:
+ - No local changes → safe to overwrite.
+ - Has local changes → read the local file, analyze the diff, and apply upstream updates while preserving local modifications.
+ - User says "just update everything" → use `--overwrite`, but confirm first.
+4. **Never use `--overwrite` without the user's explicit approval.**
+
+## Quick Reference
+
+```bash
+# Create a new project.
+npx shadcn@latest init --name my-app --preset base-nova
+npx shadcn@latest init --name my-app --preset a2r6bw --template vite
+
+# Create a monorepo project.
+npx shadcn@latest init --name my-app --preset base-nova --monorepo
+npx shadcn@latest init --name my-app --preset base-nova --template next --monorepo
+
+# Initialize existing project.
+npx shadcn@latest init --preset base-nova
+npx shadcn@latest init --defaults # shortcut: --template=next --preset=base-nova
+
+# Add components.
+npx shadcn@latest add button card dialog
+npx shadcn@latest add @magicui/shimmer-button
+npx shadcn@latest add --all
+
+# Preview changes before adding/updating.
+npx shadcn@latest add button --dry-run
+npx shadcn@latest add button --diff button.tsx
+npx shadcn@latest add @acme/form --view button.tsx
+
+# Search registries.
+npx shadcn@latest search @shadcn -q "sidebar"
+npx shadcn@latest search @tailark -q "stats"
+
+# Get component docs and example URLs.
+npx shadcn@latest docs button dialog select
+
+# View registry item details (for items not yet installed).
+npx shadcn@latest view @shadcn/button
+```
+
+**Named presets:** `base-nova`, `radix-nova`
+**Templates:** `next`, `vite`, `start`, `react-router`, `astro` (all support `--monorepo`) and `laravel` (not supported for monorepo)
+**Preset codes:** Base62 strings starting with `a` (e.g. `a2r6bw`), from [ui.shadcn.com](https://ui.shadcn.com).
+
+## Detailed References
+
+- [rules/forms.md](./rules/forms.md) — FieldGroup, Field, InputGroup, ToggleGroup, FieldSet, validation states
+- [rules/composition.md](./rules/composition.md) — Groups, overlays, Card, Tabs, Avatar, Alert, Empty, Toast, Separator, Skeleton, Badge, Button loading
+- [rules/icons.md](./rules/icons.md) — data-icon, icon sizing, passing icons as objects
+- [rules/styling.md](./rules/styling.md) — Semantic colors, variants, className, spacing, size, truncate, dark mode, cn(), z-index
+- [rules/base-vs-radix.md](./rules/base-vs-radix.md) — asChild vs render, Select, ToggleGroup, Slider, Accordion
+- [cli.md](./cli.md) — Commands, flags, presets, templates
+- [customization.md](./customization.md) — Theming, CSS variables, extending components
diff --git a/skills/shadcn/agents/openai.yml b/skills/shadcn/agents/openai.yml
new file mode 100644
index 00000000..ab636da8
--- /dev/null
+++ b/skills/shadcn/agents/openai.yml
@@ -0,0 +1,5 @@
+interface:
+ display_name: "shadcn/ui"
+ short_description: "Manages shadcn/ui components — adding, searching, fixing, debugging, styling, and composing UI."
+ icon_small: "./assets/shadcn-small.png"
+ icon_large: "./assets/shadcn.png"
diff --git a/skills/shadcn/assets/shadcn-small.png b/skills/shadcn/assets/shadcn-small.png
new file mode 100644
index 00000000..547154b9
Binary files /dev/null and b/skills/shadcn/assets/shadcn-small.png differ
diff --git a/skills/shadcn/assets/shadcn.png b/skills/shadcn/assets/shadcn.png
new file mode 100644
index 00000000..b7b6814a
Binary files /dev/null and b/skills/shadcn/assets/shadcn.png differ
diff --git a/skills/shadcn/cli.md b/skills/shadcn/cli.md
new file mode 100644
index 00000000..32124036
--- /dev/null
+++ b/skills/shadcn/cli.md
@@ -0,0 +1,255 @@
+# shadcn CLI Reference
+
+Configuration is read from `components.json`.
+
+> **IMPORTANT:** Always run commands using the project's package runner: `npx shadcn@latest`, `pnpm dlx shadcn@latest`, or `bunx --bun shadcn@latest`. Check `packageManager` from project context to choose the right one. Examples below use `npx shadcn@latest` but substitute the correct runner for the project.
+
+> **IMPORTANT:** Only use the flags documented below. Do not invent or guess flags — if a flag isn't listed here, it doesn't exist. The CLI auto-detects the package manager from the project's lockfile; there is no `--package-manager` flag.
+
+## Contents
+
+- Commands: init, add (dry-run, smart merge), search, view, docs, info, build
+- Templates: next, vite, start, react-router, astro
+- Presets: named, code, URL formats and fields
+- Switching presets
+
+---
+
+## Commands
+
+### `init` — Initialize or create a project
+
+```bash
+npx shadcn@latest init [components...] [options]
+```
+
+Initializes shadcn/ui in an existing project or creates a new project (when `--name` is provided). Optionally installs components in the same step.
+
+| Flag | Short | Description | Default |
+| ----------------------- | ----- | --------------------------------------------------------- | ------- |
+| `--template ` | `-t` | Template (next, start, vite, next-monorepo, react-router) | — |
+| `--preset [name]` | `-p` | Preset configuration (named, code, or URL) | — |
+| `--yes` | `-y` | Skip confirmation prompt | `true` |
+| `--defaults` | `-d` | Use defaults (`--template=next --preset=base-nova`) | `false` |
+| `--force` | `-f` | Force overwrite existing configuration | `false` |
+| `--cwd ` | `-c` | Working directory | current |
+| `--name ` | `-n` | Name for new project | — |
+| `--silent` | `-s` | Mute output | `false` |
+| `--rtl` | | Enable RTL support | — |
+| `--reinstall` | | Re-install existing UI components | `false` |
+| `--monorepo` | | Scaffold a monorepo project | — |
+| `--no-monorepo` | | Skip the monorepo prompt | — |
+
+`npx shadcn@latest create` is an alias for `npx shadcn@latest init`.
+
+### `add` — Add components
+
+> **IMPORTANT:** To compare local components against upstream or to preview changes, ALWAYS use `npx shadcn@latest add --dry-run`, `--diff`, or `--view`. NEVER fetch raw files from GitHub or other sources manually. The CLI handles registry resolution, file paths, and CSS diffing automatically.
+
+```bash
+npx shadcn@latest add [components...] [options]
+```
+
+Accepts component names, registry-prefixed names (`@magicui/shimmer-button`), URLs, or local paths.
+
+| Flag | Short | Description | Default |
+| --------------- | ----- | -------------------------------------------------------------------------------------------------------------------- | ------- |
+| `--yes` | `-y` | Skip confirmation prompt | `false` |
+| `--overwrite` | `-o` | Overwrite existing files | `false` |
+| `--cwd ` | `-c` | Working directory | current |
+| `--all` | `-a` | Add all available components | `false` |
+| `--path ` | `-p` | Target path for the component | — |
+| `--silent` | `-s` | Mute output | `false` |
+| `--dry-run` | | Preview all changes without writing files | `false` |
+| `--diff [path]` | | Show diffs. Without a path, shows the first 5 files. With a path, shows that file only (implies `--dry-run`) | — |
+| `--view [path]` | | Show file contents. Without a path, shows the first 5 files. With a path, shows that file only (implies `--dry-run`) | — |
+
+#### Dry-Run Mode
+
+Use `--dry-run` to preview what `add` would do without writing any files. `--diff` and `--view` both imply `--dry-run`.
+
+```bash
+# Preview all changes.
+npx shadcn@latest add button --dry-run
+
+# Show diffs for all files (top 5).
+npx shadcn@latest add button --diff
+
+# Show the diff for a specific file.
+npx shadcn@latest add button --diff button.tsx
+
+# Show contents for all files (top 5).
+npx shadcn@latest add button --view
+
+# Show the full content of a specific file.
+npx shadcn@latest add button --view button.tsx
+
+# Works with URLs too.
+npx shadcn@latest add https://api.npoint.io/abc123 --dry-run
+
+# CSS diffs.
+npx shadcn@latest add button --diff globals.css
+```
+
+**When to use dry-run:**
+
+- When the user asks "what files will this add?" or "what will this change?" — use `--dry-run`.
+- Before overwriting existing components — use `--diff` to preview the changes first.
+- When the user wants to inspect component source code without installing — use `--view`.
+- When checking what CSS changes would be made to `globals.css` — use `--diff globals.css`.
+- When the user asks to review or audit third-party registry code before installing — use `--view` to inspect the source.
+
+> **`npx shadcn@latest add --dry-run` vs `npx shadcn@latest view`:** Prefer `npx shadcn@latest add --dry-run/--diff/--view` over `npx shadcn@latest view` when the user wants to preview changes to their project. `npx shadcn@latest view` only shows raw registry metadata. `npx shadcn@latest add --dry-run` shows exactly what would happen in the user's project: resolved file paths, diffs against existing files, and CSS updates. Use `npx shadcn@latest view` only when the user wants to browse registry info without a project context.
+
+#### Smart Merge from Upstream
+
+See [Updating Components in SKILL.md](./SKILL.md#updating-components) for the full workflow.
+
+### `search` — Search registries
+
+```bash
+npx shadcn@latest search [options]
+```
+
+Fuzzy search across registries. Also aliased as `npx shadcn@latest list`. Without `-q`, lists all items.
+
+| Flag | Short | Description | Default |
+| ------------------- | ----- | ---------------------- | ------- |
+| `--query ` | `-q` | Search query | — |
+| `--limit ` | `-l` | Max items per registry | `100` |
+| `--offset ` | `-o` | Items to skip | `0` |
+| `--cwd ` | `-c` | Working directory | current |
+
+### `view` — View item details
+
+```bash
+npx shadcn@latest view [options]
+```
+
+Displays item info including file contents. Example: `npx shadcn@latest view @shadcn/button`.
+
+### `docs` — Get component documentation URLs
+
+```bash
+npx shadcn@latest docs [options]
+```
+
+Outputs resolved URLs for component documentation, examples, and API references. Accepts one or more component names. Fetch the URLs to get the actual content.
+
+Example output for `npx shadcn@latest docs input button`:
+
+```
+base radix
+
+input
+ docs https://ui.shadcn.com/docs/components/radix/input
+ examples https://raw.githubusercontent.com/.../examples/input-example.tsx
+
+button
+ docs https://ui.shadcn.com/docs/components/radix/button
+ examples https://raw.githubusercontent.com/.../examples/button-example.tsx
+```
+
+Some components include an `api` link to the underlying library (e.g. `cmdk` for the command component).
+
+### `diff` — Check for updates
+
+Do not use this command. Use `npx shadcn@latest add --diff` instead.
+
+### `info` — Project information
+
+```bash
+npx shadcn@latest info [options]
+```
+
+Displays project info and `components.json` configuration. Run this first to discover the project's framework, aliases, Tailwind version, and resolved paths.
+
+| Flag | Short | Description | Default |
+| ------------- | ----- | ----------------- | ------- |
+| `--cwd ` | `-c` | Working directory | current |
+
+**Project Info fields:**
+
+| Field | Type | Meaning |
+| -------------------- | --------- | ------------------------------------------------------------------ |
+| `framework` | `string` | Detected framework (`next`, `vite`, `react-router`, `start`, etc.) |
+| `frameworkVersion` | `string` | Framework version (e.g. `15.2.4`) |
+| `isSrcDir` | `boolean` | Whether the project uses a `src/` directory |
+| `isRSC` | `boolean` | Whether React Server Components are enabled |
+| `isTsx` | `boolean` | Whether the project uses TypeScript |
+| `tailwindVersion` | `string` | `"v3"` or `"v4"` |
+| `tailwindConfigFile` | `string` | Path to the Tailwind config file |
+| `tailwindCssFile` | `string` | Path to the global CSS file |
+| `aliasPrefix` | `string` | Import alias prefix (e.g. `@`, `~`, `@/`) |
+| `packageManager` | `string` | Detected package manager (`npm`, `pnpm`, `yarn`, `bun`) |
+
+**Components.json fields:**
+
+| Field | Type | Meaning |
+| -------------------- | --------- | ------------------------------------------------------------------------------------------ |
+| `base` | `string` | Primitive library (`radix` or `base`) — determines component APIs and available props |
+| `style` | `string` | Visual style (e.g. `nova`, `vega`) |
+| `rsc` | `boolean` | RSC flag from config |
+| `tsx` | `boolean` | TypeScript flag |
+| `tailwind.config` | `string` | Tailwind config path |
+| `tailwind.css` | `string` | Global CSS path — this is where custom CSS variables go |
+| `iconLibrary` | `string` | Icon library — determines icon import package (e.g. `lucide-react`, `@tabler/icons-react`) |
+| `aliases.components` | `string` | Component import alias (e.g. `@/components`) |
+| `aliases.utils` | `string` | Utils import alias (e.g. `@/lib/utils`) |
+| `aliases.ui` | `string` | UI component alias (e.g. `@/components/ui`) |
+| `aliases.lib` | `string` | Lib alias (e.g. `@/lib`) |
+| `aliases.hooks` | `string` | Hooks alias (e.g. `@/hooks`) |
+| `resolvedPaths` | `object` | Absolute file-system paths for each alias |
+| `registries` | `object` | Configured custom registries |
+
+**Links fields:**
+
+The `info` output includes a **Links** section with templated URLs for component docs, source, and examples. For resolved URLs, use `npx shadcn@latest docs ` instead.
+
+### `build` — Build a custom registry
+
+```bash
+npx shadcn@latest build [registry] [options]
+```
+
+Builds `registry.json` into individual JSON files for distribution. Default input: `./registry.json`, default output: `./public/r`.
+
+| Flag | Short | Description | Default |
+| ----------------- | ----- | ----------------- | ------------ |
+| `--output ` | `-o` | Output directory | `./public/r` |
+| `--cwd ` | `-c` | Working directory | current |
+
+---
+
+## Templates
+
+| Value | Framework | Monorepo support |
+| -------------- | -------------- | ---------------- |
+| `next` | Next.js | Yes |
+| `vite` | Vite | Yes |
+| `start` | TanStack Start | Yes |
+| `react-router` | React Router | Yes |
+| `astro` | Astro | Yes |
+| `laravel` | Laravel | No |
+
+All templates support monorepo scaffolding via the `--monorepo` flag. When passed, the CLI uses a monorepo-specific template directory (e.g. `next-monorepo`, `vite-monorepo`). When neither `--monorepo` nor `--no-monorepo` is passed, the CLI prompts interactively. Laravel does not support monorepo scaffolding.
+
+---
+
+## Presets
+
+Three ways to specify a preset via `--preset`:
+
+1. **Named:** `--preset base-nova` or `--preset radix-nova`
+2. **Code:** `--preset a2r6bw` (base62 string, starts with lowercase `a`)
+3. **URL:** `--preset "https://ui.shadcn.com/init?base=radix&style=nova&..."`
+
+> **IMPORTANT:** Never try to decode, fetch, or resolve preset codes manually. Preset codes are opaque — pass them directly to `npx shadcn@latest init --preset ` and let the CLI handle resolution.
+
+## Switching Presets
+
+Ask the user first: **reinstall**, **merge**, or **skip** existing components?
+
+- **Re-install** → `npx shadcn@latest init --preset --force --reinstall`. Overwrites all component files with the new preset styles. Use when the user hasn't customized components.
+- **Merge** → `npx shadcn@latest init --preset --force --no-reinstall`, then run `npx shadcn@latest info` to get the list of installed components and use the [smart merge workflow](./SKILL.md#updating-components) to update them one by one, preserving local changes. Use when the user has customized components.
+- **Skip** → `npx shadcn@latest init --preset --force --no-reinstall`. Only updates config and CSS variables, leaves existing components as-is.
diff --git a/skills/shadcn/customization.md b/skills/shadcn/customization.md
new file mode 100644
index 00000000..6e686ab0
--- /dev/null
+++ b/skills/shadcn/customization.md
@@ -0,0 +1,202 @@
+# Customization & Theming
+
+Components reference semantic CSS variable tokens. Change the variables to change every component.
+
+## Contents
+
+- How it works (CSS variables → Tailwind utilities → components)
+- Color variables and OKLCH format
+- Dark mode setup
+- Changing the theme (presets, CSS variables)
+- Adding custom colors (Tailwind v3 and v4)
+- Border radius
+- Customizing components (variants, className, wrappers)
+- Checking for updates
+
+---
+
+## How It Works
+
+1. CSS variables defined in `:root` (light) and `.dark` (dark mode).
+2. Tailwind maps them to utilities: `bg-primary`, `text-muted-foreground`, etc.
+3. Components use these utilities — changing a variable changes all components that reference it.
+
+---
+
+## Color Variables
+
+Every color follows the `name` / `name-foreground` convention. The base variable is for backgrounds, `-foreground` is for text/icons on that background.
+
+| Variable | Purpose |
+| -------------------------------------------- | -------------------------------- |
+| `--background` / `--foreground` | Page background and default text |
+| `--card` / `--card-foreground` | Card surfaces |
+| `--primary` / `--primary-foreground` | Primary buttons and actions |
+| `--secondary` / `--secondary-foreground` | Secondary actions |
+| `--muted` / `--muted-foreground` | Muted/disabled states |
+| `--accent` / `--accent-foreground` | Hover and accent states |
+| `--destructive` / `--destructive-foreground` | Error and destructive actions |
+| `--border` | Default border color |
+| `--input` | Form input borders |
+| `--ring` | Focus ring color |
+| `--chart-1` through `--chart-5` | Chart/data visualization |
+| `--sidebar-*` | Sidebar-specific colors |
+| `--surface` / `--surface-foreground` | Secondary surface |
+
+Colors use OKLCH: `--primary: oklch(0.205 0 0)` where values are lightness (0–1), chroma (0 = gray), and hue (0–360).
+
+---
+
+## Dark Mode
+
+Class-based toggle via `.dark` on the root element. In Next.js, use `next-themes`:
+
+```tsx
+import { ThemeProvider } from "next-themes"
+
+
+ {children}
+
+```
+
+---
+
+## Changing the Theme
+
+```bash
+# Apply a preset code from ui.shadcn.com.
+npx shadcn@latest init --preset a2r6bw --force
+
+# Switch to a named preset.
+npx shadcn@latest init --preset radix-nova --force
+npx shadcn@latest init --reinstall # update existing components to match
+
+# Use a custom theme URL.
+npx shadcn@latest init --preset "https://ui.shadcn.com/init?base=radix&style=nova&theme=blue&..." --force
+```
+
+Or edit CSS variables directly in `globals.css`.
+
+---
+
+## Adding Custom Colors
+
+Add variables to the file at `tailwindCssFile` from `npx shadcn@latest info` (typically `globals.css`). Never create a new CSS file for this.
+
+```css
+/* 1. Define in the global CSS file. */
+:root {
+ --warning: oklch(0.84 0.16 84);
+ --warning-foreground: oklch(0.28 0.07 46);
+}
+.dark {
+ --warning: oklch(0.41 0.11 46);
+ --warning-foreground: oklch(0.99 0.02 95);
+}
+```
+
+```css
+/* 2a. Register with Tailwind v4 (@theme inline). */
+@theme inline {
+ --color-warning: var(--warning);
+ --color-warning-foreground: var(--warning-foreground);
+}
+```
+
+When `tailwindVersion` is `"v3"` (check via `npx shadcn@latest info`), register in `tailwind.config.js` instead:
+
+```js
+// 2b. Register with Tailwind v3 (tailwind.config.js).
+module.exports = {
+ theme: {
+ extend: {
+ colors: {
+ warning: "oklch(var(--warning) / )",
+ "warning-foreground":
+ "oklch(var(--warning-foreground) / )",
+ },
+ },
+ },
+}
+```
+
+```tsx
+// 3. Use in components.
+Warning
+```
+
+---
+
+## Border Radius
+
+`--radius` controls border radius globally. Components derive values from it (`rounded-lg` = `var(--radius)`, `rounded-md` = `calc(var(--radius) - 2px)`).
+
+---
+
+## Customizing Components
+
+See also: [rules/styling.md](./rules/styling.md) for Incorrect/Correct examples.
+
+Prefer these approaches in order:
+
+### 1. Built-in variants
+
+```tsx
+
+```
+
+### 2. Tailwind classes via `className`
+
+```tsx
+...
+```
+
+### 3. Add a new variant
+
+Edit the component source to add a variant via `cva`:
+
+```tsx
+// components/ui/button.tsx
+warning: "bg-warning text-warning-foreground hover:bg-warning/90",
+```
+
+### 4. Wrapper components
+
+Compose shadcn/ui primitives into higher-level components:
+
+```tsx
+export function ConfirmDialog({ title, description, onConfirm, children }) {
+ return (
+
+ {children}
+
+
+ {title}
+ {description}
+
+
+ Cancel
+ Confirm
+
+
+
+ )
+}
+```
+
+---
+
+## Checking for Updates
+
+```bash
+npx shadcn@latest add button --diff
+```
+
+To preview exactly what would change before updating, use `--dry-run` and `--diff`:
+
+```bash
+npx shadcn@latest add button --dry-run # see all affected files
+npx shadcn@latest add button --diff button.tsx # see the diff for a specific file
+```
+
+See [Updating Components in SKILL.md](./SKILL.md#updating-components) for the full smart merge workflow.
diff --git a/skills/shadcn/evals/evals.json b/skills/shadcn/evals/evals.json
new file mode 100644
index 00000000..0df77e4b
--- /dev/null
+++ b/skills/shadcn/evals/evals.json
@@ -0,0 +1,47 @@
+{
+ "skill_name": "shadcn",
+ "evals": [
+ {
+ "id": 1,
+ "prompt": "I'm building a Next.js app with shadcn/ui (base-nova preset, lucide icons). Create a settings form component with fields for: full name, email address, and notification preferences (email, SMS, push notifications as toggle options). Add validation states for required fields.",
+ "expected_output": "A React component using FieldGroup, Field, ToggleGroup, data-invalid/aria-invalid validation, gap-* spacing, and semantic colors.",
+ "files": [],
+ "expectations": [
+ "Uses FieldGroup and Field components for form layout instead of raw div with space-y",
+ "Uses Switch for independent on/off notification toggles (not looping Button with manual active state)",
+ "Uses data-invalid on Field and aria-invalid on the input control for validation states",
+ "Uses gap-* (e.g. gap-4, gap-6) instead of space-y-* or space-x-* for spacing",
+ "Uses semantic color tokens (e.g. bg-background, text-muted-foreground, text-destructive) instead of raw colors like bg-red-500",
+ "No manual dark: color overrides"
+ ]
+ },
+ {
+ "id": 2,
+ "prompt": "Create a dialog component for editing a user profile. It should have the user's avatar at the top, input fields for name and bio, and Save/Cancel buttons with appropriate icons. Using shadcn/ui with radix-nova preset and tabler icons.",
+ "expected_output": "A React component with DialogTitle, Avatar+AvatarFallback, data-icon on icon buttons, no icon sizing classes, tabler icon imports.",
+ "files": [],
+ "expectations": [
+ "Includes DialogTitle for accessibility (visible or with sr-only class)",
+ "Avatar component includes AvatarFallback",
+ "Icons on buttons use the data-icon attribute (data-icon=\"inline-start\" or data-icon=\"inline-end\")",
+ "No sizing classes on icons inside components (no size-4, w-4, h-4, etc.)",
+ "Uses tabler icons (@tabler/icons-react) instead of lucide-react",
+ "Uses asChild for custom triggers (radix preset)"
+ ]
+ },
+ {
+ "id": 3,
+ "prompt": "Create a dashboard component that shows 4 stat cards in a grid. Each card has a title, large number, percentage change badge, and a loading skeleton state. Using shadcn/ui with base-nova preset and lucide icons.",
+ "expected_output": "A React component with full Card composition, Skeleton for loading, Badge for changes, semantic colors, gap-* spacing.",
+ "files": [],
+ "expectations": [
+ "Uses full Card composition with CardHeader, CardTitle, CardContent (not dumping everything into CardContent)",
+ "Uses Skeleton component for loading placeholders instead of custom animate-pulse divs",
+ "Uses Badge component for percentage change instead of custom styled spans",
+ "Uses semantic color tokens instead of raw color values like bg-green-500 or text-red-600",
+ "Uses gap-* instead of space-y-* or space-x-* for spacing",
+ "Uses size-* when width and height are equal instead of separate w-* h-*"
+ ]
+ }
+ ]
+}
diff --git a/skills/shadcn/mcp.md b/skills/shadcn/mcp.md
new file mode 100644
index 00000000..15b50e91
--- /dev/null
+++ b/skills/shadcn/mcp.md
@@ -0,0 +1,94 @@
+# shadcn MCP Server
+
+The CLI includes an MCP server that lets AI assistants search, browse, view, and install components from registries.
+
+---
+
+## Setup
+
+```bash
+shadcn mcp # start the MCP server (stdio)
+shadcn mcp init # write config for your editor
+```
+
+Editor config files:
+
+| Editor | Config file |
+|--------|------------|
+| Claude Code | `.mcp.json` |
+| Cursor | `.cursor/mcp.json` |
+| VS Code | `.vscode/mcp.json` |
+| OpenCode | `opencode.json` |
+| Codex | `~/.codex/config.toml` (manual) |
+
+---
+
+## Tools
+
+> **Tip:** MCP tools handle registry operations (search, view, install). For project configuration (aliases, framework, Tailwind version), use `npx shadcn@latest info` — there is no MCP equivalent.
+
+### `shadcn:get_project_registries`
+
+Returns registry names from `components.json`. Errors if no `components.json` exists.
+
+**Input:** none
+
+### `shadcn:list_items_in_registries`
+
+Lists all items from one or more registries.
+
+**Input:** `registries` (string[]), `limit` (number, optional), `offset` (number, optional)
+
+### `shadcn:search_items_in_registries`
+
+Fuzzy search across registries.
+
+**Input:** `registries` (string[]), `query` (string), `limit` (number, optional), `offset` (number, optional)
+
+### `shadcn:view_items_in_registries`
+
+View item details including full file contents.
+
+**Input:** `items` (string[]) — e.g. `["@shadcn/button", "@shadcn/card"]`
+
+### `shadcn:get_item_examples_from_registries`
+
+Find usage examples and demos with source code.
+
+**Input:** `registries` (string[]), `query` (string) — e.g. `"accordion-demo"`, `"button example"`
+
+### `shadcn:get_add_command_for_items`
+
+Returns the CLI install command.
+
+**Input:** `items` (string[]) — e.g. `["@shadcn/button"]`
+
+### `shadcn:get_audit_checklist`
+
+Returns a checklist for verifying components (imports, deps, lint, TypeScript).
+
+**Input:** none
+
+---
+
+## Configuring Registries
+
+Registries are set in `components.json`. The `@shadcn` registry is always built-in.
+
+```json
+{
+ "registries": {
+ "@acme": "https://acme.com/r/{name}.json",
+ "@private": {
+ "url": "https://private.com/r/{name}.json",
+ "headers": { "Authorization": "Bearer ${MY_TOKEN}" }
+ }
+ }
+}
+```
+
+- Names must start with `@`.
+- URLs must contain `{name}`.
+- `${VAR}` references are resolved from environment variables.
+
+Community registry index: `https://ui.shadcn.com/r/registries.json`
diff --git a/skills/shadcn/rules/base-vs-radix.md b/skills/shadcn/rules/base-vs-radix.md
new file mode 100644
index 00000000..c1ed7d11
--- /dev/null
+++ b/skills/shadcn/rules/base-vs-radix.md
@@ -0,0 +1,306 @@
+# Base vs Radix
+
+API differences between `base` and `radix`. Check the `base` field from `npx shadcn@latest info`.
+
+## Contents
+
+- Composition: asChild vs render
+- Button / trigger as non-button element
+- Select (items prop, placeholder, positioning, multiple, object values)
+- ToggleGroup (type vs multiple)
+- Slider (scalar vs array)
+- Accordion (type and defaultValue)
+
+---
+
+## Composition: asChild (radix) vs render (base)
+
+Radix uses `asChild` to replace the default element. Base uses `render`. Don't wrap triggers in extra elements.
+
+**Incorrect:**
+
+```tsx
+
+
+
+
+
+```
+
+**Correct (radix):**
+
+```tsx
+
+
+
+```
+
+**Correct (base):**
+
+```tsx
+}>Open
+```
+
+This applies to all trigger and close components: `DialogTrigger`, `SheetTrigger`, `AlertDialogTrigger`, `DropdownMenuTrigger`, `PopoverTrigger`, `TooltipTrigger`, `CollapsibleTrigger`, `DialogClose`, `SheetClose`, `NavigationMenuLink`, `BreadcrumbLink`, `SidebarMenuButton`, `Badge`, `Item`.
+
+---
+
+## Button / trigger as non-button element (base only)
+
+When `render` changes an element to a non-button (``, ``), add `nativeButton={false}`.
+
+**Incorrect (base):** missing `nativeButton={false}`.
+
+```tsx
+}>Read the docs
+```
+
+**Correct (base):**
+
+```tsx
+} nativeButton={false}>
+ Read the docs
+
+```
+
+**Correct (radix):**
+
+```tsx
+
+```
+
+Same for triggers whose `render` is not a `Button`:
+
+```tsx
+// base.
+} nativeButton={false}>
+ Pick date
+
+```
+
+---
+
+## Select
+
+**items prop (base only).** Base requires an `items` prop on the root. Radix uses inline JSX only.
+
+**Incorrect (base):**
+
+```tsx
+
+```
+
+**Correct (base):**
+
+```tsx
+const items = [
+ { label: "Select a fruit", value: null },
+ { label: "Apple", value: "apple" },
+ { label: "Banana", value: "banana" },
+]
+
+
+```
+
+**Correct (radix):**
+
+```tsx
+
+```
+
+**Placeholder.** Base uses a `{ value: null }` item in the items array. Radix uses ``.
+
+**Content positioning.** Base uses `alignItemWithTrigger`. Radix uses `position`.
+
+```tsx
+// base.
+
+
+// radix.
+
+```
+
+---
+
+## Select — multiple selection and object values (base only)
+
+Base supports `multiple`, render-function children on `SelectValue`, and object values with `itemToStringValue`. Radix is single-select with string values only.
+
+**Correct (base — multiple selection):**
+
+```tsx
+
+```
+
+**Correct (base — object values):**
+
+```tsx
+
+```
+
+---
+
+## ToggleGroup
+
+Base uses a `multiple` boolean prop. Radix uses `type="single"` or `type="multiple"`.
+
+**Incorrect (base):**
+
+```tsx
+
+ Daily
+
+```
+
+**Correct (base):**
+
+```tsx
+// Single (no prop needed), defaultValue is always an array.
+
+ Daily
+ Weekly
+
+
+// Multi-selection.
+
+ Bold
+ Italic
+
+```
+
+**Correct (radix):**
+
+```tsx
+// Single, defaultValue is a string.
+
+ Daily
+ Weekly
+
+
+// Multi-selection.
+
+ Bold
+ Italic
+
+```
+
+**Controlled single value:**
+
+```tsx
+// base — wrap/unwrap arrays.
+const [value, setValue] = React.useState("normal")
+ setValue(v[0])}>
+
+// radix — plain string.
+const [value, setValue] = React.useState("normal")
+
+```
+
+---
+
+## Slider
+
+Base accepts a plain number for a single thumb. Radix always requires an array.
+
+**Incorrect (base):**
+
+```tsx
+
+```
+
+**Correct (base):**
+
+```tsx
+
+```
+
+**Correct (radix):**
+
+```tsx
+
+```
+
+Both use arrays for range sliders. Controlled `onValueChange` in base may need a cast:
+
+```tsx
+// base.
+const [value, setValue] = React.useState([0.3, 0.7])
+ setValue(v as number[])} />
+
+// radix.
+const [value, setValue] = React.useState([0.3, 0.7])
+
+```
+
+---
+
+## Accordion
+
+Radix requires `type="single"` or `type="multiple"` and supports `collapsible`. `defaultValue` is a string. Base uses no `type` prop, uses `multiple` boolean, and `defaultValue` is always an array.
+
+**Incorrect (base):**
+
+```tsx
+
+ ...
+
+```
+
+**Correct (base):**
+
+```tsx
+
+ ...
+
+
+// Multi-select.
+
+ ...
+ ...
+
+```
+
+**Correct (radix):**
+
+```tsx
+
+ ...
+
+```
diff --git a/skills/shadcn/rules/composition.md b/skills/shadcn/rules/composition.md
new file mode 100644
index 00000000..0e105837
--- /dev/null
+++ b/skills/shadcn/rules/composition.md
@@ -0,0 +1,195 @@
+# Component Composition
+
+## Contents
+
+- Items always inside their Group component
+- Callouts use Alert
+- Empty states use Empty component
+- Toast notifications use sonner
+- Choosing between overlay components
+- Dialog, Sheet, and Drawer always need a Title
+- Card structure
+- Button has no isPending or isLoading prop
+- TabsTrigger must be inside TabsList
+- Avatar always needs AvatarFallback
+- Use Separator instead of raw hr or border divs
+- Use Skeleton for loading placeholders
+- Use Badge instead of custom styled spans
+
+---
+
+## Items always inside their Group component
+
+Never render items directly inside the content container.
+
+**Incorrect:**
+
+```tsx
+
+ Apple
+ Banana
+
+```
+
+**Correct:**
+
+```tsx
+
+
+ Apple
+ Banana
+
+
+```
+
+This applies to all group-based components:
+
+| Item | Group |
+|------|-------|
+| `SelectItem`, `SelectLabel` | `SelectGroup` |
+| `DropdownMenuItem`, `DropdownMenuLabel`, `DropdownMenuSub` | `DropdownMenuGroup` |
+| `MenubarItem` | `MenubarGroup` |
+| `ContextMenuItem` | `ContextMenuGroup` |
+| `CommandItem` | `CommandGroup` |
+
+---
+
+## Callouts use Alert
+
+```tsx
+
+ Warning
+ Something needs attention.
+
+```
+
+---
+
+## Empty states use Empty component
+
+```tsx
+
+
+
+ No projects yet
+ Get started by creating a new project.
+
+
+
+
+
+```
+
+---
+
+## Toast notifications use sonner
+
+```tsx
+import { toast } from "sonner"
+
+toast.success("Changes saved.")
+toast.error("Something went wrong.")
+toast("File deleted.", {
+ action: { label: "Undo", onClick: () => undoDelete() },
+})
+```
+
+---
+
+## Choosing between overlay components
+
+| Use case | Component |
+|----------|-----------|
+| Focused task that requires input | `Dialog` |
+| Destructive action confirmation | `AlertDialog` |
+| Side panel with details or filters | `Sheet` |
+| Mobile-first bottom panel | `Drawer` |
+| Quick info on hover | `HoverCard` |
+| Small contextual content on click | `Popover` |
+
+---
+
+## Dialog, Sheet, and Drawer always need a Title
+
+`DialogTitle`, `SheetTitle`, `DrawerTitle` are required for accessibility. Use `className="sr-only"` if visually hidden.
+
+```tsx
+
+
+ Edit Profile
+ Update your profile.
+
+ ...
+
+```
+
+---
+
+## Card structure
+
+Use full composition — don't dump everything into `CardContent`:
+
+```tsx
+
+
+ Team Members
+ Manage your team.
+
+ ...
+
+
+
+
+```
+
+---
+
+## Button has no isPending or isLoading prop
+
+Compose with `Spinner` + `data-icon` + `disabled`:
+
+```tsx
+
+```
+
+---
+
+## TabsTrigger must be inside TabsList
+
+Never render `TabsTrigger` directly inside `Tabs` — always wrap in `TabsList`:
+
+```tsx
+
+
+ Account
+ Password
+
+ ...
+
+```
+
+---
+
+## Avatar always needs AvatarFallback
+
+Always include `AvatarFallback` for when the image fails to load:
+
+```tsx
+
+
+ JD
+
+```
+
+---
+
+## Use existing components instead of custom markup
+
+| Instead of | Use |
+|---|---|
+| `
` or `` | `
` |
+| `
` with styled divs | `
` |
+| `
` | `` |
diff --git a/skills/shadcn/rules/forms.md b/skills/shadcn/rules/forms.md
new file mode 100644
index 00000000..f451e2f7
--- /dev/null
+++ b/skills/shadcn/rules/forms.md
@@ -0,0 +1,192 @@
+# Forms & Inputs
+
+## Contents
+
+- Forms use FieldGroup + Field
+- InputGroup requires InputGroupInput/InputGroupTextarea
+- Buttons inside inputs use InputGroup + InputGroupAddon
+- Option sets (2–7 choices) use ToggleGroup
+- FieldSet + FieldLegend for grouping related fields
+- Field validation and disabled states
+
+---
+
+## Forms use FieldGroup + Field
+
+Always use `FieldGroup` + `Field` — never raw `div` with `space-y-*`:
+
+```tsx
+
+
+ Email
+
+
+
+ Password
+
+
+
+```
+
+Use `Field orientation="horizontal"` for settings pages. Use `FieldLabel className="sr-only"` for visually hidden labels.
+
+**Choosing form controls:**
+
+- Simple text input → `Input`
+- Dropdown with predefined options → `Select`
+- Searchable dropdown → `Combobox`
+- Native HTML select (no JS) → `native-select`
+- Boolean toggle → `Switch` (for settings) or `Checkbox` (for forms)
+- Single choice from few options → `RadioGroup`
+- Toggle between 2–5 options → `ToggleGroup` + `ToggleGroupItem`
+- OTP/verification code → `InputOTP`
+- Multi-line text → `Textarea`
+
+---
+
+## InputGroup requires InputGroupInput/InputGroupTextarea
+
+Never use raw `Input` or `Textarea` inside an `InputGroup`.
+
+**Incorrect:**
+
+```tsx
+
+
+
+```
+
+**Correct:**
+
+```tsx
+import { InputGroup, InputGroupInput } from "@/components/ui/input-group"
+
+
+
+
+```
+
+---
+
+## Buttons inside inputs use InputGroup + InputGroupAddon
+
+Never place a `Button` directly inside or adjacent to an `Input` with custom positioning.
+
+**Incorrect:**
+
+```tsx
+
+
+
+
+```
+
+**Correct:**
+
+```tsx
+import { InputGroup, InputGroupInput, InputGroupAddon } from "@/components/ui/input-group"
+
+
+
+
+
+
+
+```
+
+---
+
+## Option sets (2–7 choices) use ToggleGroup
+
+Don't manually loop `Button` components with active state.
+
+**Incorrect:**
+
+```tsx
+const [selected, setSelected] = useState("daily")
+
+
+ {["daily", "weekly", "monthly"].map((option) => (
+
+ ))}
+
+```
+
+**Correct:**
+
+```tsx
+import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
+
+
+ Daily
+ Weekly
+ Monthly
+
+```
+
+Combine with `Field` for labelled toggle groups:
+
+```tsx
+
+ Theme
+
+ Light
+ Dark
+ System
+
+
+```
+
+> **Note:** `defaultValue` and `type`/`multiple` props differ between base and radix. See [base-vs-radix.md](./base-vs-radix.md#togglegroup).
+
+---
+
+## FieldSet + FieldLegend for grouping related fields
+
+Use `FieldSet` + `FieldLegend` for related checkboxes, radios, or switches — not `div` with a heading:
+
+```tsx
+
+```
+
+---
+
+## Field validation and disabled states
+
+Both attributes are needed — `data-invalid`/`data-disabled` styles the field (label, description), while `aria-invalid`/`disabled` styles the control.
+
+```tsx
+// Invalid.
+
+ Email
+
+ Invalid email address.
+
+
+// Disabled.
+
+ Email
+
+
+```
+
+Works for all controls: `Input`, `Textarea`, `Select`, `Checkbox`, `RadioGroupItem`, `Switch`, `Slider`, `NativeSelect`, `InputOTP`.
diff --git a/skills/shadcn/rules/icons.md b/skills/shadcn/rules/icons.md
new file mode 100644
index 00000000..bba8102f
--- /dev/null
+++ b/skills/shadcn/rules/icons.md
@@ -0,0 +1,101 @@
+# Icons
+
+**Always use the project's configured `iconLibrary` for imports.** Check the `iconLibrary` field from project context: `lucide` → `lucide-react`, `tabler` → `@tabler/icons-react`, etc. Never assume `lucide-react`.
+
+---
+
+## Icons in Button use data-icon attribute
+
+Add `data-icon="inline-start"` (prefix) or `data-icon="inline-end"` (suffix) to the icon. No sizing classes on the icon.
+
+**Incorrect:**
+
+```tsx
+
+```
+
+**Correct:**
+
+```tsx
+
+
+
+```
+
+---
+
+## No sizing classes on icons inside components
+
+Components handle icon sizing via CSS. Don't add `size-4`, `w-4 h-4`, or other sizing classes to icons inside `Button`, `DropdownMenuItem`, `Alert`, `Sidebar*`, or other shadcn components. Unless the user explicitly asks for custom icon sizes.
+
+**Incorrect:**
+
+```tsx
+
+
+
+
+ Settings
+
+```
+
+**Correct:**
+
+```tsx
+
+
+
+
+ Settings
+
+```
+
+---
+
+## Pass icons as component objects, not string keys
+
+Use `icon={CheckIcon}`, not a string key to a lookup map.
+
+**Incorrect:**
+
+```tsx
+const iconMap = {
+ check: CheckIcon,
+ alert: AlertIcon,
+}
+
+function StatusBadge({ icon }: { icon: string }) {
+ const Icon = iconMap[icon]
+ return
+}
+
+
+```
+
+**Correct:**
+
+```tsx
+// Import from the project's configured iconLibrary (e.g. lucide-react, @tabler/icons-react).
+import { CheckIcon } from "lucide-react"
+
+function StatusBadge({ icon: Icon }: { icon: React.ComponentType }) {
+ return
+}
+
+
+```
diff --git a/skills/shadcn/rules/styling.md b/skills/shadcn/rules/styling.md
new file mode 100644
index 00000000..38d47321
--- /dev/null
+++ b/skills/shadcn/rules/styling.md
@@ -0,0 +1,162 @@
+# Styling & Customization
+
+See [customization.md](../customization.md) for theming, CSS variables, and adding custom colors.
+
+## Contents
+
+- Semantic colors
+- Built-in variants first
+- className for layout only
+- No space-x-* / space-y-*
+- Prefer size-* over w-* h-* when equal
+- Prefer truncate shorthand
+- No manual dark: color overrides
+- Use cn() for conditional classes
+- No manual z-index on overlay components
+
+---
+
+## Semantic colors
+
+**Incorrect:**
+
+```tsx
+
+```
+
+**Correct:**
+
+```tsx
+
+```
+
+---
+
+## No raw color values for status/state indicators
+
+For positive, negative, or status indicators, use Badge variants, semantic tokens like `text-destructive`, or define custom CSS variables — don't reach for raw Tailwind colors.
+
+**Incorrect:**
+
+```tsx
++20.1%
+Active
+-3.2%
+```
+
+**Correct:**
+
+```tsx
++20.1%
+Active
+-3.2%
+```
+
+If you need a success/positive color that doesn't exist as a semantic token, use a Badge variant or ask the user about adding a custom CSS variable to the theme (see [customization.md](../customization.md)).
+
+---
+
+## Built-in variants first
+
+**Incorrect:**
+
+```tsx
+
+```
+
+**Correct:**
+
+```tsx
+
+```
+
+---
+
+## className for layout only
+
+Use `className` for layout (e.g. `max-w-md`, `mx-auto`, `mt-4`), **not** for overriding component colors or typography. To change colors, use semantic tokens, built-in variants, or CSS variables.
+
+**Incorrect:**
+
+```tsx
+
+ Dashboard
+
+```
+
+**Correct:**
+
+```tsx
+
+ Dashboard
+
+```
+
+To customize a component's appearance, prefer these approaches in order:
+1. **Built-in variants** — `variant="outline"`, `variant="destructive"`, etc.
+2. **Semantic color tokens** — `bg-primary`, `text-muted-foreground`.
+3. **CSS variables** — define custom colors in the global CSS file (see [customization.md](../customization.md)).
+
+---
+
+## No space-x-* / space-y-*
+
+Use `gap-*` instead. `space-y-4` → `flex flex-col gap-4`. `space-x-2` → `flex gap-2`.
+
+```tsx
+
+
+
+
+
+```
+
+---
+
+## Prefer size-* over w-* h-* when equal
+
+`size-10` not `w-10 h-10`. Applies to icons, avatars, skeletons, etc.
+
+---
+
+## Prefer truncate shorthand
+
+`truncate` not `overflow-hidden text-ellipsis whitespace-nowrap`.
+
+---
+
+## No manual dark: color overrides
+
+Use semantic tokens — they handle light/dark via CSS variables. `bg-background text-foreground` not `bg-white dark:bg-gray-950`.
+
+---
+
+## Use cn() for conditional classes
+
+Use the `cn()` utility from the project for conditional or merged class names. Don't write manual ternaries in className strings.
+
+**Incorrect:**
+
+```tsx
+
+```
+
+**Correct:**
+
+```tsx
+import { cn } from "@/lib/utils"
+
+
+```
+
+---
+
+## No manual z-index on overlay components
+
+`Dialog`, `Sheet`, `Drawer`, `AlertDialog`, `DropdownMenu`, `Popover`, `Tooltip`, `HoverCard` handle their own stacking. Never add `z-50` or `z-[999]`.
diff --git a/skills_index.json b/skills_index.json
index b4324cff..8e761b3e 100644
--- a/skills_index.json
+++ b/skills_index.json
@@ -10299,6 +10299,16 @@
"source": "community",
"date_added": "2026-02-27"
},
+ {
+ "id": "senior-frontend",
+ "path": "skills/senior-frontend",
+ "category": "uncategorized",
+ "name": "senior-frontend",
+ "description": "Frontend development skill for React, Next.js, TypeScript, and Tailwind CSS applications. Use when building React components, optimizing Next.js performance, analyzing bundle sizes, scaffolding frontend projects, implementing accessibility, or reviewing frontend code quality.",
+ "risk": "safe",
+ "source": "https://github.com/alirezarezvani/claude-skills",
+ "date_added": "2026-03-07"
+ },
{
"id": "senior-fullstack",
"path": "skills/senior-fullstack",
@@ -10489,6 +10499,16 @@
"source": "unknown",
"date_added": null
},
+ {
+ "id": "shadcn",
+ "path": "skills/shadcn",
+ "category": "uncategorized",
+ "name": "shadcn",
+ "description": "Manages shadcn/ui components and projects, providing context, documentation, and usage patterns for building modern design systems.",
+ "risk": "safe",
+ "source": "https://github.com/shadcn-ui/ui/tree/main/skills/shadcn",
+ "date_added": "2026-03-07"
+ },
{
"id": "shader-programming-glsl",
"path": "skills/shader-programming-glsl",