System Overview
The Event Tracking & Analytics System is a production-grade monitoring solution designed to observe,
record, and analyze user interactions and system state changes within the Chemical Chaos Engine
simulation environment. Built on event-driven architecture principles, the system demonstrates
enterprise-level software engineering practices.
Core Capabilities:
- Real-Time Monitoring: Continuous observation of 125+ distinct events across 11
functional categories
- State Persistence: Automatic serialization and recovery using browser
LocalStorage API
- Event-Driven Architecture: Decoupled publisher-subscriber pattern with global
event bus
- Performance Optimization: Debounced polling (100ms), lazy evaluation, efficient
delta-based updates
- Scalable Design: Category-based organization supporting unlimited event
additions without refactoring
- Cross-System Integration: Monitors both simulation engine and site-wide
navigation patterns
Key Features
Chemical Event Tracking
Monitors bond formations (single/double/triple), molecule detection, and reaction type
classification across 12 mechanisms
Structural Analysis
Detects aromatic rings, conjugated systems, chiral centers, and radical species using graph
algorithms
Environmental Metrics
Tracks pH extremes (0-14 range), temperature ranges, and maintains historical min/max
records
Performance Analytics
Measures rapid bond formation rates, reaction cascades, and session duration metrics
Navigation Tracking
Records portfolio tab switches, photo lightbox views, and documentation access patterns
Persistent Storage
Automatic save every 5 seconds with version migration and graceful quota handling
Technical Highlights
Modular Architecture: The system consists of four decoupled layers: Event Bus
(communication), Event Manager (orchestration), Statistics Tracker (data), and Persistence Manager
(storage). Each layer can be tested and modified independently.
Zero Framework Dependencies: Pure JavaScript ES6+ implementation with no external
libraries. Works in all modern browsers with LocalStorage support.
Non-Invasive Monitoring: Observes system state through a bridge pattern without
modifying core engine code, ensuring maintainability and separation of concerns.
Graceful Degradation: Functions in session-only mode if LocalStorage is unavailable.
Handles storage quota exceeded errors by pruning old data.
System Architecture
The event system implements a layered architecture with clear separation of concerns. Each layer has a
well-defined responsibility and communicates through standardized interfaces.
Component Responsibilities
1. Global Event Bus
Implements the observer pattern enabling decoupled communication. Publishers emit events without
knowledge of subscribers. Subscribers register callbacks for specific event types. Supports dynamic
subscription/unsubscription at runtime.
2. Event Manager
Central orchestration component maintaining the event registry, evaluating conditions on a scheduled
basis (every 100ms), managing unlock state, queueing notifications, and controlling system
enable/disable state.
3. Statistics Tracker
Comprehensive state container tracking chemical events (bonds, molecules, reactions), environmental
metrics (pH, temperature), structural data (rings, chirality, conjugation), performance metrics (session
time, atom counts), and navigation analytics (page views, tab switches).
4. Persistence Manager
Storage layer handling automatic serialization (every 5 seconds), state recovery on load, version
migration for backward compatibility, and graceful quota exceeded handling with data pruning.
5. State Monitoring Bridge
Non-invasive observer polling simulation state every 200ms. Detects changes via delta tracking without
modifying core engine code. Emits events to the global bus when state changes detected.
Data Flow
Event Emission Flow: External system → State change → Monitoring bridge detects delta →
Event bus emit → Event manager receives → Statistics updated → Conditions checked → Event potentially
unlocked → Persistence triggered
Condition Evaluation Flow: Scheduled check (100ms) → Iterate event registry → Skip
already-unlocked → Evaluate condition function → If met: unlock → Persist → Queue notification → Display
Event Categories
Events are organized into 11 functional categories based on the system component being monitored.
Site Navigation (5 events)
Tracks portfolio interactions: tab switches, photo lightbox opens, documentation views
Basic Chemistry (7 events)
Fundamental bonding milestones from first bond to 100,000+ formations
Bond Types (7 events)
Differentiates single, double, and triple covalent bonds
Molecular Detection (17 events)
Identifies specific formulas: H₂O, CH₄, NH₃, C₆H₆, and more
Reaction Tracking (22 events)
Monitors 12 reaction types including elimination, addition, hydrogenation
Structural Analysis (14 events)
Detects aromatic rings, conjugated systems, chiral centers, radicals
Molecular Complexity (8 events)
Tracks sizes from diatomic (2 atoms) to giga molecules (800+ atoms)
Element Usage (11 events)
Monitors utilization of all 8 atom types: H, C, N, O, S, P, Cl, Br
pH Monitoring (10 events)
Tracks pH extremes and neutral maintenance
Temperature Tracking (8 events)
Records temperature exploration from cryogenic to scorching
Performance Metrics (6 events)
Measures rapid bond formation and reaction cascades
Session Analytics (8 events)
Tracks engagement duration and atom counts
Cross-Category Mastery (9 events)
Complex Events requiring multiple simultaneous conditions
Difficulty Tier System
Easy Tier
Achievable within first 5 minutes
Medium Tier
Requires 10-20 minutes and basic understanding
Hard Tier
Demands 30-60 minutes with strategic planning
Very Hard Tier
Complex multi-step events
Extreme Tier
Rare occurrences requiring patience and skill
Legendary Tier
Ultimate challenges representing complete mastery
Implementation Details
Event Definition Schema
Each event contains: unique ID, display name, description, icon, category, difficulty tier, trigger type,
and validation function.
Statistics Tracking Dimensions
Chemical: Bond counts (total, double, triple), molecules created, reactions by type,
element usage
Structural: Aromatic rings, conjugated systems, chiral centers, radicals, hydrogen bonds
Environmental: pH range (min/max), temperature range, neutral time tracking
Performance: Session duration, peak atom count, largest molecule, rapid formation rates
Navigation: Page views, tabs visited, photos viewed, documentation opened
Key Strategies:
- Debounced Polling: Checks limited to 100ms intervals
- Skip Unlocked: Already-achieved events excluded from evaluation
- Delta Tracking: Only process state changes, not entire state
- Batched Persistence: Saves every 5 seconds, not per change
- Efficient Lookups: Hash maps for O(1) access
- Notification Queue: Sequential display prevents flooding
State Monitoring Bridge
Non-invasive observer running every 200ms. Counts bonds via particle inspection, detects molecules from
state map, tracks structures from rings/conjugation arrays, monitors pH/temperature continuously.
Persistence Layer
Auto-Save: Every 5 seconds to LocalStorage with version tags
Recovery: Automatic state restoration on page load with migration
Quota Handling: Graceful degradation with data pruning on errors
API Reference
The event system exposes a comprehensive JavaScript API accessible via
window.CHAOS_API.events
Core API Methods
toggle(enabled)
Enable/disable entire tracking system
getProgress()
Returns: { unlocked, total, percentage }
getAllByCategory()
Returns events grouped by category with unlock status
list()
Returns complete event registry (125+ definitions)
trackCustomEvent(name, data)
Emit custom events to global bus
reset()
Clear all progress with confirmation
Usage Examples
Query Progress:
const p = window.CHAOS_API.events.getProgress();
console.log(`${p.unlocked}/${p.total} (${p.percentage}%)`)
Access Statistics:
const s = window.CHAOS_API.events.stats;
console.log(`Bonds: ${s.totalBondsFormed}`);
Enable Tracking:
window.CHAOS_API.events.toggle(true);
Emit Custom Event:
window.CHAOS_EVENTS.emit('custom', {data: 'value'});
Integration
Requirements: ES6+ JavaScript, LocalStorage API, No framework dependencies
Load Order: chaos-engine-core → chaos-engine-ui → chaos-events-org →
chaos-events-monitor
Compatibility: Chrome 60+, Firefox 55+, Safari 11+, Edge 79+