extract html to show a preview for video mode and switch to .srcdoc with throttling for the preview

This commit is contained in:
Abi Raja 2024-03-08 11:16:49 -05:00
parent a0f5af0fdc
commit caa63013f5
4 changed files with 24 additions and 11 deletions

View File

@ -37,6 +37,7 @@ import ImportCodeSection from "./components/ImportCodeSection";
import { Stack } from "./lib/stacks";
import { CodeGenerationModel } from "./lib/models";
import ModelSettingsSection from "./components/ModelSettingsSection";
import { extractHtml } from "./components/preview/extractHtml";
const IS_OPENAI_DOWN = false;
@ -142,9 +143,10 @@ function App() {
cancelCodeGenerationAndReset();
};
const shouldDisablePreview = inputMode === "video";
const previewCode =
shouldDisablePreview && appState === AppState.CODING ? "" : generatedCode;
inputMode === "video" && appState === AppState.CODING
? extractHtml(generatedCode)
: generatedCode;
const cancelCodeGenerationAndReset = () => {
// When this is the first version, reset the entire app state

View File

@ -1,6 +1,6 @@
import { useEffect, useRef } from "react";
import classNames from "classnames";
// import useThrottle from "../hooks/useThrottle";
import useThrottle from "../hooks/useThrottle";
interface Props {
code: string;
@ -8,17 +8,14 @@ interface Props {
}
function Preview({ code, device }: Props) {
const throttledCode = code;
// Temporary disable throttling for the preview not updating when the code changes
// useThrottle(code, 200);
const iframeRef = useRef<HTMLIFrameElement | null>(null);
// Don't update code more often than every 200ms.
const throttledCode = useThrottle(code, 200);
useEffect(() => {
const iframe = iframeRef.current;
if (iframe && iframe.contentDocument) {
iframe.contentDocument.open();
iframe.contentDocument.write(throttledCode);
iframe.contentDocument.close();
if (iframeRef.current) {
iframeRef.current.srcdoc = throttledCode;
}
}, [throttledCode]);

View File

@ -0,0 +1,4 @@
export function extractHtml(code: string): string {
const htmlStartIndex = code.indexOf("<html>");
return htmlStartIndex !== -1 ? code.slice(htmlStartIndex) : "";
}

View File

@ -0,0 +1,10 @@
export function simpleHash(str: string, seed = 0) {
let hash = seed;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = (hash << 5) - hash + char;
hash |= 0; // Convert to 32bit integer
}
return hash;
}