8
0

writer.js 12 KB

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