8
0

insertcontent.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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.schema.getNearestSelectionRange( this.position );
  143. }
  144. /**
  145. * Handles insertion of a single node.
  146. *
  147. * @private
  148. * @param {module:engine/model/node~Node} node
  149. * @param {Object} context
  150. * @param {Boolean} context.isFirst Whether the given node is the first one in the content to be inserted.
  151. * @param {Boolean} context.isLast Whether the given node is the last one in the content to be inserted.
  152. */
  153. _handleNode( node, context ) {
  154. // Let's handle object in a special way.
  155. // * They should never be merged with other elements.
  156. // * If they are not allowed in any of the selection ancestors, they could be either autoparagraphed or totally removed.
  157. if ( this.schema.isObject( node ) ) {
  158. this._handleObject( node, context );
  159. return;
  160. }
  161. // Try to find a place for the given node.
  162. // Split the position.parent's branch up to a point where the node can be inserted.
  163. // If it isn't allowed in the whole branch, then of course don't split anything.
  164. const isAllowed = this._checkAndSplitToAllowedPosition( node, context );
  165. if ( !isAllowed ) {
  166. this._handleDisallowedNode( node, context );
  167. return;
  168. }
  169. this._insert( node );
  170. // After the node was inserted we may try to merge it with its siblings.
  171. // This should happen only if it was the first and/or last of the nodes (so only with boundary nodes)
  172. // and only if the selection was in those elements initially.
  173. //
  174. // E.g.:
  175. // <p>x^</p> + <p>y</p> => <p>x</p><p>y</p> => <p>xy[]</p>
  176. // and:
  177. // <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>
  178. // but:
  179. // <p>x</p><p>^</p><p>z</p> + <p>y</p> => <p>x</p><p>y</p><p>z</p> (no merging)
  180. // <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
  181. // it's exactly the same case as above)
  182. this._mergeSiblingsOf( node, context );
  183. }
  184. /**
  185. * @private
  186. * @param {module:engine/model/element~Element} node The object element.
  187. * @param {Object} context
  188. */
  189. _handleObject( node, context ) {
  190. // Try finding it a place in the tree.
  191. if ( this._checkAndSplitToAllowedPosition( node ) ) {
  192. this._insert( node );
  193. }
  194. // Try autoparagraphing.
  195. else {
  196. this._tryAutoparagraphing( node, context );
  197. }
  198. }
  199. /**
  200. * @private
  201. * @param {module:engine/model/node~Node} node The disallowed node which needs to be handled.
  202. * @param {Object} context
  203. */
  204. _handleDisallowedNode( node, context ) {
  205. // If the node is an element, try inserting its children (strip the parent).
  206. if ( node.is( 'element' ) ) {
  207. this.handleNodes( node.getChildren(), context );
  208. }
  209. // If text is not allowed, try autoparagraphing it.
  210. else {
  211. this._tryAutoparagraphing( node, context );
  212. }
  213. }
  214. /**
  215. * @private
  216. * @param {module:engine/model/node~Node} node The node to insert.
  217. */
  218. _insert( node ) {
  219. /* istanbul ignore if */
  220. if ( !this.schema.checkChild( this.position, node ) ) {
  221. // Algorithm's correctness check. We should never end up here but it's good to know that we did.
  222. // Note that it would often be a silent issue if we insert node in a place where it's not allowed.
  223. log.error(
  224. 'insertcontent-wrong-position: The node cannot be inserted on the given position.',
  225. { node, position: this.position }
  226. );
  227. return;
  228. }
  229. const livePos = LivePosition.createFromPosition( this.position );
  230. this.writer.insert( node, this.position );
  231. this.position = Position.createFromPosition( livePos );
  232. livePos.detach();
  233. // The last inserted object should be selected because we can't put a collapsed selection after it.
  234. if ( this.schema.isObject( node ) && !this.schema.checkChild( this.position, '$text' ) ) {
  235. this.nodeToSelect = node;
  236. } else {
  237. this.nodeToSelect = null;
  238. }
  239. this._filterAttributesOf.push( node );
  240. }
  241. /**
  242. * @private
  243. * @param {module:engine/model/node~Node} node The node which could potentially be merged.
  244. * @param {Object} context
  245. */
  246. _mergeSiblingsOf( node, context ) {
  247. if ( !( node instanceof Element ) ) {
  248. return;
  249. }
  250. const mergeLeft = this._canMergeLeft( node, context );
  251. const mergeRight = this._canMergeRight( node, context );
  252. const mergePosLeft = LivePosition.createBefore( node );
  253. const mergePosRight = LivePosition.createAfter( node );
  254. if ( mergeLeft ) {
  255. const position = LivePosition.createFromPosition( this.position );
  256. this.writer.merge( mergePosLeft );
  257. this.position = Position.createFromPosition( position );
  258. position.detach();
  259. }
  260. if ( mergeRight ) {
  261. /* istanbul ignore if */
  262. if ( !this.position.isEqual( mergePosRight ) ) {
  263. // Algorithm's correctness check. We should never end up here but it's good to know that we did.
  264. // At this point the insertion position should be after the node we'll merge. If it isn't,
  265. // it should need to be secured as in the left merge case.
  266. log.error( 'insertcontent-wrong-position-on-merge: The insertion position should equal the merge position' );
  267. }
  268. // Move the position to the previous node, so it isn't moved to the graveyard on merge.
  269. // <p>x</p>[]<p>y</p> => <p>x[]</p><p>y</p>
  270. this.position = Position.createAt( mergePosRight.nodeBefore, 'end' );
  271. // OK: <p>xx[]</p> + <p>yy</p> => <p>xx[]yy</p> (when sticks to previous)
  272. // NOK: <p>xx[]</p> + <p>yy</p> => <p>xxyy[]</p> (when sticks to next)
  273. const position = new LivePosition( this.position.root, this.position.path, 'sticksToPrevious' );
  274. this.writer.merge( mergePosRight );
  275. this.position = Position.createFromPosition( position );
  276. position.detach();
  277. }
  278. if ( mergeLeft || mergeRight ) {
  279. // After merge elements that were marked by _insert() to be filtered might be gone so
  280. // we need to mark the new container.
  281. this._filterAttributesOf.push( this.position.parent );
  282. }
  283. mergePosLeft.detach();
  284. mergePosRight.detach();
  285. }
  286. /**
  287. * Checks whether specified node can be merged with previous sibling element.
  288. *
  289. * @private
  290. * @param {module:engine/model/node~Node} node The node which could potentially be merged.
  291. * @param {Object} context
  292. * @returns {Boolean}
  293. */
  294. _canMergeLeft( node, context ) {
  295. const previousSibling = node.previousSibling;
  296. return context.isFirst &&
  297. ( previousSibling instanceof Element ) &&
  298. this.canMergeWith.has( previousSibling ) &&
  299. this.model.schema.checkMerge( previousSibling, node );
  300. }
  301. /**
  302. * Checks whether specified node can be merged with next sibling element.
  303. *
  304. * @private
  305. * @param {module:engine/model/node~Node} node The node which could potentially be merged.
  306. * @param {Object} context
  307. * @returns {Boolean}
  308. */
  309. _canMergeRight( node, context ) {
  310. const nextSibling = node.nextSibling;
  311. return context.isLast &&
  312. ( nextSibling instanceof Element ) &&
  313. this.canMergeWith.has( nextSibling ) &&
  314. this.model.schema.checkMerge( node, nextSibling );
  315. }
  316. /**
  317. * Tries wrapping the node in a new paragraph and inserting it this way.
  318. *
  319. * @private
  320. * @param {module:engine/model/node~Node} node The node which needs to be autoparagraphed.
  321. * @param {Object} context
  322. */
  323. _tryAutoparagraphing( node, context ) {
  324. const paragraph = this.writer.createElement( 'paragraph' );
  325. // Do not autoparagraph if the paragraph won't be allowed there,
  326. // cause that would lead to an infinite loop. The paragraph would be rejected in
  327. // the next _handleNode() call and we'd be here again.
  328. if ( this._getAllowedIn( paragraph, this.position.parent ) && this.schema.checkChild( paragraph, node ) ) {
  329. paragraph._appendChildren( node );
  330. this._handleNode( paragraph, context );
  331. }
  332. }
  333. /**
  334. * @private
  335. * @param {module:engine/model/node~Node} node
  336. * @returns {Boolean} Whether an allowed position was found.
  337. * `false` is returned if the node isn't allowed at any position up in the tree, `true` if was.
  338. */
  339. _checkAndSplitToAllowedPosition( node ) {
  340. const allowedIn = this._getAllowedIn( node, this.position.parent );
  341. if ( !allowedIn ) {
  342. return false;
  343. }
  344. while ( allowedIn != this.position.parent ) {
  345. // If a parent which we'd need to leave is a limit element, break.
  346. if ( this.schema.isLimit( this.position.parent ) ) {
  347. return false;
  348. }
  349. if ( this.position.isAtStart ) {
  350. const parent = this.position.parent;
  351. this.position = Position.createBefore( parent );
  352. // Special case – parent is empty (<p>^</p>) so isAtStart == isAtEnd == true.
  353. // We can remove the element after moving selection out of it.
  354. if ( parent.isEmpty ) {
  355. this.writer.remove( parent );
  356. }
  357. } else if ( this.position.isAtEnd ) {
  358. this.position = Position.createAfter( this.position.parent );
  359. } else {
  360. const tempPos = Position.createAfter( this.position.parent );
  361. this.writer.split( this.position );
  362. this.position = tempPos;
  363. this.canMergeWith.add( this.position.nodeAfter );
  364. }
  365. }
  366. return true;
  367. }
  368. /**
  369. * Gets the element in which the given node is allowed. It checks the passed element and all its ancestors.
  370. *
  371. * @private
  372. * @param {module:engine/model/node~Node} node The node to check.
  373. * @param {module:engine/model/element~Element} element The element in which the node's correctness should be checked.
  374. * @returns {module:engine/model/element~Element|null}
  375. */
  376. _getAllowedIn( node, element ) {
  377. if ( this.schema.checkChild( element, node ) ) {
  378. return element;
  379. }
  380. if ( element.parent ) {
  381. return this._getAllowedIn( node, element.parent );
  382. }
  383. return null;
  384. }
  385. }