Skip to content

Instantly share code, notes, and snippets.

@juliankrispel
Created October 19, 2018 12:45
Show Gist options
  • Save juliankrispel/5dcd61a91f5d3072289022977f565faf to your computer and use it in GitHub Desktop.
Save juliankrispel/5dcd61a91f5d3072289022977f565faf to your computer and use it in GitHub Desktop.
changing indent of selection
import { EditorState, Modifier } from 'draft-js';
import { TAB_CHARACTER } from './CONSTANTS';
const changeIndent = (editorState, isDedent) => {
const selection = editorState.getSelection();
const contentState = editorState.getCurrentContent();
let blockMap = contentState.getBlockMap();
const blockKeys = blockMap.keySeq();
const selectionStartKey = selection.getStartKey();
const selectionEndKey = selection.getEndKey();
let startKey = selectionStartKey
let endKey = selectionEndKey
const startBlock = contentState.getBlockForKey(startKey);
const endBlock = contentState.getBlockForKey(endKey);
const blockAfterStart = contentState.getBlockAfter(startKey);
const blockBeforeEnd = contentState.getBlockBefore(endKey);
let startOffset = selection.getStartOffset();
let endOffset = selection.getStartOffset();
if (startBlock.getText().length <= startOffset && blockAfterStart != null) {
startKey = blockAfterStart.getKey();
}
if (endOffset === 0 && blockBeforeEnd != null) {
endKey = blockBeforeEnd.getKey();
}
const startIndex = blockKeys.indexOf(startKey);
const endIndex = blockKeys.indexOf(endKey);
const newContentState = blockMap.takeWhile(block => {
const blockIndex = blockKeys.indexOf(block.getKey());
return blockIndex >= startIndex && blockIndex <= endIndex;
}).reduce((newContentState, block) => {
const text = block.getText();
const key = block.getKey();
let newText = `${TAB_CHARACTER}${text}`
if (isDedent === true) {
newText = text.replace(/^\s{1,4}/, '')
}
return Modifier.replaceText(
newContentState,
selection.merge({
anchorKey: key,
focusKey: key,
anchorOffset: 0,
focusOffset: 0,
}),
newText
)
}, contentState);
const newSelection = selection.merge({
anchorOffset:
selection.getAnchorOffset()
+ (
newContentState.getBlockForKey(selection.getAnchorKey()).getText().length
- contentState.getBlockForKey(selection.getAnchorKey()).getText().length
),
focusOffset:
selection.getFocusOffset()
+ (
newContentState.getBlockForKey(selection.getFocusKey()).getText().length
- contentState.getBlockForKey(selection.getFocusKey()).getText().length
),
})
return EditorState.forceSelection(
EditorState.push(
editorState,
newContentState
),
newSelection
);
}
export {
changeIndent
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment