deepsite / components /editor /preview /index-simplified.tsx
dr-data
Fix React Hook dependencies and remove empty test modules causing build errors
c127855
"use client";
import { useUpdateEffect } from "react-use";
import { useMemo, useState, useRef, useEffect, forwardRef } from "react";
import classNames from "classnames";
import { cn } from "@/lib/utils";
import { GridPattern } from "@/components/magic-ui/grid-pattern";
import { htmlTagToText } from "@/lib/html-tag-to-text";
export const Preview = forwardRef<
HTMLDivElement,
{
html: string;
isResizing: boolean;
isAiWorking: boolean;
device: "desktop" | "mobile";
iframeRef?: React.RefObject<HTMLIFrameElement | null>;
isEditableModeEnabled?: boolean;
onClickElement?: (element: HTMLElement) => void;
}
>(({
html,
isResizing,
isAiWorking,
device,
iframeRef,
isEditableModeEnabled,
onClickElement,
}, ref) => {
const [hoveredElement, setHoveredElement] = useState<HTMLElement | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [displayHtml, setDisplayHtml] = useState(html);
const htmlUpdateTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const prevHtmlRef = useRef(html);
const internalIframeRef = useRef<HTMLIFrameElement>(null);
// Use internal ref if external ref not provided
const currentIframeRef = iframeRef || internalIframeRef;
// Debug logging for initial state
useEffect(() => {
console.log('🚀 SIMPLIFIED Preview component mounted with HTML:', {
htmlLength: html.length,
htmlPreview: html.substring(0, 200) + '...',
displayHtmlLength: displayHtml.length
});
}, [html, html.length, displayHtml.length]);
// SIMPLIFIED: Reliable HTML update logic with optional smoothness
useEffect(() => {
console.log('🔄 SIMPLIFIED Preview update triggered:', {
htmlLength: html.length,
isAiWorking,
displayHtmlLength: displayHtml.length,
htmlChanged: html !== displayHtml,
htmlPreview: html.substring(0, 100) + '...'
});
// PRIORITY: Always ensure HTML updates work immediately
if (html !== displayHtml) {
console.log('📝 HTML changed! Updating display HTML immediately:', html.length, 'characters');
// Clear any pending timeout to prevent conflicts
if (htmlUpdateTimeoutRef.current) {
clearTimeout(htmlUpdateTimeoutRef.current);
}
// For AI working (streaming), add minimal smoothness
if (isAiWorking) {
console.log('🤖 AI working - adding minimal delay for smoothness');
setIsLoading(true);
htmlUpdateTimeoutRef.current = setTimeout(() => {
setDisplayHtml(html);
prevHtmlRef.current = html;
setIsLoading(false);
console.log('✅ Delayed update completed for AI streaming');
}, 100); // Very short delay for minimal smoothness
} else {
// Immediate update for manual changes
setDisplayHtml(html);
prevHtmlRef.current = html;
setIsLoading(false);
console.log('⚡ Immediate update completed for manual change');
}
}
console.log('✅ SIMPLIFIED Preview update completed, displayHtml length:', displayHtml.length);
}, [html, isAiWorking, displayHtml]);
// Add basic smooth transitions via CSS
useEffect(() => {
const iframe = currentIframeRef.current;
if (!iframe || !iframe.contentDocument) return;
const injectSmoothTransitions = () => {
const doc = iframe.contentDocument;
if (!doc) return;
const existingStyle = doc.getElementById('smooth-transitions');
if (existingStyle) return;
const style = doc.createElement('style');
style.id = 'smooth-transitions';
style.textContent = `
/* Smooth transitions for content changes */
* {
transition: opacity 0.15s ease, background-color 0.15s ease,
color 0.15s ease, border-color 0.15s ease !important;
}
/* Prevent flashing during updates */
body {
transition: opacity 0.1s ease !important;
}
/* Subtle animations for new content */
@keyframes contentFadeIn {
from { opacity: 0.8; }
to { opacity: 1; }
}
body.content-updating {
animation: contentFadeIn 0.2s ease-in-out;
}
`;
doc.head.appendChild(style);
console.log('✨ Smooth transitions injected into iframe');
};
// Inject on iframe load
iframe.addEventListener('load', injectSmoothTransitions);
// Also try to inject immediately if iframe is already loaded
if (iframe.contentDocument?.readyState === 'complete') {
injectSmoothTransitions();
}
return () => {
iframe.removeEventListener('load', injectSmoothTransitions);
};
}, [currentIframeRef, displayHtml]);
// Add content updating class for animations
useEffect(() => {
const iframe = currentIframeRef.current;
if (!iframe || !iframe.contentDocument) return;
const body = iframe.contentDocument.body;
if (!body) return;
body.classList.add('content-updating');
const timeout = setTimeout(() => {
body.classList.remove('content-updating');
}, 200);
return () => {
clearTimeout(timeout);
body.classList.remove('content-updating');
};
}, [displayHtml, currentIframeRef]);
// Cleanup timeout on unmount
useEffect(() => {
return () => {
if (htmlUpdateTimeoutRef.current) {
clearTimeout(htmlUpdateTimeoutRef.current);
}
};
}, []);
// Event handlers for editable mode
const handleMouseOver = (event: MouseEvent) => {
if (currentIframeRef?.current) {
const iframeDocument = currentIframeRef.current.contentDocument;
if (iframeDocument) {
const targetElement = event.target as HTMLElement;
if (
hoveredElement !== targetElement &&
targetElement !== iframeDocument.body
) {
console.log("🎯 Edit mode: Element hovered", {
tagName: targetElement.tagName,
id: targetElement.id || 'no-id',
className: targetElement.className || 'no-class'
});
// Remove previous hover class
if (hoveredElement) {
hoveredElement.classList.remove("hovered-element");
}
setHoveredElement(targetElement);
targetElement.classList.add("hovered-element");
} else {
return setHoveredElement(null);
}
}
}
};
const handleMouseOut = () => {
setHoveredElement(null);
};
const handleClick = (event: MouseEvent) => {
console.log("🖱️ Edit mode: Click detected in iframe", {
target: event.target,
tagName: (event.target as HTMLElement)?.tagName,
isBody: event.target === currentIframeRef?.current?.contentDocument?.body,
hasOnClickElement: !!onClickElement
});
if (currentIframeRef?.current) {
const iframeDocument = currentIframeRef.current.contentDocument;
if (iframeDocument) {
const targetElement = event.target as HTMLElement;
if (targetElement !== iframeDocument.body) {
console.log("✅ Edit mode: Valid element clicked, calling onClickElement", {
tagName: targetElement.tagName,
id: targetElement.id || 'no-id',
className: targetElement.className || 'no-class',
textContent: targetElement.textContent?.substring(0, 50) + '...'
});
// Prevent default behavior to avoid navigation
event.preventDefault();
event.stopPropagation();
onClickElement?.(targetElement);
} else {
console.log("⚠️ Edit mode: Body clicked, ignoring");
}
} else {
console.error("❌ Edit mode: No iframe document available on click");
}
} else {
console.error("❌ Edit mode: No iframe ref available on click");
}
};
// Setup event listeners for editable mode
useUpdateEffect(() => {
const cleanupListeners = () => {
if (currentIframeRef?.current?.contentDocument) {
const iframeDocument = currentIframeRef.current.contentDocument;
iframeDocument.removeEventListener("mouseover", handleMouseOver);
iframeDocument.removeEventListener("mouseout", handleMouseOut);
iframeDocument.removeEventListener("click", handleClick);
console.log("🧹 Edit mode: Cleaned up iframe event listeners");
}
};
const setupListeners = () => {
try {
if (!currentIframeRef?.current) {
console.log("⚠️ Edit mode: No iframe ref available");
return;
}
const iframeDocument = currentIframeRef.current.contentDocument;
if (!iframeDocument) {
console.log("⚠️ Edit mode: No iframe content document available");
return;
}
// Clean up existing listeners first
cleanupListeners();
if (isEditableModeEnabled) {
console.log("🎯 Edit mode: Setting up iframe event listeners");
iframeDocument.addEventListener("mouseover", handleMouseOver);
iframeDocument.addEventListener("mouseout", handleMouseOut);
iframeDocument.addEventListener("click", handleClick);
console.log("✅ Edit mode: Event listeners added successfully");
} else {
console.log("🔇 Edit mode: Disabled, no listeners added");
}
} catch (error) {
console.error("❌ Edit mode: Error setting up listeners:", error);
}
};
// Add a small delay to ensure iframe is fully loaded
const timeoutId = setTimeout(setupListeners, 100);
// Clean up when component unmounts or dependencies change
return () => {
clearTimeout(timeoutId);
cleanupListeners();
};
}, [currentIframeRef, isEditableModeEnabled]);
const selectedElement = useMemo(() => {
if (!isEditableModeEnabled) return null;
if (!hoveredElement) return null;
return hoveredElement;
}, [hoveredElement, isEditableModeEnabled]);
return (
<div
ref={ref}
className={classNames(
"bg-white overflow-hidden relative flex-1 h-full",
{
"cursor-wait": isLoading && isAiWorking,
}
)}
onClick={(e) => {
e.stopPropagation();
}}
>
<GridPattern
width={20}
height={20}
x={-1}
y={-1}
strokeDasharray={"4 2"}
className={cn(
"[mask-image:radial-gradient(300px_circle_at_center,white,transparent)] z-0 absolute inset-0 h-full w-full fill-neutral-100 stroke-neutral-100"
)}
/>
{/* Simplified loading overlay */}
{isLoading && isAiWorking && (
<div className="absolute inset-0 bg-black/5 backdrop-blur-[0.5px] transition-all duration-300 z-20 flex items-center justify-center">
<div className="bg-neutral-800/95 rounded-lg px-4 py-2 text-sm text-neutral-300 border border-neutral-700 shadow-lg">
<div className="flex items-center gap-2">
<div className="w-2 h-2 bg-blue-500 rounded-full animate-pulse"></div>
Updating preview...
</div>
</div>
</div>
)}
{/* Selected element indicator */}
{!isAiWorking && hoveredElement && selectedElement && (
<div className="absolute bottom-4 left-4 z-30">
<div className="bg-neutral-800/90 rounded-lg px-3 py-2 text-sm text-neutral-300 border border-neutral-700 shadow-lg">
<span className="font-medium">
{htmlTagToText(selectedElement.tagName.toLowerCase())}
</span>
{selectedElement.id && (
<span className="ml-2 text-neutral-400">#{selectedElement.id}</span>
)}
</div>
</div>
)}
{/* Simplified single iframe with CSS transitions */}
<iframe
id="preview-iframe"
ref={currentIframeRef}
title="output"
className={classNames(
"w-full select-none h-full transition-all duration-200 ease-out",
{
"pointer-events-none": isResizing || isAiWorking,
"opacity-95 scale-[0.999]": isLoading && isAiWorking,
"opacity-100 scale-100": !isLoading || !isAiWorking,
"bg-black": true,
"lg:max-w-md lg:mx-auto lg:!rounded-[42px] lg:border-[8px] lg:border-neutral-700 lg:shadow-2xl lg:h-[80dvh] lg:max-h-[996px]":
device === "mobile",
"lg:border-[8px] lg:border-neutral-700 lg:shadow-2xl lg:rounded-[24px]":
device === "desktop",
}
)}
srcDoc={displayHtml}
onLoad={() => {
console.log('🎯 SIMPLIFIED Preview iframe loaded with HTML length:', displayHtml.length);
setIsLoading(false);
}}
/>
</div>
);
});
Preview.displayName = "Preview";