1 | 'use strict';
|
2 |
|
3 | Object.defineProperty(exports, "__esModule", {
|
4 | value: true
|
5 | });
|
6 | exports.default = clearEmptyBlocks;
|
7 |
|
8 | var _draftJs = require('draft-js');
|
9 |
|
10 | function 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 |
|
18 | function 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 |
|
26 | function 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 |
|
38 |
|
39 |
|
40 |
|
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 |