Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you replace the selection in medium-editor once it's lost?

I am trying to add an extension that replaces the existing link functionality in medium editor to allow me to have a filelist and other custom bits. The problem is that once I show modal and you make some change in it the original selection is lost. The example for inserting code, which looked to be the same thing the main script uses is this which I editing only so far as allowing a selection object to be passed in as a second param.

What I do is on button click show the modal, set some inputs, grab the selection from the base (same as window.getSelection()) save that to extension object. Then on clicking the save button in the modal I use the function from the code insert example, passing the selection. However the selection has changed, so I am guessing it's a reference or calculated everytime maybe, so I'm not sure how to make it work.

Here's code, I trimmed out the unrelated bits:

function MediumLink() {
    var self = this;
    this.parent = true;
    //...button init

    this.modalSubmit.addEventListener('click', function () {
        //the linkSel is no longer what I set it to here
        console.log(self.linkSel);
        self.insertHtmlAtCaret('<a href="' + self.modalHref.value + '">' + self.modalName.value + '</a>', self.linkSel);
        //... hide and reset modal
    }, false);

    //https://github.com/jillix/medium-editor-custom-html
    this.insertHtmlAtCaret = function (html, sel) {
        if (sel === undefined) {
            sel = window.getSelection();
        }
        //..rest of this function is unchanged from example
    };
}
MediumLink.prototype.onClick = function () {
    var sel = this.base.selection;

    if (sel.type === 'Range') { //trying to keep sel from changing since an empty selection would have a different type
        //... set inputs in modal based on the selection

        // sel is what I want at this point, what should be passed 
        console.log(sel);
        this.linkSel = sel;
    }
};
like image 889
urbanpanda Avatar asked Mar 16 '23 23:03

urbanpanda


1 Answers

medium-editor does have support for this built in:

MediumEditor.saveSelection()  // Stores the selection internally
MediumEditor.restoreSelection() // Re-applies the stored selection

From within your extension, since you're setting this.parent = true you can access this.base to call these methods:

this.base.saveSelection()
this.base.restoreSelection()

These built-in helpers should work fine as long as you don't make large alterations to the html (or more specifically the text value itself) between when the selection is saved and when the selection is restored.

like image 62
Nate Mielnik Avatar answered Apr 25 '23 11:04

Nate Mielnik