All files / coherent.js/website/public hydration.js

0% Statements 0/150
0% Branches 0/1
0% Functions 0/1
0% Lines 0/150

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150                                                                                                                                                                                                                                                                                                           
/**
 * Client-side hydration for Coherent.js website
 * Handles data-action attributes and makes interactive components work
 */

console.log('๐ŸŒŠ Coherent.js Hydration starting...');

// Initialize global registries for Coherent.js
window.__coherentEventRegistry = window.__coherentEventRegistry || {};
window.__coherentActionRegistry = window.__coherentActionRegistry || {};

/**
 * Map button IDs to their corresponding functions for the performance page
 */
function setupPerformancePageHandlers() {
  console.log('๐ŸŽฏ Setting up performance page handlers...');
  
  const buttonMappings = [
    { id: 'run-all-tests', handler: 'runPerformanceTests' },
    { id: 'run-render-test', handler: 'runRenderingTest' },
    { id: 'run-cache-test', handler: 'runCacheTest' },
    { id: 'clear-results', handler: 'clearResults' }
  ];

  buttonMappings.forEach(mapping => {
    const button = document.getElementById(mapping.id);
    console.log(`Looking for button ${mapping.id}:`, button ? 'found' : 'not found');
    console.log(`Looking for handler ${mapping.handler}:`, typeof window[mapping.handler]);
    
    if (button && window[mapping.handler]) {
      // Remove data-action attributes to prevent conflicts
      button.removeAttribute('data-action');
      button.removeAttribute('data-event');
      
      // Remove existing listeners to avoid duplicates
      const existingHandler = button.__coherentHandler;
      if (existingHandler) {
        button.removeEventListener('click', existingHandler);
        console.log(`๐Ÿงน Removed existing handler from ${mapping.id}`);
      }

      // Create new handler
      const handler = (event) => {
        event.preventDefault();
        event.stopPropagation();
        try {
          console.log(`๐ŸŽฏ Button ${mapping.id} clicked - calling ${mapping.handler}()`);
          window[mapping.handler]();
        } catch (error) {
          console.error(`Error in ${mapping.handler}:`, error);
        }
      };

      // Attach the handler with capture to ensure it runs first
      button.addEventListener('click', handler, true);
      button.__coherentHandler = handler;
      
      console.log(`โœ… Successfully connected button ${mapping.id} to ${mapping.handler}`);
    } else {
      if (!button) console.warn(`โš ๏ธ Button not found: ${mapping.id}`);
      if (!window[mapping.handler]) console.warn(`โš ๏ธ Handler not found: ${mapping.handler}`);
    }
  });
}

/**
 * Process data-action attributes and attach event listeners
 */
function hydratePage() {
  // First try the direct approach for performance page
  if (document.querySelector('[data-coherent-component="performance"]')) {
    console.log('๐ŸŽฏ Setting up performance page handlers directly...');
    setupPerformancePageHandlers();
  }
  
  // Also process any data-action attributes
  const actionElements = document.querySelectorAll('[data-action]');
  
  console.log(`๐Ÿ” Found ${actionElements.length} elements with data-action attributes`);
  console.log('Action registry keys:', Object.keys(window.__coherentActionRegistry));
  
  actionElements.forEach(element => {
    const actionId = element.getAttribute('data-action');
    const eventType = element.getAttribute('data-event') || 'click';
    
    if (actionId && window.__coherentActionRegistry[actionId]) {
      const handler = window.__coherentActionRegistry[actionId];
      
      if (typeof handler === 'function') {
        // Remove existing event listener to avoid duplicates
        const handlerKey = `__hydrated_${eventType}`;
        if (element[handlerKey]) {
          element.removeEventListener(eventType, element[handlerKey]);
        }
        
        // Create wrapper that provides proper context
        const wrappedHandler = (event) => {
          try {
            console.log(`๐ŸŽฏ Executing action ${actionId}`);
            
            // Call the original handler
            handler.call(element, event);
          } catch (error) {
            console.error('Error in action handler:', error);
          }
        };
        
        // Attach the event listener
        element.addEventListener(eventType, wrappedHandler);
        element[handlerKey] = wrappedHandler;
        
        console.log(`โœ… Attached ${eventType} handler for action ${actionId}`);
      }
    } else {
      console.warn(`โš ๏ธ No handler found for action ${actionId} in registry with keys:`, Object.keys(window.__coherentActionRegistry));
    }
  });
}

/**
 * Initialize hydration when DOM is ready
 */
function initHydration() {
  const performHydration = () => {
    console.log('๐ŸŒŠ Starting hydration...');
    console.log('Performance functions available:', {
      runPerformanceTests: typeof window.runPerformanceTests,
      runRenderingTest: typeof window.runRenderingTest,
      runCacheTest: typeof window.runCacheTest,
      clearResults: typeof window.clearResults
    });
    
    hydratePage();
  };

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
      // Wait a bit more for deferred scripts to load
      setTimeout(performHydration, 100);
    });
  } else {
    // Wait a bit for deferred scripts if page is already loaded
    setTimeout(performHydration, 100);
  }
}

// Start hydration
initHydration();

console.log('๐ŸŒŠ Coherent.js Hydration script loaded');