utils.js 11 KB

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