UNPKG

1.58 kBJavaScriptView Raw
1'use strict';
2
3var endsWith = require('ends-with');
4
5var getCurrentIndent = require('./getCurrentIndent');
6var getCurrentCode = require('./getCurrentCode');
7
8/**
9 * User pressed Delete in an editor:
10 * Remove last idnentation before cursor
11 */
12function onBackspace(event, data, change, opts) {
13 var state = change.state;
14
15 if (state.isExpanded) {
16 return;
17 }
18
19 var startOffset = state.startOffset,
20 startText = state.startText;
21
22
23 var currentLine = state.startBlock;
24
25 // Detect and remove indentation at cursor
26 var indent = getCurrentIndent(opts, state);
27 var beforeSelection = currentLine.text.slice(0, startOffset);
28
29 // If the line before selection ending with the indentation?
30 if (endsWith(beforeSelection, indent)) {
31 // Remove indent
32 event.preventDefault();
33
34 return change.deleteBackward(indent.length).focus();
35 }
36
37 // Otherwise check if we are in an empty code container...
38 else if (opts.exitBlockType) {
39 var currentCode = getCurrentCode(opts, state);
40 var isStartOfCode = startOffset === 0 && currentCode.getFirstText() === startText;
41 // PERF: avoid checking for whole currentCode.text
42 var isEmpty = currentCode.nodes.size === 1 && currentLine.text.length === 0;
43
44 if (isStartOfCode && isEmpty) {
45
46 event.preventDefault();
47 // Convert it to default exit type
48 return change.setBlock(opts.exitBlockType).unwrapNodeByKey(currentLine.key);
49 }
50 }
51}
52
53module.exports = onBackspace;
\No newline at end of file