File size: 16,599 Bytes
c0addbd
bc666cc
7bc08d9
11e46c7
c0addbd
 
 
 
 
 
 
 
b9515a8
11e46c7
26f3666
c0addbd
 
 
 
7bc08d9
 
 
 
 
 
c0addbd
9f43bd2
 
c0addbd
50cf5bb
11e46c7
9f43bd2
e586655
 
50cf5bb
05fd38f
67d6774
05fd38f
 
67d6774
05fd38f
 
7bc08d9
 
 
67d6774
7bc08d9
67d6774
7bc08d9
 
 
 
 
50cf5bb
9f43bd2
50cf5bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc666cc
11e46c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc666cc
c0addbd
50cf5bb
7bc08d9
 
 
 
bc666cc
 
c0addbd
 
05fd38f
 
 
bc666cc
11e46c7
 
 
7bc08d9
 
 
 
 
11e46c7
67d6774
 
e586655
 
 
 
 
05fd38f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67d6774
05fd38f
11e46c7
7bc08d9
e586655
bc666cc
 
c0addbd
e586655
bc666cc
50cf5bb
7bc08d9
3a1152b
b9515a8
bc666cc
c0addbd
bc666cc
e586655
 
 
 
 
c0addbd
bc666cc
50cf5bb
11e46c7
7bc08d9
11e46c7
7bc08d9
11e46c7
7bc08d9
11e46c7
 
 
 
7bc08d9
e586655
7bc08d9
 
 
 
05fd38f
67d6774
50cf5bb
 
 
 
 
c0addbd
bc666cc
 
7bc08d9
 
 
 
 
c0addbd
bc666cc
 
c0addbd
 
 
 
 
 
 
 
bc666cc
7bc08d9
 
 
 
 
 
 
bc666cc
c0addbd
bc666cc
c0addbd
 
 
bc666cc
 
05fd38f
7bc08d9
e586655
 
67d6774
26f3666
 
 
 
 
 
 
 
 
e586655
67d6774
7bc08d9
 
e586655
67d6774
 
 
e586655
7bc08d9
bc666cc
7bc08d9
 
 
 
 
67d6774
7bc08d9
 
 
 
67d6774
05fd38f
7bc08d9
 
 
bc666cc
 
 
7bc08d9
 
05fd38f
 
 
67d6774
05fd38f
7bc08d9
67d6774
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26f3666
 
 
 
 
 
 
7bc08d9
 
 
 
67d6774
05fd38f
 
7bc08d9
 
 
05fd38f
 
7bc08d9
 
 
 
c0addbd
7bc08d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67d6774
7bc08d9
 
 
 
67d6774
05fd38f
7bc08d9
 
 
 
 
 
 
c0addbd
7bc08d9
05fd38f
 
 
 
 
 
 
 
 
 
 
 
7bc08d9
05fd38f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67d6774
05fd38f
67d6774
05fd38f
 
 
 
 
 
 
 
67d6774
05fd38f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67d6774
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05fd38f
 
 
 
 
7bc08d9
67d6774
05fd38f
 
 
 
 
 
 
 
 
 
 
67d6774
05fd38f
 
 
 
 
7bc08d9
05fd38f
 
7bc08d9
05fd38f
 
 
 
 
 
 
7bc08d9
 
b9515a8
 
 
 
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
"use client";

import { useState, useEffect, useRef } from "react";
import { useTheme } from "next-themes";
import {
  Code,
  Eye,
  Send,
  Download,
  Copy,
  Maximize2,
  Minimize2,
  FileCode2,
  X,
  Github,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
  ResizableHandle,
  ResizablePanel,
  ResizablePanelGroup,
} from "@/components/ui/resizable";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Message, PreviewState } from "@/lib/types";
// @ts-expect-error
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { customOneDark, customOneLight, generateUUID } from "@/lib/utils";
import DynamicFileRenderer from "@/webzero/preview";
import ThemeToggle from "@/components/ThemeToggle";
import { SidebarTrigger } from "@/components/ui/sidebar";
import { useSessionContext } from "@/context/SessionContext";

function CodeMessageCard({
  version,
  onClick,
}: {
  version: number;
  onClick: () => void;
}) {
  return (
    <div
      onClick={onClick}
      className="bg-muted/50 rounded-lg mb-2 cursor-pointer flex items-center gap-1"
    >
      <div className="mr-2 text-sm">Code v{version}</div>
      <FileCode2 />
    </div>
  );
}

const sendMessage = async (content: string) => {
  const response = await fetch("/api/new", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ content }),
  });

  if (!response.ok) {
    const errorData = await response.json();
    throw new Error(errorData.error || "Failed to send message");
  }

  const data = await response.json();
  return data;
};

const sendIteration = async (
  previousDescription: string,
  newUpdate: string,
  currentCode: string
) => {
  const response = await fetch("/api/iterate", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ previousDescription, newUpdate, currentCode }),
  });

  if (!response.ok) {
    const errorData = await response.json();
    throw new Error(errorData.error || "Failed to process iteration");
  }

  const data = await response.json();
  return data;
};

export function ChatPage() {
  const [message, setMessage] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [currentIteration, setCurrentIteration] = useState<{
    previousDescription: string;
    currentCode: string;
  } | null>(null);
  const [previewState, setPreviewState] = useState<PreviewState>({
    isFullscreen: false,
    isOpen: false,
  });
  const [selectedAIMessage, setSelectedAIMessage] = useState<Message | null>(
    null
  );

  const { theme } = useTheme();
  const isDark = theme === "dark";

  const messagesEndRef = useRef<HTMLDivElement>(null);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  const { sessions, currentSessionId, updateSessionMessages } =
    useSessionContext();

  const currentSession = sessions.find(
    (session) => session.id === currentSessionId
  );

  useEffect(() => {
    setSelectedAIMessage(null);
    setPreviewState((prev) => ({
      ...prev,
      isOpen: false,
      isFullscreen: false,
    }));

    if (currentSession && currentSession.messages.length > 0) {
      const lastAIMessage = currentSession.messages
        .slice()
        .reverse()
        .find((msg) => msg.from === "ai");

      if (lastAIMessage) {
        const precedingUserMessage =
          currentSession.messages[
            currentSession.messages.indexOf(lastAIMessage) - 1
          ];

        if (precedingUserMessage && precedingUserMessage.from === "user") {
          setCurrentIteration({
            previousDescription: precedingUserMessage.content,
            currentCode: lastAIMessage.content,
          });
        } else {
          setCurrentIteration(null);
        }
      } else {
        setCurrentIteration(null);
      }
    } else {
      setCurrentIteration(null);
    }
  }, [currentSessionId]);

  useEffect(() => {
    scrollToBottom();
  }, [currentSession?.messages]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!message.trim() || !currentSessionId) return;

    setIsLoading(true);
    const newUserMessage: Message = {
      id: generateUUID().toString(),
      from: "user",
      content: message,
    };

    const updatedMessages = [
      ...(currentSession?.messages || []),
      newUserMessage,
    ];
    updateSessionMessages(currentSessionId, updatedMessages);
    setMessage("");

    try {
      let response;
      if (currentIteration) {
        response = await sendIteration(
          currentIteration.previousDescription,
          message,
          currentIteration.currentCode
        );
      } else {
        response = await sendMessage(message);
      }

      updateSessionMessages(currentSessionId, [...updatedMessages, response]);
      setCurrentIteration({
        previousDescription: message,
        currentCode: response.content,
      });
      setSelectedAIMessage(response);
      setPreviewState((prev) => ({ ...prev, isOpen: true }));
    } catch (error) {
      console.error("Error:", error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleCopyCode = async (code: string) => {
    try {
      await navigator.clipboard.writeText(code);
    } catch (error) {
      console.error("Failed to copy code:", error);
    }
  };

  const handleDownloadCode = (code: string, filename: string) => {
    const blob = new Blob([code], { type: "text/plain" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = filename;
    a.click();
    URL.revokeObjectURL(url);
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSubmit(e);
    }
  };

  const toggleFullscreen = () => {
    setPreviewState((prev) => ({
      ...prev,
      isFullscreen: !prev.isFullscreen,
    }));
  };

  return (
    <div className={`flex flex-col h-full ${isDark ? "dark" : ""}`}>
      <header className="h-16 border-b flex items-center justify-between px-4 bg-background z-10">
        <div className="flex items-center">
          <SidebarTrigger />
          <ThemeToggle />
          <Button
            variant="ghost"
            size="sm"
            onClick={() =>
              window.open("https://github.com/webzero-org", "_blank")
            }
          >
            <Github />
          </Button>
        </div>
        <h1 className="text-2xl font-bold ml-4">WebZero</h1>
      </header>
      <div className="flex-1 flex overflow-hidden">
        {!currentSession || currentSession.messages.length === 0 ? (
          <div className="flex-1 flex flex-col items-center justify-center p-4 gap-2">
            <h2 className="text-4xl font-bold text-center">
              Welcome to WebZero
            </h2>
            <div className="w-full max-w-md">
              <form onSubmit={handleSubmit} className="relative">
                <Textarea
                  value={message}
                  onChange={(e) => setMessage(e.target.value)}
                  onKeyDown={handleKeyDown}
                  placeholder="Ask webzero a question..."
                  className="min-h-[100px] pr-16 resize-none prompt-box"
                />
                <Button
                  type="submit"
                  size="icon"
                  className="absolute send-button right-3"
                  disabled={isLoading || message.trim() === ""}
                >
                  <Send className="h-4 w-4" />
                </Button>
              </form>
            </div>
          </div>
        ) : (
          <ResizablePanelGroup direction="horizontal" className="flex-1">
            <ResizablePanel
              defaultSize={50}
              minSize={30}
              className={`flex flex-col h-full scrollable`}
            >
              <div className="flex flex-col h-full">
                <ScrollArea className="flex-1 px-4 mt-4 chat-scroll">
                  {currentSession.messages.map((msg, index) => (
                    <div
                      key={msg.id}
                      className={`mb-4 flex ${
                        msg.from === "user" ? "you-message" : ""
                      }`}
                    >
                      <div className="flex items-start max-w-[80%] gap-1">
                        {msg.from === "ai" && (
                          <Avatar>
                            <AvatarImage
                              className={isDark ? "invert" : ""}
                              src="https://raw.githubusercontent.com/webzero-org/website/refs/heads/main/src/app/favicon.svg"
                            />
                            <AvatarFallback>"AI"</AvatarFallback>
                          </Avatar>
                        )}
                        <div
                          className={`p-3 rounded-lg bg-muted ${
                            selectedAIMessage?.id == msg.id
                              ? "selected-card"
                              : ""
                          }`}
                        >
                          {msg.from === "user" ? (
                            <p>{msg.content}</p>
                          ) : (
                            <CodeMessageCard
                              version={(1 + index) / 2}
                              onClick={() => {
                                setSelectedAIMessage(msg);
                                setPreviewState((prev) => ({
                                  ...prev,
                                  isOpen: true,
                                }));
                              }}
                            />
                          )}
                        </div>
                      </div>
                    </div>
                  ))}
                  <div ref={messagesEndRef} />
                </ScrollArea>
                <div className="border-t p-4">
                  <form onSubmit={handleSubmit} className="relative">
                    {isLoading ? (
                      <div className="loader" />
                    ) : (
                      <>
                        <Textarea
                          value={message}
                          onChange={(e) => setMessage(e.target.value)}
                          onKeyDown={handleKeyDown}
                          placeholder={
                            currentIteration
                              ? "Describe your iteration..."
                              : "Ask webzero a question..."
                          }
                          className="min-h-[100px] pr-16 resize-none prompt-box"
                        />
                        <Button
                          type="submit"
                          size="icon"
                          className="absolute send-button right-3"
                          disabled={isLoading || message.trim() === ""}
                        >
                          <Send className="h-4 w-4" />
                        </Button>
                      </>
                    )}
                  </form>
                </div>
              </div>
            </ResizablePanel>
            {previewState.isOpen && (
              <>
                <ResizableHandle />
                <ResizablePanel defaultSize={50} minSize={30}>
                  <div
                    className={`h-full ${
                      previewState.isFullscreen ? "fullscreen-preview" : ""
                    }`}
                  >
                    <Tabs
                      defaultValue="preview"
                      className="h-full flex flex-col"
                    >
                      <div className="border-b px-4 flex justify-between items-center">
                        <TabsList>
                          <TabsTrigger
                            value="preview"
                            className="flex items-center gap-2"
                          >
                            <Eye className="h-4 w-4" /> Preview
                          </TabsTrigger>
                          <TabsTrigger
                            value="code"
                            className="flex items-center gap-1"
                          >
                            <Code className="h-4 w-4" /> Code
                          </TabsTrigger>
                        </TabsList>
                        <div className="flex items-center gap-1 p-2">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() =>
                              handleCopyCode(selectedAIMessage?.content || "")
                            }
                          >
                            <Copy className="h-4 w-4 mr-2" /> Copy
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() =>
                              handleDownloadCode(
                                selectedAIMessage?.content || "",
                                `code-${selectedAIMessage?.id || "unknown"}.tsx`
                              )
                            }
                          >
                            <Download className="h-4 w-4 mr-2" /> Download
                          </Button>
                          <Button
                            variant="ghost"
                            size="icon"
                            onClick={toggleFullscreen}
                          >
                            {previewState.isFullscreen ? (
                              <Minimize2 className="h-4 w-4" />
                            ) : (
                              <Maximize2 className="h-4 w-4" />
                            )}
                          </Button>
                          {previewState.isFullscreen && <ThemeToggle />}
                          {!previewState.isFullscreen && (
                            <Button
                              variant="ghost"
                              size="icon"
                              onClick={() => {
                                setPreviewState((prev) => ({
                                  ...prev,
                                  isOpen: false,
                                }));
                                setSelectedAIMessage(null);
                              }}
                            >
                              <X className="h-4 w-4" />
                            </Button>
                          )}
                        </div>
                      </div>
                      <TabsContent
                        value="preview"
                        className="flex-1 overflow-auto"
                      >
                        <ScrollArea className="h-full scrollable">
                          <div className="p-4">
                            <DynamicFileRenderer
                              id={selectedAIMessage?.id || ""}
                            />
                          </div>
                        </ScrollArea>
                      </TabsContent>
                      <TabsContent
                        value="code"
                        className="flex-1 overflow-auto"
                      >
                        <ScrollArea className="h-full scrollable">
                          <div className="p-4">
                            <SyntaxHighlighter
                              language="typescript"
                              style={isDark ? customOneDark : customOneLight}
                              className="!m-0 !bg-transparent"
                            >
                              {selectedAIMessage?.content || ""}
                            </SyntaxHighlighter>
                          </div>
                        </ScrollArea>
                      </TabsContent>
                    </Tabs>
                  </div>
                </ResizablePanel>
              </>
            )}
          </ResizablePanelGroup>
        )}
      </div>
    </div>
  );
}