All files / client/src hydrate.js

76.36% Statements 84/110
62% Branches 62/100
87.5% Functions 14/16
77.57% Lines 83/107

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 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327                                                        38x 4x         34x 3x               31x                 31x     31x     38x     38x     38x     5x 1x   4x     5x         38x 38x     38x 28x   28x 28x 1x   27x                 30x           7x 7x         7x     7x               2x 1x   2x     2x     2x     2x               2x 1x   2x               9x               5x       30x     30x                         39x       39x 39x   39x         39x 41x     39x 2x 2x     2x     2x 2x     2x 2x 2x         39x 39x   39x 2x 2x                   7x         7x               7x       7x       7x 7x     7x         7x 7x 7x         7x                   7x 7x 7x 7x   7x                                     39x 39x 1x   38x               39x   39x 2x                    
/**
 * Clean hydrate() API for Coherent.js
 *
 * Integrates event delegation, state serialization, and mismatch detection
 * into a simple function: hydrate(component, container, options)
 *
 * @module @coherent.js/client/hydrate
 */
 
import { eventDelegation, handlerRegistry } from './events/index.js';
import { extractState, serializeState } from './hydration/index.js';
import { detectMismatch, reportMismatches } from './hydration/index.js';
 
/**
 * Hydrate a server-rendered component
 *
 * @param {Function} component - Component function that returns virtual DOM
 * @param {HTMLElement} container - DOM element containing server-rendered HTML
 * @param {Object} [options] - Hydration options
 * @param {Object} [options.initialState] - Initial state to override extracted state
 * @param {boolean} [options.detectMismatch=true] - Enable mismatch detection (dev mode)
 * @param {boolean} [options.strict=false] - Throw on mismatch instead of warning
 * @param {Function} [options.onMismatch] - Custom mismatch handler
 * @param {Object} [options.props] - Additional props to pass to component
 * @returns {Object} Control object with unmount(), rerender(), getState(), setState()
 */
export function hydrate(component, container, options = {}) {
  // Validate inputs
  if (typeof component !== 'function') {
    throw new Error(
      `hydrate() requires a component function, received: ${typeof component}`
    );
  }
 
  if (!container || typeof container.getAttribute !== 'function') {
    throw new Error(
      `hydrate() requires a valid DOM element as container, received: ${
        container === null ? 'null' : typeof container
      }`
    );
  }
 
  // Initialize event delegation (idempotent)
  eventDelegation.initialize();
 
  // Extract options with defaults
  const {
    initialState: providedState,
    detectMismatch: shouldDetectMismatch = process.env.NODE_ENV !== 'production',
    strict = false,
    onMismatch,
    props: additionalProps = {},
  } = options;
 
  // Extract state from DOM data-state attribute, or use provided initial state
  let state = providedState ?? extractState(container) ?? {};
 
  // Store event listeners for cleanup
  const eventListeners = [];
 
  // Track registered handler IDs for cleanup
  const registeredHandlerIds = new Set();
 
  // Create component reference for handler registry
  const componentRef = {
    getState: () => state,
    setState: (newState) => {
      if (typeof newState === 'function') {
        state = { ...state, ...newState(state) };
      } else {
        state = { ...state, ...newState };
      }
      // Re-render on state change
      doRerender();
    },
  };
 
  // Generate virtual DOM from component
  const componentProps = { ...additionalProps, ...state };
  let virtualDOM = component(componentProps);
 
  // Detect mismatches if enabled
  if (shouldDetectMismatch) {
    const mismatches = detectMismatch(container, virtualDOM);
 
    Eif (mismatches.length > 0) {
      if (onMismatch) {
        onMismatch(mismatches);
      } else {
        reportMismatches(mismatches, {
          componentName: component.name || 'Anonymous',
          strict,
        });
      }
    }
  }
 
  // Walk virtual DOM and register event handlers
  registerEventHandlers(container, virtualDOM, componentRef, registeredHandlerIds);
 
  /**
   * Re-render the component with current state
   */
  function doRerender() {
    const newProps = { ...additionalProps, ...state };
    virtualDOM = component(newProps);
 
    // Update DOM with new virtual DOM
    // For now, we do a simple patch - just update text content and attributes
    // Full reconciliation would be in a separate module
    patchDOM(container, virtualDOM);
 
    // Re-register event handlers after DOM update
    registerEventHandlers(container, virtualDOM, componentRef, registeredHandlerIds);
  }
 
  /**
   * Unmount the component and clean up
   */
  function unmount() {
    // Remove registered event handlers
    for (const handlerId of registeredHandlerIds) {
      handlerRegistry.unregister(handlerId);
    }
    registeredHandlerIds.clear();
 
    // Remove direct event listeners
    for (const { element, event, handler, options } of eventListeners) {
      element.removeEventListener(event, handler, options);
    }
    eventListeners.length = 0;
 
    // Clear container's hydration marker
    container.removeAttribute('data-coherent-hydrated');
  }
 
  /**
   * Force re-render with optional new props
   * @param {Object} [newProps] - New props to merge
   */
  function rerender(newProps) {
    if (newProps) {
      Object.assign(additionalProps, newProps);
    }
    doRerender();
  }
 
  /**
   * Get current state
   * @returns {Object} Current state
   */
  function getState() {
    return { ...state };
  }
 
  /**
   * Set state and trigger re-render
   * @param {Object|Function} newState - New state or updater function
   */
  function setState(newState) {
    componentRef.setState(newState);
  }
 
  // Mark container as hydrated
  container.setAttribute('data-coherent-hydrated', 'true');
 
  // Return control object
  return {
    unmount,
    rerender,
    getState,
    setState,
  };
}
 
/**
 * Walk virtual DOM tree and register event handlers
 * @private
 */
function registerEventHandlers(domElement, vNode, componentRef, handlerIds) {
  Iif (!vNode || typeof vNode !== 'object' || Array.isArray(vNode)) {
    return;
  }
 
  const tagName = Object.keys(vNode)[0];
  const props = vNode[tagName];
 
  Iif (!props || typeof props !== 'object') {
    return;
  }
 
  // Look for event handler props (on* functions)
  const eventProps = Object.keys(props).filter(
    (key) => key.startsWith('on') && typeof props[key] === 'function'
  );
 
  for (const eventProp of eventProps) {
    const eventType = eventProp.slice(2).toLowerCase(); // onClick -> click
    const handler = props[eventProp];
 
    // Generate unique handler ID
    const handlerId = `${tagName}-${eventType}-${Math.random().toString(36).slice(2, 9)}`;
 
    // Register handler
    handlerRegistry.register(handlerId, handler, componentRef);
    handlerIds.add(handlerId);
 
    // Set data attribute on DOM element for delegation
    const attrName = `data-coherent-${eventType}`;
    Eif (domElement.setAttribute) {
      domElement.setAttribute(attrName, handlerId);
    }
  }
 
  // Recursively process children
  const children = getVNodeChildren(props);
  const domChildren = getSignificantDOMChildren(domElement);
 
  children.forEach((child, index) => {
    Eif (child && typeof child === 'object' && !Array.isArray(child) && domChildren[index]) {
      registerEventHandlers(domChildren[index], child, componentRef, handlerIds);
    }
  });
}
 
/**
 * Simple DOM patching for re-renders
 * @private
 */
function patchDOM(domElement, vNode) {
  Iif (!vNode || !domElement) {
    return;
  }
 
  // Handle text/number
  Iif (typeof vNode === 'string' || typeof vNode === 'number') {
    if (domElement.textContent !== String(vNode)) {
      domElement.textContent = String(vNode);
    }
    return;
  }
 
  // Handle arrays
  Iif (Array.isArray(vNode)) {
    return; // Array patching would need reconciliation
  }
 
  Iif (typeof vNode !== 'object') {
    return;
  }
 
  const tagName = Object.keys(vNode)[0];
  const props = vNode[tagName] || {};
 
  // Update attributes
  const attributeMap = {
    className: 'class',
    htmlFor: 'for',
  };
 
  for (const [key, value] of Object.entries(props)) {
    Eif (key === 'children' || key === 'text' || key.startsWith('on')) {
      continue;
    }
 
    const attrName = attributeMap[key] || key;
 
    if (value === true) {
      domElement.setAttribute(attrName, '');
    } else if (value === false || value === null || value === undefined) {
      domElement.removeAttribute(attrName);
    } else if (domElement.getAttribute(attrName) !== String(value)) {
      domElement.setAttribute(attrName, String(value));
    }
  }
 
  // Handle text content
  Eif (props.text !== undefined) {
    const textContent = String(props.text);
    Eif (domElement.textContent !== textContent) {
      domElement.textContent = textContent;
    }
    return;
  }
 
  // Recursively patch children
  const children = getVNodeChildren(props);
  const domChildren = getSignificantDOMChildren(domElement);
 
  children.forEach((child, index) => {
    if (domChildren[index]) {
      patchDOM(domChildren[index], child);
    }
  });
}
 
/**
 * Get children from virtual node props
 * @private
 */
function getVNodeChildren(props) {
  Iif (!props) return [];
  if (props.children) {
    return Array.isArray(props.children) ? props.children : [props.children];
  }
  return [];
}
 
/**
 * Get significant DOM children (elements and non-whitespace text)
 * @private
 */
function getSignificantDOMChildren(element) {
  Iif (!element || !element.childNodes) return [];
 
  return Array.from(element.childNodes).filter((node) => {
    Eif (node.nodeType === 1) return true; // Element
    if (node.nodeType === 3) {
      // Text node
      return node.textContent && node.textContent.trim().length > 0;
    }
    return false;
  });
}
 
export default hydrate;