deletecontent.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/controller/deletecontent
  7. */
  8. import LivePosition from '../model/liveposition';
  9. import Position from '../model/position';
  10. import Range from '../model/range';
  11. import Element from '../model/element';
  12. /**
  13. * Deletes content of the selection and merge siblings. The resulting selection is always collapsed.
  14. *
  15. * @param {module:engine/model/selection~Selection} selection Selection of which the content should be deleted.
  16. * @param {module:engine/model/batch~Batch} batch Batch to which the deltas will be added.
  17. * @param {Object} [options]
  18. * @param {Boolean} [options.leaveUnmerged=false] Whether to merge elements after removing the content of the selection.
  19. *
  20. * For example `<heading>x[x</heading><paragraph>y]y</paragraph>` will become:
  21. *
  22. * * `<heading>x^y</heading>` with the option disabled (`leaveUnmerged == false`)
  23. * * `<heading>x^</heading><paragraph>y</paragraph>` with enabled (`leaveUnmerged == true`).
  24. *
  25. * Note: {@link module:engine/model/schema~Schema#objects object} and {@link module:engine/model/schema~Schema#limits limit}
  26. * elements will not be merged.
  27. *
  28. * @param {Boolean} [options.doNotResetEntireContent=false] Whether to skip replacing the entire content with a
  29. * paragraph when the entire content was selected.
  30. *
  31. * For example `<heading>[x</heading><paragraph>y]</paragraph> will become:
  32. *
  33. * * `<paragraph>^</paragraph>` with the option disabled (`doNotResetEntireContent == false`)
  34. * * `<heading>^</heading>` with enabled (`doNotResetEntireContent == true`).
  35. */
  36. export default function deleteContent( selection, batch, options = {} ) {
  37. if ( selection.isCollapsed ) {
  38. return;
  39. }
  40. const schema = batch.document.schema;
  41. // 1. Replace the entire content with paragraph.
  42. // See: https://github.com/ckeditor/ckeditor5-engine/issues/1012#issuecomment-315017594.
  43. if ( !options.doNotResetEntireContent && shouldEntireContentBeReplacedWithParagraph( schema, selection ) ) {
  44. replaceEntireContentWithParagraph( batch, selection );
  45. return;
  46. }
  47. const selRange = selection.getFirstRange();
  48. const startPos = selRange.start;
  49. const endPos = LivePosition.createFromPosition( selRange.end );
  50. // 2. Remove the content if there is any.
  51. if ( !selRange.start.isTouching( selRange.end ) ) {
  52. batch.remove( selRange );
  53. }
  54. // 3. Merge elements in the right branch to the elements in the left branch.
  55. // The only reasonable (in terms of data and selection correctness) case in which we need to do that is:
  56. //
  57. // <heading type=1>Fo[</heading><paragraph>]ar</paragraph> => <heading type=1>Fo^ar</heading>
  58. //
  59. // However, the algorithm supports also merging deeper structures (up to the depth of the shallower branch),
  60. // as it's hard to imagine what should actually be the default behavior. Usually, specific features will
  61. // want to override that behavior anyway.
  62. if ( !options.leaveUnmerged ) {
  63. mergeBranches( batch, startPos, endPos );
  64. // We need to check and strip disallowed attributes in all nested nodes because after merge
  65. // some attributes could end up in a path where are disallowed.
  66. //
  67. // e.g. bold is disallowed for <H1>
  68. // <h1>Fo{o</h1><p>b}a<b>r</b><p> -> <h1>Fo{}a<b>r</b><h1> -> <h1>Fo{}ar<h1>.
  69. schema.removeDisallowedAttributes( startPos.parent.getChildren(), startPos, batch );
  70. }
  71. selection.setCollapsedAt( startPos );
  72. // 4. Autoparagraphing.
  73. // Check if a text is allowed in the new container. If not, try to create a new paragraph (if it's allowed here).
  74. if ( shouldAutoparagraph( schema, startPos ) ) {
  75. insertParagraph( batch, startPos, selection );
  76. }
  77. endPos.detach();
  78. }
  79. // This function is a result of reaching the Ballmer's peak for just the right amount of time.
  80. // Even I had troubles documenting it after a while and after reading it again I couldn't believe that it really works.
  81. function mergeBranches( batch, startPos, endPos ) {
  82. const startParent = startPos.parent;
  83. const endParent = endPos.parent;
  84. // If both positions ended up in the same parent, then there's nothing more to merge:
  85. // <$root><p>x[]</p><p>{}y</p></$root> => <$root><p>xy</p>[]{}</$root>
  86. if ( startParent == endParent ) {
  87. return;
  88. }
  89. // If one of the positions is a root, then there's nothing more to merge (at least in the current state of implementation).
  90. // Theoretically in this case we could unwrap the <p>: <$root>x[]<p>{}y</p></$root>, but we don't need to support it yet
  91. // so let's just abort.
  92. if ( !startParent.parent || !endParent.parent ) {
  93. return;
  94. }
  95. // Check if operations we'll need to do won't need to cross object or limit boundaries.
  96. // E.g., we can't merge endParent into startParent in this case:
  97. // <limit><startParent>x[]</startParent></limit><endParent>{}</endParent>
  98. if ( !checkCanBeMerged( startPos, endPos ) ) {
  99. return;
  100. }
  101. // Remember next positions to merge. For example:
  102. // <a><b>x[]</b></a><c><d>{}y</d></c>
  103. // will become:
  104. // <a><b>xy</b>[]</a><c>{}</c>
  105. startPos = Position.createAfter( startParent );
  106. endPos = Position.createBefore( endParent );
  107. if ( endParent.isEmpty ) {
  108. batch.remove( endParent );
  109. } else {
  110. // At the moment, next startPos is also the position to which the endParent
  111. // needs to be moved:
  112. // <a><b>x[]</b></a><c><d>{}y</d></c>
  113. // becomes:
  114. // <a><b>x</b>[]<d>y</d></a><c>{}</c>
  115. // Move the end parent only if needed.
  116. // E.g. not in this case: <p>ab</p>[]{}<p>cd</p>
  117. if ( !endPos.isEqual( startPos ) ) {
  118. batch.move( endParent, startPos );
  119. }
  120. // To then become:
  121. // <a><b>xy</b>[]</a><c>{}</c>
  122. batch.merge( startPos );
  123. }
  124. // Removes empty end ancestors:
  125. // <a>fo[o</a><b><a><c>bar]</c></a></b>
  126. // becomes:
  127. // <a>fo[]</a><b><a>{}</a></b>
  128. // So we can remove <a> and <b>.
  129. while ( endPos.parent.isEmpty ) {
  130. const parentToRemove = endPos.parent;
  131. endPos = Position.createBefore( parentToRemove );
  132. batch.remove( parentToRemove );
  133. }
  134. // Continue merging next level.
  135. mergeBranches( batch, startPos, endPos );
  136. }
  137. function shouldAutoparagraph( schema, position ) {
  138. const isTextAllowed = schema.check( { name: '$text', inside: position } );
  139. const isParagraphAllowed = schema.check( { name: 'paragraph', inside: position } );
  140. return !isTextAllowed && isParagraphAllowed;
  141. }
  142. // Check if parents of two positions can be merged by checking if there are no limit/object
  143. // boundaries between those two positions.
  144. //
  145. // E.g. in <bQ><p>x[]</p></bQ><widget><caption>{}</caption></widget>
  146. // we'll check <p>, <bQ>, <widget> and <caption>.
  147. // Usually, widget and caption are marked as objects/limits in the schema, so in this case merging will be blocked.
  148. function checkCanBeMerged( leftPos, rightPos ) {
  149. const schema = leftPos.root.document.schema;
  150. const rangeToCheck = new Range( leftPos, rightPos );
  151. for ( const value of rangeToCheck.getWalker() ) {
  152. if ( schema.objects.has( value.item.name ) || schema.limits.has( value.item.name ) ) {
  153. return false;
  154. }
  155. }
  156. return true;
  157. }
  158. function insertParagraph( batch, position, selection ) {
  159. const paragraph = new Element( 'paragraph' );
  160. batch.insert( position, paragraph );
  161. selection.setCollapsedAt( paragraph );
  162. }
  163. function replaceEntireContentWithParagraph( batch, selection ) {
  164. const limitElement = batch.document.schema.getLimitElement( selection );
  165. batch.remove( Range.createIn( limitElement ) );
  166. insertParagraph( batch, Position.createAt( limitElement ), selection );
  167. }
  168. // We want to replace the entire content with a paragraph when:
  169. // * the entire content is selected,
  170. // * selection contains at least two elements,
  171. // * whether the paragraph is allowed in schema in the common ancestor.
  172. function shouldEntireContentBeReplacedWithParagraph( schema, selection ) {
  173. const limitElement = schema.getLimitElement( selection );
  174. if ( !selection.containsEntireContent( limitElement ) ) {
  175. return false;
  176. }
  177. const range = selection.getFirstRange();
  178. if ( range.start.parent == range.end.parent ) {
  179. return false;
  180. }
  181. return schema.check( { name: 'paragraph', inside: limitElement.name } );
  182. }