Reputation: 17651
Is there a way that you can do a file drag and drop operation into the DOM and detect the cursor position/range in the DOM where the mouse pointer is during the drop operation?
I can easily capture the Drop and get the file and content, but I can't seem to figure out how to drop custom HTML markup into the page at the drop location. The drop provides a mouse position, but the question is how to convert that (or anything else) into a cursor position and range into which I can paste a new link for the file (after I've saved it dynamically).
My use case is that I'm using Ace Editor (or any contentEditable area) and am trying to drag a file into the document at the location the mouse cursor is dropped. I then want to capture the file, and insert a link that references the capture file data which in this case is captured using the file API and stored on disk using a Web Browser control. I can get everything to works except for detecting the drop location in my text document.
So, any ideas how to acquire a selection range from a drop operation? I have the mouse coordinates, but I'm not sure how to correlate those to a text position from which a range can be created to insert my link into.
Upvotes: 4
Views: 1038
Reputation: 17651
This answer is a partial that addresses the Ace Editor portion of the question, but not how to do this using raw DOM operations. I'm hoping somebody else has a solution to doing this with raw DOM.
As to the Ace Editor solution, it has supporting APIs that allow mapping PageX
and PageY
positions to be mapped to physical row and column positions in the editor document using:
var pos = editor.renderer.screenToTextCoordinates(e.pageX, e.pageY)
Using that logic makes it possible to drop files at the drop position using the following code:
var $el = $("pre[lang]") // editor element
.on("dragover", function(e) {
$(this).addClass("hover");
return false;
})
.on("dragleave", function() {
$(this).removeClass("hover");
return false;
})
.on("drop", function(e) {
e = e.originalEvent;
e.preventDefault();
// grab the file
var file = e.dataTransfer.files[0];
// do something to save the file data to disk or server
var imageUrl = "somelinktoimage";
// Ace Editor logic
var pos = editor.renderer.screenToTextCoordinates(e.pageX, e.pageY);
var sel = te.editor.getSelection();
sel.selectToPosition(pos);
var range = sel.getRange();
range.setStart(pos.row,pos.column);
range.setEnd(pos.row, pos.column);
sel.setSelectionRange(range);
te.editor.getSession().replace(range, "![" + file.name + "](" + imageUrl + ")");
return false;
});
Upvotes: 2