Skip to content

🎥 Make videos programmatically with React

3.7 KB
Raw Blame
"use client";

import type {
  CanvasSequencePropChange,
  CanvasSequencePropStatusResolver,
} from "@remotion/sdk";
import { useEffect, useRef, useState } from "react";
import { BASE_PATH } from "@/lib/base-path";
import type { PreviewHost, PreviewKeyEvent } from "@/preview/bridge";

export const getErrorMessage = (error: unknown) =>
  error instanceof Error ? error.message : String(error);

/**
 * Loads preview.html into the iframe and connects to the preview host that
 * the iframe exposes on its window.
 */
export const usePreviewHost = ({
  iframeRef,
  onError,
  onKeyDown,
  onSequencePropsChange,
  getSequencePropStatuses,
}: {
  iframeRef: React.RefObject<HTMLIFrameElement | null>;
  onError: (message: string) => void;
  onKeyDown: (event: PreviewKeyEvent) => boolean;
  onSequencePropsChange: (changes: readonly CanvasSequencePropChange[]) => void;
  getSequencePropStatuses: CanvasSequencePropStatusResolver;
}) => {
  const [host, setHost] = useState<PreviewHost | null>(null);
  const [error, setError] = useState<string | null>(null);
  const onErrorRef = useRef(onError);
  const onKeyDownRef = useRef(onKeyDown);
  const onSequencePropsChangeRef = useRef(onSequencePropsChange);
  const getSequencePropStatusesRef = useRef(getSequencePropStatuses);
  onErrorRef.current = onError;
  onKeyDownRef.current = onKeyDown;
  onSequencePropsChangeRef.current = onSequencePropsChange;
  getSequencePropStatusesRef.current = getSequencePropStatuses;

  useEffect(() => {
    const iframe = iframeRef.current;
    if (!iframe) {
      return;
    }

    let disposed = false;
    let loaded = false;
    let created: PreviewHost | null = null;
    const timeout = window.setTimeout(() => {
      if (!disposed && !created) {
        setError(
          "Timed out while loading the preview. Run `npm run build-preview` and reload the page.",
        );
      }
    }, 30_000);

    const onLoad = () => {
      if (disposed || iframe.contentWindow?.location.href === "about:blank") {
        return;
      }

      if (loaded) {
        setError("The preview reloaded. Reload this page to reconnect.");
        return;
      }

      loaded = true;
      const initialize = iframe.contentWindow?.remotionVibeCodePreview;
      if (!initialize) {
        setError(
          "The preview bundle is missing. Run `npm run build-preview` and reload the page.",
        );
        return;
      }

      initialize
        .then((createPreviewHost) => {
          if (disposed) {
            return;
          }

          created = createPreviewHost({
            onError: (message) => onErrorRef.current(message),
            onKeyDown: (event) => onKeyDownRef.current(event),
            onSequencePropsChange: (changes) =>
              onSequencePropsChangeRef.current(changes),
            getSequencePropStatuses: (nodePathInfo, keys) =>
              getSequencePropStatusesRef.current(nodePathInfo, keys),
          });
          window.clearTimeout(timeout);
          setHost(created);
        })
        .catch((err: unknown) => {
          if (!disposed) {
            setError(getErrorMessage(err));
          }
        });
    };

    const onIframeError = () => {
      if (!disposed) {
        setError("The preview iframe failed to load.");
      }
    };

    iframe.addEventListener("load", onLoad);
    iframe.addEventListener("error", onIframeError);
    iframe.src = `${BASE_PATH}/preview.html`;

    return () => {
      disposed = true;
      window.clearTimeout(timeout);
      iframe.removeEventListener("load", onLoad);
      iframe.removeEventListener("error", onIframeError);
      created?.dispose();
      setHost(null);
      iframe.src = "about:blank";
    };
  }, [iframeRef]);

  return { host, error };
};