Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 47 additions & 5 deletions assets/js/phoenix_live_view/live_socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import {
debug,
maybe,
logError,
eventContainsFiles,
} from "./utils";

import Browser from "./browser";
Expand Down Expand Up @@ -666,14 +667,55 @@ export default class LiveSocket {
},
);
this.on("dragover", (e) => e.preventDefault());
this.on("dragenter", (e) => {
const dropzone = closestPhxBinding(
e.target,
this.binding(PHX_DROP_TARGET),
);

if (!dropzone || !(dropzone instanceof HTMLElement)) {
return;
}

if (eventContainsFiles(e)) {
dropzone.classList.add("phx-files-dropzone");
}
});
this.on("dragleave", (e) => {
const dropzone = closestPhxBinding(
e.target,
this.binding(PHX_DROP_TARGET),
);

if (!dropzone || !(dropzone instanceof HTMLElement)) {
return;
}

// Avoid add/remove jitter in the case that we drag into a new child and that child would
// resolve their closest drop target to the current dropzone element
const rect = dropzone.getBoundingClientRect();
if (
e.clientX <= rect.left ||
e.clientX >= rect.right ||
e.clientY <= rect.top ||
e.clientY >= rect.bottom
) {
dropzone.classList.remove("phx-files-dropzone");
}
});
this.on("drop", (e) => {
e.preventDefault();
const dropTargetId = maybe(
closestPhxBinding(e.target, this.binding(PHX_DROP_TARGET)),
(trueTarget) => {
return trueTarget.getAttribute(this.binding(PHX_DROP_TARGET));
},

const dropzone = closestPhxBinding(
e.target,
this.binding(PHX_DROP_TARGET),
);
if (!dropzone || !(dropzone instanceof HTMLElement)) {
return;
}
dropzone.classList.remove("phx-files-dropzone");

const dropTargetId = dropzone.getAttribute(this.binding(PHX_DROP_TARGET));
const dropTarget = dropTargetId && document.getElementById(dropTargetId);
const files = Array.from(e.dataTransfer.files || []);
if (
Expand Down
11 changes: 11 additions & 0 deletions assets/js/phoenix_live_view/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,14 @@ export const channelUploader = function (entries, onError, resp, liveSocket) {
entryUploader.upload();
});
};

export const eventContainsFiles = (e) => {
if (e.dataTransfer.types) {
for (let i = 0; i < e.dataTransfer.types.length; i++) {
if (e.dataTransfer.types[i] === "Files") {
return true;
}
}
}
return false;
};
Loading