Skip to content

Commit 53c1909

Browse files
committed
chore(example): avoid re-highlighting the existing selection
1 parent c9ca81a commit 53c1909

File tree

1 file changed

+35
-4
lines changed

1 file changed

+35
-4
lines changed

example/index.js

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -83,11 +83,42 @@ highlighter
8383
});
8484

8585
/**
86-
* attach hooks
86+
* avoid re-highlighting the existing selection
8787
*/
88-
highlighter.hooks.Render.SelectedNodes.tap(
89-
(id, selectedNodes) => selectedNodes.filter(n => n.$node.textContent)
90-
);
88+
function getIds(selected) {
89+
if (!selected || !selected.$node || !selected.$node.parentNode) {
90+
return [];
91+
}
92+
return [
93+
highlighter.getIdByDom(selected.$node.parentNode),
94+
...highlighter.getExtraIdByDom(selected.$node.parentNode)
95+
].filter(i => i)
96+
}
97+
function getIntersection(arrA, arrB) {
98+
const record = {};
99+
const intersection = [];
100+
arrA.forEach(i => record[i] = true);
101+
arrB.forEach(i => record[i] && intersection.push(i) && (record[i] = false));
102+
return intersection;
103+
}
104+
highlighter.hooks.Render.SelectedNodes.tap((id, selectedNodes) => {
105+
selectedNodes = selectedNodes.filter(n => n.$node.textContent);
106+
if (selectedNodes.length === 0) {
107+
return [];
108+
}
109+
110+
const candidates = selectedNodes.slice(1).reduce(
111+
(left, selected) => getIntersection(left, getIds(selected)),
112+
getIds(selectedNodes[0])
113+
);
114+
for (let i = 0; i < candidates.length; i++) {
115+
if (highlighter.getDoms(candidates[i]).length === selectedNodes.length) {
116+
return [];
117+
}
118+
}
119+
120+
return selectedNodes;
121+
});
91122

92123
highlighter.hooks.Serialize.Restore.tap(
93124
source => log('Serialize.Restore hook -', source)

0 commit comments

Comments
 (0)