UNPKG

2.06 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = clearEmptyBlocks;
7
8var _draftJs = require('draft-js');
9
10function getEmptyCountBefore(contentState, key) {
11 var block = contentState.getBlockBefore(key);
12 if (block && block.getText() === '') {
13 return 1 + getEmptyCountBefore(contentState, block.getKey());
14 }
15 return 0;
16}
17
18function getEmptyCountAfter(contentState, key) {
19 var block = contentState.getBlockAfter(key);
20 if (block && block.getText() === '') {
21 return 1 + getEmptyCountAfter(contentState, block.getKey());
22 }
23 return 0;
24}
25
26function clearEmptyBlocks(editorState) {
27 var CS = editorState.getCurrentContent();
28 var SS = editorState.getSelection();
29 var currentKey = SS.getFocusKey();
30 var currentBlock = CS.getBlockForKey(currentKey);
31
32 var emptyBefore = getEmptyCountBefore(CS, currentKey);
33 var emptyAfter = getEmptyCountAfter(CS, currentKey);
34
35 var MAX_EMPTY_LINES = 2;
36
37 // Be carefull, all checks are very important. And its order of checks also important.
38 // 1. Check hole above current line
39 // 2. Check hole below current line
40 // 3. Check hole between two non-empty lines
41 if (emptyBefore > MAX_EMPTY_LINES || emptyAfter > MAX_EMPTY_LINES || emptyBefore + emptyAfter >= MAX_EMPTY_LINES && currentBlock.getText() === '' && currentBlock !== CS.getLastBlock()) {
42 var keyForRemove = void 0;
43 var keyForFocus = void 0;
44 if (currentBlock.getText() === '') {
45 keyForRemove = currentKey;
46 keyForFocus = CS.getKeyBefore(currentKey);
47 } else {
48 keyForRemove = CS.getKeyBefore(currentKey);
49 keyForFocus = currentKey;
50 }
51
52 var newBlockMap = CS.getBlockMap().delete(keyForRemove);
53 var newCS = new _draftJs.ContentState({ blockMap: newBlockMap });
54 var newEditorState = _draftJs.EditorState.createWithContent(newCS);
55 var newSS = _draftJs.SelectionState.createEmpty(keyForFocus || newCS.getFirstBlock().getKey());
56 var ES = _draftJs.EditorState.forceSelection(newEditorState, newSS);
57
58 return ES;
59 }
60
61 return editorState;
62}
\No newline at end of file