Skip to content

Instantly share code, notes, and snippets.

@rikschennink
Created June 13, 2024 07:48
Show Gist options
  • Save rikschennink/09c009ac482662aa38908d569d5de420 to your computer and use it in GitHub Desktop.
Save rikschennink/09c009ac482662aa38908d569d5de420 to your computer and use it in GitHub Desktop.
A quick script to simulate dropping files with a Drag & Drop operation
// drop simulation function
async function runDropSimulation(sources, path, options) {
const { wait = 1000, shouldRelease = true } = options || {};
// create the data transfer
const dataTransfer = new DataTransfer();
for (const src of sources) {
const blob = await fetch(src).then((res) => res.blob());
const file = new File([blob], src.split('/').pop(), { type: blob.type });
dataTransfer.items.add(file);
}
// helper to wait for x milliseconds
const sleep = (time) =>
new Promise((resolve) => {
setTimeout(() => {
resolve();
}, time);
});
// helper to dispatch drag events
const dispatchDragEvent = (point, type, props) => {
document.elementFromPoint(point.x, point.y).dispatchEvent(
new DragEvent(type, {
clientX: point.x,
clientY: point.y,
bubbles: true,
...props,
})
);
};
// we remember last point so we can fire drop when we're done
let lastPoint;
for (const [index, point] of path.entries()) {
await sleep(wait);
const type = index === 0 ? 'dragenter' : 'dragover';
dispatchDragEvent(point, type);
lastPoint = point;
}
// exit if should not drop
if (!shouldRelease) return;
// wait at end
await sleep(wait);
// fire pointerup on last event
dispatchDragEvent(lastPoint, 'drop', {
dataTransfer,
});
}
// how to use
await runDropSimulation(
// the files we are dragging and dropping
[
'./my-package.zip',
'./my-photo.jpeg'
],
// the drag 'n drop path
[
// origin
{
x: 0,
y: 0,
},
// move
{
x: 100,
y: 100,
},
// drop
{
x: 200,
y: 100,
},
],
{
// wait time between coordinates
wait: 1000,
// should fire drop on last coordinate or hold
shouldRelease: true,
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment