insertcontent.js 14 KB

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