This repository has been archived by the owner on Feb 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathkeyCommandBackspaceToStartOfLine.js
63 lines (54 loc) · 1.96 KB
/
keyCommandBackspaceToStartOfLine.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
* @oncall draft_js
*/
'use strict';
import type {SelectionObject} from 'DraftDOMTypes';
const EditorState = require('EditorState');
const expandRangeToStartOfLine = require('expandRangeToStartOfLine');
const getDraftEditorSelectionWithNodes = require('getDraftEditorSelectionWithNodes');
const moveSelectionBackward = require('moveSelectionBackward');
const removeTextWithStrategy = require('removeTextWithStrategy');
function keyCommandBackspaceToStartOfLine(
editorState: EditorState,
e: SyntheticKeyboardEvent<HTMLElement>,
): EditorState {
const afterRemoval = removeTextWithStrategy(
editorState,
strategyState => {
const selection = strategyState.getSelection();
if (selection.isCollapsed() && selection.getAnchorOffset() === 0) {
return moveSelectionBackward(strategyState, 1);
}
const {ownerDocument} = e.currentTarget;
const domSelection: SelectionObject =
ownerDocument.defaultView.getSelection();
// getRangeAt can technically throw if there's no selection, but we know
// there is one here because text editor has focus (the cursor is a
// selection of length 0). Therefore, we don't need to wrap this in a
// try-catch block.
let range = domSelection.getRangeAt(0);
range = expandRangeToStartOfLine(range);
return getDraftEditorSelectionWithNodes(
strategyState,
null,
range.endContainer,
range.endOffset,
range.startContainer,
range.startOffset,
).selectionState;
},
'backward',
);
if (afterRemoval === editorState.getCurrentContent()) {
return editorState;
}
return EditorState.push(editorState, afterRemoval, 'remove-range');
}
module.exports = keyCommandBackspaceToStartOfLine;