Merge pull request 'Added file paste/drop support' () from BordedDev/snek:feat/copy-paste-drag-drop into main

Reviewed-on: 
Reviewed-by: retoor <retoor@noreply@molodetz.nl>
This commit is contained in:
retoor 2025-05-06 23:27:25 +02:00
commit b0666a0090

View File

@ -32,11 +32,6 @@
}
function initInputField(textBox) {
textBox.addEventListener('change', (e) => {
e.preventDefault();
this.dispatchEvent(new CustomEvent('change', { detail: e.target.value, bubbles: true }));
});
textBox.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
@ -47,6 +42,54 @@
}
}
});
textBox.addEventListener("paste", async (e) => {
try {
const clipboardItems = await navigator.clipboard.read();
// DataTransfer needs to be used to modify the files list of the input
const dt = new DataTransfer();
for (const clipboardItem of clipboardItems) {
const fileTypes = clipboardItem.types.filter(type => !type.startsWith('text/'))
for (const fileType of fileTypes) {
const blob = await clipboardItem.getType(fileType);
// Do something with the image blob.
dt.items.add(new File([blob], "image.png", { type: fileType }));
}
}
if (dt.items.length > 0) {
const uploadButton = document.querySelector("upload-button");
const input = uploadButton.shadowRoot.querySelector('.file-input')
input.files = dt.files;
await uploadButton.uploadFiles();
}
} catch (error) {
console.error("Failed to read clipboard contents: ", error);
}
});
const chatInput = document.querySelector(".chat-area")
chatInput.addEventListener("drop", async (e) => {
e.preventDefault();
const dt = e.dataTransfer;
if (dt.items.length > 0) {
const uploadButton = document.querySelector("upload-button");
const input = uploadButton.shadowRoot.querySelector('.file-input')
input.files = dt.files;
await uploadButton.uploadFiles();
}
})
chatInput.addEventListener("dragover", async (e) => {
e.preventDefault();
e.dataTransfer.dropEffect = "link";
})
textBox.focus();
}