All files / client/src hydrate.js

91.34% Statements 95/104
82.45% Branches 47/57
94.11% Functions 16/17
91.17% Lines 93/102

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 328 329 330 331                                      9x                                           79x 5x         74x 3x               71x     79x               79x       79x       79x 79x 79x     79x 79x   1125x     79x     32x     32x       1021x 1x   1020x 1x   1019x     1020x         79x     79x 7x   7x 7x 2x   5x                 69x           1022x       1022x 1022x     1022x 1022x 1022x             1022x 1022x 1022x 1022x 1022x 1022x               4x     4x   4x 4x 4x   4x 4x       4x               3x 1x   2x 1x   2x               9x               1018x       69x               69x 69x   69x                   29x   29x                     1093x 1093x     1093x                 1026x 1006x   1026x 1006x 4x           9x                 1040x 1040x               3147x       3147x     3147x 6247x     3147x 1040x 1040x     1040x     1040x     1040x 1040x     1040x 1040x 1040x 1040x           3147x 2056x          
/**
 * 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, detectMismatch, reportMismatches } from './hydration/index.js';
import { isElementVNode, readElement, pairElementChildren } from './hydration/vnode.js';
import { patchRoot } from './hydration/patch.js';
 
/**
 * Live hydrations by container, so hydrating a container again replaces the
 * previous hydration instead of stacking a second set of handlers on it.
 * @type {WeakMap<Element, {unmount: Function}>}
 */
const hydratedContainers = new WeakMap();
 
/**
 * Hydrate a server-rendered component
 *
 * Hydrating a container that is already hydrated unmounts the previous
 * hydration first.
 *
 * @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] - Compare the server DOM with the
 *   component's output. Defaults to on when `strict` or `onMismatch` is given
 *   or `process.env.NODE_ENV` is `'development'`, off otherwise
 * @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
      }`
    );
  }
 
  // One hydration per container: drop the previous one's handlers
  hydratedContainers.get(container)?.unmount();
 
  // Initialize event delegation (idempotent)
  eventDelegation.initialize();
 
  // Extract options with defaults
  const {
    initialState: providedState,
    strict = false,
    onMismatch,
    props: additionalProps = {},
  } = options;
 
  // Mismatch detection walks the whole DOM: only when asked for, implied by
  // `strict` or `onMismatch`, or in development
  const shouldDetectMismatch = options.detectMismatch ??
    (strict || typeof onMismatch === 'function' || isDevelopment());
 
  // Extract state from DOM data-state attribute, or use provided initial state
  let state = providedState ?? extractState(container) ?? {};
  let mounted = true;
  let root = container;
 
  // Handler ids and the attributes pointing at them, from the latest render
  let registeredHandlerIds = new Set();
  let boundAttributes = [];
 
  const currentProps = () => ({ ...additionalProps, ...state });
 
  // Component reference handed to event handlers (event.state, event.setState, ...)
  const componentRef = {
    component,
    get state() {
      return state;
    },
    get props() {
      return currentProps();
    },
    getState: () => state,
    setState: (newState) => {
      if (!mounted) {
        return;
      }
      if (typeof newState === 'function') {
        state = { ...state, ...newState(state) };
      } else {
        state = { ...state, ...newState };
      }
      // Re-render on state change
      doRerender();
    },
  };
 
  // Generate virtual DOM from component
  let virtualDOM = renderComponent(component, currentProps());
 
  // 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(root, virtualDOM, componentRef, registeredHandlerIds, boundAttributes);
 
  /**
   * Re-render the component with current state
   */
  function doRerender() {
    Iif (!mounted) {
      return;
    }
 
    const previousVirtualDOM = virtualDOM;
    virtualDOM = renderComponent(component, currentProps());
 
    // Update the DOM to match the new virtual DOM
    const previousRoot = root;
    root = patchRoot(root, previousVirtualDOM, virtualDOM);
    Iif (root !== previousRoot) {
      hydratedContainers.delete(previousRoot);
      hydratedContainers.set(root, controller);
      root.setAttribute('data-coherent-hydrated', 'true');
    }
 
    // Swap handlers: register the new render's, then drop the previous ones
    const previousIds = registeredHandlerIds;
    const previousAttributes = boundAttributes;
    registeredHandlerIds = new Set();
    boundAttributes = [];
    registerEventHandlers(root, virtualDOM, componentRef, registeredHandlerIds, boundAttributes);
    releaseHandlers(previousIds, previousAttributes);
  }
 
  /**
   * Unmount the component and clean up. Terminal: later setState() and
   * rerender() calls do nothing.
   */
  function unmount() {
    Iif (!mounted) {
      return;
    }
    mounted = false;
 
    releaseHandlers(registeredHandlerIds, boundAttributes);
    registeredHandlerIds = new Set();
    boundAttributes = [];
 
    Eif (hydratedContainers.get(root) === controller) {
      hydratedContainers.delete(root);
    }
 
    // Clear container's hydration marker
    root.removeAttribute('data-coherent-hydrated');
  }
 
  /**
   * Force re-render with optional new props
   * @param {Object} [newProps] - New props to merge
   */
  function rerender(newProps) {
    if (!mounted) {
      return;
    }
    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);
  }
 
  // Return control object
  const controller = {
    unmount,
    rerender,
    getState,
    setState,
  };
 
  // Mark container as hydrated
  container.setAttribute('data-coherent-hydrated', 'true');
  hydratedContainers.set(container, controller);
 
  return controller;
}
 
/**
 * Whether the app runs in development. `process.env.NODE_ENV` is read at
 * runtime — this package's build leaves it for the app's bundler to replace —
 * and counts as production when there is no `process` at all.
 * @private
 */
function isDevelopment() {
  try {
    // eslint-disable-next-line no-restricted-globals -- replaced by the app's bundler; guarded for browsers without one
    return process.env.NODE_ENV === 'development';
  } catch {
    return false;
  }
}
 
/**
 * Call a component and resolve returned function components, as core does
 * @private
 */
function renderComponent(component, props) {
  let vNode = component(props);
  for (let guard = 0; typeof vNode === 'function' && vNode.length === 0 && guard < 100; guard++) {
    vNode = vNode();
  }
  return vNode;
}
 
/**
 * Unregister handler ids and remove the data-coherent-* attributes that still
 * point at them
 * @private
 */
function releaseHandlers(handlerIds, attributes) {
  for (const handlerId of handlerIds) {
    handlerRegistry.unregister(handlerId);
  }
  for (const { element, name, handlerId } of attributes) {
    if (element.getAttribute(name) === handlerId) {
      element.removeAttribute(name);
    }
  }
}
 
/** Prop names whose lower-cased suffix is not the DOM event type. */
const EVENT_TYPE_ALIASES = {
  doubleclick: 'dblclick',
};
 
/**
 * DOM event type for an `on*` prop: onClick -> click, onDoubleClick -> dblclick
 * @private
 */
function toEventType(propName) {
  const type = propName.slice(2).toLowerCase();
  return EVENT_TYPE_ALIASES[type] ?? type;
}
 
/**
 * Walk virtual DOM tree and register event handlers
 * @private
 */
function registerEventHandlers(domElement, vNode, componentRef, handlerIds, boundAttributes) {
  Iif (!domElement || !isElementVNode(vNode)) {
    return;
  }
 
  const { tagName, props } = readElement(vNode);
 
  // 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 = toEventType(eventProp); // onClick -> click
    const handler = props[eventProp];
 
    // Delegate this event type even if it is not one of the defaults
    eventDelegation.listen(eventType);
 
    // 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);
      boundAttributes.push({ element: domElement, name: attrName, handlerId });
    }
  }
 
  // Pair element children the way the server rendered them: null, booleans,
  // nested arrays and text never shift which element a child binds to.
  for (const [childVNode, childElement] of pairElementChildren(tagName, props, domElement)) {
    registerEventHandlers(childElement, childVNode, componentRef, handlerIds, boundAttributes);
  }
}
 
export default hydrate;