Spaces:
Running
Running
File size: 7,676 Bytes
13ae717 c9b2910 473668f 13ae717 c9b2910 473668f 13ae717 c9b2910 473668f 13ae717 c9b2910 473668f 13ae717 c9b2910 473668f c9b2910 473668f c9b2910 473668f 13ae717 ec1f23a 473668f 13ae717 473668f 13ae717 c9b2910 33dc9ee c9b2910 13ae717 44259fa 13ae717 d6180c0 13ae717 473668f 13ae717 473668f 13ae717 473668f 13ae717 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 |
"use client";
import { useUpdateEffect } from "react-use";
import { useMemo, useState, useEffect } from "react";
import classNames from "classnames";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import { GridPattern } from "@/components/magic-ui/grid-pattern";
import { htmlTagToText } from "@/lib/html-tag-to-text";
import { errorDetectorScript, ERROR_DETECTOR_ID } from "@/lib/error-detector";
import type { PreviewError } from "@/types/preview-error";
export const Preview = ({
html,
isResizing,
isAiWorking,
ref,
device,
currentTab,
iframeRef,
isEditableModeEnabled,
onClickElement,
onErrors,
}: {
html: string;
isResizing: boolean;
isAiWorking: boolean;
ref: React.RefObject<HTMLDivElement | null>;
iframeRef?: React.RefObject<HTMLIFrameElement | null>;
device: "desktop" | "mobile";
currentTab: string;
isEditableModeEnabled?: boolean;
onClickElement?: (element: HTMLElement) => void;
onErrors?: (errors: PreviewError[]) => void;
}) => {
const [hoveredElement, setHoveredElement] = useState<HTMLElement | null>(
null,
);
// Listen for error messages from the iframe
useEffect(() => {
const handleMessage = (event: MessageEvent) => {
if (event.data?.type === "PREVIEW_ERRORS" && onErrors) {
onErrors(event.data.errors);
}
};
window.addEventListener("message", handleMessage);
return () => window.removeEventListener("message", handleMessage);
}, [onErrors]);
// Defensive reset: Clear errors when HTML changes
useUpdateEffect(() => {
onErrors?.([]);
}, [html]);
// add event listener to the iframe to track hovered elements
const handleMouseOver = (event: MouseEvent) => {
if (iframeRef?.current) {
const iframeDocument = iframeRef.current.contentDocument;
if (iframeDocument) {
const targetElement = event.target as HTMLElement;
if (
hoveredElement !== targetElement &&
targetElement !== iframeDocument.body
) {
setHoveredElement(targetElement);
targetElement.classList.add("hovered-element");
} else {
return setHoveredElement(null);
}
}
}
};
const handleMouseOut = () => {
setHoveredElement(null);
};
const handleClick = (event: MouseEvent) => {
if (iframeRef?.current) {
const iframeDocument = iframeRef.current.contentDocument;
if (iframeDocument) {
const targetElement = event.target as HTMLElement;
if (targetElement !== iframeDocument.body) {
onClickElement?.(targetElement);
}
}
}
};
useUpdateEffect(() => {
const cleanupListeners = () => {
if (iframeRef?.current?.contentDocument) {
const iframeDocument = iframeRef.current.contentDocument;
iframeDocument.removeEventListener("mouseover", handleMouseOver);
iframeDocument.removeEventListener("mouseout", handleMouseOut);
iframeDocument.removeEventListener("click", handleClick);
}
};
if (iframeRef?.current) {
const iframeDocument = iframeRef.current.contentDocument;
if (iframeDocument) {
// Clean up existing listeners first
cleanupListeners();
if (isEditableModeEnabled) {
iframeDocument.addEventListener("mouseover", handleMouseOver);
iframeDocument.addEventListener("mouseout", handleMouseOut);
iframeDocument.addEventListener("click", handleClick);
}
}
}
// Clean up when component unmounts or dependencies change
return cleanupListeners;
}, [iframeRef, isEditableModeEnabled]);
const selectedElement = useMemo(() => {
if (!isEditableModeEnabled) return null;
if (!hoveredElement) return null;
return hoveredElement;
}, [hoveredElement, isEditableModeEnabled]);
// Inject error detection script into the HTML
const htmlWithErrorDetection = useMemo(() => {
if (!html) return "";
// First, remove any existing error detector script to prevent duplicates
const cleanedHtml = html.replace(
new RegExp(
`<script[^>]*id="${ERROR_DETECTOR_ID}"[^>]*>[\\s\\S]*?</script>`,
"gi",
),
"",
);
// Create the script tag with proper ID
const scriptTag = `<script id="${ERROR_DETECTOR_ID}">${errorDetectorScript}</script>`;
// If html already has a </head> tag, inject script before it
if (cleanedHtml.includes("</head>")) {
return cleanedHtml.replace("</head>", `${scriptTag}</head>`);
}
// If html already has a <body> tag, inject script after it
else if (cleanedHtml.includes("<body")) {
return cleanedHtml.replace(/<body([^>]*)>/, `<body$1>${scriptTag}`);
}
// Otherwise, wrap the content with proper HTML structure
else {
return `<!DOCTYPE html><html><head>${scriptTag}</head><body>${cleanedHtml}</body></html>`;
}
}, [html]);
return (
<div
ref={ref}
className={classNames(
"w-full border-l border-gray-900 h-full relative z-0 flex items-center justify-center",
{
"lg:p-4": currentTab !== "preview",
"max-lg:h-0": currentTab === "chat",
"max-lg:h-full": currentTab === "preview",
},
)}
onClick={(e) => {
if (isAiWorking) {
e.preventDefault();
e.stopPropagation();
toast.warning("Please wait for the AI to finish working.");
}
}}
>
<GridPattern
x={-1}
y={-1}
strokeDasharray={"4 2"}
className={cn(
"[mask-image:radial-gradient(900px_circle_at_center,white,transparent)]",
)}
/>
{!isAiWorking && hoveredElement && selectedElement && (
<div
className="cursor-pointer absolute bg-sky-500/10 border-[2px] border-dashed border-sky-500 rounded-r-lg rounded-b-lg p-3 z-10 pointer-events-none"
style={{
top:
selectedElement.getBoundingClientRect().top +
(currentTab === "preview" ? 0 : 24),
left:
selectedElement.getBoundingClientRect().left +
(currentTab === "preview" ? 0 : 24),
width: selectedElement.getBoundingClientRect().width,
height: selectedElement.getBoundingClientRect().height,
}}
>
<span className="bg-sky-500 rounded-t-md text-sm text-neutral-100 px-2 py-0.5 -translate-y-7 absolute top-0 left-0">
{htmlTagToText(selectedElement.tagName.toLowerCase())}
</span>
</div>
)}
<iframe
id="preview-iframe"
ref={iframeRef}
title="output"
className={classNames(
"w-full select-none transition-all duration-200 bg-black h-full",
{
"pointer-events-none": isResizing || isAiWorking,
"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]":
currentTab !== "preview" && device === "desktop",
},
)}
srcDoc={htmlWithErrorDetection}
onLoad={() => {
// Clear errors on fresh load as extra safety
onErrors?.([]);
if (iframeRef?.current?.contentWindow?.document?.body) {
iframeRef.current.contentWindow.document.body.scrollIntoView({
block: isAiWorking ? "end" : "start",
inline: "nearest",
behavior: isAiWorking ? "instant" : "smooth",
});
}
}}
/>
</div>
);
};
|