UNPKG

2.35 kBJavaScriptView Raw
1/**
2 * Copyright (c) Facebook, Inc. and its affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 * @format
8 *
9 * @emails oncall+draft_js
10 */
11'use strict';
12
13var DraftModifier = require("./DraftModifier");
14
15var EditorState = require("./EditorState");
16
17var getContentStateFragment = require("./getContentStateFragment");
18/**
19 * Transpose the characters on either side of a collapsed cursor, or
20 * if the cursor is at the end of the block, transpose the last two
21 * characters.
22 */
23
24
25function keyCommandTransposeCharacters(editorState) {
26 var selection = editorState.getSelection();
27
28 if (!selection.isCollapsed()) {
29 return editorState;
30 }
31
32 var offset = selection.getAnchorOffset();
33
34 if (offset === 0) {
35 return editorState;
36 }
37
38 var blockKey = selection.getAnchorKey();
39 var content = editorState.getCurrentContent();
40 var block = content.getBlockForKey(blockKey);
41 var length = block.getLength(); // Nothing to transpose if there aren't two characters.
42
43 if (length <= 1) {
44 return editorState;
45 }
46
47 var removalRange;
48 var finalSelection;
49
50 if (offset === length) {
51 // The cursor is at the end of the block. Swap the last two characters.
52 removalRange = selection.set('anchorOffset', offset - 1);
53 finalSelection = selection;
54 } else {
55 removalRange = selection.set('focusOffset', offset + 1);
56 finalSelection = removalRange.set('anchorOffset', offset + 1);
57 } // Extract the character to move as a fragment. This preserves its
58 // styling and entity, if any.
59
60
61 var movedFragment = getContentStateFragment(content, removalRange);
62 var afterRemoval = DraftModifier.removeRange(content, removalRange, 'backward'); // After the removal, the insertion target is one character back.
63
64 var selectionAfter = afterRemoval.getSelectionAfter();
65 var targetOffset = selectionAfter.getAnchorOffset() - 1;
66 var targetRange = selectionAfter.merge({
67 anchorOffset: targetOffset,
68 focusOffset: targetOffset
69 });
70 var afterInsert = DraftModifier.replaceWithFragment(afterRemoval, targetRange, movedFragment);
71 var newEditorState = EditorState.push(editorState, afterInsert, 'insert-fragment');
72 return EditorState.acceptSelection(newEditorState, finalSelection);
73}
74
75module.exports = keyCommandTransposeCharacters;
\No newline at end of file