Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

2.5 KB
Raw Blame
import { type ReactNode, forwardRef } from "react";

import {
  FlexibleSizeComponent,
  type FlexibleSizeProps,
} from "embedding-sdk-bundle/components/private/FlexibleSizeComponent";
import { PublicComponentStylesWrapper } from "embedding-sdk-bundle/components/private/PublicComponentStylesWrapper";
import { SdkError } from "embedding-sdk-bundle/components/private/PublicComponentWrapper/SdkError";
import { SdkLoader } from "embedding-sdk-bundle/components/private/PublicComponentWrapper/SdkLoader";
import { useArePluginsReady } from "embedding-sdk-bundle/hooks/private/use-are-plugins-ready";
import { useSdkSelector } from "embedding-sdk-bundle/store";
import {
  getInitStatus,
  getUsageProblem,
} from "embedding-sdk-bundle/store/selectors";
import type { CommonStylingProps } from "embedding-sdk-bundle/types/props";

export type PublicComponentWrapperProps = {
  children: ReactNode;
} & CommonStylingProps &
  Pick<FlexibleSizeProps, "height" | "width">;

export const PublicComponentWrapper = forwardRef<
  HTMLDivElement,
  PublicComponentWrapperProps
>(function PublicComponentWrapper(
  { children, className, style, height, width },
  ref,
) {
  const initStatus = useSdkSelector(getInitStatus);
  const usageProblem = useSdkSelector(getUsageProblem);
  const pluginsReady = useArePluginsReady();

  let content = children;

  if (
    initStatus.status === "uninitialized" ||
    initStatus.status === "loading"
  ) {
    content = <SdkLoader />;
  }

  if (initStatus.status === "error") {
    content = (
      <SdkError message={initStatus.error.message} error={initStatus.error} />
    );
  }

  // The SDK components should not load if there is a license error.
  if (usageProblem?.severity === "error") {
    content = null;
  }

  // Wait for EE plugins to be initialized before rendering children.
  if (!pluginsReady && content === children) {
    content = <SdkLoader />;
  }

  // EMB-875: wrap loader/error early returns in FlexibleSizeComponent so the
  // box matches the post-init tree's box (which renders its own
  // FlexibleSizeComponent inside). Prevents loader from collapsing in a
  // 0-height container then jumping to centered after init.
  const isEarlyReturn = content !== children;

  return (
    <PublicComponentStylesWrapper className={className} style={style} ref={ref}>
      {isEarlyReturn ? (
        <FlexibleSizeComponent height={height} width={width}>
          {content}
        </FlexibleSizeComponent>
      ) : (
        content
      )}
    </PublicComponentStylesWrapper>
  );
});