Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johanneslumpe/3cdb000b5f2816a70041c1306edc97f4 to your computer and use it in GitHub Desktop.
Save johanneslumpe/3cdb000b5f2816a70041c1306edc97f4 to your computer and use it in GitHub Desktop.
Selecting a consecutive entity range in draft-js
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