import { buildProjectApiPath } from "../../utils/projectRouting"; import { forwardRef, useEffect, useRef, useState } from "react"; import { installAcceleratedCanvasTracker } from "@hyperframes/core/page-motion-blur"; import { useMountEffect } from "../../hooks/useMountEffect"; import { applyPreviewVariablesToUrl } from "../../hooks/previewVariablesStore"; import { HyperframesLoader } from "../../components/ui"; import { usePlayerStore } from "../store/playerStore"; import { announcePreviewDocumentLoaded } from "../sceneSwap"; import type { IframeWindow } from "../lib/playbackTypes"; import { watchPreviewFrame } from "../lib/bridgePlayback"; import { previewUnderFrameToken, underCurrentFrameToken } from "../lib/frameToken"; import { retirePreviewEditingClient } from "../lib/previewChannel"; import { type AssetWaitState, waitForPreviewAssets } from "./previewAssetWait"; // Importing "@hyperframes/player" registers a class extending HTMLElement at // module load, which throws under SSR, hence the dynamic import behind a // `typeof window` guard. Kicking it here rather than in the mount effect puts // the chunk request in flight before the shell's first layout. Clearing the memo // on rejection stops one failure poisoning every later mount; the browser's // module map still caches a failed fetch, so recovery is a page reload. let playerModule: Promise | null = null; export function loadPlayerModule(): Promise { playerModule ??= import("@hyperframes/player").catch((err: unknown) => { playerModule = null; throw err; }); return playerModule; } if (typeof window !== "undefined") void loadPlayerModule().catch(() => {}); if (typeof window !== "undefined") installAcceleratedCanvasTracker(); interface PlayerProps { projectId?: string; directUrl?: string; onLoad: () => void; /** Fires once the loaded document is painted and every loader (shader, assets) has cleared. */ onReadyToShowChange?: (ready: boolean) => void; onPreviewError?: (message: string) => void; onCompositionLoadingChange?: (loading: boolean) => void; onPainted?: (details: { iframe: HTMLIFrameElement; startedAt: number; loadId: number }) => void; portrait?: boolean; style?: React.CSSProperties; suppressLoadingOverlay?: boolean; loadingUi?: "studio" | "host"; noLoadTimeout?: boolean; sandboxOrigin?: "opaque"; } interface HyperframesPlayerElement extends HTMLElement { iframeElement: HTMLIFrameElement; ready?: boolean; painted?: boolean; } function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null; } function getShaderTransitionLoading(event: Event): boolean | null { if (!(event instanceof CustomEvent)) return null; const detail: unknown = event.detail; if (!isRecord(detail)) return null; const state = detail.state; if (!isRecord(state)) return null; return state.loading === true && state.ready !== true; } const COMPOSITION_LOADING_OVERLAY_DELAY_MS = 400; const PREVIEW_BOOT_DEADLINE_MS = 5000; const DEFAULT_PREVIEW_ERROR = "The composition preview did not become ready."; export function shouldShowCompositionLoadingOverlay(compositionLoading: boolean): boolean { return compositionLoading; } export function readPreviewErrorMessage(event: Event): string { if (!(event instanceof CustomEvent) || !isRecord(event.detail)) return DEFAULT_PREVIEW_ERROR; return typeof event.detail.message === "string" && event.detail.message.trim() ? event.detail.message : DEFAULT_PREVIEW_ERROR; } function enableInteractiveIframe(player: HyperframesPlayerElement): void { const root = player.shadowRoot; if (!root) return; const container = root.querySelector(".hfp-container"); const iframe = root.querySelector(".hfp-iframe"); container?.style.setProperty("pointer-events", "auto"); iframe?.style.setProperty("pointer-events", "auto"); } const studioDraws = (wait: boolean, loadingUi: PlayerProps["loadingUi"]) => wait && loadingUi !== "host"; async function playerSrc( previewSource: string, opaque: boolean, onStale: (fresh: string) => void, ): Promise { const url = new URL(previewSource, window.location.origin); applyPreviewVariablesToUrl(url); const src = url.pathname + url.search; return opaque ? previewUnderFrameToken(src, onStale) : src; } /** A primed frame token found stale, or never confirmed: the preview loads again under the current one. */ function staleTokenSwap(canceled: () => boolean) { let shown: HyperframesPlayerElement | null = null; let fresher: string | null = null; let retries = 0; return { onStale(fresh: string) { if (canceled() || retries > 0) return; fresher = fresh; shown?.setAttribute("src", fresh); }, src: (primed: string) => fresher ?? primed, show(player: HyperframesPlayerElement) { shown = player; }, retry(primed: string, load: (src: string) => void, askAgain?: () => Promise) { const attempt = ++retries; if (!askAgain) return load(fresher ?? primed); void askAgain().then((current) => { if (canceled() || attempt !== retries) return; fresher = current; load(current); }); }, }; } const runtimeBootedIn = (iframe: HTMLIFrameElement) => (iframe.contentWindow as IframeWindow | null)?.__playerReady === true; /** * Renders a composition preview using the web component. * * The web component handles iframe scaling, dimension detection, and * ResizeObserver internally. This wrapper bridges its inner iframe to the * forwarded ref so useTimelinePlayer can access it for clip manifest parsing, * timeline probing, and DOM inspection. */ export const Player = forwardRef( ( { projectId, directUrl, onLoad, onReadyToShowChange, onPreviewError, onCompositionLoadingChange, onPainted, portrait, style, suppressLoadingOverlay, noLoadTimeout, ...host }, ref, ) => { const containerRef = useRef(null); const loadCountRef = useRef(0); const assetPollRef = useRef | null>(null); const assetFadeRef = useRef | null>(null); const retryPreviewRef = useRef<(() => void) | null>(null); const loadStartedAtRef = useRef(0); const loadIdRef = useRef(0); const retryCountRef = useRef(0); // Read at call time: this element outlives its first props (a shadow preview is // promoted in place), so mount-time closures would go stale. const onLoadRef = useRef(onLoad); onLoadRef.current = onLoad; const onReadyToShowChangeRef = useRef(onReadyToShowChange); onReadyToShowChangeRef.current = onReadyToShowChange; const onPreviewErrorRef = useRef(onPreviewError); onPreviewErrorRef.current = onPreviewError; const [loaded, setLoaded] = useState(false); const [assetsLoading, setAssetsLoading] = useState(false); const [assetOverlayVisible, setAssetOverlayVisible] = useState(false); const [assetOverlayFading, setAssetOverlayFading] = useState(false); const [assetWaitLong, setAssetWaitLong] = useState(false); const [shaderTransitionLoading, setShaderTransitionLoading] = useState(false); const [compositionLoading, setCompositionLoading] = useState(true); const [painted, setPainted] = useState(false); const [compositionOverlayDeferred, setCompositionOverlayDeferred] = useState(true); const [previewError, setPreviewError] = useState(null); // eslint-disable-next-line no-restricted-syntax useEffect(() => { if (!compositionLoading) { setCompositionOverlayDeferred(true); return; } const timer = setTimeout( () => setCompositionOverlayDeferred(false), COMPOSITION_LOADING_OVERLAY_DELAY_MS, ); return () => clearTimeout(timer); }, [compositionLoading]); useMountEffect(() => { const container = containerRef.current; if (!container) return; const previewSource = directUrl || (projectId ? buildProjectApiPath(projectId, "/preview") : null); if (!previewSource) return; // The Studio server puts the runtime in every page it answers a project preview frame with; a direct URL may be any page. const carriesRuntime = !directUrl; let canceled = false; let cleanup: (() => void) | undefined; const opaque = host.sandboxOrigin === "opaque"; const swap = staleTokenSwap(() => canceled); const source = playerSrc(previewSource, opaque, swap.onStale); void Promise.all([loadPlayerModule(), source]).then(([, primed]) => { if (canceled) return; const src = swap.src(primed); // Create the web component imperatively to avoid JSX custom-element typing. const player = document.createElement("hyperframes-player") as HyperframesPlayerElement; const retryPreview = () => { retryCountRef.current += 1; const attempt = retryCountRef.current; setPreviewError(null); setCompositionLoading(true); loadStartedAtRef.current = performance.now(); loadIdRef.current += 1; player.removeAttribute("no-load-timeout"); const load = (current: string) => { const retryUrl = new URL(current, window.location.origin); retryUrl.searchParams.set("_hfStudioRetry", String(attempt)); player.setAttribute("src", retryUrl.pathname + retryUrl.search); }; const askAgain = () => underCurrentFrameToken(swap.src(primed)); swap.retry(primed, load, opaque ? askAgain : undefined); }; retryPreviewRef.current = retryPreview; const iframe = player.iframeElement; const preventToggle = (e: Event) => e.stopImmediatePropagation(); const handleShaderTransitionState = (event: Event) => { const loading = getShaderTransitionLoading(event); if (loading !== null) setShaderTransitionLoading(loading); }; let loadedDocument: Document | null = null; const handleReady = () => { setPreviewError(null); setCompositionLoading(false); if (iframe.contentDocument && runtimeBootedIn(iframe)) handleLoad(); }; const handlePainted = () => { setPainted(true); onPainted?.({ iframe, startedAt: loadStartedAtRef.current, loadId: loadIdRef.current }); }; const handleError = (event: Event) => { const message = readPreviewErrorMessage(event); onPreviewErrorRef.current?.(message); setPreviewError(message); setCompositionLoading(false); }; const handleLoad = () => { const doc = iframe.contentDocument; if (doc && doc === loadedDocument) return; loadedDocument = doc; loadCountRef.current++; setLoaded(true); setPreviewError(null); setShaderTransitionLoading(false); setCompositionLoading(!player.ready); setPainted(Boolean(player.painted)); // Reveal animation on reload (hot-reload, composition switch) if (loadCountRef.current > 1) { container.classList.remove("preview-revealing"); void container.offsetWidth; container.classList.add("preview-revealing"); const onEnd = () => container.classList.remove("preview-revealing"); container.addEventListener("animationend", onEnd, { once: true }); } onLoadRef.current(); announcePreviewDocumentLoaded(iframe); // Show a loading overlay until every `