insertcontent.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/model/utils/insertcontent
  7. */
  8. import Position from '../position';
  9. import LivePosition from '../liveposition';
  10. import Element from '../element';
  11. import Range from '../range';
  12. import log from '@ckeditor/ckeditor5-utils/src/log';
  13. import DocumentSelection from '../documentselection';
  14. /**
  15. * Inserts content into the editor (specified selection) as one would expect the paste
  16. * functionality to work.
  17. *
  18. * **Note:** Use {@link module:engine/model/model~Model#insertContent} instead of this function.
  19. * This function is only exposed to be reusable in algorithms
  20. * which change the {@link module:engine/model/model~Model#insertContent}
  21. * method's behavior.
  22. *
  23. * @param {module:engine/model/model~Model} model The model in context of which the insertion
  24. * should be performed.
  25. * @param {module:engine/model/documentfragment~DocumentFragment|module:engine/model/item~Item} content The content to insert.
  26. * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection} selection
  27. * Selection into which the content should be inserted.
  28. */
  29. export default function insertContent( model, content, selection ) {
  30. model.change( writer => {
  31. if ( !selection.isCollapsed ) {
  32. model.deleteContent( selection );
  33. }
  34. const insertion = new Insertion( model, writer, selection.anchor );
  35. let nodesToInsert;
  36. if ( content.is( 'documentFragment' ) ) {
  37. nodesToInsert = content.getChildren();
  38. } else {
  39. nodesToInsert = [ content ];
  40. }
  41. insertion.handleNodes( nodesToInsert, {
  42. // The set of children being inserted is the only set in this context
  43. // so it's the first and last (it's a hack ;)).
  44. isFirst: true,
  45. isLast: true
  46. } );
  47. const newRange = insertion.getSelectionRange();
  48. /* istanbul ignore else */
  49. if ( newRange ) {
  50. if ( selection instanceof DocumentSelection ) {
  51. writer.setSelection( newRange );
  52. } else {
  53. selection.setTo( newRange );
  54. }
  55. } else {
  56. // We are not testing else because it's a safe check for unpredictable edge cases:
  57. // an insertion without proper range to select.
  58. /**
  59. * Cannot determine a proper selection range after insertion.
  60. *
  61. * @warning insertcontent-no-range
  62. */
  63. log.warn( 'insertcontent-no-range: Cannot determine a proper selection range after insertion.' );
  64. }
  65. } );
  66. }
  67. /**
  68. * Utility class for performing content insertion.
  69. *
  70. * @private
  71. */
  72. class Insertion {
  73. constructor( model, writer, position ) {
  74. /**
  75. * The model in context of which the insertion should be performed.
  76. *
  77. * @member {module:engine/model~Model} #model
  78. */
  79. this.model = model;
  80. /**
  81. * Batch to which deltas will be added.
  82. *
  83. * @member {module:engine/controller/writer~Batch} #writer
  84. */
  85. this.writer = writer;
  86. /**
  87. * The position at which (or near which) the next node will be inserted.
  88. *
  89. * @member {module:engine/model/position~Position} #position
  90. */
  91. this.position = position;
  92. /**
  93. * Elements with which the inserted elements can be merged.
  94. *
  95. * <p>x^</p><p>y</p> + <p>z</p> (can merge to <p>x</p>)
  96. * <p>x</p><p>^y</p> + <p>z</p> (can merge to <p>y</p>)
  97. * <p>x^y</p> + <p>z</p> (can merge to <p>xy</p> which will be split during the action,
  98. * so both its pieces will be added to this set)
  99. *
  100. *
  101. * @member {Set} #canMergeWith
  102. */
  103. this.canMergeWith = new Set( [ this.position.parent ] );
  104. /**
  105. * Schema of the model.
  106. *
  107. * @member {module:engine/model/schema~Schema} #schema
  108. */
  109. this.schema = model.schema;
  110. this._filterAttributesOf = [];
  111. }
  112. /**
  113. * Handles insertion of a set of nodes.
  114. *
  115. * @param {Iterable.<module:engine/model/node~Node>} nodes Nodes to insert.
  116. * @param {Object} parentContext Context in which parent of these nodes was supposed to be inserted.
  117. * If the parent context is passed it means that the parent element was stripped (was not allowed).
  118. */
  119. handleNodes( nodes, parentContext ) {
  120. nodes = Array.from( nodes );
  121. for ( let i = 0; i < nodes.length; i++ ) {
  122. const node = nodes[ i ];
  123. this._handleNode( node, {
  124. isFirst: i === 0 && parentContext.isFirst,
  125. isLast: ( i === ( nodes.length - 1 ) ) && parentContext.isLast
  126. } );
  127. }
  128. // TMP this will become a postfixer.
  129. this.schema.removeDisallowedAttributes( this._filterAttributesOf, this.writer );
  130. this._filterAttributesOf = [];
  131. }
  132. /**
  133. * Returns range to be selected after insertion.
  134. * Returns null if there is no valid range to select after insertion.
  135. *
  136. * @returns {module:engine/model/range~Range|null}
  137. */
  138. getSelectionRange() {
  139. if ( this.nodeToSelect ) {
  140. return Range.createOn( this.nodeToSelect );
  141. }
  142. return this.model.document.getNearestSelectionRange( this.position );
  143. }
  144. /**
  145. * Handles insertion of a single node.
  146. *
  147. * @param {module:engine/model/node~Node} node
  148. * @param {Object} context
  149. * @param {Boolean} context.isFirst Whether the given node is the first one in the content to be inserted.
  150. * @param {Boolean} context.isLast Whether the given node is the last one in the content to be inserted.
  151. */
  152. _handleNode( node, context ) {
  153. // Let's handle object in a special way.
  154. // * They should never be merged with other elements.
  155. // * If they are not allowed in any of the selection ancestors, they could be either autoparagraphed or totally removed.
  156. if ( this.schema.isObject( node ) ) {
  157. this._handleObject( node, context );
  158. return;
  159. }
  160. // Try to find a place for the given node.
  161. // Split the position.parent's branch up to a point where the node can be inserted.
  162. // If it isn't allowed in the whole branch, then of course don't split anything.
  163. const isAllowed = this._checkAndSplitToAllowedPosition( node, context );
  164. if ( !isAllowed ) {
  165. this._handleDisallowedNode( node, context );
  166. return;
  167. }
  168. this._insert( node );
  169. // After the node was inserted we may try to merge it with its siblings.
  170. // This should happen only if it was the first and/or last of the nodes (so only with boundary nodes)
  171. // and only if the selection was in those elements initially.
  172. //
  173. // E.g.:
  174. // <p>x^</p> + <p>y</p> => <p>x</p><p>y</p> => <p>xy[]</p>
  175. // and:
  176. // <p>x^y</p> + <p>z</p> => <p>x</p>^<p>y</p> + <p>z</p> => <p>x</p><p>y</p><p>z</p> => <p>xy[]z</p>
  177. // but:
  178. // <p>x</p><p>^</p><p>z</p> + <p>y</p> => <p>x</p><p>y</p><p>z</p> (no merging)
  179. // <p>x</p>[<img>]<p>z</p> + <p>y</p> => <p>x</p><p>y</p><p>z</p> (no merging, note: after running deletetContents
  180. // it's exactly the same case as above)
  181. this._mergeSiblingsOf( node, context );
  182. }
  183. /**
  184. * @param {module:engine/model/element~Element} node The object element.
  185. * @param {Object} context
  186. */
  187. _handleObject( node, context ) {
  188. // Try finding it a place in the tree.
  189. if ( this._checkAndSplitToAllowedPosition( node ) ) {
  190. this._insert( node );
  191. }
  192. // Try autoparagraphing.
  193. else {
  194. this._tryAutoparagraphing( node, context );
  195. }
  196. }
  197. /**
  198. * @param {module:engine/model/node~Node} node The disallowed node which needs to be handled.
  199. * @param {Object} context
  200. */
  201. _handleDisallowedNode( node, context ) {
  202. // If the node is an element, try inserting its children (strip the parent).
  203. if ( node.is( 'element' ) ) {
  204. this.handleNodes( node.getChildren(), context );
  205. }
  206. // If text is not allowed, try autoparagraphing it.
  207. else {
  208. this._tryAutoparagraphing( node, context );
  209. }
  210. }
  211. /**
  212. * @param {module:engine/model/node~Node} node The node to insert.
  213. */
  214. _insert( node ) {
  215. /* istanbul ignore if */
  216. if ( !this.schema.checkChild( this.position, node ) ) {
  217. // Algorithm's correctness check. We should never end up here but it's good to know that we did.
  218. // Note that it would often be a silent issue if we insert node in a place where it's not allowed.
  219. log.error(
  220. 'insertcontent-wrong-position: The node cannot be inserted on the given position.',
  221. { node, position: this.position }
  222. );
  223. return;
  224. }
  225. const livePos = LivePosition.createFromPosition( this.position );
  226. this.writer.insert( node, this.position );
  227. this.position = Position.createFromPosition( livePos );
  228. livePos.detach();
  229. // The last inserted object should be selected because we can't put a collapsed selection after it.
  230. if ( this.schema.isObject( node ) && !this.schema.checkChild( this.position, '$text' ) ) {
  231. this.nodeToSelect = node;
  232. } else {
  233. this.nodeToSelect = null;
  234. }
  235. this._filterAttributesOf.push( node );
  236. }
  237. /**
  238. * @param {module:engine/model/node~Node} node The node which could potentially be merged.
  239. * @param {Object} context
  240. */
  241. _mergeSiblingsOf( node, context ) {
  242. if ( !( node instanceof Element ) ) {
  243. return;
  244. }
  245. const mergeLeft = context.isFirst && ( node.previousSibling instanceof Element ) && this.canMergeWith.has( node.previousSibling );
  246. const mergeRight = context.isLast && ( node.nextSibling instanceof Element ) && this.canMergeWith.has( node.nextSibling );
  247. const mergePosLeft = LivePosition.createBefore( node );
  248. const mergePosRight = LivePosition.createAfter( node );
  249. if ( mergeLeft ) {
  250. const position = LivePosition.createFromPosition( this.position );
  251. this.writer.merge( mergePosLeft );
  252. this.position = Position.createFromPosition( position );
  253. position.detach();
  254. }
  255. if ( mergeRight ) {
  256. /* istanbul ignore if */
  257. if ( !this.position.isEqual( mergePosRight ) ) {
  258. // Algorithm's correctness check. We should never end up here but it's good to know that we did.
  259. // At this point the insertion position should be after the node we'll merge. If it isn't,
  260. // it should need to be secured as in the left merge case.
  261. log.error( 'insertcontent-wrong-position-on-merge: The insertion position should equal the merge position' );
  262. }
  263. // Move the position to the previous node, so it isn't moved to the graveyard on merge.
  264. // <p>x</p>[]<p>y</p> => <p>x[]</p><p>y</p>
  265. this.position = Position.createAt( mergePosRight.nodeBefore, 'end' );
  266. // OK: <p>xx[]</p> + <p>yy</p> => <p>xx[]yy</p> (when sticks to previous)
  267. // NOK: <p>xx[]</p> + <p>yy</p> => <p>xxyy[]</p> (when sticks to next)
  268. const position = new LivePosition( this.position.root, this.position.path, 'sticksToPrevious' );
  269. this.writer.merge( mergePosRight );
  270. this.position = Position.createFromPosition( position );
  271. position.detach();
  272. }
  273. if ( mergeLeft || mergeRight ) {
  274. // After merge elements that were marked by _insert() to be filtered might be gone so
  275. // we need to mark the new container.
  276. this._filterAttributesOf.push( this.position.parent );
  277. }
  278. mergePosLeft.detach();
  279. mergePosRight.detach();
  280. }
  281. /**
  282. * Tries wrapping the node in a new paragraph and inserting it this way.
  283. *
  284. * @param {module:engine/model/node~Node} node The node which needs to be autoparagraphed.
  285. * @param {Object} context
  286. */
  287. _tryAutoparagraphing( node, context ) {
  288. const paragraph = this.writer.createElement( 'paragraph' );
  289. // Do not autoparagraph if the paragraph won't be allowed there,
  290. // cause that would lead to an infinite loop. The paragraph would be rejected in
  291. // the next _handleNode() call and we'd be here again.
  292. if ( this._getAllowedIn( paragraph, this.position.parent ) && this.schema.checkChild( paragraph, node ) ) {
  293. paragraph.appendChildren( node );
  294. this._handleNode( paragraph, context );
  295. }
  296. }
  297. /**
  298. * @param {module:engine/model/node~Node} node
  299. * @returns {Boolean} Whether an allowed position was found.
  300. * `false` is returned if the node isn't allowed at any position up in the tree, `true` if was.
  301. */
  302. _checkAndSplitToAllowedPosition( node ) {
  303. const allowedIn = this._getAllowedIn( node, this.position.parent );
  304. if ( !allowedIn ) {
  305. return false;
  306. }
  307. while ( allowedIn != this.position.parent ) {
  308. // If a parent which we'd need to leave is a limit element, break.
  309. if ( this.schema.isLimit( this.position.parent ) ) {
  310. return false;
  311. }
  312. if ( this.position.isAtStart ) {
  313. const parent = this.position.parent;
  314. this.position = Position.createBefore( parent );
  315. // Special case – parent is empty (<p>^</p>) so isAtStart == isAtEnd == true.
  316. // We can remove the element after moving selection out of it.
  317. if ( parent.isEmpty ) {
  318. this.writer.remove( parent );
  319. }
  320. } else if ( this.position.isAtEnd ) {
  321. this.position = Position.createAfter( this.position.parent );
  322. } else {
  323. const tempPos = Position.createAfter( this.position.parent );
  324. this.writer.split( this.position );
  325. this.position = tempPos;
  326. this.canMergeWith.add( this.position.nodeAfter );
  327. }
  328. }
  329. return true;
  330. }
  331. /**
  332. * Gets the element in which the given node is allowed. It checks the passed element and all its ancestors.
  333. *
  334. * @param {module:engine/model/node~Node} node The node to check.
  335. * @param {module:engine/model/element~Element} element The element in which the node's correctness should be checked.
  336. * @returns {module:engine/model/element~Element|null}
  337. */
  338. _getAllowedIn( node, element ) {
  339. if ( this.schema.checkChild( element, node ) ) {
  340. return element;
  341. }
  342. if ( element.parent ) {
  343. return this._getAllowedIn( node, element.parent );
  344. }
  345. return null;
  346. }
  347. }