hookehuyr

docs: 添加 CLAUDE.md 项目开发指南文档

添加详细的开发指南文档,涵盖项目架构、核心命令、技术栈说明、关键实现模式(如认证流程、离线/弱网支持、API 层架构、导航系统)以及开发工作流。此文档旨在为开发者提供全面的项目上下文和开发指引,确保代码修改符合现有架构规范。
Showing 1 changed file with 226 additions and 0 deletions
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Development Commands
### Core Commands
- `pnpm dev:weapp` - Start WeChat mini-program development server
- `pnpm dev:h5` - Start H5 development server
- `pnpm build:weapp` - Build for production (WeChat mini-program)
- `pnpm lint` - Run ESLint
### Other Platform Builds
- `pnpm dev:alipay` - Alipay mini-program development
- `pnpm dev:swan` - Baidu mini-program development
- `pnpm dev:tt` - ByteDance mini-program development
## Project Architecture
This is a **Taro 4 + Vue 3 + NutUI** WeChat mini-program template with built-in authentication, offline support, and weak network handling.
### Technology Stack
- **Framework**: Taro 4.x (multi-platform mini-program framework)
- **UI**: Vue 3 + NutUI 4.x (JD.com's UI library)
- **State Management**: Pinia
- **HTTP Client**: axios-miniprogram
- **Styling**: Less + TailwindCSS (dual design width system)
- **Build Tool**: Webpack 5
### Dual Design Width System
The project uses **two different design widths** configured in `config/index.js:16-23`:
- **NutUI components**: 375px base width
- **All other pages**: 750px base width
When working with styles, always check if you're using NutUI components or custom components to determine which width to reference.
### Key Architectural Patterns
#### 1. Authentication Flow (Required)
The project has a sophisticated authentication system with automatic session management:
**Startup Flow** (`src/app.js:26-214`):
1. App saves launch path for auth callback
2. Checks network status and handles weak network scenarios
3. Attempts silent auth if not authenticated
4. On auth success, enables offline booking cache polling
**Core Files**:
- `src/utils/authRedirect.js` - All auth logic (silent refresh, navigation, state)
- `src/utils/request.js` - HTTP client with 401 auto-refresh interceptor
- `src/pages/auth/index.vue` - Auth page (must be preserved)
**How 401 Auto-Refresh Works** (`src/utils/request.js:241-276`):
1. API returns 401
2. Interceptor saves current page path
3. Calls `refreshSession()` to get new session via WeChat login
4. Retries original request with new session
5. If refresh fails, redirects to auth page
**Important**: The backend MUST provide `/srv/?a=openid_wxapp` endpoint for WeChat login.
#### 2. Offline/Weak Network Support
The app gracefully handles network issues through multiple mechanisms:
**Network Detection** (`src/utils/network.js`):
- Monitors network status changes
- Detects weak network conditions
- Provides offline caching capabilities
**Offline Booking Cache** (`src/composables/useOfflineBookingCache.js`):
- Caches booking data for offline access
- Supports reading/writing cached data
- Used when network is unavailable
**Cache Polling** (`src/composables/useOfflineBookingCachePolling.js`):
- Background polling to refresh cached data
- Reference-counted enable/disable mechanism
- Only runs when network is available
**Weak Network UI** (`src/utils/uiText.js`):
- Centralized copy management for weak network scenarios
- Provides modal options for user interaction
**Fallback Flow** (`src/utils/request.js:143-168`):
1. Request times out or fails
2. Checks if offline cache exists
3. If yes, redirects to offline booking list
4. If no, shows weak network modal
#### 3. API Layer Architecture
**API Definition Pattern** (`src/api/index.js`):
```javascript
export const yourAPI = (params) => {
return buildApiUrl('your_action', params)
}
```
**Request Wrapper** (`src/api/fn.js`):
- All API calls go through this wrapper
- Handles common error scenarios
- Provides consistent interface
**URL Building** (`src/utils/tools.js`):
- `buildApiUrl(action, params)` - Constructs full API URL
- Automatically merges default parameters from `src/utils/config.js`
#### 4. Navigation System
**Enhanced Navigation Hook** (`src/hooks/useGo.js`):
```javascript
import { useGo } from '@/hooks/useGo'
const go = useGo()
go('/page-name') // Auto-completes path
go('/page', { id: 123 }) // With query params
```
**Route Storage** (`src/stores/router.js`):
- Maintains stack of visited routes
- Used for auth callback navigation
- Automatically managed by auth flow
### Path Aliases
All configured in `config/index.js:30-38`:
```javascript
@/utils src/utils
@/components src/components
@/images src/assets/images
@/assets src/assets
@/composables src/composables
@/api src/api
@/stores src/stores
@/hooks src/hooks
```
### Configuration Management
**Environment Config** (`src/utils/config.js`):
**⚠️ MUST BE MODIFIED before use**:
- `BASE_URL` - Set development/production domain
- `REQUEST_DEFAULT_PARAMS.f` - Set business module identifier
- `REQUEST_DEFAULT_PARAMS.client_name` - Set application name
**Build Config** (`config/index.js`):
- Path aliases
- Design width rules
- NutUI auto-import
- Platform-specific settings
## Important Implementation Details
### Session Management
- Session ID stored in `localStorage` with key `sessionid`
- Set by `authRedirect.refreshSession()` after successful WeChat login
- Automatically injected into request headers by `request.js` interceptor
- Cleared on logout or explicit manual intervention
### Promise Single-Pattern
The auth system uses Promise singletons to prevent concurrent login attempts:
- `auth_promise` in `authRedirect.js` ensures only one refresh at a time
- All concurrent 401s share the same refresh Promise
- `.finally()` ensures cleanup regardless of success/failure
### Request Timeout Handling
- Default timeout: 5 seconds (`src/utils/request.js:79`)
- Timeout detection via `is_timeout_error()` helper
- Network error detection via `is_network_error()` helper
- Both trigger weak network fallback flow
### NutUI Auto-Import
NutUI components are auto-imported via unplugin-vue-components (`config/index.js:91-93`). No manual imports needed.
### TailwindCSS Integration
- Preflight disabled for mini-program compatibility
- `rem2rpx` conversion enabled
- Content paths configured in `tailwind.config.js`
## Optional Features
These features can be removed if not needed:
- **WeChat Pay**: `src/utils/wechatPay.js`, `src/api/wx/`
- **QR Code**: `src/components/qrCode.vue`, `src/components/qrCodeSearch.vue`
- **Poster Builder**: `src/components/PosterBuilder/`
- **Time Picker**: `src/components/time-picker-data/`
- **Offline Cache**: Entire offline booking cache system
## Critical Files Summary
### Must Understand Before Modifying
1. **`src/utils/authRedirect.js`** - Complete auth flow logic
2. **`src/utils/request.js`** - HTTP client with interceptors
3. **`src/app.js`** - App startup sequence and network handling
4. **`src/utils/config.js`** - Server configuration (requires modification)
### Key Business Logic
1. **`src/api/index.js`** - API definitions
2. **`src/api/fn.js`** - Request wrapper
3. **`src/stores/main.js`** - Primary state management
4. **`src/stores/router.js`** - Route state for auth callbacks
### UI/UX
1. **`src/utils/uiText.js`** - Centralized copy management
2. **`src/utils/network.js`** - Network status utilities
3. **`src/composables/`** - Reusable composition API hooks
## Development Workflow
When adding new features:
1. Define API in `src/api/index.js` using `buildApiUrl()`
2. Create page in `src/pages/your-page/`
3. Add route to `src/app.config.js`
4. Use `useGo()` hook for navigation
5. Leverage Pinia stores for state management
6. Follow dual design width rules (375px for NutUI, 750px for custom)
When modifying auth/network behavior:
- Always read both `authRedirect.js` and `request.js` together
- Test 401 refresh flow thoroughly
- Verify weak network fallback scenarios
- Check offline cache interactions
When debugging:
- Check `src/utils/config.js` for correct BASE_URL
- Verify sessionid in localStorage
- Enable verbose logging in request interceptor
- Use Taro's built-in network status monitoring