insertcontent.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  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. * If `selectable` is not passed, the content will be inserted using the current selection of the model document.
  23. *
  24. * **Note:** Use {@link module:engine/model/model~Model#insertContent} instead of this function.
  25. * This function is only exposed to be reusable in algorithms which change the {@link module:engine/model/model~Model#insertContent}
  26. * method's behavior.
  27. *
  28. * @param {module:engine/model/model~Model} model The model in context of which the insertion
  29. * should be performed.
  30. * @param {module:engine/model/documentfragment~DocumentFragment|module:engine/model/item~Item} content The content to insert.
  31. * @param {module:engine/model/selection~Selectable} [selectable=model.document.selection]
  32. * Selection into which the content should be inserted.
  33. * @param {Number|'before'|'end'|'after'|'on'|'in'} [placeOrOffset] Sets place or offset of the selection.
  34. * @returns {module:engine/model/range~Range} Range which contains all the performed changes. This is a range that, if removed,
  35. * would return the model to the state before the insertion. If no changes were preformed by `insertContent`, returns a range collapsed
  36. * at the insertion position.
  37. */
  38. export default function insertContent( model, content, selectable, placeOrOffset ) {
  39. return model.change( writer => {
  40. let selection;
  41. if ( !selectable ) {
  42. selection = model.document.selection;
  43. } else if ( selectable instanceof Selection || selectable instanceof DocumentSelection ) {
  44. selection = selectable;
  45. } else {
  46. selection = writer.createSelection( selectable, placeOrOffset );
  47. }
  48. const insertionPosition = selection.getFirstPosition();
  49. if ( !selection.isCollapsed ) {
  50. model.deleteContent( selection, { doNotAutoparagraph: true } );
  51. }
  52. const insertion = new Insertion( model, writer, insertionPosition );
  53. let nodesToInsert;
  54. if ( content.is( 'documentFragment' ) ) {
  55. nodesToInsert = content.getChildren();
  56. } else {
  57. nodesToInsert = [ content ];
  58. }
  59. insertion.handleNodes( nodesToInsert, {
  60. // The set of children being inserted is the only set in this context
  61. // so it's the first and last (it's a hack ;)).
  62. isFirst: true,
  63. isLast: true
  64. } );
  65. const newRange = insertion.getSelectionRange();
  66. /* istanbul ignore else */
  67. if ( newRange ) {
  68. if ( selection instanceof DocumentSelection ) {
  69. writer.setSelection( newRange );
  70. } else {
  71. selection.setTo( newRange );
  72. }
  73. } else {
  74. // We are not testing else because it's a safe check for unpredictable edge cases:
  75. // an insertion without proper range to select.
  76. /**
  77. * Cannot determine a proper selection range after insertion.
  78. *
  79. * @warning insertcontent-no-range
  80. */
  81. log.warn( 'insertcontent-no-range: Cannot determine a proper selection range after insertion.' );
  82. }
  83. const affectedRange = insertion.getAffectedRange() || model.createRange( insertionPosition );
  84. insertion.destroy();
  85. return affectedRange;
  86. } );
  87. }
  88. /**
  89. * Utility class for performing content insertion.
  90. *
  91. * @private
  92. */
  93. class Insertion {
  94. constructor( model, writer, position ) {
  95. /**
  96. * The model in context of which the insertion should be performed.
  97. *
  98. * @member {module:engine/model~Model} #model
  99. */
  100. this.model = model;
  101. /**
  102. * Batch to which operations will be added.
  103. *
  104. * @member {module:engine/controller/writer~Batch} #writer
  105. */
  106. this.writer = writer;
  107. /**
  108. * The position at which (or near which) the next node will be inserted.
  109. *
  110. * @member {module:engine/model/position~Position} #position
  111. */
  112. this.position = position;
  113. /**
  114. * Elements with which the inserted elements can be merged.
  115. *
  116. * <p>x^</p><p>y</p> + <p>z</p> (can merge to <p>x</p>)
  117. * <p>x</p><p>^y</p> + <p>z</p> (can merge to <p>y</p>)
  118. * <p>x^y</p> + <p>z</p> (can merge to <p>xy</p> which will be split during the action,
  119. * so both its pieces will be added to this set)
  120. *
  121. *
  122. * @member {Set} #canMergeWith
  123. */
  124. this.canMergeWith = new Set( [ this.position.parent ] );
  125. /**
  126. * Schema of the model.
  127. *
  128. * @member {module:engine/model/schema~Schema} #schema
  129. */
  130. this.schema = model.schema;
  131. this._filterAttributesOf = [];
  132. /**
  133. * Beginning of the affected range. See {@link module:engine/model/utils/insertcontent~Insertion#getAffectedRange}.
  134. *
  135. * @private
  136. * @member {module:engine/model/liveposition~LivePosition|null} #_affectedStart
  137. */
  138. this._affectedStart = null;
  139. /**
  140. * End of the affected range. See {@link module:engine/model/utils/insertcontent~Insertion#getAffectedRange}.
  141. *
  142. * @private
  143. * @member {module:engine/model/liveposition~LivePosition|null} #_affectedEnd
  144. */
  145. this._affectedEnd = null;
  146. }
  147. /**
  148. * Handles insertion of a set of nodes.
  149. *
  150. * @param {Iterable.<module:engine/model/node~Node>} nodes Nodes to insert.
  151. * @param {Object} parentContext Context in which parent of these nodes was supposed to be inserted.
  152. * If the parent context is passed it means that the parent element was stripped (was not allowed).
  153. */
  154. handleNodes( nodes, parentContext ) {
  155. nodes = Array.from( nodes );
  156. for ( let i = 0; i < nodes.length; i++ ) {
  157. const node = nodes[ i ];
  158. this._handleNode( node, {
  159. isFirst: i === 0 && parentContext.isFirst,
  160. isLast: ( i === ( nodes.length - 1 ) ) && parentContext.isLast
  161. } );
  162. }
  163. // TMP this will become a post-fixer.
  164. this.schema.removeDisallowedAttributes( this._filterAttributesOf, this.writer );
  165. this._filterAttributesOf = [];
  166. }
  167. /**
  168. * Returns range to be selected after insertion.
  169. * Returns `null` if there is no valid range to select after insertion.
  170. *
  171. * @returns {module:engine/model/range~Range|null}
  172. */
  173. getSelectionRange() {
  174. if ( this.nodeToSelect ) {
  175. return Range._createOn( this.nodeToSelect );
  176. }
  177. return this.model.schema.getNearestSelectionRange( this.position );
  178. }
  179. /**
  180. * Returns a range which contains all the performed changes. This is a range that, if removed, would return the model to the state
  181. * before the insertion. Returns `null` if no changes were done.
  182. *
  183. * @returns {module:engine/model/range~Range|null}
  184. */
  185. getAffectedRange() {
  186. if ( !this._affectedStart ) {
  187. return null;
  188. }
  189. return new Range( this._affectedStart, this._affectedEnd );
  190. }
  191. /**
  192. * Destroys `Insertion` instance.
  193. */
  194. destroy() {
  195. if ( this._affectedStart ) {
  196. this._affectedStart.detach();
  197. }
  198. if ( this._affectedEnd ) {
  199. this._affectedEnd.detach();
  200. }
  201. }
  202. /**
  203. * Handles insertion of a single node.
  204. *
  205. * @private
  206. * @param {module:engine/model/node~Node} node
  207. * @param {Object} context
  208. * @param {Boolean} context.isFirst Whether the given node is the first one in the content to be inserted.
  209. * @param {Boolean} context.isLast Whether the given node is the last one in the content to be inserted.
  210. */
  211. _handleNode( node, context ) {
  212. // Let's handle object in a special way.
  213. // * They should never be merged with other elements.
  214. // * If they are not allowed in any of the selection ancestors, they could be either autoparagraphed or totally removed.
  215. if ( this.schema.isObject( node ) ) {
  216. this._handleObject( node, context );
  217. return;
  218. }
  219. // Try to find a place for the given node.
  220. // Split the position.parent's branch up to a point where the node can be inserted.
  221. // If it isn't allowed in the whole branch, then of course don't split anything.
  222. const isAllowed = this._checkAndSplitToAllowedPosition( node, context );
  223. if ( !isAllowed ) {
  224. this._handleDisallowedNode( node, context );
  225. return;
  226. }
  227. this._insert( node );
  228. // After the node was inserted we may try to merge it with its siblings.
  229. // This should happen only if it was the first and/or last of the nodes (so only with boundary nodes)
  230. // and only if the selection was in those elements initially.
  231. //
  232. // E.g.:
  233. // <p>x^</p> + <p>y</p> => <p>x</p><p>y</p> => <p>xy[]</p>
  234. // and:
  235. // <p>x^y</p> + <p>z</p> => <p>x</p>^<p>y</p> + <p>z</p> => <p>x</p><p>z</p><p>y</p> => <p>xz[]y</p>
  236. // but:
  237. // <p>x</p><p>^</p><p>z</p> + <p>y</p> => <p>x</p><p>y</p><p>z</p> (no merging)
  238. // <p>x</p>[<img>]<p>z</p> + <p>y</p> => <p>x</p><p>y</p><p>z</p> (no merging, note: after running deleteContents
  239. // it's exactly the same case as above)
  240. this._mergeSiblingsOf( node, context );
  241. }
  242. /**
  243. * @private
  244. * @param {module:engine/model/element~Element} node The object element.
  245. * @param {Object} context
  246. */
  247. _handleObject( node, context ) {
  248. // Try finding it a place in the tree.
  249. if ( this._checkAndSplitToAllowedPosition( node ) ) {
  250. this._insert( node );
  251. }
  252. // Try autoparagraphing.
  253. else {
  254. this._tryAutoparagraphing( node, context );
  255. }
  256. }
  257. /**
  258. * @private
  259. * @param {module:engine/model/node~Node} node The disallowed node which needs to be handled.
  260. * @param {Object} context
  261. */
  262. _handleDisallowedNode( node, context ) {
  263. // If the node is an element, try inserting its children (strip the parent).
  264. if ( node.is( 'element' ) ) {
  265. this.handleNodes( node.getChildren(), context );
  266. }
  267. // If text is not allowed, try autoparagraphing it.
  268. else {
  269. this._tryAutoparagraphing( node, context );
  270. }
  271. }
  272. /**
  273. * @private
  274. * @param {module:engine/model/node~Node} node The node to insert.
  275. */
  276. _insert( node ) {
  277. /* istanbul ignore if */
  278. if ( !this.schema.checkChild( this.position, node ) ) {
  279. // Algorithm's correctness check. We should never end up here but it's good to know that we did.
  280. // Note that it would often be a silent issue if we insert node in a place where it's not allowed.
  281. log.error(
  282. 'insertcontent-wrong-position: The node cannot be inserted on the given position.',
  283. { node, position: this.position }
  284. );
  285. return;
  286. }
  287. const livePos = LivePosition.fromPosition( this.position, 'toNext' );
  288. this._setAffectedBoundaries( this.position );
  289. this.writer.insert( node, this.position );
  290. this.position = livePos.toPosition();
  291. livePos.detach();
  292. // The last inserted object should be selected because we can't put a collapsed selection after it.
  293. if ( this.schema.isObject( node ) && !this.schema.checkChild( this.position, '$text' ) ) {
  294. this.nodeToSelect = node;
  295. } else {
  296. this.nodeToSelect = null;
  297. }
  298. this._filterAttributesOf.push( node );
  299. }
  300. /**
  301. * Sets `_affectedStart` and `_affectedEnd` to the given `position`. Should be used before a change is done during insertion process to
  302. * mark the affected range.
  303. *
  304. * This method is used before inserting a node or splitting a parent node. `_affectedStart` and `_affectedEnd` are also changed
  305. * during merging, but the logic there is more complicated so it is left out of this function.
  306. *
  307. * @private
  308. * @param {module:engine/model/position~Position} position
  309. */
  310. _setAffectedBoundaries( position ) {
  311. // Set affected boundaries stickiness so that those position will "expand" when something is inserted in between them:
  312. // <paragraph>Foo][bar</paragraph> -> <paragraph>Foo]xx[bar</paragraph>
  313. // This is why it cannot be a range but two separate positions.
  314. if ( !this._affectedStart ) {
  315. this._affectedStart = LivePosition.fromPosition( position, 'toPrevious' );
  316. }
  317. // If `_affectedEnd` is before the new boundary position, expand `_affectedEnd`. This can happen if first inserted node was
  318. // inserted into the parent but the next node is moved-out of that parent:
  319. // (1) <paragraph>Foo][</paragraph> -> <paragraph>Foo]xx[</paragraph>
  320. // (2) <paragraph>Foo]xx[</paragraph> -> <paragraph>Foo]xx</paragraph><widget></widget>[
  321. if ( !this._affectedEnd || this._affectedEnd.isBefore( position ) ) {
  322. if ( this._affectedEnd ) {
  323. this._affectedEnd.detach();
  324. }
  325. this._affectedEnd = LivePosition.fromPosition( position, 'toNext' );
  326. }
  327. }
  328. /**
  329. * @private
  330. * @param {module:engine/model/node~Node} node The node which could potentially be merged.
  331. * @param {Object} context
  332. */
  333. _mergeSiblingsOf( node, context ) {
  334. if ( !( node instanceof Element ) ) {
  335. return;
  336. }
  337. const mergeLeft = this._canMergeLeft( node, context );
  338. const mergeRight = this._canMergeRight( node, context );
  339. const mergePosLeft = LivePosition._createBefore( node );
  340. mergePosLeft.stickiness = 'toNext';
  341. const mergePosRight = LivePosition._createAfter( node );
  342. mergePosRight.stickiness = 'toNext';
  343. if ( mergeLeft ) {
  344. const livePosition = LivePosition.fromPosition( this.position );
  345. livePosition.stickiness = 'toNext';
  346. // If `_affectedStart` is sames as merge position, it means that the element "marked" by `_affectedStart` is going to be
  347. // removed and its contents will be moved. This won't transform `LivePosition` so `_affectedStart` needs to be moved
  348. // by hand to properly reflect affected range. (Due to `_affectedStart` and `_affectedEnd` stickiness, the "range" is
  349. // shown as `][`).
  350. //
  351. // Example - insert `<paragraph>Abc</paragraph><paragraph>Xyz</paragraph>` at the end of `<paragraph>Foo^</paragraph>`:
  352. //
  353. // <paragraph>Foo</paragraph><paragraph>Bar</paragraph> -->
  354. // <paragraph>Foo</paragraph>]<paragraph>Abc</paragraph><paragraph>Xyz</paragraph>[<paragraph>Bar</paragraph> -->
  355. // <paragraph>Foo]Abc</paragraph><paragraph>Xyz</paragraph>[<paragraph>Bar</paragraph>
  356. //
  357. // Note, that if we are here then something must have been inserted, so `_affectedStart` and `_affectedEnd` have to be set.
  358. if ( this._affectedStart.isEqual( mergePosLeft ) ) {
  359. this._affectedStart.detach();
  360. this._affectedStart = LivePosition._createAt( mergePosLeft.nodeBefore, 'end', 'toPrevious' );
  361. }
  362. this.writer.merge( mergePosLeft );
  363. // If only one element (the merged one) is in the "affected range", also move the affected range end appropriately.
  364. //
  365. // Example - insert `<paragraph>Abc</paragraph>` at the of `<paragraph>Foo^</paragraph>`:
  366. //
  367. // <paragraph>Foo</paragraph><paragraph>Bar</paragraph> -->
  368. // <paragraph>Foo</paragraph>]<paragraph>Abc</paragraph>[<paragraph>Bar</paragraph> -->
  369. // <paragraph>Foo]Abc</paragraph>[<paragraph>Bar</paragraph> -->
  370. // <paragraph>Foo]Abc[</paragraph><paragraph>Bar</paragraph>
  371. if ( mergePosLeft.isEqual( this._affectedEnd ) && context.isLast ) {
  372. this._affectedEnd.detach();
  373. this._affectedEnd = LivePosition._createAt( mergePosLeft.nodeBefore, 'end', 'toNext' );
  374. }
  375. this.position = livePosition.toPosition();
  376. livePosition.detach();
  377. }
  378. if ( mergeRight ) {
  379. /* istanbul ignore if */
  380. if ( !this.position.isEqual( mergePosRight ) ) {
  381. // Algorithm's correctness check. We should never end up here but it's good to know that we did.
  382. // At this point the insertion position should be after the node we'll merge. If it isn't,
  383. // it should need to be secured as in the left merge case.
  384. log.error( 'insertcontent-wrong-position-on-merge: The insertion position should equal the merge position' );
  385. }
  386. // Move the position to the previous node, so it isn't moved to the graveyard on merge.
  387. // <p>x</p>[]<p>y</p> => <p>x[]</p><p>y</p>
  388. this.position = Position._createAt( mergePosRight.nodeBefore, 'end' );
  389. // OK: <p>xx[]</p> + <p>yy</p> => <p>xx[]yy</p> (when sticks to previous)
  390. // NOK: <p>xx[]</p> + <p>yy</p> => <p>xxyy[]</p> (when sticks to next)
  391. const livePosition = LivePosition.fromPosition( this.position, 'toPrevious' );
  392. // See comment above on moving `_affectedStart`.
  393. if ( this._affectedEnd.isEqual( mergePosRight ) ) {
  394. this._affectedEnd.detach();
  395. this._affectedEnd = LivePosition._createAt( mergePosRight.nodeBefore, 'end', 'toNext' );
  396. }
  397. this.writer.merge( mergePosRight );
  398. // See comment above on moving `_affectedStart`.
  399. if ( mergePosRight.getShiftedBy( -1 ).isEqual( this._affectedStart ) && context.isFirst ) {
  400. this._affectedStart.detach();
  401. this._affectedStart = LivePosition._createAt( mergePosRight.nodeBefore, 0, 'toPrevious' );
  402. }
  403. this.position = livePosition.toPosition();
  404. livePosition.detach();
  405. }
  406. if ( mergeLeft || mergeRight ) {
  407. // After merge elements that were marked by _insert() to be filtered might be gone so
  408. // we need to mark the new container.
  409. this._filterAttributesOf.push( this.position.parent );
  410. }
  411. mergePosLeft.detach();
  412. mergePosRight.detach();
  413. }
  414. /**
  415. * Checks whether specified node can be merged with previous sibling element.
  416. *
  417. * @private
  418. * @param {module:engine/model/node~Node} node The node which could potentially be merged.
  419. * @param {Object} context
  420. * @returns {Boolean}
  421. */
  422. _canMergeLeft( node, context ) {
  423. const previousSibling = node.previousSibling;
  424. return context.isFirst &&
  425. ( previousSibling instanceof Element ) &&
  426. this.canMergeWith.has( previousSibling ) &&
  427. this.model.schema.checkMerge( previousSibling, node );
  428. }
  429. /**
  430. * Checks whether specified node can be merged with next sibling element.
  431. *
  432. * @private
  433. * @param {module:engine/model/node~Node} node The node which could potentially be merged.
  434. * @param {Object} context
  435. * @returns {Boolean}
  436. */
  437. _canMergeRight( node, context ) {
  438. const nextSibling = node.nextSibling;
  439. return context.isLast &&
  440. ( nextSibling instanceof Element ) &&
  441. this.canMergeWith.has( nextSibling ) &&
  442. this.model.schema.checkMerge( node, nextSibling );
  443. }
  444. /**
  445. * Tries wrapping the node in a new paragraph and inserting it this way.
  446. *
  447. * @private
  448. * @param {module:engine/model/node~Node} node The node which needs to be autoparagraphed.
  449. * @param {Object} context
  450. */
  451. _tryAutoparagraphing( node, context ) {
  452. const paragraph = this.writer.createElement( 'paragraph' );
  453. // Do not autoparagraph if the paragraph won't be allowed there,
  454. // cause that would lead to an infinite loop. The paragraph would be rejected in
  455. // the next _handleNode() call and we'd be here again.
  456. if ( this._getAllowedIn( paragraph, this.position.parent ) && this.schema.checkChild( paragraph, node ) ) {
  457. paragraph._appendChild( node );
  458. this._handleNode( paragraph, context );
  459. }
  460. }
  461. /**
  462. * @private
  463. * @param {module:engine/model/node~Node} node
  464. * @returns {Boolean} Whether an allowed position was found.
  465. * `false` is returned if the node isn't allowed at any position up in the tree, `true` if was.
  466. */
  467. _checkAndSplitToAllowedPosition( node ) {
  468. const allowedIn = this._getAllowedIn( node, this.position.parent );
  469. if ( !allowedIn ) {
  470. return false;
  471. }
  472. while ( allowedIn != this.position.parent ) {
  473. // If a parent which we'd need to leave is a limit element, break.
  474. if ( this.schema.isLimit( this.position.parent ) ) {
  475. return false;
  476. }
  477. if ( this.position.isAtStart ) {
  478. // If insertion position is at the beginning of the parent, move it out instead of splitting.
  479. // <p>^Foo</p> -> ^<p>Foo</p>
  480. const parent = this.position.parent;
  481. this.position = this.writer.createPositionBefore( parent );
  482. // Special case – parent is empty (<p>^</p>).
  483. // We can remove the element after moving insertion position out of it.
  484. if ( parent.isEmpty ) {
  485. this.writer.remove( parent );
  486. }
  487. } else if ( this.position.isAtEnd ) {
  488. // If insertion position is at the end of the parent, move it out instead of splitting.
  489. // <p>Foo^</p> -> <p>Foo</p>^
  490. this.position = this.writer.createPositionAfter( this.position.parent );
  491. } else {
  492. const tempPos = this.writer.createPositionAfter( this.position.parent );
  493. this._setAffectedBoundaries( this.position );
  494. this.writer.split( this.position );
  495. this.position = tempPos;
  496. this.canMergeWith.add( this.position.nodeAfter );
  497. }
  498. }
  499. return true;
  500. }
  501. /**
  502. * Gets the element in which the given node is allowed. It checks the passed element and all its ancestors.
  503. *
  504. * @private
  505. * @param {module:engine/model/node~Node} node The node to check.
  506. * @param {module:engine/model/element~Element} element The element in which the node's correctness should be checked.
  507. * @returns {module:engine/model/element~Element|null}
  508. */
  509. _getAllowedIn( node, element ) {
  510. if ( this.schema.checkChild( element, node ) ) {
  511. return element;
  512. }
  513. if ( element.parent ) {
  514. return this._getAllowedIn( node, element.parent );
  515. }
  516. return null;
  517. }
  518. }