Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

keyCommandTransposeCharacters.js 2.3 KiB

3 лет назад
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. var DraftModifier = require("./DraftModifier");
  13. var EditorState = require("./EditorState");
  14. var getContentStateFragment = require("./getContentStateFragment");
  15. /**
  16. * Transpose the characters on either side of a collapsed cursor, or
  17. * if the cursor is at the end of the block, transpose the last two
  18. * characters.
  19. */
  20. function keyCommandTransposeCharacters(editorState) {
  21. var selection = editorState.getSelection();
  22. if (!selection.isCollapsed()) {
  23. return editorState;
  24. }
  25. var offset = selection.getAnchorOffset();
  26. if (offset === 0) {
  27. return editorState;
  28. }
  29. var blockKey = selection.getAnchorKey();
  30. var content = editorState.getCurrentContent();
  31. var block = content.getBlockForKey(blockKey);
  32. var length = block.getLength(); // Nothing to transpose if there aren't two characters.
  33. if (length <= 1) {
  34. return editorState;
  35. }
  36. var removalRange;
  37. var finalSelection;
  38. if (offset === length) {
  39. // The cursor is at the end of the block. Swap the last two characters.
  40. removalRange = selection.set('anchorOffset', offset - 1);
  41. finalSelection = selection;
  42. } else {
  43. removalRange = selection.set('focusOffset', offset + 1);
  44. finalSelection = removalRange.set('anchorOffset', offset + 1);
  45. } // Extract the character to move as a fragment. This preserves its
  46. // styling and entity, if any.
  47. var movedFragment = getContentStateFragment(content, removalRange);
  48. var afterRemoval = DraftModifier.removeRange(content, removalRange, 'backward'); // After the removal, the insertion target is one character back.
  49. var selectionAfter = afterRemoval.getSelectionAfter();
  50. var targetOffset = selectionAfter.getAnchorOffset() - 1;
  51. var targetRange = selectionAfter.merge({
  52. anchorOffset: targetOffset,
  53. focusOffset: targetOffset
  54. });
  55. var afterInsert = DraftModifier.replaceWithFragment(afterRemoval, targetRange, movedFragment);
  56. var newEditorState = EditorState.push(editorState, afterInsert, 'insert-fragment');
  57. return EditorState.acceptSelection(newEditorState, finalSelection);
  58. }
  59. module.exports = keyCommandTransposeCharacters;