Home Reference Source

application/components/common/rich-editor/libs/getCurrentlySelectedBlock.js

  1. const getCurrentlySelectedBlock = (editorState) => {
  2. const selection = editorState.getSelection();
  3. const startKey = selection.getStartKey();
  4. let endKey = selection.getEndKey();
  5. const content = editorState.getCurrentContent();
  6. let target = selection;
  7.  
  8. // Triple-click can lead to a selection that includes offset 0 of the
  9. // following block. The `SelectionState` for this case is accurate, but
  10. // we should avoid toggling block type for the trailing block because it
  11. // is a confusing interaction.
  12. if (startKey !== endKey && selection.getEndOffset() === 0) {
  13. const blockBefore = content.getBlockBefore(endKey);
  14. if (!blockBefore) {
  15. throw new Error('Got unexpected null or undefined');
  16. }
  17.  
  18. endKey = blockBefore.getKey();
  19. target = target.merge({
  20. anchorKey: startKey,
  21. anchorOffset: selection.getStartOffset(),
  22. focusKey: endKey,
  23. focusOffset: blockBefore.getLength(),
  24. isBackward: false
  25. });
  26. }
  27.  
  28. const hasAtomicBlock = content.getBlockMap()
  29. .skipWhile((_, k) => k !== startKey)
  30. .takeWhile((_, k) => k !== endKey)
  31. .some(v => v.getType() === 'atomic');
  32.  
  33. const currentBlock = content.getBlockForKey(startKey);
  34.  
  35. return {
  36. content,
  37. currentBlock,
  38. hasAtomicBlock,
  39. target
  40. };
  41. };
  42.  
  43. export default getCurrentlySelectedBlock;