Allow pasting images (#472)

Fixes #283
This commit is contained in:
Will Chen
2025-06-23 15:33:21 -07:00
committed by GitHub
parent 37fb643f6f
commit fa1fb9cc4d
3 changed files with 50 additions and 1 deletions

View File

@@ -1,4 +1,4 @@
import { useState, useRef } from "react";
import React, { useState, useRef } from "react";
export function useAttachments() {
const [attachments, setAttachments] = useState<File[]>([]);
@@ -45,6 +45,50 @@ export function useAttachments() {
setAttachments([]);
};
const addAttachments = (files: File[]) => {
setAttachments((attachments) => [...attachments, ...files]);
};
const handlePaste = async (e: React.ClipboardEvent) => {
const clipboardData = e.clipboardData;
if (!clipboardData) return;
const items = Array.from(clipboardData.items);
const imageItems = items.filter((item) => item.type.startsWith("image/"));
if (imageItems.length > 0) {
e.preventDefault(); // Prevent default paste behavior for images
const imageFiles: File[] = [];
// Generate base timestamp once to avoid collisions
const baseTimestamp = new Date().toISOString().replace(/[:.]/g, "-");
for (let i = 0; i < imageItems.length; i++) {
const item = imageItems[i];
const file = item.getAsFile();
if (file) {
// Create a more descriptive filename with timestamp and counter
const extension = file.type.split("/")[1] || "png";
const filename =
imageItems.length === 1
? `pasted-image-${baseTimestamp}.${extension}`
: `pasted-image-${baseTimestamp}-${i + 1}.${extension}`;
const newFile = new File([file], filename, {
type: file.type,
});
imageFiles.push(newFile);
}
}
if (imageFiles.length > 0) {
addAttachments(imageFiles);
// Show a brief toast or indication that image was pasted
console.log(`Pasted ${imageFiles.length} image(s) from clipboard`);
}
}
};
return {
attachments,
fileInputRef,
@@ -56,5 +100,6 @@ export function useAttachments() {
handleDragLeave,
handleDrop,
clearAttachments,
handlePaste,
};
}