import React, { useState, useEffect, useRef } from "https://esm.sh/react";
import { createRoot } from "https://esm.sh/react-dom/client";
const MODEL = "claude-3-sonnet-20240229";
function applyDiffs(html, diffs) {
console.log("Applying diffs. Initial HTML:", html);
console.log("Diffs to apply:", diffs);
try {
let replacements;
try {
({ replacements } = JSON.parse(diffs));
console.log("Parsed replacements:", replacements);
} catch (e) {
console.error("Error parsing JSON:", e);
return html;
}
if (!Array.isArray(replacements)) {
console.error("Replacements is not an array:", replacements);
return html;
}
for (const replacement of replacements) {
console.log("Processing replacement:", replacement);
const startLine = replacement.full_start_line?.trim();
const endLine = replacement.full_end_line?.trim();
const newContent = replacement.new_content_without_line_nums;
console.log("Start line:", startLine);
console.log("End line:", endLine);
console.log("New content:", newContent);
if (startLine && endLine && newContent !== undefined) {
const startIndex = html.indexOf(startLine);
const endIndex = html.indexOf(endLine, startIndex) + endLine.length;
console.log("Start index:", startIndex, "End index:", endIndex);
if (startIndex !== -1 && endIndex !== -1) {
html = html.substring(0, startIndex) + newContent + html.substring(endIndex);
} else {
console.log("Start or end line not found in HTML");
}
console.log("HTML after replacement:", html);
}
}
return html;
} catch (error) {
console.error("Error in applyDiffs:", error);
return html;
}
}
function parseHTMLFromResponse(content) {
const htmlMatch = content.match(/```html\s*([\s\S]*?)\s*```/);
console.log("Parsed HTML from response:", htmlMatch && htmlMatch[1] ? htmlMatch[1].trim() : null);
return htmlMatch && htmlMatch[1] ? htmlMatch[1].trim() : null;
}
function parseDiffsFromResponse(content) {
try {
const jsonMatch = content.match(/\{[\s\S]*\}/);
console.log("Parsed diffs from response:", jsonMatch ? jsonMatch[0] : null);
return jsonMatch ? jsonMatch[0] : null;
} catch (e) {
console.error("Error parsing JSON:", e);
return null;
}
}
function App() {
const [messages, setMessages] = useState<Array<{ role: string; content: string }>>([]);
const [edits, setEdits] = useState<Array<{ id: number; content: string }>>([]);
const [input, setInput] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [htmlOutput, setHtmlOutput] = useState("");
const clearInput = () => setInput("");
const messagesEndRef = useRef<HTMLDivElement>(null);
const iframeRef = useRef<HTMLIFrameElement>(null);
useEffect(() => {
if (iframeRef.current) {
const iframeDoc = iframeRef.current.contentDocument;
iframeDoc?.open();
iframeDoc?.write(htmlOutput);
iframeDoc?.close();
}
}, [htmlOutput]);
const sendMessage = async (e?: React.FormEvent) => {
e?.preventDefault();
if (input.trim() === "") return;
const newMessages = [
...messages,
{ role: "user", content: input }
];