You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

moveSelectionForward.js 1.4 KiB

3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 warning = require("fbjs/lib/warning");
  13. /**
  14. * Given a collapsed selection, move the focus `maxDistance` forward within
  15. * the selected block. If the selection will go beyond the end of the block,
  16. * move focus to the start of the next block, but no further.
  17. *
  18. * This function is not Unicode-aware, so surrogate pairs will be treated
  19. * as having length 2.
  20. */
  21. function moveSelectionForward(editorState, maxDistance) {
  22. var selection = editorState.getSelection(); // Should eventually make this an invariant
  23. process.env.NODE_ENV !== "production" ? warning(selection.isCollapsed(), 'moveSelectionForward should only be called with a collapsed SelectionState') : void 0;
  24. var key = selection.getStartKey();
  25. var offset = selection.getStartOffset();
  26. var content = editorState.getCurrentContent();
  27. var focusKey = key;
  28. var focusOffset;
  29. var block = content.getBlockForKey(key);
  30. if (maxDistance > block.getText().length - offset) {
  31. focusKey = content.getKeyAfter(key);
  32. focusOffset = 0;
  33. } else {
  34. focusOffset = offset + maxDistance;
  35. }
  36. return selection.merge({
  37. focusKey: focusKey,
  38. focusOffset: focusOffset
  39. });
  40. }
  41. module.exports = moveSelectionForward;