feat: add paste from clipboard

- add paste image from clipboard (ctrl+v)
- validate if the file is an image
This commit is contained in:
Jirawat Boonkumnerd 2023-11-18 06:30:11 +07:00
parent dbf89928ec
commit 3d2978f5d2
No known key found for this signature in database
GPG Key ID: 4ADDC83E1C02CC27
2 changed files with 39 additions and 6 deletions

View File

@ -77,10 +77,12 @@ function App() {
// Initial version creation
function doCreate(referenceImages: string[]) {
setReferenceImages(referenceImages);
doGenerateCode({
generationType: "create",
image: referenceImages[0],
});
if (referenceImages.length > 0) {
doGenerateCode({
generationType: "create",
image: referenceImages[0],
});
}
}
// Subsequent updates

View File

@ -1,4 +1,4 @@
import { useState, useEffect, useMemo } from "react";
import { useState, useEffect, useMemo, useCallback } from "react";
import { useDropzone } from "react-dropzone";
// import { PromptImage } from "../../../types";
import { toast } from "react-hot-toast";
@ -89,6 +89,37 @@ function ImageUpload({ setReferenceImages }: Props) {
},
});
const pasteEvent = useCallback(
(event: ClipboardEvent) => {
const clipboardData = event.clipboardData;
if (!clipboardData) return;
const items = clipboardData.items;
const files = [];
for (let i = 0; i < items.length; i++) {
const file = items[i].getAsFile();
if (file && file.type.startsWith("image/")) {
files.push(file);
}
}
// Convert images to data URLs and set the prompt images state
Promise.all(files.map((file) => fileToDataURL(file)))
.then((dataUrls) => {
setReferenceImages(dataUrls.map((dataUrl) => dataUrl as string));
})
.catch((error) => {
// TODO: Display error to user
console.error("Error reading files:", error);
});
},
[setReferenceImages]
);
useEffect(() => {
window.addEventListener("paste", pasteEvent);
}, [pasteEvent]);
useEffect(() => {
return () => files.forEach((file) => URL.revokeObjectURL(file.preview));
}, [files]); // Added files as a dependency
@ -108,7 +139,7 @@ function ImageUpload({ setReferenceImages }: Props) {
{/* eslint-disable-next-line @typescript-eslint/no-explicit-any */}
<div {...getRootProps({ style: style as any })}>
<input {...getInputProps()} />
<p>Drop a screenshot here, or click to select</p>
<p>Drop a screenshot here, paste from clipboard, or click to select</p>
</div>
</section>
);