Skip to content
This repository was archived by the owner on Aug 16, 2022. It is now read-only.

Commit b8c92fe

Browse files
committed
fix snap to word properly
1 parent 8f740ff commit b8c92fe

File tree

1 file changed

+17
-9
lines changed

1 file changed

+17
-9
lines changed

code/src/content/content.js

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -53,24 +53,32 @@
5353
range.detach();
5454

5555
// modify() works on the focus of the selection
56-
const endNode = sel.focusNode;
57-
const endOffset = sel.focusOffset;
56+
let endNode = sel.focusNode;
57+
let endOffset = sel.focusOffset;
5858
sel.collapse(sel.anchorNode, sel.anchorOffset);
5959
sel.modify('move', direction[0], 'character');
6060
sel.modify('move', direction[1], 'word');
61-
// remove the whitespace after the word
62-
if (direction[0] === 'backward') {
63-
sel.modify('move', 'backward', 'character');
64-
}
6561
sel.extend(endNode, endOffset);
6662
sel.modify('extend', direction[1], 'character');
6763
sel.modify('extend', direction[0], 'word');
68-
// remove the whitespace after the word
69-
if (direction[0] === 'forward') {
64+
65+
// It seems in Chrome when moving a word, it would count the following whitespace of the word.
66+
// A problem with the whitespace is if users repeat the action, the selection would be extended unexpectedly.
67+
// The following code removes that whitespace.
68+
if (direction[0] === 'forward' &&
69+
sel.focusNode.textContent.charAt(sel.focusOffset - 1) === ' ') {
70+
// for the forward selection, the whitespace could appear in the focusNode
7071
sel.modify('extend', 'backward', 'character');
72+
} else if (direction[0] === 'backward' &&
73+
sel.anchorNode.textContent.charAt(sel.anchorOffset - 1) === ' ') {
74+
// for the backward selection, the whitespace could appear in the anchorNode
75+
endNode = sel.focusNode;
76+
endOffset = sel.focusOffset;
77+
sel.collapse(sel.anchorNode, sel.anchorOffset - 1);
78+
sel.extend(endNode, endOffset);
7179
}
7280
}
73-
return sel.toString().trim();
81+
return sel.toString();
7482
};
7583

7684
browser.runtime.onMessage.addListener((request, _, sendResponse) => {

0 commit comments

Comments
 (0)