"use client"; import { useState, useEffect, useRef, forwardRef, useImperativeHandle, } from "react"; import classNames from "classnames"; import { Button } from "@/components/ui/button"; import { Maximize, Minimize } from "lucide-react"; interface LivePreviewProps { currentPageData: { path: string; html: string } | undefined; isAiWorking: boolean; defaultHTML: string; className?: string; } export interface LivePreviewRef { reset: () => void; } export const LivePreview = forwardRef( ({ currentPageData, isAiWorking, defaultHTML, className }, ref) => { const [isMaximized, setIsMaximized] = useState(false); const [displayedHtml, setDisplayedHtml] = useState(""); const latestHtmlRef = useRef(""); const displayedHtmlRef = useRef(""); const intervalRef = useRef(null); const reset = () => { setIsMaximized(false); setDisplayedHtml(""); latestHtmlRef.current = ""; displayedHtmlRef.current = ""; if (intervalRef.current) { clearInterval(intervalRef.current); intervalRef.current = null; } }; useImperativeHandle(ref, () => ({ reset, })); useEffect(() => { displayedHtmlRef.current = displayedHtml; }, [displayedHtml]); useEffect(() => { if (currentPageData?.html && currentPageData.html !== defaultHTML) { latestHtmlRef.current = currentPageData.html; } }, [currentPageData?.html, defaultHTML]); useEffect(() => { if (!currentPageData?.html || currentPageData.html === defaultHTML) { return; } if (!displayedHtml || !isAiWorking) { setDisplayedHtml(currentPageData.html); if (intervalRef.current) { clearInterval(intervalRef.current); intervalRef.current = null; } return; } if (isAiWorking && !intervalRef.current) { intervalRef.current = setInterval(() => { if ( latestHtmlRef.current && latestHtmlRef.current !== displayedHtmlRef.current ) { setDisplayedHtml(latestHtmlRef.current); } }, 3000); } }, [currentPageData?.html, defaultHTML, isAiWorking, displayedHtml]); useEffect(() => { if (!isAiWorking && intervalRef.current) { clearInterval(intervalRef.current); intervalRef.current = null; if (latestHtmlRef.current) { setDisplayedHtml(latestHtmlRef.current); } } }, [isAiWorking]); useEffect(() => { return () => { if (intervalRef.current) { clearInterval(intervalRef.current); intervalRef.current = null; } }; }, []); if (!displayedHtml) { return null; } return (
Live Preview {isAiWorking && ( • Updating )}