utils.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/model/operation/utils
  7. */
  8. import Node from '../node';
  9. import Text from '../text';
  10. import TextProxy from '../textproxy';
  11. import Range from '../range';
  12. import DocumentFragment from '../documentfragment';
  13. import NodeList from '../nodelist';
  14. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  15. /**
  16. * Contains functions used for composing model tree by {@link module:engine/model/operation/operation~Operation operations}.
  17. * Those functions are built on top of {@link module:engine/model/node~Node node}, and it's child classes', APIs.
  18. *
  19. * @protected
  20. * @namespace utils
  21. */
  22. /**
  23. * Inserts given nodes at given position.
  24. *
  25. * @protected
  26. * @function module:engine/model/operation/utils~utils.insert
  27. * @param {module:engine/model/position~Position} position Position at which nodes should be inserted.
  28. * @param {module:engine/model/node~NodeSet} nodes Nodes to insert.
  29. * @returns {module:engine/model/range~Range} Range spanning over inserted elements.
  30. */
  31. export function _insert( position, nodes ) {
  32. nodes = _normalizeNodes( nodes );
  33. // We have to count offset before inserting nodes because they can get merged and we would get wrong offsets.
  34. const offset = nodes.reduce( ( sum, node ) => sum + node.offsetSize, 0 );
  35. const parent = position.parent;
  36. // Insertion might be in a text node, we should split it if that's the case.
  37. _splitNodeAtPosition( position );
  38. const index = position.index;
  39. // Insert nodes at given index. After splitting we have a proper index and insertion is between nodes,
  40. // using basic `Element` API.
  41. parent._insertChild( index, nodes );
  42. // Merge text nodes, if possible. Merging is needed only at points where inserted nodes "touch" "old" nodes.
  43. _mergeNodesAtIndex( parent, index + nodes.length );
  44. _mergeNodesAtIndex( parent, index );
  45. return new Range( position, position.getShiftedBy( offset ) );
  46. }
  47. /**
  48. * Removed nodes in given range. Only {@link module:engine/model/range~Range#isFlat flat} ranges are accepted.
  49. *
  50. * @protected
  51. * @function module:engine/model/operation/utils~utils._remove
  52. * @param {module:engine/model/range~Range} range Range containing nodes to remove.
  53. * @returns {Array.<module:engine/model/node~Node>}
  54. */
  55. export function _remove( range ) {
  56. if ( !range.isFlat ) {
  57. /**
  58. * Trying to remove a range which starts and ends in different element.
  59. *
  60. * @error operation-utils-remove-range-not-flat
  61. */
  62. throw new CKEditorError( 'operation-utils-remove-range-not-flat: ' +
  63. 'Trying to remove a range which starts and ends in different element.' );
  64. }
  65. const parent = range.start.parent;
  66. // Range may be inside text nodes, we have to split them if that's the case.
  67. _splitNodeAtPosition( range.start );
  68. _splitNodeAtPosition( range.end );
  69. // Remove the text nodes using basic `Element` API.
  70. const removed = parent._removeChildren( range.start.index, range.end.index - range.start.index );
  71. // Merge text nodes, if possible. After some nodes were removed, node before and after removed range will be
  72. // touching at the position equal to the removed range beginning. We check merging possibility there.
  73. _mergeNodesAtIndex( parent, range.start.index );
  74. return removed;
  75. }
  76. /**
  77. * Moves nodes in given range to given target position. Only {@link module:engine/model/range~Range#isFlat flat} ranges are accepted.
  78. *
  79. * @protected
  80. * @function module:engine/model/operation/utils~utils.move
  81. * @param {module:engine/model/range~Range} sourceRange Range containing nodes to move.
  82. * @param {module:engine/model/position~Position} targetPosition Position to which nodes should be moved.
  83. * @returns {module:engine/model/range~Range} Range containing moved nodes.
  84. */
  85. export function _move( sourceRange, targetPosition ) {
  86. if ( !sourceRange.isFlat ) {
  87. /**
  88. * Trying to move a range which starts and ends in different element.
  89. *
  90. * @error operation-utils-move-range-not-flat
  91. */
  92. throw new CKEditorError( 'operation-utils-move-range-not-flat: ' +
  93. 'Trying to move a range which starts and ends in different element.' );
  94. }
  95. const nodes = _remove( sourceRange );
  96. // We have to fix `targetPosition` because model changed after nodes from `sourceRange` got removed and
  97. // that change might have an impact on `targetPosition`.
  98. targetPosition = targetPosition._getTransformedByDeletion( sourceRange.start, sourceRange.end.offset - sourceRange.start.offset );
  99. return _insert( targetPosition, nodes );
  100. }
  101. /**
  102. * Sets given attribute on nodes in given range. The attributes are only set on top-level nodes of the range, not on its children.
  103. *
  104. * @protected
  105. * @function module:engine/model/operation/utils~utils._setAttribute
  106. * @param {module:engine/model/range~Range} range Range containing nodes that should have the attribute set. Must be a flat range.
  107. * @param {String} key Key of attribute to set.
  108. * @param {*} value Attribute value.
  109. */
  110. export function _setAttribute( range, key, value ) {
  111. // Range might start or end in text nodes, so we have to split them.
  112. _splitNodeAtPosition( range.start );
  113. _splitNodeAtPosition( range.end );
  114. // Iterate over all items in the range.
  115. for ( const item of range.getItems( { shallow: true } ) ) {
  116. // Iterator will return `TextProxy` instances but we know that those text proxies will
  117. // always represent full text nodes (this is guaranteed thanks to splitting we did before).
  118. // So, we can operate on those text proxies' text nodes.
  119. const node = item.is( 'textProxy' ) ? item.textNode : item;
  120. if ( value !== null ) {
  121. node._setAttribute( key, value );
  122. } else {
  123. node._removeAttribute( key );
  124. }
  125. // After attributes changing it may happen that some text nodes can be merged. Try to merge with previous node.
  126. _mergeNodesAtIndex( node.parent, node.index );
  127. }
  128. // Try to merge last changed node with it's previous sibling (not covered by the loop above).
  129. _mergeNodesAtIndex( range.end.parent, range.end.index );
  130. }
  131. /**
  132. * Normalizes given object or an array of objects to an array of {@link module:engine/model/node~Node nodes}. See
  133. * {@link module:engine/model/node~NodeSet NodeSet} for details on how normalization is performed.
  134. *
  135. * @protected
  136. * @function module:engine/model/operation/utils~utils.normalizeNodes
  137. * @param {module:engine/model/node~NodeSet} nodes Objects to normalize.
  138. * @returns {Array.<module:engine/model/node~Node>} Normalized nodes.
  139. */
  140. export function _normalizeNodes( nodes ) {
  141. const normalized = [];
  142. if ( !( nodes instanceof Array ) ) {
  143. nodes = [ nodes ];
  144. }
  145. // Convert instances of classes other than Node.
  146. for ( let i = 0; i < nodes.length; i++ ) {
  147. if ( typeof nodes[ i ] == 'string' ) {
  148. normalized.push( new Text( nodes[ i ] ) );
  149. } else if ( nodes[ i ] instanceof TextProxy ) {
  150. normalized.push( new Text( nodes[ i ].data, nodes[ i ].getAttributes() ) );
  151. } else if ( nodes[ i ] instanceof DocumentFragment || nodes[ i ] instanceof NodeList ) {
  152. for ( const child of nodes[ i ] ) {
  153. normalized.push( child );
  154. }
  155. } else if ( nodes[ i ] instanceof Node ) {
  156. normalized.push( nodes[ i ] );
  157. }
  158. // Skip unrecognized type.
  159. }
  160. // Merge text nodes.
  161. for ( let i = 1; i < normalized.length; i++ ) {
  162. const node = normalized[ i ];
  163. const prev = normalized[ i - 1 ];
  164. if ( node instanceof Text && prev instanceof Text && _haveSameAttributes( node, prev ) ) {
  165. // Doing this instead changing `prev.data` because `data` is readonly.
  166. normalized.splice( i - 1, 2, new Text( prev.data + node.data, prev.getAttributes() ) );
  167. i--;
  168. }
  169. }
  170. return normalized;
  171. }
  172. // Checks if nodes before and after given index in given element are {@link module:engine/model/text~Text text nodes} and
  173. // merges them into one node if they have same attributes.
  174. //
  175. // Merging is done by removing two text nodes and inserting a new text node containing data from both merged text nodes.
  176. //
  177. // @private
  178. // @param {module:engine/model/element~Element} element Parent element of nodes to merge.
  179. // @param {Number} index Index between nodes to merge.
  180. function _mergeNodesAtIndex( element, index ) {
  181. const nodeBefore = element.getChild( index - 1 );
  182. const nodeAfter = element.getChild( index );
  183. // Check if both of those nodes are text objects with same attributes.
  184. if ( nodeBefore && nodeAfter && nodeBefore.is( 'text' ) && nodeAfter.is( 'text' ) && _haveSameAttributes( nodeBefore, nodeAfter ) ) {
  185. // Append text of text node after index to the before one.
  186. const mergedNode = new Text( nodeBefore.data + nodeAfter.data, nodeBefore.getAttributes() );
  187. // Remove separate text nodes.
  188. element._removeChildren( index - 1, 2 );
  189. // Insert merged text node.
  190. element._insertChild( index - 1, mergedNode );
  191. }
  192. }
  193. // Checks if given position is in a text node, and if so, splits the text node in two text nodes, each of them
  194. // containing a part of original text node.
  195. //
  196. // @private
  197. // @param {module:engine/model/position~Position} position Position at which node should be split.
  198. function _splitNodeAtPosition( position ) {
  199. const textNode = position.textNode;
  200. const element = position.parent;
  201. if ( textNode ) {
  202. const offsetDiff = position.offset - textNode.startOffset;
  203. const index = textNode.index;
  204. element._removeChildren( index, 1 );
  205. const firstPart = new Text( textNode.data.substr( 0, offsetDiff ), textNode.getAttributes() );
  206. const secondPart = new Text( textNode.data.substr( offsetDiff ), textNode.getAttributes() );
  207. element._insertChild( index, [ firstPart, secondPart ] );
  208. }
  209. }
  210. // Checks whether two given nodes have same attributes.
  211. //
  212. // @private
  213. // @param {module:engine/model/node~Node} nodeA Node to check.
  214. // @param {module:engine/model/node~Node} nodeB Node to check.
  215. // @returns {Boolean} `true` if nodes have same attributes, `false` otherwise.
  216. function _haveSameAttributes( nodeA, nodeB ) {
  217. const iteratorA = nodeA.getAttributes();
  218. const iteratorB = nodeB.getAttributes();
  219. for ( const attr of iteratorA ) {
  220. if ( attr[ 1 ] !== nodeB.getAttribute( attr[ 0 ] ) ) {
  221. return false;
  222. }
  223. iteratorB.next();
  224. }
  225. return iteratorB.next().done;
  226. }
  227. /**
  228. * Value that can be normalized to an array of {@link module:engine/model/node~Node nodes}.
  229. *
  230. * Non-arrays are normalized as follows:
  231. * * {@link module:engine/model/node~Node Node} is left as is,
  232. * * {@link module:engine/model/textproxy~TextProxy TextProxy} and `String` are normalized to {@link module:engine/model/text~Text Text},
  233. * * {@link module:engine/model/nodelist~NodeList NodeList} is normalized to an array containing all nodes that are in that node list,
  234. * * {@link module:engine/model/documentfragment~DocumentFragment DocumentFragment} is normalized to an array containing all of it's
  235. * * children.
  236. *
  237. * Arrays are processed item by item like non-array values and flattened to one array. Normalization always results in
  238. * a flat array of {@link module:engine/model/node~Node nodes}. Consecutive text nodes (or items normalized to text nodes) will be
  239. * merged if they have same attributes.
  240. *
  241. * @typedef {module:engine/model/node~Node|module:engine/model/textproxy~TextProxy|String|
  242. * module:engine/model/nodelist~NodeList|module:engine/model/documentfragment~DocumentFragment|Iterable}
  243. * module:engine/model/node~NodeSet
  244. */