一旦丢失,如何替换中型编辑器中的选择?

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

我正在尝试添加一个扩展来替换 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 中现有的 link 功能,我只编辑了允许将选择对象作为第二个参数传入的功能。

我所做的是单击按钮显示模态,设置一些输入,从基础中获取选择(与 window.getSelection() 相同),将其保存到扩展对象。然后单击模式中的保存按钮,我使用代码插入示例中的函数,传递选择。但是选择已经改变了,所以我猜它可能是一个参考或者每次都计算,所以我不确定如何让它工作。

这是代码,我删除了不相关的部分:

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;
    }
};

好的,我认为问题归结为:

如果在执行其他操作时选择丢失,我们如何保存并重现它。

我不知道是否有内置的媒体编辑器功能,但我遇到了同样的问题,简短的回答是使用范围和 X 路径来保存选择。

需要范围来突出显示选择和 X 路径,以便在所有节点和文本中准确选择。

参考这个: How to calculate the XPath position of an element using Javascript?

medium-editor 确实支持这个内置的:

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

在您的扩展中,由于您正在设置 this.parent = true,您可以访问 this.base 来调用这些方法:

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

只要您在保存选择和取消选择之间不对 html(或更具体地说是文本值本身)进行大的改动,这些内置助手应该可以正常工作已恢复。