Skip to content

Commit d0041f1

Browse files
authored
Merge pull request #1197 from ModelEngine-Group/wmc/refactor_0902
♻️ Add cursor rules of frontend
2 parents 9285895 + 3104758 commit d0041f1

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

60 files changed

+445
-81
lines changed
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
---
2+
globs: frontend/components/**/*.tsx
3+
description: Component layer rules for reusable UI components
4+
---
5+
6+
### Purpose and Scope
7+
8+
- Component layer contains reusable UI components for `frontend/components/**/*.tsx`
9+
- Responsibilities: Create reusable components, implement business logic, handle interactions, provide consistent UI
10+
- **MANDATORY**: All components must use TypeScript and functional components
11+
12+
### Component Organization
13+
14+
- **`components/ui/`** - Base UI components (buttons, inputs, dialogs, etc.)
15+
- **`components/auth/`** - Authentication-related components
16+
- **`components/providers/`** - Context providers and global state management
17+
- Use index files for clean imports: `export { Button } from './button'`
18+
19+
### Component Structure
20+
21+
- Use functional components with TypeScript
22+
- Define proper interfaces for all props
23+
- Use React hooks for state management
24+
- Implement proper error boundaries where needed
25+
- Follow single responsibility principle
26+
27+
### Props and State Management
28+
29+
- All props must be typed with interfaces
30+
- Use optional props with default values when appropriate
31+
- Prefer controlled components over uncontrolled
32+
- Use local state for component-specific data
33+
- Use context for shared state across components
34+
- **CRITICAL**: All logging must use [logger.ts](mdc:frontend/lib/logger.ts) - never use console.log
35+
36+
### Styling and Design
37+
38+
- Use Tailwind CSS classes for styling
39+
- Follow design system patterns and spacing
40+
- Ensure responsive design with mobile-first approach
41+
- Use CSS variables for theme colors
42+
- Implement proper focus states and accessibility
43+
44+
### Internationalization
45+
46+
- All user-facing text must use `useTranslation` hook
47+
- Use descriptive translation keys: `t('button.save')` instead of `t('save')`
48+
- Provide fallback text for missing translations
49+
- Group related translations in namespaces
50+
51+
### Error Handling
52+
53+
- Implement proper error boundaries for component trees
54+
- Handle async operations with loading and error states
55+
- Provide meaningful error messages to users
56+
- Log errors appropriately for debugging
57+
58+
### Example
59+
```tsx
60+
// frontend/components/ui/button.tsx
61+
import React from 'react';
62+
import { useTranslation } from 'react-i18next';
63+
import { cn } from '@/lib/utils';
64+
65+
interface ButtonProps {
66+
children: React.ReactNode;
67+
variant?: 'primary' | 'secondary' | 'outline';
68+
size?: 'sm' | 'md' | 'lg';
69+
disabled?: boolean;
70+
loading?: boolean;
71+
onClick?: () => void;
72+
className?: string;
73+
}
74+
75+
export function Button({
76+
children,
77+
variant = 'primary',
78+
size = 'md',
79+
disabled = false,
80+
loading = false,
81+
onClick,
82+
className,
83+
}: ButtonProps) {
84+
const { t } = useTranslation('common');
85+
86+
return (
87+
<button
88+
className={cn(
89+
'inline-flex items-center justify-center rounded-md font-medium transition-colors',
90+
variant === 'primary' && 'bg-primary text-primary-foreground hover:bg-primary/90',
91+
variant === 'secondary' && 'bg-secondary text-secondary-foreground hover:bg-secondary/80',
92+
variant === 'outline' && 'border border-input bg-background hover:bg-accent',
93+
size === 'sm' && 'h-9 px-3 text-sm',
94+
size === 'md' && 'h-10 px-4 py-2',
95+
size === 'lg' && 'h-11 px-8 text-lg',
96+
className
97+
)}
98+
disabled={disabled || loading}
99+
onClick={onClick}
100+
>
101+
{loading && <div className="mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent" />}
102+
{children}
103+
</button>
104+
);
105+
}
106+
```
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
---
2+
globs: frontend/hooks/**/*.ts
3+
description: Hook layer rules for custom React hooks and state management
4+
---
5+
6+
### Purpose and Scope
7+
8+
- Hook layer contains custom React hooks for `frontend/hooks/**/*.ts`
9+
- Responsibilities: Encapsulate state logic, provide service interfaces, handle loading/error states
10+
- **MANDATORY**: All hooks must be named `useXxx` and use TypeScript
11+
12+
### Hook Organization
13+
14+
- **`hooks/useAuth.ts`** - Authentication state and operations
15+
- **`hooks/useConfig.ts`** - Configuration management
16+
- **`hooks/useChat.ts`** - Chat-related state and operations
17+
- **`hooks/useMemory.ts`** - Memory management
18+
- Use descriptive names indicating the hook's purpose
19+
20+
### Hook Structure
21+
22+
- Use TypeScript for all hook definitions
23+
- Return objects with descriptive property names
24+
- Handle loading, error, and success states consistently
25+
- Implement proper cleanup for side effects
26+
- Use proper dependency arrays in useEffect
27+
28+
### Essential Hook Usage
29+
30+
| Hook | Purpose | When to Use |
31+
|------|---------|-------------|
32+
| `useState` | Store component state | Simple state like toggles, counters |
33+
| `useReducer` | Complex state logic | Multiple state dependencies |
34+
| `useContext` | Share data between components | Theme, user info, global state |
35+
| `useEffect` | Handle side effects | Data fetching, subscriptions, timers |
36+
| `useCallback` | Prevent function recreation | Callbacks passed to child components |
37+
| `useMemo` | Cache calculations | Expensive computations |
38+
| `useRef` | Store mutable values | DOM nodes, timer IDs |
39+
40+
### State Management
41+
42+
- Use useState for local component state
43+
- Use useReducer for complex state logic
44+
- Use useContext for shared state across components
45+
- Implement proper state updates and immutability
46+
- Handle async state updates correctly
47+
- **CRITICAL**: All logging must use [logger.ts](mdc:frontend/lib/logger.ts) - never use console.log
48+
49+
### Error Handling
50+
51+
- Handle async errors gracefully
52+
- Provide meaningful error messages
53+
- Log errors appropriately for debugging
54+
- Implement retry logic for transient failures
55+
56+
### Example
57+
```typescript
58+
// frontend/hooks/useAuth.ts
59+
import { useState, useEffect, useCallback } from 'react';
60+
import { authService } from '@/services/authService';
61+
62+
export function useAuth() {
63+
const [user, setUser] = useState(null);
64+
const [isLoading, setIsLoading] = useState(true);
65+
const [error, setError] = useState(null);
66+
67+
const login = useCallback(async (credentials) => {
68+
setIsLoading(true);
69+
setError(null);
70+
try {
71+
const response = await authService.login(credentials);
72+
if (response.success) {
73+
setUser(response.data.user);
74+
} else {
75+
setError(response.error);
76+
}
77+
} catch (err) {
78+
setError(err.message);
79+
} finally {
80+
setIsLoading(false);
81+
}
82+
}, []);
83+
84+
return { user, isLoading, error, login };
85+
}
86+
```
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
---
2+
globs: frontend/app/**/*.tsx
3+
description: Page layer rules for Next.js App Router pages and layouts
4+
---
5+
6+
### Purpose and Scope
7+
8+
- Page layer handles routing and layouts for `frontend/app/**/*.tsx`
9+
- Responsibilities: Define routes, handle data fetching, provide layouts, coordinate state
10+
- **MANDATORY**: All pages must support internationalization through `[locale]` dynamic route
11+
12+
### File Structure
13+
14+
- **`page.tsx`** - Page components that define routes
15+
- **`layout.tsx`** - Layout components that wrap pages
16+
- **`loading.tsx`** - Loading UI components
17+
- Use kebab-case for new route segments
18+
- Prefer nested layouts over prop drilling
19+
20+
### Internationalization
21+
22+
- Client components: `const { t } = useTranslation('namespace')`
23+
- Server components: `getTranslations` from `next-intl`
24+
- Organize translation keys by feature/namespace
25+
26+
### Data Fetching
27+
28+
- Use Server Components for initial data fetching
29+
- Use `fetch` with proper caching for server-side data
30+
- Client-side fetching: custom hooks in `hooks/` directory
31+
- Handle loading and error states appropriately
32+
33+
### Layout and Metadata
34+
35+
- Define metadata in `layout.tsx` using Next.js metadata API
36+
- Use dynamic metadata for page-specific information
37+
- Ensure responsive design with Tailwind CSS
38+
- Maintain consistent layout structure
39+
40+
### State Management
41+
42+
- Use React Context for shared page-level state
43+
- Keep page-specific state local to component
44+
- Use custom hooks for complex state logic
45+
- Avoid prop drilling with context providers
46+
- **CRITICAL**: All logging must use [logger.ts](mdc:frontend/lib/logger.ts) - never use console.log
47+
48+
### Example
49+
```tsx
50+
// frontend/app/[locale]/chat/page.tsx
51+
import { useTranslations } from 'next-intl';
52+
53+
export default function ChatPage({ params }: { params: { locale: string } }) {
54+
const t = useTranslations('chat');
55+
return (
56+
<div className="flex h-screen">
57+
<h1 className="text-2xl font-bold p-4">{t('title')}</h1>
58+
</div>
59+
);
60+
}
61+
```
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
---
2+
globs: frontend/services/**/*.ts
3+
description: Compact service layer rules for API calls and data management
4+
---
5+
6+
### Purpose and Scope
7+
8+
- Service layer handles API communication and data management for `frontend/services/**/*.ts`
9+
- **CRITICAL**: All API URLs must come from [api.ts](mdc:frontend/services/api.ts) - never hardcode URLs
10+
- Responsibilities: API calls, request/response transformation, error handling, type safety
11+
12+
### API URL Management
13+
14+
- **MANDATORY**: Import and use `API_ENDPOINTS` from [api.ts](mdc:frontend/services/api.ts)
15+
- **FORBIDDEN**: Hardcoded URLs, direct string concatenation for endpoints
16+
- Use `fetchWithErrorHandling` from [api.ts](mdc:frontend/services/api.ts) for all requests
17+
18+
### Service Organization
19+
20+
- **`services/api.ts`** - Base configuration, endpoints, error handling
21+
- **`services/*Service.ts`** - Domain-specific API calls (auth, chat, config, etc.)
22+
- Use descriptive names matching the domain they serve
23+
24+
### Error Handling
25+
26+
- Use `ApiError` class from [api.ts](mdc:frontend/services/api.ts)
27+
- Handle 401/499 status codes for session expiration
28+
- Provide meaningful error messages for user feedback
29+
30+
### Type Safety
31+
32+
- Define TypeScript interfaces for all request/response data
33+
- Use generic types for reusable API functions
34+
- Export types for use in components and hooks
35+
- **CRITICAL**: All logging must use [logger.ts](mdc:frontend/lib/logger.ts) - never use console.log
36+
37+
### Example
38+
```typescript
39+
// frontend/services/authService.ts
40+
import { API_ENDPOINTS, fetchWithErrorHandling, ApiError } from './api';
41+
42+
export const authService = {
43+
async signin(credentials: SigninRequest): Promise<SigninResponse> {
44+
const response = await fetchWithErrorHandling(API_ENDPOINTS.user.signin, {
45+
method: 'POST',
46+
headers: { 'Content-Type': 'application/json' },
47+
body: JSON.stringify(credentials),
48+
});
49+
return response.json();
50+
}
51+
};
52+
```
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
---
2+
globs: frontend/types/**/*.ts
3+
description: Type layer rules for TypeScript type definitions and interfaces
4+
---
5+
6+
### Purpose and Scope
7+
8+
- Type layer contains TypeScript definitions for `frontend/types/**/*.ts`
9+
- Responsibilities: Define type-safe interfaces, API types, reusable utilities, ensure consistency
10+
- **MANDATORY**: All types must be exported and use TypeScript
11+
12+
### Type Organization
13+
14+
- **`types/auth.ts`** - Authentication-related types
15+
- **`types/chat.ts`** - Chat and conversation types
16+
- **`types/config.ts`** - Configuration types
17+
- **`types/api.ts`** - API-related types
18+
- Use descriptive names matching the domain they represent
19+
20+
### Type Definition Standards
21+
22+
- Use interfaces for object shapes and API contracts
23+
- Use type aliases for unions, primitives, and computed types
24+
- Use enums for fixed sets of string/number values
25+
- Use generic types for reusable type patterns
26+
- Export all types for use in other modules
27+
28+
### API Type Definitions
29+
30+
- Define separate interfaces for request and response data
31+
- Use consistent naming conventions (e.g., `UserRequest`, `UserResponse`)
32+
- Include optional fields with proper typing
33+
- Use union types for status fields and enums
34+
- Provide JSDoc comments for complex types
35+
36+
### Component Props Types
37+
38+
- Define interfaces for all component props
39+
- Use descriptive property names
40+
- Include proper optional/required field indicators
41+
- Use generic types for reusable component patterns
42+
- Export types for use in component files
43+
- **CRITICAL**: All logging must use [logger.ts](mdc:frontend/lib/logger.ts) - never use console.log
44+
45+
### Utility Types
46+
47+
- Create utility types for common patterns
48+
- Use mapped types for transformations
49+
- Implement conditional types for complex logic
50+
- Provide type guards for runtime validation
51+
52+
### Example
53+
```typescript
54+
// frontend/types/auth.ts
55+
export interface User {
56+
id: string;
57+
email: string;
58+
name: string;
59+
avatar?: string;
60+
role: UserRole;
61+
createdAt: string;
62+
updatedAt: string;
63+
}
64+
65+
// Utility types
66+
export type UserUpdateData = Partial<Pick<User, 'name' | 'avatar'>>;
67+
export type UserCreateData = Omit<User, 'id' | 'createdAt' | 'updatedAt'>;
68+
```

0 commit comments

Comments
 (0)