8
0

insertcontent.js 15 KB

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