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.

getContentStateFragment.js.flow 2.1 KiB

пре 3 година
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 { BlockMap } from "./BlockMap";
  13. import type ContentState from "./ContentState";
  14. import type SelectionState from "./SelectionState";
  15. const randomizeBlockMapKeys = require("./randomizeBlockMapKeys");
  16. const removeEntitiesAtEdges = require("./removeEntitiesAtEdges");
  17. const getContentStateFragment = (contentState: ContentState, selectionState: SelectionState): BlockMap => {
  18. const startKey = selectionState.getStartKey();
  19. const startOffset = selectionState.getStartOffset();
  20. const endKey = selectionState.getEndKey();
  21. const endOffset = selectionState.getEndOffset(); // Edge entities should be stripped to ensure that we don't preserve
  22. // invalid partial entities when the fragment is reused. We do, however,
  23. // preserve entities that are entirely within the selection range.
  24. const contentWithoutEdgeEntities = removeEntitiesAtEdges(contentState, selectionState);
  25. const blockMap = contentWithoutEdgeEntities.getBlockMap();
  26. const blockKeys = blockMap.keySeq();
  27. const startIndex = blockKeys.indexOf(startKey);
  28. const endIndex = blockKeys.indexOf(endKey) + 1;
  29. return randomizeBlockMapKeys(blockMap.slice(startIndex, endIndex).map((block, blockKey) => {
  30. const text = block.getText();
  31. const chars = block.getCharacterList();
  32. if (startKey === endKey) {
  33. return block.merge({
  34. text: text.slice(startOffset, endOffset),
  35. characterList: chars.slice(startOffset, endOffset)
  36. });
  37. }
  38. if (blockKey === startKey) {
  39. return block.merge({
  40. text: text.slice(startOffset),
  41. characterList: chars.slice(startOffset)
  42. });
  43. }
  44. if (blockKey === endKey) {
  45. return block.merge({
  46. text: text.slice(0, endOffset),
  47. characterList: chars.slice(0, endOffset)
  48. });
  49. }
  50. return block;
  51. }));
  52. };
  53. module.exports = getContentStateFragment;