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.
 
 
 
 

98 lines
2.4 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. /**
  13. * Identify the range to delete from a segmented entity.
  14. *
  15. * Rules:
  16. *
  17. * Example: 'John F. Kennedy'
  18. *
  19. * - Deletion from within any non-whitespace (i.e. ['John', 'F.', 'Kennedy'])
  20. * will return the range of that text.
  21. *
  22. * 'John F. Kennedy' -> 'John F.'
  23. * ^
  24. *
  25. * - Forward deletion of whitespace will remove the following section:
  26. *
  27. * 'John F. Kennedy' -> 'John Kennedy'
  28. * ^
  29. *
  30. * - Backward deletion of whitespace will remove the previous section:
  31. *
  32. * 'John F. Kennedy' -> 'F. Kennedy'
  33. * ^
  34. */
  35. var DraftEntitySegments = {
  36. getRemovalRange: function getRemovalRange(selectionStart, selectionEnd, text, entityStart, direction) {
  37. var segments = text.split(' ');
  38. segments = segments.map(function (
  39. /*string*/
  40. segment,
  41. /*number*/
  42. ii) {
  43. if (direction === 'forward') {
  44. if (ii > 0) {
  45. return ' ' + segment;
  46. }
  47. } else if (ii < segments.length - 1) {
  48. return segment + ' ';
  49. }
  50. return segment;
  51. });
  52. var segmentStart = entityStart;
  53. var segmentEnd;
  54. var segment;
  55. var removalStart = null;
  56. var removalEnd = null;
  57. for (var jj = 0; jj < segments.length; jj++) {
  58. segment = segments[jj];
  59. segmentEnd = segmentStart + segment.length; // Our selection overlaps this segment.
  60. if (selectionStart < segmentEnd && segmentStart < selectionEnd) {
  61. if (removalStart !== null) {
  62. removalEnd = segmentEnd;
  63. } else {
  64. removalStart = segmentStart;
  65. removalEnd = segmentEnd;
  66. }
  67. } else if (removalStart !== null) {
  68. break;
  69. }
  70. segmentStart = segmentEnd;
  71. }
  72. var entityEnd = entityStart + text.length;
  73. var atStart = removalStart === entityStart;
  74. var atEnd = removalEnd === entityEnd;
  75. if (!atStart && atEnd || atStart && !atEnd) {
  76. if (direction === 'forward') {
  77. if (removalEnd !== entityEnd) {
  78. removalEnd++;
  79. }
  80. } else if (removalStart !== entityStart) {
  81. removalStart--;
  82. }
  83. }
  84. return {
  85. start: removalStart,
  86. end: removalEnd
  87. };
  88. }
  89. };
  90. module.exports = DraftEntitySegments;