Skip to content

Instantly share code, notes, and snippets.

@torjusb
Created April 27, 2016 11:29
Show Gist options
  • Save torjusb/7a69c8ed1e20f94b4f73e3db65888d5f to your computer and use it in GitHub Desktop.
Save torjusb/7a69c8ed1e20f94b4f73e3db65888d5f to your computer and use it in GitHub Desktop.
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