Skip to content

Instantly share code, notes, and snippets.

@JenniferFuBook
Created December 31, 2022 00:44
Show Gist options
  • Save JenniferFuBook/08cd8f6788730a0422790433f65012d4 to your computer and use it in GitHub Desktop.
Save JenniferFuBook/08cd8f6788730a0422790433f65012d4 to your computer and use it in GitHub Desktop.
import React from 'react';
import styles from '../styles/Home.module.css';
const IMAGE_COUNT = 10;
const IMAGE_SIZE = 1024;
const MASK_FILE_PREFIX = 'mask';
export default function Home() {
const [value, setValue] = React.useState<string>('');
const [value2, setValue2] = React.useState<string>('');
const [fileName, setFileName] = React.useState<string>('');
const [prompt, setPrompt] = React.useState<string>('');
const [imageIndex, setImageIndex] = React.useState<number>(0);
const [images, setImages] = React.useState<string[]>([]);
const handleInput = React.useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
setValue(e.target.value);
}, []);
const handleInput2 = React.useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
setValue2(e.target.value);
}, []);
const handleKeyDown = React.useCallback(
async (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
setFileName(value);
setPrompt(value2);
setImageIndex(0);
setImages([]);
const response = await fetch('/api/hello', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
fileName: value,
maskFileName: `${MASK_FILE_PREFIX}-${value}`,
prompt: value2,
n: IMAGE_COUNT,
size: `${IMAGE_SIZE}x${IMAGE_SIZE}`,
}),
});
const data = await response.json();
setValue('');
setValue2('');
setImages(data.result.map((image: {url: string}) => image.url));
}
}, [value, value2]);
const handleNextImage = React.useCallback(() => {
setImageIndex((imageIndex + 1) % IMAGE_COUNT);
}, [imageIndex]);
return (
<main className={styles.main}>
<div>Please type your local file name</div>
<input value={value} onChange={handleInput} />
<div>File name: {fileName ? `${fileName}, Mask file name: ${MASK_FILE_PREFIX}-${fileName}` : fileName} </div>
<div>Please type your prompt</div>
<input value={value2} onChange={handleInput2} onKeyDown={handleKeyDown} />
<div>Prompt: {prompt}</div>
<button onClick={handleNextImage}>Click to view the next image > </button>
{images.length === 0? <div>Loading...</div> :
<iframe
src={images[imageIndex]}
width={IMAGE_SIZE}
height={IMAGE_SIZE}
/>}
</main>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment