Skip to content

Drop in a screenshot and convert it to clean code (HTML/Tailwind/React/Vue)

Python

support to the backend via websockets and display progress to user

Abi Raja53c6b13887f5
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 1b5412c2..152f3280 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -2,10 +2,19 @@ import { useState } from "react";
import ImageUpload from "./components/ImageUpload";
import CodePreview from "./components/CodePreview";
import Preview from "./components/Preview";
+import { generateCode } from "./generateCode";
function App() {
+ const [generatedCode, setGeneratedCode] = useState<string>("");
const [referenceImages, setReferenceImages] = useState<string[]>([]);
+ function startCodeGeneration(referenceImages: string[]) {
+ setReferenceImages(referenceImages);
+ generateCode(referenceImages[0], function (token) {
+ setGeneratedCode((prev) => prev + token);
+ });
+ }
+
return (
<div className="mx-auto mt-10 max-w-2xl">
<h1 className="text-2xl mb-4">Drag & Drop a Screenshot</h1>
@@ -19,11 +28,11 @@ function App() {
{referenceImages.length === 0 && (
<>
- <ImageUpload setReferenceImages={setReferenceImages} />
+ <ImageUpload setReferenceImages={startCodeGeneration} />
</>
)}
- <CodePreview content="Hello World" />
+ <CodePreview content={generatedCode} />
<Preview />
</div>
);
diff --git a/frontend/src/generateCode.ts b/frontend/src/generateCode.ts
new file mode 100644
index 00000000..4770f646
--- /dev/null
+++ b/frontend/src/generateCode.ts
@@ -0,0 +1,42 @@
+import toast from "react-hot-toast";
+
+const WS_BACKEND_URL = "ws://localhost:8000";
+
+export function generateCode(
+ imageUrl: string,
+ onChange: (chunk: string) => void
+) {
+ const ws = new WebSocket(`${WS_BACKEND_URL}/generate-code`);
+
+ ws.addEventListener("open", () => {
+ ws.send(
+ JSON.stringify({
+ image: imageUrl,
+ })
+ );
+ });
+
+ ws.addEventListener("message", async (event: MessageEvent) => {
+ const response = JSON.parse(event.data);
+ if (response.type === "chunk") {
+ onChange(response.value);
+ }
+ });
+
+ ws.addEventListener("close", (event) => {
+ console.log("Connection closed", event.code, event.reason);
+ if (event.code != 1000) {
+ console.error("WebSocket error code", event);
+ toast.error(
+ "We ran into an error. Try again or contact support at [email protected]"
+ );
+ }
+ });
+
+ ws.addEventListener("error", (error) => {
+ console.error("WebSocket error", error);
+ toast.error(
+ "We ran into an error. Try again or contact support at [email protected]"
+ );
+ });
+}