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

75 строки
2.4 KiB

  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. * @flow strict-local
  9. * @emails oncall+draft_js
  10. */
  11. 'use strict';
  12. const DraftModifier = require("./DraftModifier");
  13. const EditorState = require("./EditorState");
  14. const 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: EditorState): EditorState {
  21. const selection = editorState.getSelection();
  22. if (!selection.isCollapsed()) {
  23. return editorState;
  24. }
  25. const offset = selection.getAnchorOffset();
  26. if (offset === 0) {
  27. return editorState;
  28. }
  29. const blockKey = selection.getAnchorKey();
  30. const content = editorState.getCurrentContent();
  31. const block = content.getBlockForKey(blockKey);
  32. const length = block.getLength(); // Nothing to transpose if there aren't two characters.
  33. if (length <= 1) {
  34. return editorState;
  35. }
  36. let removalRange;
  37. let 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. const movedFragment = getContentStateFragment(content, removalRange);
  48. const afterRemoval = DraftModifier.removeRange(content, removalRange, 'backward'); // After the removal, the insertion target is one character back.
  49. const selectionAfter = afterRemoval.getSelectionAfter();
  50. const targetOffset = selectionAfter.getAnchorOffset() - 1;
  51. const targetRange = selectionAfter.merge({
  52. anchorOffset: targetOffset,
  53. focusOffset: targetOffset
  54. });
  55. const afterInsert = DraftModifier.replaceWithFragment(afterRemoval, targetRange, movedFragment);
  56. const newEditorState = EditorState.push(editorState, afterInsert, 'insert-fragment');
  57. return EditorState.acceptSelection(newEditorState, finalSelection);
  58. }
  59. module.exports = keyCommandTransposeCharacters;