'use client' import { Button } from '@/components/ui/button' import { Form } from './form' import { useState } from 'react' import { DragAndDrop } from './draganddrop' const STEPS = { INITIAL: 'INITIAL', LOADING: 'LOADING', PREVIEW: 'PREVIEW', ERROR: 'ERROR', } const toBase64 = (file: File) => { return new Promise((resolve, reject) => { const reader = new FileReader() reader.readAsDataURL(file) reader.onload = () => resolve(reader.result as string) reader.onerror = (error) => reject(error) }) } async function* streamReader(res: Response) { const reader = res.body?.getReader() const decoder = new TextDecoder() if (reader == null) return while (true) { const { done, value } = await reader.read() const chunk = decoder.decode(value) yield chunk if (done) break } } export default function Home() { const [result, setResult] = useState('') const [step, setStep] = useState(STEPS.INITIAL) const transformToCode = async (body: string) => { setStep(STEPS.LOADING) const res = await fetch('/api/generate-code-from-image', { method: 'POST', body, headers: { 'Content-Type': 'application/json', }, }) if (!res.ok || res.body == null) { setStep(STEPS.ERROR) throw new Error('Error al generar el código') } setStep(STEPS.PREVIEW) // leer el streaming de datos for await (const chunk of streamReader(res)) { setResult((prev) => prev + chunk) } } const transformImageToCode = async (file: File) => { const img = await toBase64(file) await transformToCode(JSON.stringify({ img })) } const transformUrlToCode = async (url: string) => { await transformToCode(JSON.stringify({ url })) } const [background, html = ''] = result.split('|||') return (
{step === STEPS.LOADING && (
Loading...
)} {step === STEPS.INITIAL && (
)} {step === STEPS.PREVIEW && (