writer.js 11 KB

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