Frontend Utilities Documentation
This document provides comprehensive documentation for all utility functions, classes, and helper modules in the STO Education Platform frontend.Utilities Overview
The application includes various utility modules that provide common functionality, helper functions, and specialized tools used throughout the application.Utility Categories
1. Update Detection Utility
Location: src/utils/updateDetector.ts
Purpose
Handles automatic detection of application updates and notifies users when new versions are available.Features
- Version Comparison: Compares current app version with server version
- Multiple Detection Methods: Uses version numbers, build times, and hashes
- Automatic Monitoring: Periodic checks for updates
- User Notifications: Notifies users when updates are available
- Cooldown System: Prevents excessive update checks
- Event-driven: Listener pattern for update notifications
Classes
UpdateDetector
Interfaces
UpdateInfo
ServerVersionInfo
Key Methods
Constructor
- Initializes the update detector
- Sets up version information from various sources
- Configures check interval (default: 5 minutes)
- Logs initialization information
startMonitoring
- Starts automatic update monitoring
- Performs immediate check for updates
- Sets up periodic checking interval
- Listens for page visibility changes
- Listens for window focus events
checkForUpdates
- Checks for application updates
- Implements cooldown system to prevent excessive checks
- Compares current version with server version
- Returns true if update is available
getCurrentVersion
- Retrieves current application version
- Tries multiple sources:
- Vite injected globals (
__APP_VERSION__) - Meta tags (
meta[name="app-version"]) - Environment variables (
VITE_APP_VERSION)
- Vite injected globals (
getCurrentBuildTime
- Retrieves current build time
- Tries multiple sources:
- Vite injected globals (
__BUILD_TIME__) - Meta tags (
meta[name="build-time"]) - Environment variables (
VITE_BUILD_TIME)
- Vite injected globals (
getCurrentHash
- Retrieves current build hash
- Tries multiple sources:
- Vite injected globals (
__BUILD_HASH__) - Meta tags (
meta[name="build-hash"]) - Environment variables (
VITE_BUILD_HASH)
- Vite injected globals (
compareVersions
- Compares semantic version numbers
- Returns -1 if update needed, 0 if equal, 1 if current is newer
- Handles version parts of different lengths
compareBuildTimes
- Compares build timestamps
- Normalizes dates to ignore seconds and milliseconds
- Returns true if server build is newer
getServerVersion
- Fetches server version from
/version.json - Handles network errors gracefully
- Returns ‘unknown’ if fetch fails
onUpdateAvailable
- Registers update notification listener
- Allows components to subscribe to update events
removeListener
- Removes update notification listener
- Cleans up event handlers
forceCheck
- Forces immediate update check
- Bypasses cooldown system
- Useful for manual update checking
Update Detection Methods
1. Version Number Comparison
- Compares semantic version numbers (e.g., “1.2.3”)
- Most reliable method for major updates
2. Build Time Comparison
- Compares build timestamps
- Useful for detecting minor updates
- Normalizes timestamps for accurate comparison
3. Build Hash Comparison
- Compares build hashes
- Detects any code changes
- Most sensitive detection method
Usage Example
Singleton Instance
Integration with Vite
The utility integrates with Vite’s build process through:- Global Variables: Injected via
vite.config.ts - Meta Tags: Generated during build
- Version File: Creates
/public/version.json
Error Handling
- Network Errors: Graceful handling of fetch failures
- Parse Errors: Safe JSON parsing with fallbacks
- Invalid Versions: Handles malformed version strings
- Missing Data: Fallbacks for missing version information
Performance Considerations
- Cooldown System: Prevents excessive API calls
- Lazy Loading: Only checks when needed
- Efficient Comparison: Optimized version comparison algorithms
- Memory Management: Proper cleanup of event listeners
Custom Hooks
1. Mochi Events Hook
Location: src/hooks/useMochiEvents.ts
Purpose
Provides real-time event handling for the Mochi gamification system using Supabase real-time subscriptions.Features
- Real-time Subscriptions: Listens to database changes
- Toast Notifications: Shows user-friendly notifications
- Event Filtering: Filters relevant events for Mochi reactions
- Automatic Cleanup: Unsubscribes from channels on unmount
Implementation
Event Types
Assignment Submissions
- Table:
assignment_submissions - Event:
INSERT - Action: Shows congratulatory message
- Message: ”🍡 Mochi is proud of your submission! Keep it up!”
Session Attendance
- Table:
session_attendance - Event:
INSERT - Condition: Only for attended sessions
- Action: Shows attendance celebration
- Message: ”🎉 Mochi is happy you attended class!”
Usage Example
Dependencies
- Supabase: Real-time subscriptions
- React Toastify: Toast notifications
- React: useEffect hook for lifecycle management
Type Definitions
Location: src/lib/types.ts
Purpose
Centralized TypeScript type definitions for the entire application.Core Types
Education System Types
Teacher Subject Types
User Registration Types
Course Types
Profile Types
Teacher Mark Scheme Types
Library Utilities
1. Authentication Utilities
Location: src/lib/auth.ts
Purpose
Provides authentication-related utility functions and helpers.Features
- User Session Management: Handles user session operations
- Profile Retrieval: Fetches user profile information
- Session Validation: Validates user sessions
- Error Handling: Comprehensive error handling
Key Functions
2. Payment Utilities
Location: src/lib/paymob.ts
Purpose
Handles PayMob payment gateway integration and payment processing.Features
- Payment Intent Creation: Creates payment intentions
- Payment Link Generation: Generates payment URLs
- Billing Data Handling: Manages billing information
- Error Handling: Comprehensive payment error handling
Key Functions
3. Analytics Utilities
Location: src/lib/posthog.ts
Purpose
Provides PostHog analytics integration with custom hooks and utility functions.Features
- Event Tracking: Custom event tracking
- User Identification: User identification and properties
- Feature Flags: Feature flag support
- Group Analytics: Group-based analytics
Custom Hook
4. Supabase Utilities
Location: src/lib/supabase.ts
Purpose
Provides Supabase client configuration and initialization.Implementation
Utility Best Practices
1. Error Handling
- Graceful Degradation: Handle errors without breaking functionality
- User-friendly Messages: Provide clear error messages
- Logging: Comprehensive error logging for debugging
- Fallbacks: Provide fallback values when possible
2. Performance Optimization
- Lazy Loading: Load utilities only when needed
- Caching: Cache expensive operations
- Debouncing: Prevent excessive function calls
- Memory Management: Proper cleanup of resources
3. Type Safety
- TypeScript Interfaces: Define clear interfaces
- Generic Types: Use generics for reusable utilities
- Type Guards: Implement type checking functions
- Documentation: Document type definitions
4. Testing
- Unit Tests: Test individual utility functions
- Integration Tests: Test utility integrations
- Mock Dependencies: Mock external dependencies
- Edge Cases: Test error conditions and edge cases
Future Utility Enhancements
1. Planned Features
- Caching Layer: Implement utility-level caching
- Performance Monitoring: Add performance metrics
- Advanced Error Handling: Enhanced error recovery
- Utility Composition: Better utility composition patterns
2. Performance Improvements
- Bundle Optimization: Optimize utility bundle size
- Tree Shaking: Better tree shaking support
- Lazy Loading: Advanced lazy loading strategies
- Memory Optimization: Better memory management
3. Developer Experience
- Better Documentation: Enhanced documentation
- Development Tools: Better development utilities
- Debugging Support: Enhanced debugging capabilities
- Testing Utilities: Better testing support