- 进入关卡成功后显示 toast 提示消耗体力及剩余体力 - 将 StorageManager 中 UserInfo 接口移至模块顶层,修复嵌套接口语法问题 - WxSDK.getWx() 改为 static 公开方法,便于外部调用
13 KiB
UI Components Complete Analysis - Index
📚 Documentation Files Created
This analysis consists of three comprehensive documents:
1. UI_COMPONENT_ANALYSIS.md (Main Reference)
1,424 lines | 45 KB
- Detailed breakdown of all 10 files
- Complete method signatures and implementations
- Lifecycle method documentation
- Data manager interactions
- Game flow explanations
- Key concepts and patterns
Best for: Deep dives into specific components, understanding implementation details
2. QUICK_REFERENCE.md (Developer Cheat Sheet)
~400 lines | 8.6 KB
- Component overview table
- Lifecycle stages summary
- Key data flows (visual)
- Component properties summary
- Points & scoring system quick look
- Timer system overview
- Hint/clue system
- Navigation stack examples
- Toast system usage
- WeChat integration quick reference
- Common tasks & code snippets
- File complexity metrics
Best for: Quick lookups, copy-paste code patterns, understanding overall architecture
3. ARCHITECTURE_DIAGRAM.md (Visual Reference)
~1,000 lines | 26 KB
- System architecture diagram
- Page state machine
- Page stack visualization with session traces
- Component communication diagrams
- Data flow diagrams (level completion, hint unlocking)
- Timer sequence diagrams
- Input box creation flow
- Share challenge mode flow
- ViewManager caching mechanism
- Error handling paths
Best for: Understanding flow, tracing execution, visual learners
🎯 Component Summary
Core Infrastructure
- main.ts (92 lines) - App bootstrap, register pages and managers
- BaseView.ts (132 lines) - Abstract page lifecycle interface
- ViewManager.ts (320 lines) - Stack-based page navigation system
UI Pages (All extend BaseView)
- PageLoading.ts (141 lines) - Splash screen, load data, detect share code
- PageHome.ts (119 lines) - Landing page hub with game/PK buttons
- PageLevel.ts (823 lines) ⭐ Most Complex - Main game with timer, hints, scoring
- PagePreviewLevels.ts (247 lines) - Scrollable list of selected levels
- PassModal.ts (155 lines) - Completion modal with next/share buttons
Notification System
- Toast.ts (50 lines) - Individual toast notification with fade animation
- ToastManager.ts (59 lines) - Singleton manager for toast creation
Total: ~2,138 lines across 10 files
🔑 Key Topics Quick Index
Game Mechanics
| Topic | Location | Key Method |
|---|---|---|
| 60-second countdown | PageLevel | startCountdown() / onCountdownTick() |
| Hint/clue system (3 levels) | PageLevel | onUnlockClue(index) |
| Answer verification | PageLevel | onSubmitAnswer() / getAnswer() |
| Level progression | PageLevel | nextLevel() |
| Points earning | PageLevel | showSuccess() + UserAssetsManager.earnPoint() |
| Points spending | PageLevel | onUnlockClue() + UserAssetsManager.consumePoint() |
UI Management
| Topic | Location | Key Method |
|---|---|---|
| Page navigation | ViewManager | open() / back() / replace() |
| Page lifecycle | BaseView | onViewLoad/Show/Hide/Destroy |
| Page caching | ViewManager | _viewCache Map |
| Page stacking | ViewManager | _viewStack array (LIFO) |
| Toast notifications | ToastManager | show(content, duration) |
Special Features
| Topic | Location | Key Method |
|---|---|---|
| Share challenge mode | PageLevel + ShareManager | _isShareMode flag |
| WeChat integration | PageHome, PassModal, WxSDK | initShare() / shareAppMessage() |
| Server progress sync | PageLoading | _syncProgressFromServer() |
| Level preloading | PageLevel | preloadNextLevel() |
📊 Complexity Breakdown
PageLevel.ts (823 lines - 38% of total code)
├─ Input management
├─ Timer system
├─ Hint unlocking
├─ Answer validation
├─ Point interactions
├─ Audio effects
├─ Modal handling
└─ Share mode support
ViewManager.ts (320 lines - 15% of total code)
├─ Page registration
├─ Stack management
├─ Instance caching
├─ Lifecycle coordination
└─ Error handling
All Other Components (995 lines - 47% of total code)
🎮 Game Flow Overview
User Launches App
↓
main.ts registers pages & managers
↓
PageLoading loads auth + levels (parallel)
↓
┌─ Detect Share Code ──→ Enter Share Mode (PageLevel)
│ ↓
│ Play Levels
│ ↓
│ Return Home
│
└─ Normal Path ──→ Open PageHome
↓
┌──────┴──────┐
↓ ↓
Play Game Create Challenge
(PageLevel) (PageWriteLevels)
↓ ↓
Win Level PagePreviewLevels
↓ ↓
PassModal PassModal/Share
↓ ↓
Next/Back Share to WeChat
💾 Data Manager Interactions
By Page
PageLoading
- AuthManager.initialize()
- LevelDataManager.initialize()
- StorageManager.getMaxUnlockedLevelIndex()
- StorageManager.onLevelCompleted()
- ShareManager.joinShare()
- WxSDK.getShareCodeFromLaunch()
PageHome
- WxSDK.initShare()
- checkPrivacySetting()
- requirePrivacyAuthorize()
PageLevel (Most interactions)
- LevelDataManager (load, preload, get count)
- StorageManager (get/set progress, get points)
- UserAssetsManager (earn/consume points)
- ShareManager (share mode, report progress)
- WxSDK (vibration, sharing)
- ToastManager (notifications)
- ViewManager (navigation)
PagePreviewLevels
- LevelDataManager.ensureLevelReady()
PassModal
- WxSDK.shareAppMessage()
⚠️ Important Flags & Preventing Issues
Double-Submission Prevention
// In PageLevel.onSubmitAnswer()
if (this._isTransitioning) return; // Blocks rapid re-submission
Double-Click Unlock Prevention
// In PageLevel.onUnlockClue()
if (this._isUnlocking) return; // Blocks rapid hint unlocking
Share Mode Detection
// In PageLevel.onViewLoad()
this._isShareMode = params?.shareMode === true;
Timer Running Flag
// In PageLevel.onCountdownTick()
if (this._isTimeUp) return; // Prevents countdown after timeout
🔄 Page Lifecycle Details
First-Time Open
- ViewManager.open() called
- Prefab instantiated
- onViewLoad() called (do heavy init here)
- Page added to stack
- onViewShow() called
Re-open (if cached)
- ViewManager.open() called
- Cache hit found
- Previous page onViewHide() called
- This page onViewShow() called (not onViewLoad!)
- Page already in stack (or re-added)
Close/Back
- ViewManager.back() called
- Current page onViewHide() called
- Current page destroyed (if not cached)
- Previous page onViewShow() called
Destroy
- onViewDestroy() called
- All listeners removed
- Resources cleaned up
- Node destroyed
📝 Common Code Patterns
Open Page with Parameters
ViewManager.instance.open('PageLevel', {
params: { shareMode: true },
onComplete: (view) => {
console.log('PageLevel opened');
},
onError: (err) => {
console.error('Failed to open:', err);
}
});
Get Page Parameters
onViewLoad(): void {
const params = this.getParams();
if (params?.shareMode) {
// Handle share mode
}
}
Show Toast Notification
ToastManager.show('提示信息', 2000); // 2 second display
Check & Consume Points
if (StorageManager.hasPoints()) {
const success = await UserAssetsManager.consumePoint(levelId, hintIndex);
if (success) {
this.updatePointsLabel();
}
}
Schedule & Unschedule
startCountdown(): void {
this.schedule(this.onCountdownTick, 1); // Every 1 second
}
stopCountdown(): void {
this.unschedule(this.onCountdownTick); // Stop callback
}
🐛 Known Patterns to Watch
Caching Implications
- Pages with cache:true keep their onViewLoad() state
- onViewShow() is called each time, even if cached
- If you modify state in onViewLoad(), it persists!
- Solution: Reset state in onViewShow() if needed
Share Mode Edge Cases
- Share mode doesn't save local progress
- Share mode uses ShareManager instead of LevelDataManager
- Share mode clears state on return to home
- Must check _isShareMode before saving
Modal Positioning
- PassModal instantiated with z-index 999 (topmost)
- Added to Canvas root node (not PageLevel child)
- This allows full-screen coverage with proper Widget alignment
Timer Edge Cases
- Timer continues even if page is hidden
- Must stop timer on destroy or completion
- onTimeUp() plays sound but doesn't end game automatically
- Wrong answer doesn't stop timer
🎯 Tips for Modifications
Adding New Hint Types
- Add hint4 config to RuntimeLevelConfig
- Add unLockItem4 property to PageLevel
- Add tipsItem4 property to PageLevel
- Call showUnlockButton(4) in _applyLevelConfig()
- Handle in onUnlockClue() switch/case
Adding Page Analytics
- Add tracking in onViewLoad() (first visit)
- Add tracking in onViewShow() (each visit)
- Use page viewId for identification
- Track user actions in event handlers
Changing Point System
- Modify UserAssetsManager (not shown)
- Update updatePointsLabel() display format
- Adjust hasPoints() check if needed
- Test unlock flow with new values
Adjusting Timer
- Change
_countdown = 60to desired seconds - Update display frequency if needed
- Adjust point calculation if time-based
- Test timeout behavior
📖 How to Use This Documentation
For a new developer:
- Start with QUICK_REFERENCE.md for overview
- Read UI_COMPONENT_ANALYSIS.md sections for specific pages
- Reference ARCHITECTURE_DIAGRAM.md for flow understanding
For debugging:
- Find error in component name
- Look up methods in UI_COMPONENT_ANALYSIS.md
- Check flow in ARCHITECTURE_DIAGRAM.md
- Use QUICK_REFERENCE.md for code patterns
For adding features:
- Understand game flow in QUICK_REFERENCE.md
- Find where to hook in UI_COMPONENT_ANALYSIS.md
- Check data flows in ARCHITECTURE_DIAGRAM.md
- Copy patterns from QUICK_REFERENCE.md
For optimization:
- Note complexity metrics in QUICK_REFERENCE.md
- Identify bottlenecks in PageLevel.ts
- Check async operations in PageLoading.ts
- Review caching in ViewManager.ts
🔗 Cross-References
Frequently Referenced Files
- PageLevel.ts - Most complex, used from PageHome and PageLoading
- ViewManager.ts - Used by all pages for navigation
- StorageManager - Used by PageLoading and PageLevel
- UserAssetsManager - Used by PageLevel for points
- LevelDataManager - Used by PageLoading and PageLevel
Integration Points
main.ts (startup)
↓
PageLoading (data loading)
├─ AuthManager
├─ LevelDataManager
└─ ShareManager
↓
PageHome (navigation hub)
├─ PageLevel (game)
│ ├─ StorageManager
│ ├─ UserAssetsManager
│ ├─ WxSDK
│ └─ PassModal (modal)
│ └─ WxSDK
│
└─ PageWriteLevels (not analyzed)
└─ PagePreviewLevels
└─ LevelDataManager
📊 File Statistics
| Metric | Value |
|---|---|
| Total Lines | 2,138 |
| Total Files Analyzed | 10 |
| Most Complex File | PageLevel.ts (823 lines, 38%) |
| Most Reused Manager | ViewManager |
| Total Data Managers Used | 7+ |
| UI Components | 5 pages + 2 utilities |
| Lifecycle Methods | 4 per BaseView |
| Key Patterns | Stack navigation, caching, events |
🚀 Next Steps for Development
- Run the game and trace through the flows documented here
- Add logging to key methods to understand real execution order
- Modify a page to get familiar with lifecycle
- Create new page following BaseView pattern
- Add new feature using documented patterns
📞 Quick Troubleshooting
Page not showing?
- Check ViewManager.open() called
- Verify prefab has BaseView component
- Check registration in main.ts
Points not updating?
- Verify UserAssetsManager call succeeds
- Check updatePointsLabel() is called
- Test StorageManager.getPoints() returns value
Timer not stopping?
- Check stopCountdown() called on completion
- Verify unschedule() works in Cocos
- Test onDestroy calls stopCountdown()
Modal not appearing?
- Check z-index set to 999
- Verify added to Canvas root
- Test instantiate() succeeds
- Check onViewLoad/Show called manually
Share mode broken?
- Verify share code detected in PageLoading
- Check _isShareMode set properly
- Test ShareManager.joinShare() succeeds
- Verify clearShareMode() called on exit
✅ Analysis Complete
All 10 UI component files have been thoroughly analyzed and documented.
Total Documentation: 3 comprehensive guides
- UI_COMPONENT_ANALYSIS.md - Deep technical reference (1,424 lines)
- QUICK_REFERENCE.md - Developer cheat sheet (~400 lines)
- ARCHITECTURE_DIAGRAM.md - Visual flow diagrams (~1,000 lines)
- This file - Navigation & index (this document)
Ready for: Development, debugging, feature implementation, onboarding