Skip to content

The open alternative to Salesforce, designed for AI.

2.0 KB
Raw Blame
import { MUTATION_TYPE_UPDATE_PROPERTY, ROOT_ID } from '@remote-dom/core';
import {
  BatchingRemoteConnection,
  connectRemoteNode,
  setRemoteId,
  type RemoteConnection,
} from '@remote-dom/core/elements';

import { REMOTE_RENDER_CONTAINER_TAG } from '@/constants/RemoteRenderContainerTag';
import { workerGeometryStore } from '@/polyfills/geometry/states/workerGeometryStore';
import { workerInputSelectionStore } from '@/polyfills/input-selection/states/workerInputSelectionStore';
import { workerFocusTransport } from '@/polyfills/dom/states/workerFocusTransport';
import { workerScrollStore } from '@/polyfills/scroll/states/workerScrollStore';
import { installStyleBridge } from '@/polyfills/style/utils/installStyleBridge';

type RemoteRenderRoot = {
  renderContainer: Element;
  flushPendingMutations: () => void;
};

export const attachRemoteRenderRootToWorkerDocument = (
  connection: RemoteConnection,
): RemoteRenderRoot => {
  const batchedConnection = new BatchingRemoteConnection({
    call: connection.call,
    mutate: (records) =>
      connection.mutate(
        records.filter(([mutationType, remoteNodeId]) => {
          const isRootPropertyUpdate =
            mutationType === MUTATION_TYPE_UPDATE_PROPERTY &&
            remoteNodeId === ROOT_ID;

          return !isRootPropertyUpdate;
        }),
      ),
  });
  const remoteRoot = document.body;
  const renderContainer = document.createElement(REMOTE_RENDER_CONTAINER_TAG);
  const styleContainer = document.createElement(REMOTE_RENDER_CONTAINER_TAG);

  setRemoteId(remoteRoot, ROOT_ID);
  connectRemoteNode(remoteRoot, batchedConnection);
  remoteRoot.append(renderContainer, styleContainer);
  workerGeometryStore.setRootElement(remoteRoot);
  workerFocusTransport.setRootElement(remoteRoot);
  workerInputSelectionStore.setRootElement(remoteRoot);
  workerScrollStore.setRootElement(remoteRoot);
  installStyleBridge(styleContainer);

  return {
    renderContainer,
    flushPendingMutations: () => batchedConnection.flush(),
  };
};