quill编辑器嵌套文本标注解决方案:解决重叠标注失效问题

本文探讨在Quill编辑器(版本1.3.7)中处理嵌套文本标注的方案,尤其针对接口返回数据中存在重叠标注范围的情况,导致标注失效的问题。
问题描述:
当Quill编辑器接收包含重叠start和end值的文本标注数据时,标注功能失效。
示例数据:
Quill文本内容:"输出支部盟员担任省人大常委人"
接口返回数据:
const response = {
"errorwordlist": [
{
"start": 9,
"end": 13,
"replacetext": "人大常委会/人大常委会委员/人大常委会组成人员(请根据实际情况选择)",
// ... other properties
},
{
"start": 8,
"end": 13,
"replacetext": "省人大常委会",
// ... other properties
}
],
// ... other properties
};原始代码(存在问题):
使用updateContents方法进行标注:
response.errorwordlist.forEach(item => {
let length = item.end - item.start;
if (length > 0) {
this.editor.updateContents([
{ retain: item.start },
{ retain: length, attributes: { click: item } },
]);
}
});自定义Blot (click):
// ... (Blot代码,略) ...
解决方案:
核心思路是:1. 对标注数据进行排序和合并;2. 修改updateContents逻辑,处理排序后的数据;3. (可选) 优化自定义Blot,使其能更好地处理嵌套结构。
首先,对response.errorwordlist按start值进行升序排序。然后,合并重叠的标注。合并策略:如果一个标注完全包含在另一个标注内,则忽略被包含的标注;如果两个标注部分重叠,则合并成一个新的标注,新的start值为较小的start值,新的end值为较大的end值。
function mergeOverlappingAnnotations(annotations) {
annotations.sort((a, b) => a.start - b.start);
let mergedAnnotations = [];
let currentAnnotation = annotations[0];
for (let i = 1; i < annotations.length; i++) {
let nextAnnotation = annotations[i];
if (nextAnnotation.start <= currentAnnotation.end) {
currentAnnotation.end = Math.max(currentAnnotation.end, nextAnnotation.end);
} else {
mergedAnnotations.push(currentAnnotation);
currentAnnotation = nextAnnotation;
}
}
mergedAnnotations.push(currentAnnotation);
return mergedAnnotations;
}
let mergedAnnotations = mergeOverlappingAnnotations(response.errorwordlist);updateContents逻辑:使用排序后的数据,依次应用标注:
mergedAnnotations.forEach(item => {
let length = item.end - item.start;
if (length > 0) {
this.editor.updateContents([
{ retain: item.start },
{ retain: length, attributes: { click: item } },
]);
}
});如果需要更精细的嵌套控制,可以修改自定义Blot的create方法,使其能够处理嵌套属性,例如,在Blot中递归处理嵌套的标注信息。
最终效果:
通过以上步骤,Quill编辑器能够正确处理重叠的文本标注,呈现预期的嵌套标注效果。 需要注意的是,复杂的嵌套标注可能需要更复杂的Blot设计和数据处理逻辑。 确保你的自定义Blot能够正确地渲染和处理嵌套的属性。
请注意,代码片段中省略了一些细节,例如错误处理和自定义Blot的完整实现。 你需要根据你的实际情况补充完整代码。 这个解决方案提供了一个处理重叠标注的总体思路和关键步骤。
以上就是在Quill编辑器中如何处理文本标注的嵌套问题?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号