8
0

insertcontent.js 13 KB

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