deletecontent.js 7.9 KB

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