insertcontent.js 13 KB

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