forked from ianstormtaylor/slate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfix-selection-in-zero-width-block.js
32 lines (30 loc) · 1.16 KB
/
fix-selection-in-zero-width-block.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* Fixes a selection within the DOM when the cursor is in Slate's special
* zero-width block. Slate handles empty blocks in a special manner and the
* cursor can end up either before or after the non-breaking space. This
* causes different behavior in Android and so we make sure the seleciton is
* always before the zero-width space.
*
* @param {Window} window
*/
export default function fixSelectionInZeroWidthBlock(window) {
const domSelection = window.getSelection()
const { anchorNode } = domSelection
const { dataset } = anchorNode.parentElement
const isZeroWidth = dataset ? dataset.slateZeroWidth === 'n' : false
// We are doing three checks to see if we need to move the cursor.
// Is this a zero-width slate span?
// Is the current cursor position not at the start of it?
// Is there more than one character (i.e. the zero-width space char) in here?
if (
isZeroWidth &&
anchorNode.textContent.length === 1 &&
domSelection.anchorOffset !== 0
) {
const range = window.document.createRange()
range.setStart(anchorNode, 0)
range.setEnd(anchorNode, 0)
domSelection.removeAllRanges()
domSelection.addRange(range)
}
}