我遇到的需求是,根据接口返回的start和end值,在quill中对文本进行标注,标注功能已经开发好,但如果两个词的start和end值存在重叠,标注就会失效。quill版本:1.3.7,主要代码如下。
1、数据如下:
quill文本:输出支部盟员担任省人大常委人
接口数据:
const response = {
"errorWordList": [
{
"alertMessage": "建议用 \"人大常委会/人大常委会委员/人大常委会组成人员(请根据实际情况选择)\" 替换 \"人大常委\"",
"replaceText": "人大常委会/人大常委会委员/人大常委会组成人员(请根据实际情况选择)",
"level": 19,
"tagIds": "90009,90004",
"sourceText": "人大常委",
"start": 9,
"selfWord": 0,
"end": 13,
"id": 1,
"explanation": "输出支部盟员担任省<p style=\"color:red;font-size:15;font-weight:bold;\">人大常委</p>人\\n\\n",
"isTry": 0,
"jdType": 1
},
{
"alertMessage": "建议使用规范用词 \"省人大常委会\"",
"replaceText": "省人大常委会",
"level": 19,
"tagIds": "90009,90004",
"sourceText": "省人大常委",
"start": 8,
"selfWord": 0,
"end": 13,
"id": 2,
"explanation": "输出支部盟员担任省<p style=\"color:red;font-size:15;font-weight:bold;\">人大常委</p>人\\n\\n",
"isTry": 0,
"jdType": 1
}
],
"sensitiveWordList": [],
"privacyList": []
};
2、使用updateContents进行标注:
if (response .errorWordList && response .errorWordList.length > 0){
response .errorWordList.forEach(function (item,index) {
let length = item.end-item.start;
if (length >0){
if (item.start != 0){
this.Editor.updateContents(
[
{ retain: item.start },
{ retain: length , attributes: {click:item}},
]
);
}else{
this.Editor.updateContents(
[
{ retain: length , attributes: {click:item}},
]
);
}
}
});
}
3、自定义blot:
import Quill from 'quill';
import md5 from 'js-md5';
const Inline = Quill.import('blots/inline');
class Click extends Inline {
static create(value) {
let node = super.create(value);
if (value){
let id = value.id;
let jdType = value.jdType;
if (!jdType){
if (value.indexOf("_") != -1){
let array = value.split('_');
if (array && array.length>1){
id = array[1];
jdType = array[0];
if (id && id != 'null' && jdType && jdType != 'null'){
node.setAttribute('data-id', id);
node.setAttribute('data-tab', jdType);
}
}
}
}else{
node.setAttribute('data-tab', jdType);
node.setAttribute('data-id', md5(jdType+'_'+id));
}
let tab = Number(jdType);
if (tab == 1){
node.setAttribute('class', 'error-word-mark');
}else if (tab == 2){
node.setAttribute('class', 'sensitive-word-mark');
}
}
return node;
}
static formats(domNode) {
let tab = domNode.getAttribute('data-tab');
let id = domNode.getAttribute('data-id');
if (tab && tab !='null' && id && id != 'null'){
return tab+'_'+id;
}else{
return null;
}
}
}
Click.blotName = 'click';
Click.tagName = 'span';
export { Click as default };
4、标注效果如下:
<p>输出支部盟员担任<span data-tab="1" data-id="ab35e84a215f0f711ed629c2abb9efa0" class="error-word-mark focus-mark">省人大常委</span>人</p>
5、想要的效果:
<p>输出支部盟员担任<span data-tab="1" data-id="ab35e84a215f0f711ed629c2abb9efa0" class="error-word-mark focus-mark">省<span data-tab="1" data-id="ghjce84a215f0f711ed629c2abb9rhjs" class="error-word-mark">人大常委</span></span>人</p>
这个问题困扰了很久,一直解决不了,期待大家回复,非常感谢!