Drag the file to the cursor position under the mouse

Is it possible to perform a drag and drop operation of a file in the DOM and determine the position / range of the cursor in the DOM, where the mouse pointer is located during the drag and drop operation?

I can easily capture Drop and get the file and contents, but I can’t figure out how to remove the custom HTML markup on the page at the drop point. A drop provides the mouse position, but the question is how to convert this (or something else) to the position and range of the cursor into which I can insert a new link for the file (after I saved it dynamically).

My use case is that I use the Ace Editor (or any contentEditable area) and try to drag the file into the document at the place where the mouse cursor is dropped. Then I want to capture the file and insert a link that refers to 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 work except finding a drag and drop location in a text document .

So, any ideas on how to get the selection range from the drop operation? I have mouse coordinates, but I'm not sure how to correlate them with the text position from which a range can be created to insert my link.

+4
source share
1 answer

This answer is partial, which refers to the part of the Ace editor of the question, but not how to do it using raw DOM operations. I hope someone else has the solution to do this with the raw DOM.

As for the Ace Editor solution, it has supporting APIs that allow you to map positions PageXboth PageYfor matching with physical rows and columns in an editor document using:

var pos = editor.renderer.screenToTextCoordinates(e.pageX, e.pageY)

Using this logic, you can 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;
});
+1
source

Source: https://habr.com/ru/post/1622690/


All Articles