quill - 文本搜索后如何设置选择?

标签 quill

我正在尝试向 Quill 添加搜索功能,并希望突出显示它找到的文本。我在获取它找到的文本的范围索引时遇到问题,很可能我没有使用正确的方法。

到目前为止,我使用 getContents() 获取文本,并且可以通过迭代各行来查找匹配项。但是,我无法找到 setSelection() 的正确索引位置。第二个问题是我希望窗口滚动到找到选择的位置,但它没有滚动到 View 中。

...
myKeyPhrases = ['obvious', 'orange', 'apple'];

var myDelta = editor.getContents();
myDelta.eachLine((line, attributes, i) => {

    mytext = line.filter((op) => typeof op.insert === 'string').map((op) => op.insert).join('');
    mytext = mytext.toLowerCase();

    ndx = isKeyPhraseFound(mytext, myKeyPhrases); 
    if (ndx >= 0){
        // The code finds the matches OK to here.
        // The next 4 lines don't get the correct range and scroll.
        index = i;
        editor.focus();
        editor.setSelection(index, 1, Quill.sources.USER); 
        editor.scrollIntoView();
        return index;
    }
});

我想要的结果是选择找到的文本匹配项,并且滚动窗口以便显示所选内容。实际结果是选择了错误的文本,并且窗口没有滚动以查看选择。

最佳答案

你基本上就在那里。我怀疑你的问题是你正在过滤掉 block 元素,其作用类似于 Quill 的 getText方法。根据文档:

Non-string content are omitted, so the returned string’s length may be shorter than the editor’s as returned by getLength.

这是因为非文本元素的长度通常为 1,因此对于您省略的每一个元素,您的索引都会漂移 1。

对此的一个简单解决方法是用长度为 1 的换行符替换任何非文本元素,并且带来的额外好处是导致搜索失败(除非您让用户使用换行符进行搜索 - 也许那么您可以选择另一个特殊字符,例如控制字符)。

以下方法应返回 Quill 内容的纯文本表示形式,其长度与 quill.getLength 匹配,因此应该能够使用您想要的任何 JavaScript 文本搜索方法进行搜索(例如 indexOf 用于简单搜索)。

function textContents() {
  return quill.getContents().ops
    .reduce((text, op) => {
      if (typeof op.insert === 'string') {
        // If the op is a string insertion, just concat
        return text + op.insert;
      } else {
        // Otherwise it's a block. Represent this as a newline,
        // which will preserve the length of 1, and also prevent
        // searches matching across the block
        return text + '\n';
      }
    }, '');

}

这是一个粗略的示例:https://codepen.io/alecgibson/pen/GLVzPb

关于quill - 文本搜索后如何设置选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55868019/

相关文章:

reactjs - 如何在 Quill JS (react-quill) 中创建撤销/重做按钮?

mysql - 使用 play 框架从 mysql 读取并插入 mongo(多线程问题)的运行脚本问题

django - QuillJS不适用于textarea

javascript - 羽毛笔列表空白

angular6 - 如何在 JHipster 项目中渲染没有 html 标签的 ngx-quill-editor 内容?

quill - quill可以限制上传图片的大小吗?

angular - 在 ngx quill 字段上粘贴时删除颜色

javascript - 如何在没有 html 标记的情况下显示 React Quill 的内容?

javascript - 如何覆盖 ngx-quill 编辑器链接并使其在同一选项卡中打开?默认情况下它在新选项卡中打开

javascript - 使用 Quill 进行 socket.io 富文本编辑