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.flow 1.5 KiB

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