import React from "react";
import { flushSync } from "react-dom";
const isClassComponent = (Component) => {
  return !!(typeof Component === "function" && Component.prototype && Component.prototype.isReactComponent);
};
const isForwardRefComponent = (Component) => {
  return !!(typeof Component === "object" && Component?.$$typeof?.toString() === "Symbol(react.forward_ref)");
};
class ReactRenderer {
  /**
   * Immediately creates element and renders the provided React component.
   */
  constructor(component, { editor, props = {}, as = "div", className = "" }) {
    this.ref = null;
    this.id = Math.floor(Math.random() * 4294967295).toString();
    this.component = component;
    this.editor = editor;
    this.props = props;
    this.element = document.createElement(as);
    this.element.classList.add("react-renderer");
    if (className) {
      this.element.classList.add(...className.split(" "));
    }
    if (this.editor.isInitialized) {
      flushSync(() => {
        this.render();
      });
    } else {
      this.render();
    }
  }
  /**
   * Render the React component.
   */
  render() {
    const Component = this.component;
    const props = this.props;
    const editor = this.editor;
    if (isClassComponent(Component) || isForwardRefComponent(Component)) {
      props.ref = (ref) => {
        this.ref = ref;
      };
    }
    this.reactElement = React.createElement(Component, props);
    editor?.contentComponent?.setRenderer(this.id, this);
  }
  /**
   * Re-renders the React component with new props.
   */
  updateProps(props = {}) {
    this.props = {
      ...this.props,
      ...props
    };
    this.render();
  }
  /**
   * Destroy the React component.
   */
  destroy() {
    const editor = this.editor;
    editor?.contentComponent?.removeRenderer(this.id);
  }
  /**
   * Update the attributes of the element that holds the React component.
   */
  updateAttributes(attributes) {
    Object.keys(attributes).forEach((key) => {
      this.element.setAttribute(key, attributes[key]);
    });
  }
}
export {
  ReactRenderer
};
//# sourceMappingURL=react-renderer.js.map
