8
0

insertcontent.js 15 KB

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