feature-builder
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseFeature Builder
功能构建器
This skill builds complete, production-ready React features with proper separation of concerns across presentation, business logic, and data access layers.
这个技能采用关注点分离的原则,构建完整的、可用于生产环境的React功能,涵盖展示层、业务逻辑层和数据访问层。
Purpose
用途
Transform feature requirements into complete, working implementations that include:
- UI Components - Using react-component-generator
- Business Logic - Hooks, stores, validation, transformations
- API Integration - Data fetching, mutations, caching
- State Management - Zustand for global state, React Query for server state
- Error Handling - Comprehensive error management
- Type Safety - Full TypeScript support
将功能需求转化为完整的可运行实现,包括:
- UI组件 - 使用react-component-generator
- 业务逻辑 - Hooks、存储、验证、转换
- API集成 - 数据获取、变更、缓存
- 状态管理 - 使用Zustand管理全局状态,React Query管理服务端状态
- 错误处理 - 全面的错误管理
- 类型安全 - 完整的TypeScript支持
When to Use This Skill
适用场景
Use this skill when:
- User requests a complete feature (not just a UI component)
- Request involves business logic and data management
- User mentions: "implement", "build", "create feature"
- Examples:
- "Implement user authentication"
- "Build a shopping cart"
- "Create a product listing with filters"
- "Add file upload functionality"
- "Implement real-time notifications"
在以下场景使用本技能:
- 用户请求完整的功能(而非仅UI组件)
- 请求涉及业务逻辑和数据管理
- 用户提到:「实现」「构建」「创建功能」
- 示例:
- 「实现用户认证」
- 「构建购物车」
- 「创建带筛选功能的产品列表」
- 「添加文件上传功能」
- 「实现实时通知」
Architecture
架构
Features are built with 3-layer architecture:
┌──────────────────────────────────────┐
│ Presentation Layer │ ← UI Components
│ (React components, Tailwind CSS) │
├──────────────────────────────────────┤
│ Business Logic Layer │ ← Hooks, Stores, Validation
│ (Zustand, hooks, utils) │
├──────────────────────────────────────┤
│ Data Access Layer │ ← API Calls, React Query
│ (API client, queries, mutations) │
└──────────────────────────────────────┘Reference for complete details.
references/layered-architecture.md功能采用三层架构构建:
┌──────────────────────────────────────┐
│ Presentation Layer │ ← UI Components
│ (React components, Tailwind CSS) │
├──────────────────────────────────────┤
│ Business Logic Layer │ ← Hooks, Stores, Validation
│ (Zustand, hooks, utils) │
├──────────────────────────────────────┤
│ Data Access Layer │ ← API Calls, React Query
│ (API client, queries, mutations) │
└──────────────────────────────────────┘完整细节请参考。
references/layered-architecture.mdWorkflow
工作流程
Step 1: Analyze Feature Request
步骤1:分析功能需求
When user requests a feature, analyze:
-
Feature Type:
- Authentication/Authorization
- CRUD operations
- File handling
- Real-time updates
- Search/Filter
- Complex workflows (multi-step, cart, checkout)
-
Required Layers:
- Does it need UI? (Almost always yes)
- Does it need business logic? (Forms, validation, calculations)
- Does it need API integration? (Server data, persistence)
- Does it need global state? (Shared across components)
-
Dependencies:
- What other features does it depend on?
- What APIs does it need?
- What libraries are required? (React Query, Zustand, Zod)
当用户请求功能时,分析以下内容:
-
功能类型:
- 认证/授权
- CRUD操作
- 文件处理
- 实时更新
- 搜索/筛选
- 复杂工作流(多步骤、购物车、结账)
-
所需层级:
- 是否需要UI?(几乎总是需要)
- 是否需要业务逻辑?(表单、验证、计算)
- 是否需要API集成?(服务端数据、持久化)
- 是否需要全局状态?(跨组件共享)
-
依赖项:
- 依赖其他哪些功能?
- 需要哪些API?
- 需要哪些库?(React Query、Zustand、Zod)
Step 2: Plan Architecture
步骤2:规划架构
Design the feature structure:
features/
└── [feature-name]/
├── components/ # Presentation Layer
│ ├── FeatureMain.tsx
│ ├── FeatureForm.tsx
│ └── index.ts
├── hooks/ # Business Logic
│ ├── useFeature.ts
│ └── index.ts
├── stores/ # Global State (if needed)
│ ├── featureStore.ts
│ └── index.ts
├── api/ # Data Access
│ ├── featureApi.ts
│ ├── queries.ts
│ └── index.ts
├── utils/ # Utilities
│ ├── validation.ts
│ └── transforms.ts
├── types/ # TypeScript Types
│ └── feature.types.ts
└── index.ts # Public API设计功能结构:
features/
└── [feature-name]/
├── components/ # 展示层
│ ├── FeatureMain.tsx
│ ├── FeatureForm.tsx
│ └── index.ts
├── hooks/ # 业务逻辑层
│ ├── useFeature.ts
│ └── index.ts
├── stores/ # 全局状态(如有需要)
│ ├── featureStore.ts
│ └── index.ts
├── api/ # 数据访问层
│ ├── featureApi.ts
│ ├── queries.ts
│ └── index.ts
├── utils/ # 工具类
│ ├── validation.ts
│ └── transforms.ts
├── types/ # TypeScript类型定义
│ └── feature.types.ts
└── index.ts # 公共APIStep 3: Clarify Requirements (Interactive)
步骤3:明确需求(交互式)
Use to gather necessary details:
AskUserQuestiontypescript
AskUserQuestion({
questions: [
{
question: "What data needs to be managed?",
header: "Data",
multiSelect: false,
options: [
{ label: "User data", description: "Authentication, profiles" },
{ label: "Products", description: "E-commerce items" },
{ label: "Posts/Content", description: "Blog posts, articles" },
{ label: "Files", description: "File uploads/downloads" },
]
},
{
question: "What operations are needed?",
header: "Operations",
multiSelect: true,
options: [
{ label: "Create", description: "Add new items" },
{ label: "Read/List", description: "Fetch and display data" },
{ label: "Update", description: "Modify existing items" },
{ label: "Delete", description: "Remove items" },
{ label: "Search", description: "Find specific items" },
{ label: "Filter", description: "Filter by criteria" },
]
},
{
question: "Does this need authentication?",
header: "Auth",
multiSelect: false,
options: [
{ label: "Yes, required", description: "User must be logged in" },
{ label: "Optional", description: "Works with or without auth" },
{ label: "No", description: "Public feature" },
]
},
{
question: "Any additional requirements?",
header: "Extra",
multiSelect: false,
options: [
{ label: "No, that's all", description: "Just the basics" },
{ label: "Yes, let me specify", description: "Use 'Other' to describe" },
]
}
]
})使用收集必要信息:
AskUserQuestiontypescript
AskUserQuestion({
questions: [
{
question: "What data needs to be managed?",
header: "Data",
multiSelect: false,
options: [
{ label: "User data", description: "Authentication, profiles" },
{ label: "Products", description: "E-commerce items" },
{ label: "Posts/Content", description: "Blog posts, articles" },
{ label: "Files", description: "File uploads/downloads" },
]
},
{
question: "What operations are needed?",
header: "Operations",
multiSelect: true,
options: [
{ label: "Create", description: "Add new items" },
{ label: "Read/List", description: "Fetch and display data" },
{ label: "Update", description: "Modify existing items" },
{ label: "Delete", description: "Remove items" },
{ label: "Search", description: "Find specific items" },
{ label: "Filter", description: "Filter by criteria" },
]
},
{
question: "Does this need authentication?",
header: "Auth",
multiSelect: false,
options: [
{ label: "Yes, required", description: "User must be logged in" },
{ label: "Optional", description: "Works with or without auth" },
{ label: "No", description: "Public feature" },
]
},
{
question: "Any additional requirements?",
header: "Extra",
multiSelect: false,
options: [
{ label: "No, that's all", description: "Just the basics" },
{ label: "Yes, let me specify", description: "Use 'Other' to describe" },
]
}
]
})Step 4: Generate Feature Code
步骤4:生成功能代码
Generate code for each layer:
为每个层级生成代码:
4.1 Types First
4.1 先定义类型
typescript
// features/user-auth/types/auth.types.ts
export interface User {
id: string;
email: string;
name: string;
role: 'admin' | 'user';
}
export interface LoginCredentials {
email: string;
password: string;
}
export interface LoginResponse {
user: User;
accessToken: string;
refreshToken: string;
}typescript
// features/user-auth/types/auth.types.ts
export interface User {
id: string;
email: string;
name: string;
role: 'admin' | 'user';
}
export interface LoginCredentials {
email: string;
password: string;
}
export interface LoginResponse {
user: User;
accessToken: string;
refreshToken: string;
}4.2 API Layer
4.2 API层
typescript
// features/user-auth/api/authApi.ts
export const authApi = {
login: async (credentials: LoginCredentials): Promise<LoginResponse> => {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(credentials),
});
if (!response.ok) throw new Error('Login failed');
return response.json();
},
// ... other methods
};
// features/user-auth/api/queries.ts
import { useMutation } from '@tanstack/react-query';
export function useLogin() {
return useMutation({
mutationFn: authApi.login,
onSuccess: (data) => {
// Handle success
},
});
}typescript
// features/user-auth/api/authApi.ts
export const authApi = {
login: async (credentials: LoginCredentials): Promise<LoginResponse> => {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(credentials),
});
if (!response.ok) throw new Error('Login failed');
return response.json();
},
// ... other methods
};
// features/user-auth/api/queries.ts
import { useMutation } from '@tanstack/react-query';
export function useLogin() {
return useMutation({
mutationFn: authApi.login,
onSuccess: (data) => {
// Handle success
},
});
}4.3 Business Logic Layer
4.3 业务逻辑层
typescript
// features/user-auth/stores/authStore.ts
import { create } from 'zustand';
export const useAuthStore = create<AuthStore>((set) => ({
user: null,
token: null,
isAuthenticated: false,
setUser: (user) => set({ user, isAuthenticated: true }),
setToken: (token) => set({ token }),
clearAuth: () => set({ user: null, token: null, isAuthenticated: false }),
}));
// features/user-auth/hooks/useAuth.ts
export function useAuth() {
const { setUser, setToken } = useAuthStore();
const { mutate: login, isPending, error } = useLogin();
const handleLogin = async (credentials: LoginCredentials) => {
return new Promise((resolve, reject) => {
login(credentials, {
onSuccess: (data) => {
setToken(data.accessToken);
setUser(data.user);
localStorage.setItem('token', data.accessToken);
resolve(data);
},
onError: (error) => reject(error),
});
});
};
return { login: handleLogin, isLoading: isPending, error };
}
// features/user-auth/utils/validation.ts
import { z } from 'zod';
export const loginSchema = z.object({
email: z.string().email('Invalid email'),
password: z.string().min(8, 'Password must be at least 8 characters'),
});typescript
// features/user-auth/stores/authStore.ts
import { create } from 'zustand';
export const useAuthStore = create<AuthStore>((set) => ({
user: null,
token: null,
isAuthenticated: false,
setUser: (user) => set({ user, isAuthenticated: true }),
setToken: (token) => set({ token }),
clearAuth: () => set({ user: null, token: null, isAuthenticated: false }),
}));
// features/user-auth/hooks/useAuth.ts
export function useAuth() {
const { setUser, setToken } = useAuthStore();
const { mutate: login, isPending, error } = useLogin();
const handleLogin = async (credentials: LoginCredentials) => {
return new Promise((resolve, reject) => {
login(credentials, {
onSuccess: (data) => {
setToken(data.accessToken);
setUser(data.user);
localStorage.setItem('token', data.accessToken);
resolve(data);
},
onError: (error) => reject(error),
});
});
};
return { login: handleLogin, isLoading: isPending, error };
}
// features/user-auth/utils/validation.ts
import { z } from 'zod';
export const loginSchema = z.object({
email: z.string().email('Invalid email'),
password: z.string().min(8, 'Password must be at least 8 characters'),
});4.4 Presentation Layer
4.4 展示层
typescript
// features/user-auth/components/LoginForm.tsx
import { useAuth } from '../hooks/useAuth';
import { loginSchema } from '../utils/validation';
export const LoginForm: React.FC = () => {
const { login, isLoading, error } = useAuth();
const [formData, setFormData] = useState({ email: '', password: '' });
const [validationErrors, setValidationErrors] = useState<Record<string, string>>({});
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
// Validate
try {
loginSchema.parse(formData);
setValidationErrors({});
} catch (err) {
if (err instanceof z.ZodError) {
const errors = err.errors.reduce((acc, error) => {
acc[error.path[0]] = error.message;
return acc;
}, {} as Record<string, string>);
setValidationErrors(errors);
return;
}
}
// Submit
try {
await login(formData);
router.push('/dashboard');
} catch (err) {
// Error handled by useAuth
}
};
return (
<form onSubmit={handleSubmit} className="space-y-4 max-w-md mx-auto">
<div>
<label htmlFor="email" className="block text-sm font-medium text-gray-700">
Email
</label>
<input
id="email"
type="email"
value={formData.email}
onChange={(e) => setFormData({ ...formData, email: e.target.value })}
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md"
/>
{validationErrors.email && (
<p className="mt-1 text-sm text-red-600">{validationErrors.email}</p>
)}
</div>
<div>
<label htmlFor="password" className="block text-sm font-medium text-gray-700">
Password
</label>
<input
id="password"
type="password"
value={formData.password}
onChange={(e) => setFormData({ ...formData, password: e.target.value })}
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md"
/>
{validationErrors.password && (
<p className="mt-1 text-sm text-red-600">{validationErrors.password}</p>
)}
</div>
{error && (
<p className="text-sm text-red-600">Invalid email or password</p>
)}
<button
type="submit"
disabled={isLoading}
className="w-full px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 disabled:opacity-50"
>
{isLoading ? 'Logging in...' : 'Login'}
</button>
</form>
);
};typescript
// features/user-auth/components/LoginForm.tsx
import { useAuth } from '../hooks/useAuth';
import { loginSchema } from '../utils/validation';
export const LoginForm: React.FC = () => {
const { login, isLoading, error } = useAuth();
const [formData, setFormData] = useState({ email: '', password: '' });
const [validationErrors, setValidationErrors] = useState<Record<string, string>>({});
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
// Validate
try {
loginSchema.parse(formData);
setValidationErrors({});
} catch (err) {
if (err instanceof z.ZodError) {
const errors = err.errors.reduce((acc, error) => {
acc[error.path[0]] = error.message;
return acc;
}, {} as Record<string, string>);
setValidationErrors(errors);
return;
}
}
// Submit
try {
await login(formData);
router.push('/dashboard');
} catch (err) {
// Error handled by useAuth
}
};
return (
<form onSubmit={handleSubmit} className="space-y-4 max-w-md mx-auto">
<div>
<label htmlFor="email" className="block text-sm font-medium text-gray-700">
Email
</label>
<input
id="email"
type="email"
value={formData.email}
onChange={(e) => setFormData({ ...formData, email: e.target.value })}
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md"
/>
{validationErrors.email && (
<p className="mt-1 text-sm text-red-600">{validationErrors.email}</p>
)}
</div>
<div>
<label htmlFor="password" className="block text-sm font-medium text-gray-700">
Password
</label>
<input
id="password"
type="password"
value={formData.password}
onChange={(e) => setFormData({ ...formData, password: e.target.value })}
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md"
/>
{validationErrors.password && (
<p className="mt-1 text-sm text-red-600">{validationErrors.password}</p>
)}
</div>
{error && (
<p className="text-sm text-red-600">Invalid email or password</p>
)}
<button
type="submit"
disabled={isLoading}
className="w-full px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 disabled:opacity-50"
>
{isLoading ? 'Logging in...' : 'Login'}
</button>
</form>
);
};Step 5: Provide Implementation Guide
步骤5:提供实现指南
After generating code, provide:
- Installation requirements:
bash
npm install @tanstack/react-query zustand zod axios- Setup instructions:
typescript
// app/providers.tsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
const queryClient = new QueryClient();
export function Providers({ children }: { children: React.ReactNode }) {
return (
<QueryClientProvider client={queryClient}>
{children}
</QueryClientProvider>
);
}- Usage examples:
typescript
// app/login/page.tsx
import { LoginForm } from '@/features/user-auth';
export default function LoginPage() {
return (
<div className="min-h-screen flex items-center justify-center">
<LoginForm />
</div>
);
}- Testing suggestions:
typescript
// features/user-auth/__tests__/useAuth.test.ts
import { renderHook, waitFor } from '@testing-library/react';
import { useAuth } from '../hooks/useAuth';
describe('useAuth', () => {
it('should login successfully', async () => {
const { result } = renderHook(() => useAuth());
await act(async () => {
await result.current.login({
email: 'test@example.com',
password: 'password123',
});
});
expect(result.current.error).toBeNull();
});
});生成代码后,提供以下内容:
- 安装依赖:
bash
npm install @tanstack/react-query zustand zod axios- 设置说明:
typescript
// app/providers.tsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
const queryClient = new QueryClient();
export function Providers({ children }: { children: React.ReactNode }) {
return (
<QueryClientProvider client={queryClient}>
{children}
</QueryClientProvider>
);
}- 使用示例:
typescript
// app/login/page.tsx
import { LoginForm } from '@/features/user-auth';
export default function LoginPage() {
return (
<div className="min-h-screen flex items-center justify-center">
<LoginForm />
</div>
);
}- 测试建议:
typescript
// features/user-auth/__tests__/useAuth.test.ts
import { renderHook, waitFor } from '@testing-library/react';
import { useAuth } from '../hooks/useAuth';
describe('useAuth', () => {
it('should login successfully', async () => {
const { result } = renderHook(() => useAuth());
await act(async () => {
await result.current.login({
email: 'test@example.com',
password: 'password123',
});
});
expect(result.current.error).toBeNull();
});
});Integration with Other Skills
与其他技能的集成
With react-component-generator
与react-component-generator集成
When building UI components:
- Use react-component-generator templates as base
- Enhance with business logic integration
- Connect to hooks and stores
构建UI组件时:
- 以react-component-generator的模板为基础
- 增强业务逻辑集成
- 连接到hooks和存储
With ui-analyzer
与ui-analyzer集成
When implementing from design:
- Use ui-analyzer to extract UI structure
- Build business logic layer
- Connect UI to business logic
从设计稿实现时:
- 使用ui-analyzer提取UI结构
- 构建业务逻辑层
- 将UI与业务逻辑连接
With prompt-optimizer
与prompt-optimizer集成
If feature request is vague:
- Activate prompt-optimizer first
- Clarify requirements
- Then build feature
如果功能请求模糊:
- 先激活prompt-optimizer
- 明确需求
- 再构建功能
Common Feature Patterns
常见功能模式
Reference for detailed patterns:
references/business-logic-patterns.md- Authentication & Authorization
- Form Handling with Validation
- Data Fetching with React Query
- File Upload
- Search & Filtering
- Shopping Cart
- Real-time Updates (WebSocket)
详细模式请参考:
references/business-logic-patterns.md- 认证与授权
- 带验证的表单处理
- 使用React Query获取数据
- 文件上传
- 搜索与筛选
- 购物车
- 实时更新(WebSocket)
Best Practices
最佳实践
- Always use layered architecture - Separation of concerns
- TypeScript everything - Full type safety
- Validate on both sides - Client (UX) and server (security)
- Handle errors gracefully - User-friendly error messages
- Optimize for performance - React Query caching, memoization
- Make it accessible - ARIA labels, keyboard navigation
- Test business logic - Unit tests for hooks and stores
- Document complex logic - Comments for future maintenance
- 始终使用分层架构 - 关注点分离
- 全栈TypeScript - 完整的类型安全
- 双向验证 - 客户端(用户体验)和服务端(安全)
- 优雅处理错误 - 友好的错误提示
- 性能优化 - React Query缓存、记忆化
- 可访问性 - ARIA标签、键盘导航
- 测试业务逻辑 - hooks和存储的单元测试
- 文档化复杂逻辑 - 便于未来维护的注释
Example Complete Feature: User Authentication
完整功能示例:用户认证
User Request: "Implement user authentication with login and registration"
Generated Structure:
features/
└── user-auth/
├── components/
│ ├── LoginForm.tsx
│ ├── RegisterForm.tsx
│ ├── ProtectedRoute.tsx
│ └── index.ts
├── hooks/
│ ├── useAuth.ts
│ ├── usePermission.ts
│ └── index.ts
├── stores/
│ ├── authStore.ts
│ └── index.ts
├── api/
│ ├── authApi.ts
│ ├── queries.ts
│ └── index.ts
├── utils/
│ ├── validation.ts
│ └── index.ts
├── types/
│ └── auth.types.ts
└── index.tsIncludes:
- ✅ Login form with validation
- ✅ Registration form with validation
- ✅ JWT token management
- ✅ Protected routes
- ✅ Permission checking
- ✅ Persistent auth state
- ✅ Error handling
- ✅ Loading states
- ✅ Type-safe API calls
用户请求:「实现带登录和注册的用户认证功能」
生成的结构:
features/
└── user-auth/
├── components/
│ ├── LoginForm.tsx
│ ├── RegisterForm.tsx
│ ├── ProtectedRoute.tsx
│ └── index.ts
├── hooks/
│ ├── useAuth.ts
│ ├── usePermission.ts
│ └── index.ts
├── stores/
│ ├── authStore.ts
│ └── index.ts
├── api/
│ ├── authApi.ts
│ ├── queries.ts
│ └── index.ts
├── utils/
│ ├── validation.ts
│ └── index.ts
├── types/
│ └── auth.types.ts
└── index.ts包含内容:
- ✅ 带验证的登录表单
- ✅ 带验证的注册表单
- ✅ JWT令牌管理
- ✅ 受保护的路由
- ✅ 权限检查
- ✅ 持久化认证状态
- ✅ 错误处理
- ✅ 加载状态
- ✅ 类型安全的API调用
Output Format
输出格式
When generating a feature, provide:
markdown
undefined生成功能时,请提供以下格式:
markdown
undefined[Feature Name] Implementation
[功能名称] 实现
Overview
概述
[Brief description of what was implemented]
[实现内容的简要描述]
Structure
结构
[Directory tree showing all files]
[展示所有文件的目录树]
Installation
安装
bash
[Required dependencies]bash
[所需依赖]Code
代码
Types
类型定义
[TypeScript interfaces and types]
[TypeScript接口和类型]
API Layer
API层
[API client and React Query hooks]
[API客户端和React Query hooks]
Business Logic
业务逻辑
[Zustand stores and custom hooks]
[Zustand存储和自定义hooks]
UI Components
UI组件
[React components]
[React组件]
Validation
验证规则
[Validation schemas]
[验证 schema]
Setup Instructions
设置说明
[How to integrate into the project]
[如何集成到项目中]
Usage Examples
使用示例
[How to use the feature]
[如何使用该功能]
Testing
测试
[Test examples]
[测试示例]
Next Steps
下一步
[What else might be needed]
This skill enables rapid development of production-ready features with proper architecture and best practices![可能还需要的内容]
这个技能能快速开发符合架构规范和最佳实践的生产级功能!