Created
April 27, 2016 11:29
-
-
Save torjusb/7a69c8ed1e20f94b4f73e3db65888d5f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import { EditorState, Modifier, SelectionState } from 'draft-js'; | |
/** | |
* Will remove the last block in the editor if it's empty. | |
* | |
* @param {EditorState} editorState | |
* @return {EditorState} | |
*/ | |
export default function trimContent(editorState) { | |
const content = editorState.getCurrentContent(); | |
const lastBlock = content.getBlockMap().last(); | |
if (lastBlock.getType() === 'unstyled' && lastBlock.getText().trim() === '') { | |
const blockBefore = content.getBlockBefore(lastBlock.getKey()); | |
const targetRange = new SelectionState({ | |
anchorKey: blockBefore.getKey(), | |
anchorOffset: blockBefore.getLength(), | |
focusKey: lastBlock.getKey(), | |
focusOffset: lastBlock.getLength(), | |
}); | |
const withoutLastBlock = Modifier.removeRange(content, targetRange, 'backward'); | |
return EditorState.push(editorState, withoutLastBlock, 'remove-range'); | |
} | |
return editorState; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment