insertcontent.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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. // When disallowed node is a text but text is allowed in current parent it means that our node
  200. // contains disallowed attributes and we have to remove them.
  201. else if ( node.is( 'text' ) && this.schema.check( { name: '$text', inside: this.position } ) ) {
  202. removeDisallowedAttributes( node, this.position, this.schema );
  203. this._handleNode( node, context );
  204. }
  205. // Try autoparagraphing.
  206. else {
  207. this._tryAutoparagraphing( node, context );
  208. }
  209. }
  210. /**
  211. * @param {module:engine/model/node~Node} node The node to insert.
  212. */
  213. _insert( node ) {
  214. /* istanbul ignore if */
  215. if ( !this._checkIsAllowed( node, this.position ) ) {
  216. // Algorithm's correctness check. We should never end up here but it's good to know that we did.
  217. // Note that it would often be a silent issue if we insert node in a place where it's not allowed.
  218. log.error(
  219. 'insertcontent-wrong-position: The node cannot be inserted on the given position.',
  220. { node, position: this.position }
  221. );
  222. return;
  223. }
  224. const livePos = LivePosition.createFromPosition( this.position );
  225. this.batch.insert( this.position, node );
  226. this.position = Position.createFromPosition( livePos );
  227. livePos.detach();
  228. // The last inserted object should be selected because we can't put a collapsed selection after it.
  229. if ( this._checkIsObject( node ) && !this.schema.check( { name: '$text', inside: this.position } ) ) {
  230. this.nodeToSelect = node;
  231. } else {
  232. this.nodeToSelect = null;
  233. }
  234. }
  235. /**
  236. * @param {module:engine/model/node~Node} node The node which could potentially be merged.
  237. * @param {Object} context
  238. */
  239. _mergeSiblingsOf( node, context ) {
  240. if ( !( node instanceof Element ) ) {
  241. return;
  242. }
  243. const mergeLeft = context.isFirst && ( node.previousSibling instanceof Element ) && this.canMergeWith.has( node.previousSibling );
  244. const mergeRight = context.isLast && ( node.nextSibling instanceof Element ) && this.canMergeWith.has( node.nextSibling );
  245. const mergePosLeft = LivePosition.createBefore( node );
  246. const mergePosRight = LivePosition.createAfter( node );
  247. if ( mergeLeft ) {
  248. const position = LivePosition.createFromPosition( this.position );
  249. // When need to check a direct child of node that is going to be merged
  250. // and strip it from the disallowed attributes according to the new parent.
  251. removeDisallowedAttributes( Array.from( node.getChildren() ), [ mergePosLeft.nodeBefore ], this.schema );
  252. this.batch.merge( mergePosLeft );
  253. this.position = Position.createFromPosition( position );
  254. position.detach();
  255. }
  256. if ( mergeRight ) {
  257. /* istanbul ignore if */
  258. if ( !this.position.isEqual( mergePosRight ) ) {
  259. // Algorithm's correctness check. We should never end up here but it's good to know that we did.
  260. // At this point the insertion position should be after the node we'll merge. If it isn't,
  261. // it should need to be secured as in the left merge case.
  262. log.error( 'insertcontent-wrong-position-on-merge: The insertion position should equal the merge position' );
  263. }
  264. // Move the position to the previous node, so it isn't moved to the graveyard on merge.
  265. // <p>x</p>[]<p>y</p> => <p>x[]</p><p>y</p>
  266. this.position = Position.createAt( mergePosRight.nodeBefore, 'end' );
  267. // OK: <p>xx[]</p> + <p>yy</p> => <p>xx[]yy</p> (when sticks to previous)
  268. // NOK: <p>xx[]</p> + <p>yy</p> => <p>xxyy[]</p> (when sticks to next)
  269. const position = new LivePosition( this.position.root, this.position.path, 'sticksToPrevious' );
  270. // When need to check a direct child of node that is going to be merged
  271. // and strip it from the disallowed attributes according to the new parent.
  272. removeDisallowedAttributes( Array.from( node.getChildren() ), [ mergePosLeft.nodeAfter ], this.schema );
  273. this.batch.merge( mergePosRight );
  274. this.position = Position.createFromPosition( position );
  275. position.detach();
  276. }
  277. mergePosLeft.detach();
  278. mergePosRight.detach();
  279. }
  280. /**
  281. * Tries wrapping the node in a new paragraph and inserting it this way.
  282. *
  283. * @param {module:engine/model/node~Node} node The node which needs to be autoparagraphed.
  284. * @param {Object} context
  285. */
  286. _tryAutoparagraphing( node, context ) {
  287. const paragraph = new Element( 'paragraph' );
  288. // Do not autoparagraph if the paragraph won't be allowed there,
  289. // cause that would lead to an infinite loop. The paragraph would be rejected in
  290. // the next _handleNode() call and we'd be here again.
  291. if ( this._getAllowedIn( paragraph, this.position.parent ) ) {
  292. // When node is a text and is disallowed by schema it means that contains disallowed attributes
  293. // and we need to remove them.
  294. if ( node.is( 'text' ) && !this._checkIsAllowed( node, [ paragraph ] ) ) {
  295. removeDisallowedAttributes( node, [ paragraph ], this.schema );
  296. }
  297. if ( this._checkIsAllowed( node, [ paragraph ] ) ) {
  298. paragraph.appendChildren( node );
  299. this._handleNode( paragraph, context );
  300. }
  301. }
  302. }
  303. /**
  304. * @param {module:engine/model/node~Node} node
  305. * @returns {Boolean} Whether an allowed position was found.
  306. * `false` is returned if the node isn't allowed at any position up in the tree, `true` if was.
  307. */
  308. _checkAndSplitToAllowedPosition( node ) {
  309. const allowedIn = this._getAllowedIn( node, this.position.parent );
  310. if ( !allowedIn ) {
  311. return false;
  312. }
  313. while ( allowedIn != this.position.parent ) {
  314. // If a parent which we'd need to leave is a limit element, break.
  315. if ( this.schema.limits.has( this.position.parent.name ) ) {
  316. return false;
  317. }
  318. if ( this.position.isAtStart ) {
  319. const parent = this.position.parent;
  320. this.position = Position.createBefore( parent );
  321. // Special case – parent is empty (<p>^</p>) so isAtStart == isAtEnd == true.
  322. // We can remove the element after moving selection out of it.
  323. if ( parent.isEmpty ) {
  324. this.batch.remove( parent );
  325. }
  326. } else if ( this.position.isAtEnd ) {
  327. this.position = Position.createAfter( this.position.parent );
  328. } else {
  329. const tempPos = Position.createAfter( this.position.parent );
  330. this.batch.split( this.position );
  331. this.position = tempPos;
  332. this.canMergeWith.add( this.position.nodeAfter );
  333. }
  334. }
  335. return true;
  336. }
  337. /**
  338. * Gets the element in which the given node is allowed. It checks the passed element and all its ancestors.
  339. *
  340. * @param {module:engine/model/node~Node} node The node to check.
  341. * @param {module:engine/model/element~Element} element The element in which the node's correctness should be checked.
  342. * @returns {module:engine/model/element~Element|null}
  343. */
  344. _getAllowedIn( node, element ) {
  345. if ( this._checkIsAllowed( node, [ element ] ) ) {
  346. return element;
  347. }
  348. if ( element.parent ) {
  349. return this._getAllowedIn( node, element.parent );
  350. }
  351. return null;
  352. }
  353. /**
  354. * Check whether the given node is allowed in the specified schema path.
  355. *
  356. * @param {module:engine/model/node~Node} node
  357. * @param {module:engine/model/schema~SchemaPath} path
  358. */
  359. _checkIsAllowed( node, path ) {
  360. return this.schema.check( {
  361. name: getNodeSchemaName( node ),
  362. attributes: Array.from( node.getAttributeKeys() ),
  363. inside: path
  364. } );
  365. }
  366. /**
  367. * Checks whether according to the schema this is an object type element.
  368. *
  369. * @param {module:engine/model/node~Node} node The node to check.
  370. */
  371. _checkIsObject( node ) {
  372. return this.schema.objects.has( getNodeSchemaName( node ) );
  373. }
  374. }
  375. // Gets a name under which we should check this node in the schema.
  376. //
  377. // @private
  378. // @param {module:engine/model/node~Node} node The node.
  379. function getNodeSchemaName( node ) {
  380. if ( node.is( 'text' ) ) {
  381. return '$text';
  382. }
  383. return node.name;
  384. }
  385. // Removes disallowed by schema attributes from given text nodes.
  386. //
  387. // @private
  388. // @param {module:engine/model/node~Node|Array<module:engine/model/node~Node>} nodes
  389. // @param {module:engine/model/schema~SchemaPath} schemaPath
  390. // @param {module:engine/model/schema~Schema} schema
  391. function removeDisallowedAttributes( nodes, schemaPath, schema ) {
  392. if ( !Array.isArray( nodes ) ) {
  393. nodes = [ nodes ];
  394. }
  395. for ( const node of nodes ) {
  396. for ( const attribute of node.getAttributeKeys() ) {
  397. if ( !schema.check( { name: getNodeSchemaName( node ), attributes: attribute, inside: schemaPath } ) ) {
  398. node.removeAttribute( attribute );
  399. }
  400. }
  401. }
  402. }