Created
May 10, 2016 07:57
-
-
Save johanneslumpe/3cdb000b5f2816a70041c1306edc97f4 to your computer and use it in GitHub Desktop.
Selecting a consecutive entity range in draft-js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const maybeSelectConsecutiveEntity = editorState => { | |
const selection = editorState.getSelection(); | |
if (!selection.isCollapsed()) { | |
return editorState; | |
} | |
const startKey = selection.getStartKey(); | |
const startOffset = selection.getStartOffset(); | |
const prevOffset = startOffset - 1; | |
const block = editorState.getCurrentContent().getBlockForKey(startKey); | |
const characterList = block.getCharacterList(); | |
const prevChar = characterList.get(prevOffset); | |
const nextChar = characterList.get(startOffset); | |
if (!prevChar || !nextChar) { | |
return editorState; | |
} | |
const prevEntity = prevChar.getEntity(); | |
const nextEntity = nextChar.getEntity(); | |
const entity = prevEntity === nextEntity && prevEntity; | |
if (!entity) { | |
return editorState; | |
} | |
let finalPrevOffset = prevOffset; | |
let finalNextOffset = startOffset; | |
while(finalPrevOffset > 0) { | |
finalPrevOffset--; | |
const char = characterList.get(finalPrevOffset); | |
if (char.getEntity() !== entity) { | |
finalPrevOffset++; | |
break; | |
} | |
} | |
const blockLength = block.getLength(); | |
while(finalNextOffset < blockLength) { | |
finalNextOffset++; | |
const char = characterList.get(finalNextOffset); | |
if (char.getEntity() !== entity) { | |
break; | |
} | |
} | |
return EditorState.forceSelection(editorState, selection.merge({ | |
anchorOffset: finalPrevOffset, | |
focusOffset: finalNextOffset, | |
})); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment