Files
mp-xieyingeng/UI_COMPONENTS_INDEX.md
richarjiang 69c0986996 feat: 进入关卡时 toast 提示体力消耗,修复 StorageManager 接口位置和 WxSDK 访问级别
- 进入关卡成功后显示 toast 提示消耗体力及剩余体力
- 将 StorageManager 中 UserInfo 接口移至模块顶层,修复嵌套接口语法问题
- WxSDK.getWx() 改为 static 公开方法,便于外部调用
2026-04-10 10:10:19 +08:00

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

  1. ViewManager.open() called
  2. Prefab instantiated
  3. onViewLoad() called (do heavy init here)
  4. Page added to stack
  5. onViewShow() called

Re-open (if cached)

  1. ViewManager.open() called
  2. Cache hit found
  3. Previous page onViewHide() called
  4. This page onViewShow() called (not onViewLoad!)
  5. Page already in stack (or re-added)

Close/Back

  1. ViewManager.back() called
  2. Current page onViewHide() called
  3. Current page destroyed (if not cached)
  4. Previous page onViewShow() called

Destroy

  1. onViewDestroy() called
  2. All listeners removed
  3. Resources cleaned up
  4. 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

  1. Add hint4 config to RuntimeLevelConfig
  2. Add unLockItem4 property to PageLevel
  3. Add tipsItem4 property to PageLevel
  4. Call showUnlockButton(4) in _applyLevelConfig()
  5. Handle in onUnlockClue() switch/case

Adding Page Analytics

  1. Add tracking in onViewLoad() (first visit)
  2. Add tracking in onViewShow() (each visit)
  3. Use page viewId for identification
  4. Track user actions in event handlers

Changing Point System

  1. Modify UserAssetsManager (not shown)
  2. Update updatePointsLabel() display format
  3. Adjust hasPoints() check if needed
  4. Test unlock flow with new values

Adjusting Timer

  1. Change _countdown = 60 to desired seconds
  2. Update display frequency if needed
  3. Adjust point calculation if time-based
  4. Test timeout behavior

📖 How to Use This Documentation

For a new developer:

  1. Start with QUICK_REFERENCE.md for overview
  2. Read UI_COMPONENT_ANALYSIS.md sections for specific pages
  3. Reference ARCHITECTURE_DIAGRAM.md for flow understanding

For debugging:

  1. Find error in component name
  2. Look up methods in UI_COMPONENT_ANALYSIS.md
  3. Check flow in ARCHITECTURE_DIAGRAM.md
  4. Use QUICK_REFERENCE.md for code patterns

For adding features:

  1. Understand game flow in QUICK_REFERENCE.md
  2. Find where to hook in UI_COMPONENT_ANALYSIS.md
  3. Check data flows in ARCHITECTURE_DIAGRAM.md
  4. Copy patterns from QUICK_REFERENCE.md

For optimization:

  1. Note complexity metrics in QUICK_REFERENCE.md
  2. Identify bottlenecks in PageLevel.ts
  3. Check async operations in PageLoading.ts
  4. 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

  1. Run the game and trace through the flows documented here
  2. Add logging to key methods to understand real execution order
  3. Modify a page to get familiar with lifecycle
  4. Create new page following BaseView pattern
  5. 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