hydrateToElement function

BloomMountHandle hydrateToElement(
  1. BloomNode root,
  2. Element container, {
  3. HydrationMismatchHandler? onMismatch,
})

Hydrates server-rendered DOM inside container against root.

Attaches listeners, refs, lifecycle hooks, and reactive regions to the existing nodes. Falls back to a clean full mount (previous behavior) only when the root structure itself mismatches.

Implementation

BloomMountHandle hydrateToElement(
  BloomNode root,
  web.Element container, {
  HydrationMismatchHandler? onMismatch,
}) {
  final region = _Region();
  final hctx = _HydrationContext(onMismatch: onMismatch);
  try {
    final sibs = _liveChildren(container);
    final consumed = _hydrateNode(root, sibs, 0, container, region, hctx);
    if (consumed != sibs.length) {
      throw _HydrationAbort(
        'root with exactly ${sibs.length} top-level nodes',
        'consumed $consumed nodes',
      );
    }
    return BloomMountHandle._(
      container,
      region.disposers.toList(),
      region: region,
    );
  } catch (e) {
    if (e is _HydrationAbort) {
      hctx.report(
        boundary: 'root',
        expected: e.expected,
        actual: e.actual,
        recovery: 'remounted target',
      );
    } else {
      hctx.report(
        boundary: 'root',
        expected: 'hydratable DOM',
        actual: '${e.runtimeType}: $e',
        recovery: 'remounted target',
      );
    }
    for (final d in region.disposers) {
      try {
        d();
      } catch (_) {}
    }
    if (container.childNodes.length > 0) container.textContent = '';
    return mountToElement(root, container);
  }
}