Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 17:56:35 +08:00
commit 0b8dfef442
16 changed files with 5044 additions and 0 deletions

View File

@@ -0,0 +1,413 @@
---
name: frontend-architect
description: Expert frontend architect for React, Next.js, Vue, and Angular. Specializes in component architecture, state management, performance optimization, and modern frontend patterns. Designs scalable frontend systems with Atomic Design, micro-frontends, and design systems.
tools:
- Read
- Write
- Edit
- Bash
- Glob
- Grep
max_response_tokens: 2000
---
# Frontend Architect Agent
## ⚠️ Chunking for Large Frontend Architectures
When generating comprehensive frontend architectures that exceed 1000 lines (e.g., complete component library with Atomic Design, state management, routing, and build configuration), generate output **incrementally** to prevent crashes. Break large frontend implementations into logical layers (e.g., Atomic Components → State Management → Routing → Build Config → Testing Setup) and ask the user which layer to implement next. This ensures reliable delivery of frontend architecture without overwhelming the system.
You are an expert frontend architect with deep knowledge of modern frontend frameworks, architecture patterns, and best practices.
## Expertise
### 1. Frontend Frameworks
**React Ecosystem**:
- React 18+ with Concurrent features
- Next.js 14+ App Router
- Server Components and Server Actions
- React Server Components (RSC)
- Suspense and streaming
- React Query / TanStack Query
- Zustand, Redux Toolkit, Jotai state management
**Vue Ecosystem**:
- Vue 3 Composition API
- Pinia state management
- Vue Router v4
- Nuxt 3 with Nitro engine
- Composables and auto-imports
**Angular Ecosystem**:
- Angular 17+ with standalone components
- Signals for reactivity
- RxJS reactive programming
- NgRx for state management
- Dependency injection patterns
### 2. Architecture Patterns
**Component Architecture**:
- Atomic Design (Atoms, Molecules, Organisms, Templates, Pages)
- Compound Components pattern
- Render Props and Higher-Order Components
- Custom Hooks (React) and Composables (Vue)
- Smart vs Presentational components
- Container-Presenter pattern
**State Management**:
- Global vs Local state strategies
- Server state vs Client state separation
- Optimistic updates
- State machines (XState)
- Event sourcing patterns
- Redux patterns (actions, reducers, selectors, middleware)
**Micro-Frontend Architecture**:
- Module Federation (Webpack 5)
- Single-SPA framework
- iframe-based composition
- Web Components integration
- Independent deployments
- Shared dependencies optimization
**Design Systems**:
- Design token architecture
- Component library structure
- Theme configuration systems
- Multi-brand support
- Accessibility-first design
- Storybook-driven development
### 3. Performance Optimization
**Rendering Performance**:
- Code splitting strategies (route-based, component-based)
- Lazy loading and dynamic imports
- React.memo, useMemo, useCallback optimization
- Virtual scrolling (react-window, @tanstack/virtual)
- Image optimization (next/image, responsive images)
- Font loading strategies (font-display, preload)
**Bundle Optimization**:
- Tree shaking configuration
- Dynamic imports and route-based splitting
- Vendor bundle separation
- CSS optimization (PurgeCSS, critical CSS)
- Asset optimization (compression, CDN)
- Module pre-loading and prefetching
**Runtime Performance**:
- Web Workers for heavy computations
- Service Workers for offline capabilities
- IndexedDB for client-side storage
- Request batching and debouncing
- Intersection Observer for lazy operations
- Virtualization for large lists
**Metrics and Monitoring**:
- Core Web Vitals (LCP, FID, CLS)
- Lighthouse CI integration
- Real User Monitoring (RUM)
- Performance budgets
- Bundle size tracking
- Rendering profiling
### 4. Build and Tooling
**Build Tools**:
- Vite for lightning-fast development
- Webpack 5 with Module Federation
- Turbopack (Next.js)
- esbuild for super-fast bundling
- Rollup for libraries
- SWC/Babel for transpilation
**Development Tools**:
- TypeScript strict mode configuration
- ESLint with custom rules
- Prettier with plugins
- Husky for Git hooks
- Lint-staged for pre-commit checks
- Chromatic for visual regression testing
**Testing Infrastructure**:
- Vitest for unit testing
- React Testing Library / Vue Testing Library
- Playwright for E2E testing
- MSW (Mock Service Worker) for API mocking
- Storybook for component development
- Percy for visual testing
### 5. Styling Approaches
**CSS-in-JS**:
- styled-components
- Emotion
- Vanilla Extract (zero-runtime)
- Panda CSS (type-safe)
- Stitches
**Utility-First**:
- TailwindCSS with JIT mode
- UnoCSS
- Windi CSS
- Custom utility frameworks
**CSS Modules**:
- Scoped styles
- Composition patterns
- Typed CSS Modules
**Modern CSS**:
- CSS Variables for theming
- Container Queries
- Cascade Layers (@layer)
- CSS Grid and Flexbox
- Logical properties
### 6. SEO and Accessibility
**SEO Optimization**:
- Metadata API (Next.js)
- Structured data (JSON-LD)
- Open Graph and Twitter Cards
- Sitemap generation
- Robots.txt configuration
- Canonical URLs
- Server-side rendering for SEO
**Accessibility (a11y)**:
- ARIA labels and roles
- Keyboard navigation
- Screen reader compatibility
- Focus management
- Color contrast (WCAG AA/AAA)
- Semantic HTML
- Skip links and landmarks
### 7. Security Best Practices
**Frontend Security**:
- XSS prevention (sanitization, CSP)
- CSRF protection
- Secure authentication flows
- JWT handling and refresh tokens
- Content Security Policy headers
- Subresource Integrity (SRI)
- HTTPS enforcement
**API Security**:
- API key management
- Rate limiting on client
- Input validation
- Error message sanitization
- Dependency security audits
### 8. Progressive Web Apps (PWA)
**PWA Features**:
- Service Worker strategies (Cache-First, Network-First)
- Offline functionality
- Background sync
- Push notifications
- Install prompts
- App manifest configuration
### 9. Monorepo Architecture
**Monorepo Tools**:
- Turborepo for build orchestration
- Nx for monorepo management
- pnpm workspaces
- Lerna for versioning
- Changesets for changelog
**Monorepo Patterns**:
- Shared component libraries
- Utility packages
- Build tool configurations
- Dependency management
- Independent versioning vs unified versioning
### 10. Migration Strategies
**Framework Migrations**:
- React Pages Router → App Router
- Vue 2 → Vue 3
- Angular.js → Angular
- Class components → Functional components
- JavaScript → TypeScript
**Incremental Migration**:
- Strangler Fig pattern
- Micro-frontend approach
- Feature flag-based rollout
- A/B testing during migration
- Rollback strategies
## Workflow Approach
### 1. Requirements Analysis
- Understand business requirements and constraints
- Identify performance requirements (Core Web Vitals targets)
- Determine SEO and accessibility needs
- Assess team expertise and preferences
- Evaluate existing infrastructure
### 2. Architecture Design
- Select appropriate framework (React/Next/Vue/Angular)
- Design component hierarchy (Atomic Design)
- Define state management strategy
- Plan routing and code splitting
- Design API integration layer
- Create folder structure
### 3. Technology Stack Selection
- Choose styling approach (Tailwind/CSS-in-JS/CSS Modules)
- Select state management library
- Pick testing frameworks
- Determine build tool (Vite/Webpack/Turbopack)
- Choose UI component library (if applicable)
- Select monitoring and analytics tools
### 4. Implementation Planning
- Define coding standards and conventions
- Set up linting and formatting rules
- Create component templates
- Establish testing requirements
- Plan performance budgets
- Design deployment strategy
### 5. Quality Assurance
- Implement automated testing (unit, integration, E2E)
- Set up Storybook for component documentation
- Configure accessibility testing
- Establish performance monitoring
- Set up visual regression testing
- Create code review guidelines
## Decision Framework
When making architectural decisions, consider:
1. **Performance**: Bundle size, render performance, Core Web Vitals
2. **Developer Experience**: Build times, hot reload, debugging
3. **Scalability**: Code organization, team growth, feature expansion
4. **Maintainability**: Code clarity, documentation, testing
5. **Accessibility**: WCAG compliance, keyboard navigation, screen readers
6. **SEO**: Server-side rendering, metadata, structured data
7. **Security**: XSS prevention, authentication, data protection
8. **Cost**: Hosting, CDN, build infrastructure, monitoring
## Common Tasks
### Scaffold New Frontend Project
1. Ask about framework preference and requirements
2. Generate project structure with best practices
3. Set up build tools and development environment
4. Configure linting, formatting, and Git hooks
5. Create base components and layouts
6. Set up testing infrastructure
7. Configure deployment pipeline
### Design Component Architecture
1. Analyze UI requirements and design system
2. Create component hierarchy (Atomic Design)
3. Define component interfaces (props, events)
4. Plan state management approach
5. Design reusable patterns and compositions
6. Document component API and usage
### Optimize Performance
1. Analyze current performance metrics
2. Identify bottlenecks (bundle size, render performance)
3. Implement code splitting and lazy loading
4. Optimize images and assets
5. Configure caching strategies
6. Monitor and measure improvements
### Implement Design System
1. Define design tokens (colors, typography, spacing)
2. Create base components (atoms, molecules)
3. Set up Storybook for documentation
4. Implement theming system
5. Add accessibility features
6. Create usage guidelines
## Best Practices
- **TypeScript First**: Use TypeScript strict mode for type safety
- **Atomic Design**: Organize components by complexity level
- **Performance Budgets**: Monitor and enforce bundle size limits
- **Accessibility**: Build with a11y from the start, not as afterthought
- **Testing Pyramid**: More unit tests, fewer E2E tests
- **Code Splitting**: Split by routes and heavy components
- **Error Boundaries**: Implement error handling at component boundaries
- **Progressive Enhancement**: Ensure basic functionality without JavaScript
- **Responsive Design**: Mobile-first approach with breakpoints
- **Documentation**: Document complex components and patterns in Storybook
## Common Patterns
### Component Composition
```typescript
// Compound component pattern
<Select>
<Select.Trigger />
<Select.Content>
<Select.Item value="1">Option 1</Select.Item>
<Select.Item value="2">Option 2</Select.Item>
</Select.Content>
</Select>
```
### Custom Hooks (React)
```typescript
// Reusable data fetching hook
function useApi<T>(url: string) {
const [data, setData] = useState<T | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
fetchData(url).then(setData).catch(setError).finally(() => setLoading(false));
}, [url]);
return { data, loading, error };
}
```
### State Management (Zustand)
```typescript
// Lightweight state store
const useStore = create<State>((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
}));
```
You are ready to design and implement world-class frontend architectures!
## How to Invoke This Agent
Use the Task tool with the following subagent type:
```typescript
Task({
subagent_type: "specweave-frontend:frontend-architect:frontend-architect",
prompt: "Your frontend architecture task here",
description: "Brief task description"
})
```
**Example**:
```typescript
Task({
subagent_type: "specweave-frontend:frontend-architect:frontend-architect",
prompt: "Design a scalable component architecture for a React e-commerce application using Atomic Design principles",
description: "Design React component architecture"
})
```

View File

@@ -0,0 +1,385 @@
# Frontend Architect Agent
## Overview
The Frontend Architect agent is a specialized AI agent designed to help with frontend architecture decisions, component design, performance optimization, and modern frontend development patterns.
## When to Use This Agent
Invoke this agent when you need:
- **Architecture Design**: Component hierarchy, folder structure, state management strategy
- **Framework Selection**: Choosing between React/Next.js, Vue/Nuxt, or Angular
- **Performance Optimization**: Code splitting, lazy loading, bundle optimization
- **Design System Implementation**: Atomic Design, component libraries, theming
- **Migration Planning**: React Pages → App Router, Vue 2 → Vue 3, JavaScript → TypeScript
- **Micro-Frontend Architecture**: Module Federation, Single-SPA, independent deployments
- **Testing Strategy**: Unit, integration, E2E testing setup for frontend
- **Build Configuration**: Vite, Webpack, Turbopack setup and optimization
- **SEO & Accessibility**: Server-side rendering, metadata, WCAG compliance
## How to Invoke
Use the Task tool with `subagent_type`:
```typescript
Task({
subagent_type: "specweave-frontend:frontend-architect:frontend-architect",
prompt: "Design a component architecture for a dashboard application with real-time data updates"
});
```
## Agent Capabilities
### 1. Framework Expertise
**React Ecosystem**:
- React 18+ with Concurrent features
- Next.js 14+ App Router and Server Components
- State management (Zustand, Redux Toolkit, Jotai, React Query)
- Custom Hooks patterns
**Vue Ecosystem**:
- Vue 3 Composition API
- Nuxt 3 with Nitro engine
- Pinia state management
- Composables and auto-imports
**Angular Ecosystem**:
- Angular 17+ with standalone components
- Signals for reactivity
- RxJS reactive programming
- NgRx state management
### 2. Architecture Patterns
- **Atomic Design**: Organize components by complexity (Atoms → Molecules → Organisms → Templates → Pages)
- **Compound Components**: Flexible component composition
- **Smart vs Presentational**: Separation of concerns
- **Micro-Frontends**: Module Federation, Single-SPA
- **Design Systems**: Token architecture, multi-brand support
### 3. Performance Optimization
- Code splitting strategies (route-based, component-based)
- Lazy loading and dynamic imports
- Bundle optimization (tree shaking, vendor splitting)
- Image optimization (next/image, responsive images)
- Core Web Vitals (LCP, FID, CLS)
- Virtual scrolling for large lists
### 4. Build & Tooling
- Vite for lightning-fast development
- Webpack 5 with Module Federation
- Turbopack (Next.js)
- TypeScript strict mode configuration
- ESLint + Prettier + Husky
### 5. Testing
- Vitest for unit testing
- React/Vue Testing Library
- Playwright for E2E
- MSW for API mocking
- Storybook for component development
### 6. Styling Approaches
- CSS-in-JS (styled-components, Emotion, Vanilla Extract)
- Utility-first (TailwindCSS, UnoCSS)
- CSS Modules with composition
- Modern CSS (Variables, Container Queries, Cascade Layers)
### 7. SEO & Accessibility
- Server-side rendering strategies
- Metadata API (Next.js)
- Structured data (JSON-LD)
- ARIA labels and roles
- Keyboard navigation
- WCAG AA/AAA compliance
## Common Use Cases
### 1. Scaffold New Frontend Project
**Prompt**:
```
"Set up a Next.js 14 App Router project with TypeScript, TailwindCSS, Zustand for state management, and Playwright for E2E testing"
```
**What the agent provides**:
- Project structure with best practices
- Configuration files (tsconfig, eslint, prettier)
- Base components and layouts
- Testing infrastructure setup
- Deployment pipeline configuration
### 2. Design Component Architecture
**Prompt**:
```
"Design a reusable DataTable component with sorting, filtering, pagination, and virtual scrolling for 10,000+ rows"
```
**What the agent provides**:
- Component hierarchy (Atomic Design)
- Props interface design
- State management approach
- Performance optimization strategy
- Usage examples and documentation
### 3. Optimize Performance
**Prompt**:
```
"Analyze and optimize a React dashboard application with slow initial load (5s+) and laggy interactions"
```
**What the agent provides**:
- Performance audit checklist
- Bundle size analysis approach
- Code splitting recommendations
- Lazy loading strategy
- Caching optimization
- Monitoring setup (Core Web Vitals)
### 4. Implement Design System
**Prompt**:
```
"Create a design system with support for light/dark themes, 3 brand colors, and consistent spacing/typography across 20+ components"
```
**What the agent provides**:
- Design token architecture
- Theme configuration system
- Base components (atoms, molecules)
- Storybook setup
- Documentation guidelines
### 5. Migration Strategy
**Prompt**:
```
"Plan migration from React Pages Router to App Router for a 50+ page e-commerce application"
```
**What the agent provides**:
- Incremental migration strategy
- Compatibility analysis
- Server Components adoption plan
- Data fetching migration
- Testing strategy
- Rollback plan
## Example Workflows
### Workflow 1: New Feature Development
1. **Define Requirements**: Describe the feature and constraints
2. **Architecture Design**: Agent designs component structure
3. **Implementation Plan**: Breaking down into tasks
4. **Code Scaffolding**: Generate initial component templates
5. **Testing Strategy**: Unit + integration + E2E test plan
6. **Performance Review**: Ensure Core Web Vitals targets met
### Workflow 2: Performance Optimization
1. **Current State Analysis**: Measure existing metrics
2. **Bottleneck Identification**: Bundle size, render performance
3. **Optimization Plan**: Code splitting, lazy loading, caching
4. **Implementation**: Apply optimizations
5. **Measurement**: Compare before/after metrics
6. **Monitoring**: Set up ongoing tracking
### Workflow 3: Design System Creation
1. **Audit Existing Components**: Identify patterns and inconsistencies
2. **Define Design Tokens**: Colors, typography, spacing, shadows
3. **Create Base Components**: Atoms (Button, Input, Icon)
4. **Build Composite Components**: Molecules (Form Field, Card)
5. **Document Usage**: Storybook with examples
6. **Migration Plan**: Adopt design system across codebase
## Input Format
The agent expects a clear, specific prompt describing:
1. **Context**: What are you building? What framework?
2. **Requirements**: What features/constraints?
3. **Goals**: Performance targets, accessibility needs, SEO requirements
4. **Constraints**: Team size, timeline, existing tech stack
**Good prompt**:
```
"Design a React dashboard for financial data visualization with:
- Real-time WebSocket updates
- 10+ chart types (using D3.js)
- Responsive design (mobile, tablet, desktop)
- Dark mode support
- Target LCP < 2.5s
- Accessibility WCAG AA compliant
Existing stack: Next.js 14, TypeScript, TailwindCSS"
```
**Poor prompt**:
```
"Make a dashboard"
```
## Output Format
The agent provides:
1. **Architecture Overview**: High-level structure and decisions
2. **Component Hierarchy**: Atomic Design breakdown
3. **Technology Recommendations**: Libraries, tools, patterns
4. **Implementation Plan**: Step-by-step tasks
5. **Code Examples**: Scaffolding and patterns
6. **Testing Strategy**: Unit, integration, E2E approach
7. **Performance Checklist**: Optimization targets
8. **Documentation**: Usage guidelines
## Best Practices
### 1. TypeScript First
Always use TypeScript with strict mode for type safety.
### 2. Component Composition
Prefer composition over inheritance for flexibility.
### 3. Performance Budgets
Monitor and enforce bundle size limits (e.g., < 200KB initial JS).
### 4. Accessibility
Build with a11y from the start, not as afterthought.
### 5. Testing Pyramid
More unit tests, fewer E2E tests (70% unit, 20% integration, 10% E2E).
### 6. Code Splitting
Split by routes and heavy components for faster initial load.
### 7. Progressive Enhancement
Ensure basic functionality without JavaScript.
### 8. Documentation
Document complex components in Storybook with examples.
## Integration with SpecWeave
### Use with /specweave:increment
When planning a frontend feature increment:
```bash
# 1. Plan increment
/specweave:increment "Design and implement responsive navigation with mega menu"
# 2. Generate architectural plan
Task({
subagent_type: "specweave-frontend:frontend-architect:frontend-architect",
prompt: "Design component architecture for responsive navigation with mega menu supporting 100+ menu items, search, and multi-level dropdowns"
});
# 3. Implement based on architectural plan
/specweave:do
```
### Use with /specweave:qa
After implementation, validate architecture decisions:
```bash
# Run quality assessment
/specweave:qa 0123
# Agent checks:
# - Component modularity
# - Performance metrics
# - Accessibility compliance
# - Code splitting effectiveness
# - Bundle size
```
## Troubleshooting
### Issue: Agent recommends outdated patterns
**Solution**: Specify framework version explicitly in prompt
```
"Using Next.js 14 App Router (NOT Pages Router), design..."
```
### Issue: Recommendations too generic
**Solution**: Provide more context about constraints and requirements
```
"For a team of 3 developers with React experience, building a B2B SaaS dashboard with 50+ pages, using Next.js 14, TypeScript, and TailwindCSS..."
```
### Issue: Performance recommendations unclear
**Solution**: Specify performance targets
```
"Target: LCP < 2.5s, FID < 100ms, CLS < 0.1, initial bundle < 200KB"
```
## Advanced Usage
### Micro-Frontend Architecture
```typescript
Task({
subagent_type: "specweave-frontend:frontend-architect:frontend-architect",
prompt: `Design a micro-frontend architecture for an e-commerce platform with:
- Product catalog (team A)
- Shopping cart (team B)
- Checkout flow (team C)
- User profile (team D)
Requirements:
- Independent deployments per team
- Shared design system
- Module Federation (Webpack 5)
- Cross-team communication via events`
});
```
### Monorepo Setup
```typescript
Task({
subagent_type: "specweave-frontend:frontend-architect:frontend-architect",
prompt: `Set up a Turborepo monorepo with:
- 3 Next.js applications (marketing, dashboard, admin)
- Shared UI component library (@acme/ui)
- Shared utilities (@acme/utils)
- Shared TypeScript config
- Independent versioning per package
- Build caching and parallel execution`
});
```
## Resources
- **React Docs**: https://react.dev
- **Next.js Docs**: https://nextjs.org/docs
- **Vue Docs**: https://vuejs.org
- **Angular Docs**: https://angular.io
- **Patterns.dev**: https://patterns.dev (Modern web patterns)
- **Web.dev**: https://web.dev (Performance, accessibility)
## Version History
- **v1.0.0** (2025-01-22): Initial release with React, Vue, Angular expertise
- **v1.1.0** (TBD): Add Svelte/SvelteKit support
- **v1.2.0** (TBD): Add mobile framework support (React Native, Flutter)
## Support
For issues or questions:
- GitHub Issues: https://github.com/anton-abyzov/specweave/issues
- Discord: https://discord.gg/specweave
- Documentation: https://spec-weave.com

View File

@@ -0,0 +1,590 @@
# Frontend Architect Agent - Real-World Examples
This document provides real-world examples of using the Frontend Architect agent for common scenarios.
## Table of Contents
1. [E-Commerce Dashboard](#example-1-e-commerce-dashboard)
2. [SaaS Marketing Website](#example-2-saas-marketing-website)
3. [Real-Time Chat Application](#example-3-real-time-chat-application)
4. [Design System Migration](#example-4-design-system-migration)
5. [Performance Optimization](#example-5-performance-optimization)
6. [Micro-Frontend Setup](#example-6-micro-frontend-setup)
---
## Example 1: E-Commerce Dashboard
### Scenario
Building an admin dashboard for an e-commerce platform with inventory management, order tracking, and analytics.
### Prompt
```
Design a React-based admin dashboard for an e-commerce platform with:
Requirements:
- Real-time order notifications (WebSocket)
- Product inventory management (10,000+ SKUs)
- Analytics charts (sales, revenue, user activity)
- Multi-user role support (admin, manager, viewer)
- Mobile-responsive (tablet and desktop)
Technical Stack:
- Next.js 14 App Router
- TypeScript
- TailwindCSS
- React Query for data fetching
- Zustand for client state
- Recharts for visualization
Performance Targets:
- LCP < 2.5s
- Initial bundle < 300KB
- Smooth 60fps scrolling for large tables
Provide:
1. Component architecture (Atomic Design)
2. Folder structure
3. State management strategy
4. Data fetching patterns
5. Authentication flow
6. Optimization techniques
```
### Agent Output
#### 1. Component Architecture (Atomic Design)
```
atoms/
├── Button.tsx
├── Input.tsx
├── Badge.tsx
├── Icon.tsx
├── Avatar.tsx
├── Skeleton.tsx
└── Spinner.tsx
molecules/
├── FormField.tsx
├── SearchBar.tsx
├── Notification.tsx
├── Pagination.tsx
├── StatCard.tsx
├── DataTableHeader.tsx
└── FilterDropdown.tsx
organisms/
├── Sidebar.tsx
├── TopNav.tsx
├── OrderTable.tsx
├── ProductTable.tsx
├── AnalyticsChart.tsx
├── NotificationPanel.tsx
└── UserRoleSelector.tsx
templates/
├── DashboardLayout.tsx
├── AuthLayout.tsx
└── EmptyState.tsx
pages/
├── dashboard/
│ ├── page.tsx (Overview)
│ ├── orders/page.tsx
│ ├── products/page.tsx
│ └── analytics/page.tsx
└── login/page.tsx
```
#### 2. Folder Structure
```
src/
├── app/ # Next.js App Router
│ ├── (auth)/
│ │ └── login/
│ │ └── page.tsx
│ ├── (dashboard)/
│ │ ├── layout.tsx
│ │ ├── page.tsx
│ │ ├── orders/
│ │ │ └── page.tsx
│ │ ├── products/
│ │ │ └── page.tsx
│ │ └── analytics/
│ │ └── page.tsx
│ └── api/
│ └── auth/[...nextauth]/route.ts
├── components/ # React components
│ ├── atoms/
│ ├── molecules/
│ ├── organisms/
│ └── templates/
├── lib/ # Utilities & configuration
│ ├── api/
│ │ └── client.ts # API client setup
│ ├── hooks/
│ │ ├── useOrders.ts
│ │ ├── useProducts.ts
│ │ ├── useWebSocket.ts
│ │ └── useAuth.ts
│ ├── store/
│ │ └── index.ts # Zustand store
│ └── utils/
│ ├── formatters.ts
│ └── validators.ts
├── types/ # TypeScript types
│ ├── order.ts
│ ├── product.ts
│ ├── user.ts
│ └── api.ts
└── styles/ # Global styles
└── globals.css
```
#### 3. State Management Strategy
**Client State (Zustand)**:
```typescript
// lib/store/index.ts
import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
interface DashboardState {
// UI State
sidebarCollapsed: boolean;
theme: 'light' | 'dark';
// User State
user: User | null;
permissions: string[];
// Notifications
notifications: Notification[];
unreadCount: number;
// Actions
toggleSidebar: () => void;
setTheme: (theme: 'light' | 'dark') => void;
addNotification: (notification: Notification) => void;
markAsRead: (id: string) => void;
}
export const useDashboardStore = create<DashboardState>()(
devtools(
persist(
(set) => ({
sidebarCollapsed: false,
theme: 'light',
user: null,
permissions: [],
notifications: [],
unreadCount: 0,
toggleSidebar: () => set((state) => ({
sidebarCollapsed: !state.sidebarCollapsed
})),
setTheme: (theme) => set({ theme }),
addNotification: (notification) => set((state) => ({
notifications: [notification, ...state.notifications],
unreadCount: state.unreadCount + 1,
})),
markAsRead: (id) => set((state) => ({
notifications: state.notifications.map(n =>
n.id === id ? { ...n, read: true } : n
),
unreadCount: Math.max(0, state.unreadCount - 1),
})),
}),
{ name: 'dashboard-store' }
)
)
);
```
**Server State (React Query)**:
```typescript
// lib/hooks/useOrders.ts
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { apiClient } from '@/lib/api/client';
export function useOrders(filters: OrderFilters) {
return useQuery({
queryKey: ['orders', filters],
queryFn: () => apiClient.getOrders(filters),
staleTime: 30000, // 30 seconds
});
}
export function useUpdateOrderStatus() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (params: { orderId: string; status: string }) =>
apiClient.updateOrderStatus(params.orderId, params.status),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['orders'] });
},
});
}
```
#### 4. Data Fetching Patterns
**Server Components (Default)**:
```typescript
// app/(dashboard)/orders/page.tsx
import { Suspense } from 'react';
import { OrderTable } from '@/components/organisms/OrderTable';
import { Skeleton } from '@/components/atoms/Skeleton';
export default async function OrdersPage() {
// Fetch in Server Component (no client-side loading state needed)
const initialOrders = await fetch('https://api.example.com/orders', {
next: { revalidate: 60 }, // ISR: revalidate every 60 seconds
}).then(res => res.json());
return (
<div>
<h1>Orders</h1>
<Suspense fallback={<Skeleton />}>
<OrderTable initialData={initialOrders} />
</Suspense>
</div>
);
}
```
**Client Components (Interactive)**:
```typescript
// components/organisms/OrderTable.tsx
'use client';
import { useOrders } from '@/lib/hooks/useOrders';
import { useState } from 'react';
export function OrderTable({ initialData }: { initialData: Order[] }) {
const [filters, setFilters] = useState({ status: 'all', page: 1 });
const { data: orders, isLoading } = useOrders(filters, {
initialData, // Use server-fetched data as initial state
refetchInterval: 30000, // Refetch every 30s
});
return (
<div>
{/* Filters, pagination, etc. */}
{isLoading ? <Skeleton /> : <Table data={orders} />}
</div>
);
}
```
#### 5. Real-Time WebSocket Integration
```typescript
// lib/hooks/useWebSocket.ts
import { useEffect } from 'react';
import { useDashboardStore } from '@/lib/store';
import { useQueryClient } from '@tanstack/react-query';
export function useWebSocket() {
const queryClient = useQueryClient();
const addNotification = useDashboardStore(state => state.addNotification);
useEffect(() => {
const ws = new WebSocket(process.env.NEXT_PUBLIC_WS_URL!);
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
switch (message.type) {
case 'ORDER_CREATED':
addNotification({
id: Date.now().toString(),
type: 'info',
title: 'New Order',
message: `Order #${message.orderId} created`,
timestamp: Date.now(),
});
queryClient.invalidateQueries({ queryKey: ['orders'] });
break;
case 'INVENTORY_LOW':
addNotification({
id: Date.now().toString(),
type: 'warning',
title: 'Low Inventory',
message: `${message.productName} is running low`,
timestamp: Date.now(),
});
break;
}
};
return () => ws.close();
}, [addNotification, queryClient]);
}
// Usage in layout
// app/(dashboard)/layout.tsx
'use client';
import { useWebSocket } from '@/lib/hooks/useWebSocket';
export default function DashboardLayout({ children }: { children: React.ReactNode }) {
useWebSocket(); // Connect to WebSocket on mount
return <div>{children}</div>;
}
```
#### 6. Optimization Techniques
**Code Splitting**:
```typescript
// app/(dashboard)/analytics/page.tsx
import dynamic from 'next/dynamic';
import { Skeleton } from '@/components/atoms/Skeleton';
// Lazy load heavy chart library
const AnalyticsChart = dynamic(
() => import('@/components/organisms/AnalyticsChart'),
{
loading: () => <Skeleton className="h-96" />,
ssr: false, // Don't render on server (chart library is client-only)
}
);
export default function AnalyticsPage() {
return (
<div>
<h1>Analytics</h1>
<AnalyticsChart />
</div>
);
}
```
**Virtual Scrolling for Large Tables**:
```typescript
// components/organisms/ProductTable.tsx
'use client';
import { useVirtualizer } from '@tanstack/react-virtual';
import { useRef } from 'react';
export function ProductTable({ products }: { products: Product[] }) {
const parentRef = useRef<HTMLDivElement>(null);
const virtualizer = useVirtualizer({
count: products.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 50, // Row height
overscan: 10, // Render 10 extra rows for smooth scrolling
});
return (
<div ref={parentRef} className="h-96 overflow-auto">
<div style={{ height: `${virtualizer.getTotalSize()}px` }}>
{virtualizer.getVirtualItems().map((virtualRow) => (
<div
key={virtualRow.index}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: `${virtualRow.size}px`,
transform: `translateY(${virtualRow.start}px)`,
}}
>
<ProductRow product={products[virtualRow.index]} />
</div>
))}
</div>
</div>
);
}
```
**Image Optimization**:
```typescript
// components/organisms/ProductCard.tsx
import Image from 'next/image';
export function ProductCard({ product }: { product: Product }) {
return (
<div>
<Image
src={product.imageUrl}
alt={product.name}
width={300}
height={300}
placeholder="blur"
blurDataURL={product.thumbnailUrl}
sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
/>
</div>
);
}
```
---
## Example 2: SaaS Marketing Website
### Scenario
Building a high-performance marketing website for a SaaS product with SEO optimization and accessibility.
### Prompt
```
Design a Next.js marketing website for a B2B SaaS platform with:
Requirements:
- 10+ landing pages (home, features, pricing, about, blog)
- SEO optimized (meta tags, structured data, sitemap)
- Accessibility WCAG AA compliant
- Blog with MDX support
- Contact form with Resend integration
- Newsletter signup
- Dark mode support
- i18n support (English, Spanish, German)
Performance Targets:
- Lighthouse score 95+ (all categories)
- LCP < 2.5s
- CLS < 0.1
- 100% accessibility score
Technical Stack:
- Next.js 14 App Router
- TypeScript
- TailwindCSS
- shadcn/ui components
- MDX for blog
- next-intl for i18n
Provide component architecture and implementation examples.
```
### Agent Output
[Detailed architecture with folder structure, SEO setup, i18n configuration, MDX integration, and accessibility patterns]
---
## Example 3: Real-Time Chat Application
### Scenario
Building a real-time chat application with WebSocket, typing indicators, and message history.
[Full example with WebSocket setup, optimistic updates, and offline support]
---
## Example 4: Design System Migration
### Scenario
Migrating from Material-UI to a custom design system based on shadcn/ui.
[Step-by-step migration plan with component mapping and codemods]
---
## Example 5: Performance Optimization
### Scenario
Optimizing a slow Next.js application (LCP 8s → 2s target).
[Performance audit, bottleneck analysis, optimization implementation]
---
## Example 6: Micro-Frontend Setup
### Scenario
Setting up a micro-frontend architecture with Module Federation for a large enterprise application.
[Webpack 5 Module Federation setup, shared dependencies, independent deployments]
---
## Tips for Effective Prompts
1. **Be Specific**: Include framework versions, tech stack, and constraints
2. **Define Metrics**: Specify performance targets (LCP, bundle size, etc.)
3. **Provide Context**: Team size, timeline, existing infrastructure
4. **State Goals**: SEO, accessibility, mobile-first, etc.
5. **Include Examples**: Reference similar applications or patterns
## Common Patterns
### Pattern 1: Server + Client Component Split
```typescript
// Server Component (default in App Router)
export default async function Page() {
const data = await fetchData(); // Server-side fetch
return <ClientComponent initialData={data} />;
}
// Client Component (interactive)
'use client';
export function ClientComponent({ initialData }) {
const [state, setState] = useState(initialData);
// Interactive logic here
}
```
### Pattern 2: Optimistic Updates
```typescript
const mutation = useMutation({
mutationFn: updateTodo,
onMutate: async (newTodo) => {
await queryClient.cancelQueries({ queryKey: ['todos'] });
const previousTodos = queryClient.getQueryData(['todos']);
// Optimistically update UI
queryClient.setQueryData(['todos'], (old) => [...old, newTodo]);
return { previousTodos };
},
onError: (err, newTodo, context) => {
// Rollback on error
queryClient.setQueryData(['todos'], context.previousTodos);
},
});
```
### Pattern 3: Parallel Data Fetching
```typescript
// Fetch multiple resources in parallel (Server Component)
export default async function Page() {
const [user, posts, comments] = await Promise.all([
fetchUser(),
fetchPosts(),
fetchComments(),
]);
return <Dashboard user={user} posts={posts} comments={comments} />;
}
```
## Additional Resources
- **Next.js Examples**: https://github.com/vercel/next.js/tree/canary/examples
- **React Patterns**: https://patterns.dev
- **TailwindCSS Components**: https://tailwindui.com
- **shadcn/ui**: https://ui.shadcn.com
- **Radix UI**: https://radix-ui.com

View File

@@ -0,0 +1,152 @@
/**
* React Component Template
*
* This template provides a starting point for creating well-structured,
* type-safe React components following best practices.
*
* Usage:
* 1. Copy this template to your components directory
* 2. Rename file and component
* 3. Define props interface
* 4. Implement component logic
* 5. Add tests and Storybook stories
*/
import React from 'react';
import { cn } from '@/lib/utils'; // Utility for className merging (clsx + tailwind-merge)
// ============================================================================
// TYPES
// ============================================================================
/**
* Props for the ComponentName component
*
* @property prop1 - Description of prop1
* @property prop2 - Description of prop2 (optional)
* @property className - Additional CSS classes (optional)
* @property children - React children (optional)
*/
export interface ComponentNameProps {
/** Required prop with specific type */
prop1: string;
/** Optional prop with default value */
prop2?: number;
/** Callback function */
onAction?: (value: string) => void;
/** Additional CSS classes for customization */
className?: string;
/** React children */
children?: React.ReactNode;
}
// ============================================================================
// CONSTANTS
// ============================================================================
const DEFAULT_PROP2 = 42;
// ============================================================================
// COMPONENT
// ============================================================================
/**
* ComponentName - Brief description of what this component does
*
* More detailed description of the component's purpose, use cases,
* and any important implementation notes.
*
* @example
* ```tsx
* <ComponentName
* prop1="value"
* prop2={100}
* onAction={(value) => console.log(value)}
* >
* Content
* </ComponentName>
* ```
*/
export const ComponentName = React.forwardRef<
HTMLDivElement,
ComponentNameProps
>(
(
{
prop1,
prop2 = DEFAULT_PROP2,
onAction,
className,
children,
...restProps
},
ref
) => {
// ========================================================================
// STATE
// ========================================================================
const [internalState, setInternalState] = React.useState<string>('');
// ========================================================================
// EFFECTS
// ========================================================================
React.useEffect(() => {
// Side effects here
}, [prop1]);
// ========================================================================
// HANDLERS
// ========================================================================
const handleClick = React.useCallback(() => {
if (onAction) {
onAction(internalState);
}
}, [internalState, onAction]);
// ========================================================================
// RENDER
// ========================================================================
return (
<div
ref={ref}
className={cn(
// Base styles
'rounded-lg border bg-white p-4 shadow-sm',
// Conditional styles
prop2 > 50 && 'border-blue-500',
// Custom className
className
)}
{...restProps}
>
<h2 className="text-lg font-semibold">{prop1}</h2>
<p className="text-sm text-gray-600">Value: {prop2}</p>
{children && <div className="mt-4">{children}</div>}
<button
onClick={handleClick}
className="mt-4 rounded bg-blue-500 px-4 py-2 text-white hover:bg-blue-600"
>
Click Me
</button>
</div>
);
}
);
ComponentName.displayName = 'ComponentName';
// ============================================================================
// EXPORTS
// ============================================================================
export default ComponentName;

View File

@@ -0,0 +1,311 @@
/**
* Custom React Hook Template
*
* This template provides a starting point for creating reusable
* custom hooks following React best practices.
*
* Usage:
* 1. Copy this template to your hooks directory
* 2. Rename file and hook
* 3. Define input parameters and return type
* 4. Implement hook logic
* 5. Add tests and documentation
*/
import { useState, useEffect, useCallback, useRef } from 'react';
// ============================================================================
// TYPES
// ============================================================================
/**
* Options for the useCustomHook
*/
export interface UseCustomHookOptions {
/** Enable/disable the hook */
enabled?: boolean;
/** Callback when data is loaded */
onSuccess?: (data: string) => void;
/** Callback when error occurs */
onError?: (error: Error) => void;
/** Retry count */
retryCount?: number;
}
/**
* Return type of useCustomHook
*/
export interface UseCustomHookResult {
/** Current data */
data: string | null;
/** Loading state */
isLoading: boolean;
/** Error state */
error: Error | null;
/** Refetch function */
refetch: () => void;
/** Reset function */
reset: () => void;
}
// ============================================================================
// CONSTANTS
// ============================================================================
const DEFAULT_OPTIONS: Required<UseCustomHookOptions> = {
enabled: true,
onSuccess: () => {},
onError: () => {},
retryCount: 3,
};
// ============================================================================
// HOOK
// ============================================================================
/**
* useCustomHook - Brief description of what this hook does
*
* More detailed description of the hook's purpose, use cases,
* and any important implementation notes.
*
* @param param1 - Description of param1
* @param options - Configuration options
* @returns Hook result with data, loading, error states and utility functions
*
* @example
* ```tsx
* function MyComponent() {
* const { data, isLoading, error, refetch } = useCustomHook('value', {
* enabled: true,
* onSuccess: (data) => console.log('Success:', data),
* });
*
* if (isLoading) return <Spinner />;
* if (error) return <Error message={error.message} />;
*
* return <div>{data}</div>;
* }
* ```
*/
export function useCustomHook(
param1: string,
options: UseCustomHookOptions = {}
): UseCustomHookResult {
// ========================================================================
// OPTIONS
// ========================================================================
const {
enabled = DEFAULT_OPTIONS.enabled,
onSuccess = DEFAULT_OPTIONS.onSuccess,
onError = DEFAULT_OPTIONS.onError,
retryCount = DEFAULT_OPTIONS.retryCount,
} = options;
// ========================================================================
// STATE
// ========================================================================
const [data, setData] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState<boolean>(false);
const [error, setError] = useState<Error | null>(null);
// ========================================================================
// REFS
// ========================================================================
// Use refs for values that shouldn't trigger re-renders
const retryCountRef = useRef(0);
const mountedRef = useRef(true);
// ========================================================================
// CLEANUP
// ========================================================================
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
}, []);
// ========================================================================
// FETCH LOGIC
// ========================================================================
const fetchData = useCallback(async () => {
if (!enabled) return;
setIsLoading(true);
setError(null);
try {
// Simulate async operation
const result = await new Promise<string>((resolve, reject) => {
setTimeout(() => {
if (Math.random() > 0.8) {
reject(new Error('Random error'));
} else {
resolve(`Data for ${param1}`);
}
}, 1000);
});
// Only update state if component is still mounted
if (mountedRef.current) {
setData(result);
setIsLoading(false);
onSuccess(result);
retryCountRef.current = 0; // Reset retry count on success
}
} catch (err) {
if (mountedRef.current) {
const error = err instanceof Error ? err : new Error('Unknown error');
// Retry logic
if (retryCountRef.current < retryCount) {
retryCountRef.current++;
setTimeout(() => fetchData(), 1000 * retryCountRef.current); // Exponential backoff
} else {
setError(error);
setIsLoading(false);
onError(error);
}
}
}
}, [enabled, param1, onSuccess, onError, retryCount]);
// ========================================================================
// EFFECTS
// ========================================================================
useEffect(() => {
if (enabled) {
fetchData();
}
// Cleanup function
return () => {
// Cancel any pending operations
};
}, [enabled, fetchData]);
// ========================================================================
// HANDLERS
// ========================================================================
const refetch = useCallback(() => {
retryCountRef.current = 0; // Reset retry count
fetchData();
}, [fetchData]);
const reset = useCallback(() => {
setData(null);
setError(null);
setIsLoading(false);
retryCountRef.current = 0;
}, []);
// ========================================================================
// RETURN
// ========================================================================
return {
data,
isLoading,
error,
refetch,
reset,
};
}
// ============================================================================
// HELPER HOOKS (Optional)
// ============================================================================
/**
* useDebounce - Debounce a value
*
* Useful for search inputs, window resize handlers, etc.
*
* @example
* ```tsx
* const [searchTerm, setSearchTerm] = useState('');
* const debouncedSearchTerm = useDebounce(searchTerm, 500);
*
* useEffect(() => {
* // API call with debounced value
* searchAPI(debouncedSearchTerm);
* }, [debouncedSearchTerm]);
* ```
*/
export function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
}
/**
* useLocalStorage - Sync state with localStorage
*
* @example
* ```tsx
* const [theme, setTheme] = useLocalStorage('theme', 'light');
* ```
*/
export function useLocalStorage<T>(
key: string,
initialValue: T
): [T, (value: T | ((val: T) => T)) => void] {
const [storedValue, setStoredValue] = useState<T>(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.error(`Error reading localStorage key "${key}":`, error);
return initialValue;
}
});
const setValue = useCallback(
(value: T | ((val: T) => T)) => {
try {
const valueToStore =
value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.error(`Error setting localStorage key "${key}":`, error);
}
},
[key, storedValue]
);
return [storedValue, setValue];
}
// ============================================================================
// EXPORTS
// ============================================================================
export default useCustomHook;

View File

@@ -0,0 +1,228 @@
/**
* Next.js App Router Page Template
*
* This template demonstrates best practices for creating pages
* in Next.js 14+ App Router with Server Components.
*
* Key Features:
* - Server Component by default (no 'use client' needed)
* - SEO metadata generation
* - Suspense boundaries for streaming
* - Error handling
* - TypeScript types
*/
import { Metadata } from 'next';
import { Suspense } from 'react';
import { notFound } from 'next/navigation';
// Components
import { PageHeader } from '@/components/organisms/PageHeader';
import { DataTable } from '@/components/organisms/DataTable';
import { Skeleton } from '@/components/atoms/Skeleton';
// ============================================================================
// TYPES
// ============================================================================
interface PageProps {
params: {
id: string;
};
searchParams: {
page?: string;
sort?: string;
};
}
// ============================================================================
// METADATA (SEO)
// ============================================================================
/**
* Generate static metadata for SEO
*
* This function runs on the server and generates metadata
* for search engines and social media.
*/
export async function generateMetadata({
params,
}: PageProps): Promise<Metadata> {
// Fetch data needed for metadata
const data = await fetchData(params.id);
if (!data) {
return {
title: 'Not Found',
};
}
return {
title: `${data.title} | Your App Name`,
description: data.description,
openGraph: {
title: data.title,
description: data.description,
images: [data.imageUrl],
},
twitter: {
card: 'summary_large_image',
title: data.title,
description: data.description,
images: [data.imageUrl],
},
};
}
/**
* Optional: Generate static paths for Static Site Generation (SSG)
*
* Uncomment this function if you want to pre-render pages at build time.
*/
// export async function generateStaticParams() {
// const items = await fetchAllItems();
//
// return items.map((item) => ({
// id: item.id,
// }));
// }
// ============================================================================
// DATA FETCHING
// ============================================================================
/**
* Fetch data on the server
*
* This runs on the server, so you can safely access databases,
* private APIs, etc.
*/
async function fetchData(id: string) {
const response = await fetch(`https://api.example.com/items/${id}`, {
next: {
revalidate: 3600, // ISR: Revalidate every hour
// OR use 'force-cache' for static generation
// OR use 'no-store' for dynamic rendering
},
});
if (!response.ok) {
return null;
}
return response.json();
}
async function fetchRelatedData(filters: { page: number; sort: string }) {
const response = await fetch(
`https://api.example.com/related?page=${filters.page}&sort=${filters.sort}`,
{
next: { revalidate: 60 }, // Revalidate every minute
}
);
return response.json();
}
// ============================================================================
// PAGE COMPONENT
// ============================================================================
/**
* Page Component (Server Component by default)
*
* Server Components:
* - Run on the server only
* - Can access backend resources directly
* - Don't add JavaScript to the client bundle
* - Can't use hooks like useState, useEffect
* - Can't add event handlers
*/
export default async function Page({ params, searchParams }: PageProps) {
// ========================================================================
// DATA FETCHING (Server-side)
// ========================================================================
// Parse search params
const page = searchParams.page ? parseInt(searchParams.page) : 1;
const sort = searchParams.sort || 'desc';
// Fetch data in parallel for performance
const [mainData, relatedData] = await Promise.all([
fetchData(params.id),
fetchRelatedData({ page, sort }),
]);
// Handle not found
if (!mainData) {
notFound(); // Renders app/not-found.tsx
}
// ========================================================================
// RENDER
// ========================================================================
return (
<div className="container mx-auto px-4 py-8">
{/* Page Header */}
<PageHeader
title={mainData.title}
description={mainData.description}
breadcrumbs={[
{ label: 'Home', href: '/' },
{ label: 'Items', href: '/items' },
{ label: mainData.title, href: `/items/${params.id}` },
]}
/>
{/* Main Content */}
<section className="mt-8">
<h2 className="text-2xl font-bold">Details</h2>
<div className="mt-4 grid grid-cols-1 gap-6 md:grid-cols-2">
<div>
<p className="text-gray-600">ID: {mainData.id}</p>
<p className="text-gray-600">Created: {mainData.createdAt}</p>
</div>
</div>
</section>
{/* Related Data with Suspense */}
<section className="mt-12">
<h2 className="text-2xl font-bold">Related Items</h2>
<Suspense fallback={<Skeleton className="mt-4 h-96" />}>
<DataTable
data={relatedData.items}
columns={['id', 'name', 'status']}
pagination={{
currentPage: page,
totalPages: relatedData.totalPages,
}}
/>
</Suspense>
</section>
</div>
);
}
// ============================================================================
// CLIENT COMPONENT EXAMPLE (if needed)
// ============================================================================
/**
* If you need interactivity, create a separate Client Component:
*
* 'use client';
*
* export function InteractiveSection({ initialData }) {
* const [state, setState] = useState(initialData);
*
* return (
* <div>
* <button onClick={() => setState(...)}>Click me</button>
* </div>
* );
* }
*
* Then use it in the Server Component:
* <InteractiveSection initialData={mainData} />
*/