ZuhairAhmed commited on
Commit
11e46c7
·
1 Parent(s): 9f43bd2

working iteration

Browse files
src/app/api/iterate/route.ts ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from "next/server";
2
+ import { promises as fs } from "fs";
3
+ import path from "path";
4
+ import { v4 as uuidv4 } from "uuid";
5
+
6
+ export const runtime = "nodejs";
7
+
8
+ const url = "http://127.0.0.1:7860/api/v1/run/iterate?stream=false";
9
+
10
+ export async function POST(req: NextRequest) {
11
+ try {
12
+ const body = await req.json();
13
+ const { previousDescription, newUpdate, currentCode } = body;
14
+
15
+ const response = await fetch(url, {
16
+ method: "POST",
17
+ headers: {
18
+ "Content-Type": "application/json",
19
+ },
20
+ body: JSON.stringify({
21
+ input_value: `
22
+ ## Previous Description
23
+
24
+ ${previousDescription}
25
+
26
+ ## New Update
27
+
28
+ ${newUpdate}
29
+
30
+ ## Earlier Component Code
31
+
32
+ ${currentCode}
33
+ `,
34
+ output_type: "chat",
35
+ input_type: "chat",
36
+ tweaks: {},
37
+ }),
38
+ });
39
+
40
+ const data = await response.json();
41
+ const code = data.outputs[0].outputs[0].outputs.message.message.text;
42
+ const formattedCode = code.replace(/^```tsx\n|\n```$/g, "");
43
+
44
+ const id = uuidv4();
45
+ const generatedDir = path.resolve(
46
+ process.cwd(),
47
+ "src",
48
+ "components",
49
+ "generated"
50
+ );
51
+ const filename = path.join(generatedDir, `${id}.tsx`);
52
+
53
+ await fs.mkdir(generatedDir, { recursive: true });
54
+ await fs.writeFile(filename, formattedCode, "utf8");
55
+
56
+ return NextResponse.json({
57
+ id,
58
+ from: "ai",
59
+ content: formattedCode,
60
+ });
61
+ } catch (error) {
62
+ console.error("Error in iterate API:", error);
63
+ return NextResponse.json(
64
+ { error: "Failed to process the iteration request" },
65
+ { status: 500 }
66
+ );
67
+ }
68
+ }
src/app/api/new/route.ts CHANGED
@@ -5,7 +5,7 @@ import { v4 as uuidv4 } from "uuid";
5
 
6
  export const runtime = "nodejs";
7
 
8
- const url = "https://web-zero-web-zero.hf.space/api/v1/run/new?stream=false";
9
 
10
  export async function POST(req: NextRequest) {
11
  try {
 
5
 
6
  export const runtime = "nodejs";
7
 
8
+ const url = "http://127.0.0.1:7860/api/v1/run/new?stream=false";
9
 
10
  export async function POST(req: NextRequest) {
11
  try {
src/components/theme-provider.tsx CHANGED
@@ -7,7 +7,6 @@ export function ThemeProvider({ children }: React.PropsWithChildren<{}>) {
7
  return (
8
  <NextThemesProvider
9
  attribute="class"
10
- defaultTheme="system"
11
  enableSystem
12
  disableTransitionOnChange
13
  storageKey="theme"
 
7
  return (
8
  <NextThemesProvider
9
  attribute="class"
 
10
  enableSystem
11
  disableTransitionOnChange
12
  storageKey="theme"
src/webzero/chat-page.tsx CHANGED
@@ -1,18 +1,17 @@
1
  "use client";
2
 
3
- import { useState } from "react";
4
- import { useTheme } from "next-themes"; // Import useTheme for theme management
5
  import {
6
  Code,
7
  Eye,
8
- Sun,
9
- Moon,
10
  Send,
11
  Download,
12
  Copy,
13
  Maximize2,
14
  Minimize2,
15
  FileCode2,
 
16
  } from "lucide-react";
17
  import { Button } from "@/components/ui/button";
18
  import { Textarea } from "@/components/ui/textarea";
@@ -22,7 +21,7 @@ import { Message, PreviewState } from "@/lib/types";
22
  // @ts-expect-error
23
  import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
24
  import { customOneDark, customOneLight, generateUUID } from "@/lib/utils";
25
- import CodeRenderer from "@/webzero/preview";
26
  import ThemeToggle from "@/components/ThemeToggle";
27
 
28
  const sendMessage = async (content: string) => {
@@ -43,6 +42,28 @@ const sendMessage = async (content: string) => {
43
  return data;
44
  };
45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  export function ChatPage() {
47
  const [message, setMessage] = useState("");
48
  const [isLoading, setIsLoading] = useState(false);
@@ -52,9 +73,21 @@ export function ChatPage() {
52
  isFullscreen: false,
53
  isOpen: false,
54
  });
 
55
 
56
- const { theme } = useTheme(); // Get the current theme
57
- const isDark = theme === "dark"; // Determine if the current theme is dark
 
 
 
 
 
 
 
 
 
 
 
58
 
59
  const handleSubmit = async (e: React.FormEvent) => {
60
  e.preventDefault();
@@ -71,8 +104,20 @@ export function ChatPage() {
71
  setMessage("");
72
 
73
  try {
74
- const response = await sendMessage(newMessage.content);
 
 
 
 
 
 
 
 
 
75
  setChatHistory((prev) => [...prev, response]);
 
 
 
76
  } catch (error) {
77
  console.error("Error:", error);
78
  } finally {
@@ -103,16 +148,14 @@ export function ChatPage() {
103
 
104
  return (
105
  <div className={`min-h-screen flex ${isDark ? "dark" : ""}`}>
106
- {/* Main Content */}
107
  <div className="flex flex-1 flex-col w-full">
108
  <header className="h-16 border-b flex items-center justify-between px-4">
109
  <ThemeToggle />
110
  </header>
111
 
112
  <div className="flex flex-1">
113
- {/* Chat/Input Area */}
114
  <div className="flex flex-col flex-1 h-fit">
115
- <ScrollArea className="flex-1 p-4 chat-scroll">
116
  {chatHistory.map((msg) => (
117
  <div
118
  key={msg.id}
@@ -152,7 +195,11 @@ export function ChatPage() {
152
  <Textarea
153
  value={message}
154
  onChange={(e) => setMessage(e.target.value)}
155
- placeholder="Ask webzero a question..."
 
 
 
 
156
  className="min-h-[100px] pr-24 resize-none"
157
  />
158
  <div className="absolute top-2 right-3 flex items-center gap-2">
@@ -166,15 +213,18 @@ export function ChatPage() {
166
  </div>
167
  </div>
168
 
169
- {/* Preview/Code Panel */}
 
 
 
170
  {selectedMessage?.content &&
171
- selectedMessage.from == "ai" &&
172
  previewState.isOpen && (
173
  <div
174
  className={`border-l ${
175
  previewState.isFullscreen
176
  ? "fixed inset-0 z-50 bg-background"
177
- : "flex2 mw66"
178
  }`}
179
  >
180
  <Tabs defaultValue="preview" className="h-full flex flex-col">
@@ -197,14 +247,14 @@ export function ChatPage() {
197
  </TabsTrigger>
198
  </TabsList>
199
 
200
- <div className="p-4 border-b flex justify-end gap-2">
201
  {previewState.isFullscreen && <ThemeToggle />}
202
  <Button
203
  variant="outline"
204
  size="sm"
205
  onClick={() => handleCopyCode(selectedMessage.content)}
206
  >
207
- <Copy />
208
  Copy
209
  </Button>
210
 
@@ -218,7 +268,7 @@ export function ChatPage() {
218
  )
219
  }
220
  >
221
- <Download />
222
  Download
223
  </Button>
224
 
@@ -228,24 +278,37 @@ export function ChatPage() {
228
  onClick={toggleFullscreen}
229
  >
230
  {previewState.isFullscreen ? (
231
- <Minimize2 />
232
  ) : (
233
- <Maximize2 />
234
  )}
235
  </Button>
 
 
 
 
 
 
 
 
 
 
 
 
 
236
  </div>
237
  </div>
238
 
239
  <TabsContent value="preview" className="flex-1 p-4">
240
  <ScrollArea className="preview-scroll">
241
- <CodeRenderer id={selectedMessage.id} />
242
  </ScrollArea>
243
  </TabsContent>
244
 
245
  <TabsContent value="code" className="flex-1">
246
  <ScrollArea className="preview-scroll">
247
  <SyntaxHighlighter
248
- language={"typescript"}
249
  style={isDark ? customOneDark : customOneLight}
250
  className="!m-0 !bg-transparent"
251
  >
 
1
  "use client";
2
 
3
+ import { useState, useEffect } from "react";
4
+ import { useTheme } from "next-themes";
5
  import {
6
  Code,
7
  Eye,
 
 
8
  Send,
9
  Download,
10
  Copy,
11
  Maximize2,
12
  Minimize2,
13
  FileCode2,
14
+ X,
15
  } from "lucide-react";
16
  import { Button } from "@/components/ui/button";
17
  import { Textarea } from "@/components/ui/textarea";
 
21
  // @ts-expect-error
22
  import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
23
  import { customOneDark, customOneLight, generateUUID } from "@/lib/utils";
24
+ import DynamicFileRenderer from "@/webzero/preview";
25
  import ThemeToggle from "@/components/ThemeToggle";
26
 
27
  const sendMessage = async (content: string) => {
 
42
  return data;
43
  };
44
 
45
+ const sendIteration = async (
46
+ previousDescription: string,
47
+ newUpdate: string,
48
+ currentCode: string
49
+ ) => {
50
+ const response = await fetch("/api/iterate", {
51
+ method: "POST",
52
+ headers: {
53
+ "Content-Type": "application/json",
54
+ },
55
+ body: JSON.stringify({ previousDescription, newUpdate, currentCode }),
56
+ });
57
+
58
+ if (!response.ok) {
59
+ const errorData = await response.json();
60
+ throw new Error(errorData.error || "Failed to process iteration");
61
+ }
62
+
63
+ const data = await response.json();
64
+ return data;
65
+ };
66
+
67
  export function ChatPage() {
68
  const [message, setMessage] = useState("");
69
  const [isLoading, setIsLoading] = useState(false);
 
73
  isFullscreen: false,
74
  isOpen: false,
75
  });
76
+ const [previousDescription, setPreviousDescription] = useState<string>("");
77
 
78
+ const { theme } = useTheme();
79
+ const isDark = theme === "dark";
80
+
81
+ useEffect(() => {
82
+ const savedChatHistory = localStorage.getItem("chatHistory");
83
+ if (savedChatHistory) {
84
+ setChatHistory(JSON.parse(savedChatHistory));
85
+ }
86
+ }, []);
87
+
88
+ useEffect(() => {
89
+ localStorage.setItem("chatHistory", JSON.stringify(chatHistory));
90
+ }, [chatHistory]);
91
 
92
  const handleSubmit = async (e: React.FormEvent) => {
93
  e.preventDefault();
 
104
  setMessage("");
105
 
106
  try {
107
+ let response;
108
+ if (selectedMessage && selectedMessage.from === "ai") {
109
+ response = await sendIteration(
110
+ previousDescription,
111
+ message,
112
+ selectedMessage.content
113
+ );
114
+ } else {
115
+ response = await sendMessage(message);
116
+ }
117
  setChatHistory((prev) => [...prev, response]);
118
+ setPreviousDescription(message);
119
+ setSelectedMessage(response);
120
+ setPreviewState((prev) => ({ ...prev, isOpen: true }));
121
  } catch (error) {
122
  console.error("Error:", error);
123
  } finally {
 
148
 
149
  return (
150
  <div className={`min-h-screen flex ${isDark ? "dark" : ""}`}>
 
151
  <div className="flex flex-1 flex-col w-full">
152
  <header className="h-16 border-b flex items-center justify-between px-4">
153
  <ThemeToggle />
154
  </header>
155
 
156
  <div className="flex flex-1">
 
157
  <div className="flex flex-col flex-1 h-fit">
158
+ <ScrollArea className="flex-1 p-4 h-[calc(100vh-8rem)]">
159
  {chatHistory.map((msg) => (
160
  <div
161
  key={msg.id}
 
195
  <Textarea
196
  value={message}
197
  onChange={(e) => setMessage(e.target.value)}
198
+ placeholder={
199
+ selectedMessage && selectedMessage.from === "ai"
200
+ ? "Describe your iteration..."
201
+ : "Ask webzero a question..."
202
+ }
203
  className="min-h-[100px] pr-24 resize-none"
204
  />
205
  <div className="absolute top-2 right-3 flex items-center gap-2">
 
213
  </div>
214
  </div>
215
 
216
+ {previewState.isFullscreen && (
217
+ <div className="fixed inset-0 bg-background/80 backdrop-blur-sm z-40" />
218
+ )}
219
+
220
  {selectedMessage?.content &&
221
+ selectedMessage.from === "ai" &&
222
  previewState.isOpen && (
223
  <div
224
  className={`border-l ${
225
  previewState.isFullscreen
226
  ? "fixed inset-0 z-50 bg-background"
227
+ : "w-1/2"
228
  }`}
229
  >
230
  <Tabs defaultValue="preview" className="h-full flex flex-col">
 
247
  </TabsTrigger>
248
  </TabsList>
249
 
250
+ <div className="flex items-center gap-2">
251
  {previewState.isFullscreen && <ThemeToggle />}
252
  <Button
253
  variant="outline"
254
  size="sm"
255
  onClick={() => handleCopyCode(selectedMessage.content)}
256
  >
257
+ <Copy className="h-4 w-4 mr-2" />
258
  Copy
259
  </Button>
260
 
 
268
  )
269
  }
270
  >
271
+ <Download className="h-4 w-4 mr-2" />
272
  Download
273
  </Button>
274
 
 
278
  onClick={toggleFullscreen}
279
  >
280
  {previewState.isFullscreen ? (
281
+ <Minimize2 className="h-4 w-4" />
282
  ) : (
283
+ <Maximize2 className="h-4 w-4" />
284
  )}
285
  </Button>
286
+
287
+ <Button
288
+ variant="ghost"
289
+ size="icon"
290
+ onClick={() =>
291
+ setPreviewState((prev) => ({
292
+ ...prev,
293
+ isOpen: false,
294
+ }))
295
+ }
296
+ >
297
+ <X className="h-4 w-4" />
298
+ </Button>
299
  </div>
300
  </div>
301
 
302
  <TabsContent value="preview" className="flex-1 p-4">
303
  <ScrollArea className="preview-scroll">
304
+ <DynamicFileRenderer id={selectedMessage.id} />
305
  </ScrollArea>
306
  </TabsContent>
307
 
308
  <TabsContent value="code" className="flex-1">
309
  <ScrollArea className="preview-scroll">
310
  <SyntaxHighlighter
311
+ language="typescript"
312
  style={isDark ? customOneDark : customOneLight}
313
  className="!m-0 !bg-transparent"
314
  >
src/webzero/preview.tsx CHANGED
@@ -7,7 +7,11 @@ interface DynamicFileProps {
7
 
8
  const DynamicFileRenderer: React.FC<DynamicFileProps> = ({ id }) => {
9
  const DynamicComponent = dynamic(
10
- () => import(`../components/generated/${id}.tsx`),
 
 
 
 
11
  {
12
  loading: () => <div>Loading...</div>,
13
  ssr: false,
 
7
 
8
  const DynamicFileRenderer: React.FC<DynamicFileProps> = ({ id }) => {
9
  const DynamicComponent = dynamic(
10
+ () =>
11
+ import(`@/components/generated/${id}`).catch(() => {
12
+ console.error(`Failed to load component with id: ${id}`);
13
+ return () => <div>Error loading component</div>;
14
+ }),
15
  {
16
  loading: () => <div>Loading...</div>,
17
  ssr: false,
tsconfig.json CHANGED
@@ -23,6 +23,12 @@
23
  "@/*": ["./src/*"]
24
  }
25
  },
26
- "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", "pages/api/sendMessage.js"],
27
- "exclude": ["node_modules"]
 
 
 
 
 
 
28
  }
 
23
  "@/*": ["./src/*"]
24
  }
25
  },
26
+ "include": [
27
+ "next-env.d.ts",
28
+ "**/*.ts",
29
+ "**/*.tsx",
30
+ ".next/types/**/*.ts",
31
+ "pages/api/sendMessage.js"
32
+ ],
33
+ "exclude": ["node_modules", "src/components/generated"]
34
  }