deletecontent.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. /**
  2. * @license Copyright (c) 2003-2019, 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 Range from '../range';
  10. import DocumentSelection from '../documentselection';
  11. /**
  12. * Deletes content of the selection and merge siblings. The resulting selection is always collapsed.
  13. *
  14. * **Note:** Use {@link module:engine/model/model~Model#deleteContent} instead of this function.
  15. * This function is only exposed to be reusable in algorithms
  16. * which change the {@link module:engine/model/model~Model#deleteContent}
  17. * method's behavior.
  18. *
  19. * @param {module:engine/model/model~Model} model The model in context of which the insertion
  20. * should be performed.
  21. * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection} selection
  22. * Selection of which the content should be deleted.
  23. * @param {module:engine/model/batch~Batch} batch Batch to which the operations will be added.
  24. * @param {Object} [options]
  25. * @param {Boolean} [options.leaveUnmerged=false] Whether to merge elements after removing the content of the selection.
  26. *
  27. * For example `<heading>x[x</heading><paragraph>y]y</paragraph>` will become:
  28. *
  29. * * `<heading>x^y</heading>` with the option disabled (`leaveUnmerged == false`)
  30. * * `<heading>x^</heading><paragraph>y</paragraph>` with enabled (`leaveUnmerged == true`).
  31. *
  32. * Note: {@link module:engine/model/schema~Schema#isObject object} and {@link module:engine/model/schema~Schema#isLimit limit}
  33. * elements will not be merged.
  34. *
  35. * @param {Boolean} [options.doNotResetEntireContent=false] Whether to skip replacing the entire content with a
  36. * paragraph when the entire content was selected.
  37. *
  38. * For example `<heading>[x</heading><paragraph>y]</paragraph>` will become:
  39. *
  40. * * `<paragraph>^</paragraph>` with the option disabled (`doNotResetEntireContent == false`)
  41. * * `<heading>^</heading>` with enabled (`doNotResetEntireContent == true`).
  42. *
  43. * @param {Boolean} [options.doNotAutoparagraph=false] Whether to create a paragraph if after content deletion selection is moved
  44. * to a place where text cannot be inserted.
  45. *
  46. * For example `<paragraph>x</paragraph>[<image src="foo.jpg"></image>]` will become:
  47. *
  48. * * `<paragraph>x</paragraph><paragraph>[]</paragraph>` with the option disabled (`doNotAutoparagraph == false`)
  49. * * `<paragraph>x[]</paragraph>` with the option enabled (`doNotAutoparagraph == true`).
  50. *
  51. * **Note:** if there is no valid position for the selection, the paragraph will always be created:
  52. *
  53. * `[<image src="foo.jpg"></image>]` -> `<paragraph>[]</paragraph>`.
  54. */
  55. export default function deleteContent( model, selection, options = {} ) {
  56. if ( selection.isCollapsed ) {
  57. return;
  58. }
  59. const selRange = selection.getFirstRange();
  60. // If the selection is already removed, don't do anything.
  61. if ( selRange.root.rootName == '$graveyard' ) {
  62. return;
  63. }
  64. const schema = model.schema;
  65. model.change( writer => {
  66. // 1. Replace the entire content with paragraph.
  67. // See: https://github.com/ckeditor/ckeditor5-engine/issues/1012#issuecomment-315017594.
  68. if ( !options.doNotResetEntireContent && shouldEntireContentBeReplacedWithParagraph( schema, selection ) ) {
  69. replaceEntireContentWithParagraph( writer, selection, schema );
  70. return;
  71. }
  72. const startPos = selRange.start;
  73. const endPos = LivePosition.fromPosition( selRange.end, 'toNext' );
  74. // 2. Remove the content if there is any.
  75. if ( !selRange.start.isTouching( selRange.end ) ) {
  76. writer.remove( selRange );
  77. }
  78. // 3. Merge elements in the right branch to the elements in the left branch.
  79. // The only reasonable (in terms of data and selection correctness) case in which we need to do that is:
  80. //
  81. // <heading type=1>Fo[</heading><paragraph>]ar</paragraph> => <heading type=1>Fo^ar</heading>
  82. //
  83. // However, the algorithm supports also merging deeper structures (up to the depth of the shallower branch),
  84. // as it's hard to imagine what should actually be the default behavior. Usually, specific features will
  85. // want to override that behavior anyway.
  86. if ( !options.leaveUnmerged ) {
  87. mergeBranches( writer, startPos, endPos );
  88. // TMP this will be replaced with a postfixer.
  89. // We need to check and strip disallowed attributes in all nested nodes because after merge
  90. // some attributes could end up in a path where are disallowed.
  91. //
  92. // e.g. bold is disallowed for <H1>
  93. // <h1>Fo{o</h1><p>b}a<b>r</b><p> -> <h1>Fo{}a<b>r</b><h1> -> <h1>Fo{}ar<h1>.
  94. schema.removeDisallowedAttributes( startPos.parent.getChildren(), writer );
  95. }
  96. collapseSelectionAt( writer, selection, startPos );
  97. // 4. Add a paragraph to set selection in it.
  98. // Check if a text is allowed in the new container. If not, try to create a new paragraph (if it's allowed here).
  99. if ( shouldAutoparagraph( schema, startPos ) ) {
  100. // If auto-paragraphing is off, find the closest valid selection range and collapse the selection there.
  101. // If there is no valid selection range, create paragraph anyway and set selection there.
  102. const validSelectionRange = schema.getNearestSelectionRange( startPos );
  103. if ( options.doNotAutoparagraph && validSelectionRange ) {
  104. collapseSelectionAt( writer, selection, validSelectionRange );
  105. } else {
  106. insertParagraph( writer, startPos, selection );
  107. }
  108. }
  109. endPos.detach();
  110. } );
  111. }
  112. // This function is a result of reaching the Ballmer's peak for just the right amount of time.
  113. // Even I had troubles documenting it after a while and after reading it again I couldn't believe that it really works.
  114. function mergeBranches( writer, startPos, endPos ) {
  115. const startParent = startPos.parent;
  116. const endParent = endPos.parent;
  117. // If both positions ended up in the same parent, then there's nothing more to merge:
  118. // <$root><p>x[]</p><p>{}y</p></$root> => <$root><p>xy</p>[]{}</$root>
  119. if ( startParent == endParent ) {
  120. return;
  121. }
  122. // If one of the positions is a limit element, then there's nothing to merge because we don't want to cross the limit boundaries.
  123. if ( writer.model.schema.isLimit( startParent ) || writer.model.schema.isLimit( endParent ) ) {
  124. return;
  125. }
  126. // Check if operations we'll need to do won't need to cross object or limit boundaries.
  127. // E.g., we can't merge endParent into startParent in this case:
  128. // <limit><startParent>x[]</startParent></limit><endParent>{}</endParent>
  129. if ( !checkCanBeMerged( startPos, endPos, writer.model.schema ) ) {
  130. return;
  131. }
  132. // Remember next positions to merge. For example:
  133. // <a><b>x[]</b></a><c><d>{}y</d></c>
  134. // will become:
  135. // <a><b>xy</b>[]</a><c>{}</c>
  136. startPos = writer.createPositionAfter( startParent );
  137. endPos = writer.createPositionBefore( endParent );
  138. if ( !endPos.isEqual( startPos ) ) {
  139. // In this case, before we merge, we need to move `endParent` to the `startPos`:
  140. // <a><b>x[]</b></a><c><d>{}y</d></c>
  141. // becomes:
  142. // <a><b>x</b>[]<d>y</d></a><c>{}</c>
  143. writer.insert( endParent, startPos );
  144. }
  145. // Merge two siblings:
  146. // <a>x</a>[]<b>y</b> -> <a>xy</a> (the usual case)
  147. // <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)
  148. writer.merge( startPos );
  149. // Remove empty end ancestors:
  150. // <a>fo[o</a><b><a><c>bar]</c></a></b>
  151. // becomes:
  152. // <a>fo[]</a><b><a>{}</a></b>
  153. // So we can remove <a> and <b>.
  154. while ( endPos.parent.isEmpty ) {
  155. const parentToRemove = endPos.parent;
  156. endPos = writer.createPositionBefore( parentToRemove );
  157. writer.remove( parentToRemove );
  158. }
  159. // Continue merging next level.
  160. mergeBranches( writer, startPos, endPos );
  161. }
  162. function shouldAutoparagraph( schema, position ) {
  163. const isTextAllowed = schema.checkChild( position, '$text' );
  164. const isParagraphAllowed = schema.checkChild( position, 'paragraph' );
  165. return !isTextAllowed && isParagraphAllowed;
  166. }
  167. // Check if parents of two positions can be merged by checking if there are no limit/object
  168. // boundaries between those two positions.
  169. //
  170. // E.g. in <bQ><p>x[]</p></bQ><widget><caption>{}</caption></widget>
  171. // we'll check <p>, <bQ>, <widget> and <caption>.
  172. // Usually, widget and caption are marked as objects/limits in the schema, so in this case merging will be blocked.
  173. function checkCanBeMerged( leftPos, rightPos, schema ) {
  174. const rangeToCheck = new Range( leftPos, rightPos );
  175. for ( const value of rangeToCheck.getWalker() ) {
  176. if ( schema.isLimit( value.item ) ) {
  177. return false;
  178. }
  179. }
  180. return true;
  181. }
  182. function insertParagraph( writer, position, selection ) {
  183. const paragraph = writer.createElement( 'paragraph' );
  184. writer.insert( paragraph, position );
  185. collapseSelectionAt( writer, selection, writer.createPositionAt( paragraph, 0 ) );
  186. }
  187. function replaceEntireContentWithParagraph( writer, selection ) {
  188. const limitElement = writer.model.schema.getLimitElement( selection );
  189. writer.remove( writer.createRangeIn( limitElement ) );
  190. insertParagraph( writer, writer.createPositionAt( limitElement, 0 ), selection );
  191. }
  192. // We want to replace the entire content with a paragraph when:
  193. // * the entire content is selected,
  194. // * selection contains at least two elements,
  195. // * whether the paragraph is allowed in schema in the common ancestor.
  196. function shouldEntireContentBeReplacedWithParagraph( schema, selection ) {
  197. const limitElement = schema.getLimitElement( selection );
  198. if ( !selection.containsEntireContent( limitElement ) ) {
  199. return false;
  200. }
  201. const range = selection.getFirstRange();
  202. if ( range.start.parent == range.end.parent ) {
  203. return false;
  204. }
  205. return schema.checkChild( limitElement, 'paragraph' );
  206. }
  207. // Helper function that sets the selection. Depending whether given `selection` is a document selection or not,
  208. // uses a different method to set it.
  209. function collapseSelectionAt( writer, selection, positionOrRange ) {
  210. if ( selection instanceof DocumentSelection ) {
  211. writer.setSelection( positionOrRange );
  212. } else {
  213. selection.setTo( positionOrRange );
  214. }
  215. }