File size: 13,116 Bytes
25c879d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
869a182
 
 
 
 
 
 
 
 
 
 
25c879d
 
 
 
 
 
 
 
 
869a182
 
 
 
136e687
869a182
 
e04e5ed
0dd540c
 
 
869a182
7e90cf1
 
869a182
 
 
136e687
869a182
 
136e687
869a182
 
 
 
 
 
 
 
 
25c879d
 
 
 
 
869a182
25c879d
869a182
 
 
 
 
 
136e687
 
25c879d
 
136e687
25c879d
7e90cf1
 
 
136e687
7e90cf1
 
25c879d
7e90cf1
 
 
 
136e687
7e90cf1
25c879d
136e687
869a182
 
 
 
 
25c879d
 
 
 
 
869a182
 
 
 
 
 
 
 
 
 
25c879d
869a182
25c879d
869a182
 
 
 
 
 
 
 
e04e5ed
 
25c879d
e04e5ed
 
25c879d
 
 
 
 
869a182
7e90cf1
 
869a182
 
 
 
 
 
 
 
 
 
 
 
 
25c879d
869a182
 
 
 
 
25c879d
7038f00
25c879d
 
869a182
25c879d
869a182
 
 
 
 
 
25c879d
869a182
 
 
 
25c879d
 
 
 
 
85b81db
869a182
85b81db
 
 
 
 
 
 
25c879d
85b81db
 
 
 
 
 
 
25c879d
869a182
 
 
 
25c879d
869a182
 
 
 
 
 
 
 
 
 
 
25c879d
 
869a182
 
25c879d
869a182
 
 
 
 
 
 
 
 
 
 
 
136e687
7e90cf1
136e687
 
869a182
 
 
 
76914ae
869a182
 
 
 
25c879d
869a182
 
 
 
 
76914ae
66f2f84
869a182
 
 
 
 
 
 
 
 
 
 
 
 
136e687
869a182
 
 
 
 
 
 
 
 
 
25c879d
 
 
 
 
 
 
869a182
 
 
 
25c879d
869a182
 
 
 
 
 
 
 
0dd540c
 
 
 
 
 
 
 
 
 
 
 
 
 
25c879d
0dd540c
 
 
 
25c879d
0dd540c
 
 
 
 
 
 
 
 
 
 
 
869a182
25c879d
 
 
 
7e90cf1
 
25c879d
 
 
 
7e90cf1
 
 
 
869a182
0dd540c
 
 
 
 
 
 
 
 
 
 
 
25c879d
0dd540c
 
e04e5ed
 
 
 
 
 
 
 
869a182
 
 
 
 
 
 
 
 
 
 
25c879d
 
869a182
 
 
 
 
e04e5ed
869a182
 
 
 
 
 
 
0dd540c
25c879d
0dd540c
 
 
 
869a182
25c879d
869a182
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
"use client";

import {
  useState,
  forwardRef,
  useImperativeHandle,
  useEffect,
  useRef,
} from "react";
import { DEFAULT_HTML } from "@/lib/constants";
import { PreviewRef } from "@/lib/types";
import {
  MinimizeIcon,
  MaximizeIcon,
  DownloadIcon,
  RefreshIcon,
} from "./ui/icons";
import { useModel } from "@/lib/contexts/model-context";
import { Loader2, Share2 } from "lucide-react";
import { cn } from "@/lib/utils";
import { generateShareLink } from "@/lib/sharelink";
import { ShareDialog } from "./share-dialog";
import posthog from "posthog-js";

interface PreviewProps {
  initialHtml?: string;
  onCodeChange?: (html: string, save?: boolean) => void;
  onAuthErrorChange?: (show: boolean) => void;
  onLoadingChange?: (loading: boolean) => void;
  onErrorChange?: (error: string | null) => void;
  currentVersion?: string;
}

export const Preview = forwardRef<PreviewRef, PreviewProps>(function Preview(
  {
    initialHtml,
    onCodeChange,
    onAuthErrorChange,
    onLoadingChange,
    onErrorChange,
    currentVersion,
  },
  ref,
) {
  const [html, setHtml] = useState<string>(initialHtml || "");
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [isPartialGenerating, setIsPartialGenerating] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [showAuthError, setShowAuthError] = useState(false);
  const [refreshKey, setRefreshKey] = useState(0);
  const [isSharing, setIsSharing] = useState(false);
  const [shareDialogOpen, setShareDialogOpen] = useState(false);
  const [shareUrl, setShareUrl] = useState<string>("");
  const { selectedModelId } = useModel();
  const renderCount = useRef(0);
  const headUpdated = useRef(false);

  // Update html when initialHtml changes
  useEffect(() => {
    if (initialHtml && !isPartialGenerating) {
      setHtml(initialHtml);
    }
  }, [initialHtml, isPartialGenerating]);

  // Update parent component when error changes
  useEffect(() => {
    if (onErrorChange) {
      onErrorChange(error);
    }
  }, [error, onErrorChange]);

  useImperativeHandle(ref, () => ({
    generateCode: async (
      prompt: string,
      colors: string[] = [],
      previousPrompt?: string,
    ) => {
      await generateCode(prompt, colors, previousPrompt);
    },
  }));

  const toggleFullscreen = () => {
    setIsFullscreen(!isFullscreen);
  };

  const partialUpdate = (htmlStr: string) => {
    const parser = new DOMParser();
    const partialDoc = parser.parseFromString(htmlStr, "text/html");
    const iframe = document.querySelector("iframe");
    if (!iframe || !iframe.contentDocument) return;

    const iframeContainer = iframe.contentDocument;
    if (iframeContainer?.body && iframeContainer) {
      iframeContainer.body.innerHTML = partialDoc.body?.innerHTML;
    }
    if (renderCount.current % 10 === 0 && !headUpdated.current) {
      setHtml(htmlStr);
      if (htmlStr.includes("</head>")) {
        setTimeout(() => {
          headUpdated.current = true;
        }, 1000);
      }
    }
    renderCount.current++;
  };

  const downloadHtml = () => {
    if (!html) return;

    // Get current version and generate filename
    // If we have a currentVersion, use it; otherwise omit version part
    const timestamp = new Date()
      .toISOString()
      .replace(/[:.]/g, "-")
      .replace("T", "_")
      .slice(0, 19);

    // Load current version from localStorage if we have an ID
    let versionLabel = "";
    if (currentVersion) {
      versionLabel = `-${currentVersion}`;
    }

    // Format the filename with or without version
    const filename = `novita-anysite-generated${versionLabel}-${timestamp}.html`;

    const blob = new Blob([html], { type: "text/html" });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);
  };

  const refreshPreview = () => {
    if (!html) return;
    setRefreshKey((prev) => prev + 1);
  };

  const generateCode = async (
    prompt: string,
    colors: string[] = [],
    previousPrompt?: string,
  ) => {
    setLoading(true);
    renderCount.current = 0;
    headUpdated.current = false;
    if (onLoadingChange) {
      onLoadingChange(true);
    }
    setError(null);
    setShowAuthError(false);
    if (onAuthErrorChange) {
      onAuthErrorChange(false);
    }

    // Clear HTML content when generation starts
    setHtml("");

    // Initialize generated code variable at function scope so it's accessible in finally block
    let generatedCode = "";

    try {
      // Only include html in the request if it's not DEFAULT_HTML
      const isDefaultHtml = initialHtml === DEFAULT_HTML;

      posthog.capture("Generate code", { model: selectedModelId });

      const response = await fetch("/api/generate-code", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          prompt,
          html: isDefaultHtml ? undefined : html,
          previousPrompt: isDefaultHtml ? undefined : previousPrompt,
          colors,
          modelId: selectedModelId,
        }),
      });

      if (!response.ok) {
        posthog.capture("Generate code", {
          type: "failed",
          model: selectedModelId,
          status: response.status,
        });
        // Check specifically for 401 error (authentication required)
        if (response.status === 401 || response.status === 403) {
          try {
            const errorData = await response.json();
            if (errorData.openLogin) {
              setShowAuthError(true);
              if (onAuthErrorChange) {
                onAuthErrorChange(true);
              }
              throw new Error("Signing in to Hugging Face is required.");
            }
          } catch (e) {
            // Fall back to default auth error handling if JSON parsing fails
            setShowAuthError(true);
            if (onAuthErrorChange) {
              onAuthErrorChange(true);
            }
            throw new Error("Signing in to Hugging Face is required.");
          }
        }

        const errorData = await response.json();
        throw new Error(errorData.message || "Failed to generate code");
      }

      // Handle streaming response
      const reader = response.body?.getReader();
      const decoder = new TextDecoder();
      let lastRenderTime = 0;

      if (reader) {
        while (true) {
          const { done, value } = await reader.read();
          if (done) {
            if (!generatedCode.includes("</html>")) {
              generatedCode += "</html>";
            }
            const finalCode = generatedCode.match(
              /<!DOCTYPE html>[\s\S]*<\/html>/,
            )?.[0];
            if (finalCode) {
              // Update state with the final code
              setHtml(finalCode);
              // Only call onCodeChange once with the final code
              // Add a small delay to ensure all state updates have been applied
              if (onCodeChange) {
                setTimeout(() => {
                  onCodeChange(finalCode, true);
                }, 50);
              }
            }
            setIsPartialGenerating(false);
            break;
          } else {
            setIsPartialGenerating(true);
          }

          const chunkText = decoder.decode(value, { stream: true });
          let parsedChunk: any;
          let appended = false;
          try {
            // Try to parse as JSON
            parsedChunk = JSON.parse(chunkText);
          } catch (parseError) {
            appended = true;
            // If JSON parsing fails, treat it as plain text (backwards compatibility)
            generatedCode += chunkText;
          }
          if (parsedChunk && parsedChunk.type === "error") {
            throw new Error(parsedChunk.message || "An error occurred");
          } else if (!appended) {
            generatedCode += chunkText;
          }
          const newCode = generatedCode.match(/<!DOCTYPE html>[\s\S]*/)?.[0];
          if (newCode) {
            // Force-close the HTML tag so the iframe doesn't render half-finished markup
            let partialDoc = newCode;
            if (!partialDoc.endsWith("</html>")) {
              partialDoc += "\n</html>";
            }

            // Throttle the re-renders to avoid flashing/flicker
            const now = Date.now();
            if (now - lastRenderTime > 200) {
              // Update the UI with partial code, but don't call onCodeChange
              partialUpdate(partialDoc);
              if (onCodeChange) {
                onCodeChange(partialDoc, false);
              }

              lastRenderTime = now;
            }
          }
        }
      }
    } catch (err) {
      const errorMessage =
        (err as Error).message || "An error occurred while generating code";
      posthog.capture("Generate code", {
        type: "failed",
        model: selectedModelId,
        error: errorMessage,
      });
      setError(errorMessage);
      if (onErrorChange) {
        onErrorChange(errorMessage);
      }
      console.error("Error generating code:", err);
    } finally {
      setLoading(false);
      if (onLoadingChange) {
        onLoadingChange(false);
      }
    }
  };

  const handleShare = async () => {
    if (!html) {
      setError("No HTML content to share");
      return;
    }

    setIsSharing(true);
    setError(null);

    try {
      const uploadedUrl = await generateShareLink(html);
      setShareUrl(uploadedUrl);
      setShareDialogOpen(true);
    } catch (err) {
      const errorMessage = (err as Error).message || "Failed to share HTML";
      setError(errorMessage);
      if (onErrorChange) {
        onErrorChange(errorMessage);
      }
      console.error("Error sharing HTML:", err);
    } finally {
      setIsSharing(false);
    }
  };

  const handleShareDialogClose = (open: boolean) => {
    setShareDialogOpen(open);
    if (!open) {
      setShareUrl("");
    }
  };

  return (
    <div
      className={`${isFullscreen ? "fixed inset-0 z-10 bg-novita-dark" : "h-full"} p-4 pl-2`}
    >
      {isPartialGenerating && (
        <div className="w-full bg-slate-50 border-b border-slate-200 py-2 px-4">
          <div className="container mx-auto flex items-center justify-center">
            <div className="flex items-center space-x-2 text-slate-700">
              <Loader2 className="h-4 w-4 animate-spin" />
              <span className="text-sm font-medium">building...</span>
            </div>
          </div>
        </div>
      )}
      <div className="bg-white text-black h-full overflow-hidden relative isolation-auto">
        <div className="absolute top-3 right-3 flex gap-2 z-[100]">
          <button
            onClick={handleShare}
            disabled={isSharing || !html}
            className="bg-novita-gray/90 text-white p-2 px-3 text-xs rounded-md shadow-md hover:bg-novita-gray/70 transition-colors flex items-center justify-center disabled:opacity-50 disabled:cursor-not-allowed"
            aria-label="Share Link"
            title="Share Link"
          >
            {isSharing ? (
              <Loader2 className="h-3 w-3 mr-2 animate-spin" />
            ) : (
              <Share2 className="h-3 w-3 mr-2" />
            )}
            {isSharing ? "Sharing..." : "Share Link"}
          </button>

          <button
            onClick={refreshPreview}
            className="bg-novita-gray/90 text-white p-2 rounded-md shadow-md hover:bg-novita-gray/70 transition-colors flex items-center justify-center"
            aria-label="Refresh Preview"
            title="Refresh Preview"
          >
            <RefreshIcon />
          </button>
          <button
            onClick={downloadHtml}
            className="bg-novita-gray/90 text-white p-2 rounded-md shadow-md hover:bg-novita-gray/70 transition-colors flex items-center justify-center"
            aria-label="Download HTML"
            title="Download HTML"
          >
            <DownloadIcon />
          </button>
          <button
            onClick={toggleFullscreen}
            className="bg-novita-gray/90 text-white p-2 rounded-md shadow-md hover:bg-novita-gray/70 transition-colors flex items-center justify-center"
            aria-label={isFullscreen ? "Exit Fullscreen" : "Full Screen"}
            title={isFullscreen ? "Exit Fullscreen" : "Full Screen"}
          >
            {isFullscreen ? <MinimizeIcon /> : <MaximizeIcon />}
          </button>
        </div>
        <iframe
          key={refreshKey}
          className={cn("relative z-10 w-full h-full select-none", {
            "pointer-events-none": loading,
          })}
          srcDoc={html}
          title="Preview"
        />
      </div>

      <ShareDialog
        open={shareDialogOpen}
        onOpenChange={handleShareDialogClose}
        shareUrl={shareUrl}
      />
    </div>
  );
});