* Remove last indentation before cursor, return undefined if no modification is done * * @param {Draft.EditorState} editorState * @return {Draft.EditorState|undefined}
(editorState)
| 13 | * @return {Draft.EditorState|undefined} |
| 14 | */ |
| 15 | function removeIndent(editorState) { |
| 16 | var contentState = editorState.getCurrentContent(); |
| 17 | var selection = editorState.getSelection(); |
| 18 | |
| 19 | if (!selection.isCollapsed()) { |
| 20 | return; |
| 21 | } |
| 22 | |
| 23 | var startKey = selection.getStartKey(); |
| 24 | var startOffset = selection.getStartOffset(); |
| 25 | var currentBlock = contentState.getBlockForKey(startKey); |
| 26 | var blockText = currentBlock.getText(); |
| 27 | |
| 28 | // Detect newline separator and indentation |
| 29 | var newLine = getNewLine(blockText); |
| 30 | var indent = getIndentation(blockText); |
| 31 | |
| 32 | // Get current line |
| 33 | var lines = getLines(blockText, newLine); |
| 34 | var lineAnchor = getLineAnchorForOffset(blockText, startOffset, newLine); |
| 35 | |
| 36 | var currentLine = lines.get(lineAnchor.getLine()); |
| 37 | var beforeSelection = currentLine.slice(0, lineAnchor.getOffset()); |
| 38 | |
| 39 | // If the line before selection ending with the indentation? |
| 40 | if (!endsWith(beforeSelection, indent)) { |
| 41 | return; |
| 42 | } |
| 43 | |
| 44 | // Remove indent |
| 45 | var beforeIndentOffset = startOffset - indent.length; |
| 46 | var rangeToRemove = selection.merge({ |
| 47 | focusKey: startKey, |
| 48 | focusOffset: beforeIndentOffset, |
| 49 | anchorKey: startKey, |
| 50 | anchorOffset: startOffset, |
| 51 | isBackward: true |
| 52 | }); |
| 53 | |
| 54 | var newContentState = Draft.Modifier.removeRange( |
| 55 | contentState, |
| 56 | rangeToRemove, |
| 57 | 'backward' |
| 58 | ); |
| 59 | var newEditorState = Draft.EditorState.push( |
| 60 | editorState, |
| 61 | newContentState, |
| 62 | 'remove-range' |
| 63 | ); |
| 64 | |
| 65 | return Draft.EditorState.forceSelection( |
| 66 | newEditorState, |
| 67 | newContentState.getSelectionAfter() |
| 68 | ); |
| 69 | } |
| 70 | |
| 71 | module.exports = removeIndent; |
no test coverage detected