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.
 
 
 
 

59 line
1.9 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. *
  9. * @emails oncall+draft_js
  10. */
  11. 'use strict';
  12. var randomizeBlockMapKeys = require("./randomizeBlockMapKeys");
  13. var removeEntitiesAtEdges = require("./removeEntitiesAtEdges");
  14. var getContentStateFragment = function getContentStateFragment(contentState, selectionState) {
  15. var startKey = selectionState.getStartKey();
  16. var startOffset = selectionState.getStartOffset();
  17. var endKey = selectionState.getEndKey();
  18. var endOffset = selectionState.getEndOffset(); // Edge entities should be stripped to ensure that we don't preserve
  19. // invalid partial entities when the fragment is reused. We do, however,
  20. // preserve entities that are entirely within the selection range.
  21. var contentWithoutEdgeEntities = removeEntitiesAtEdges(contentState, selectionState);
  22. var blockMap = contentWithoutEdgeEntities.getBlockMap();
  23. var blockKeys = blockMap.keySeq();
  24. var startIndex = blockKeys.indexOf(startKey);
  25. var endIndex = blockKeys.indexOf(endKey) + 1;
  26. return randomizeBlockMapKeys(blockMap.slice(startIndex, endIndex).map(function (block, blockKey) {
  27. var text = block.getText();
  28. var chars = block.getCharacterList();
  29. if (startKey === endKey) {
  30. return block.merge({
  31. text: text.slice(startOffset, endOffset),
  32. characterList: chars.slice(startOffset, endOffset)
  33. });
  34. }
  35. if (blockKey === startKey) {
  36. return block.merge({
  37. text: text.slice(startOffset),
  38. characterList: chars.slice(startOffset)
  39. });
  40. }
  41. if (blockKey === endKey) {
  42. return block.merge({
  43. text: text.slice(0, endOffset),
  44. characterList: chars.slice(0, endOffset)
  45. });
  46. }
  47. return block;
  48. }));
  49. };
  50. module.exports = getContentStateFragment;