documentfragment.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module module:engine/model/documentfragment
  7. */
  8. import NodeList from './nodelist';
  9. import Element from './element';
  10. import Text from './text';
  11. import TextProxy from './textproxy';
  12. import isIterable from '@ckeditor/ckeditor5-utils/src/isiterable';
  13. /**
  14. * DocumentFragment represents a part of model which does not have a common root but it's top-level nodes
  15. * can be seen as siblings. In other words, it is a detached part of model tree, without a root.
  16. *
  17. * DocumentFragment has own {@link module:engine/model/markercollection~MarkerCollection}. Markers from this collection
  18. * will be set to the {@link module:engine/model/model~Model#markers model markers} by a
  19. * {@link module:engine/model/writer~Writer#insert} function.
  20. */
  21. export default class DocumentFragment {
  22. /**
  23. * Creates an empty `DocumentFragment`.
  24. *
  25. * @param {module:engine/model/node~Node|Iterable.<module:engine/model/node~Node>} [children]
  26. * Nodes to be contained inside the `DocumentFragment`.
  27. */
  28. constructor( children ) {
  29. /**
  30. * DocumentFragment static markers map. This is a list of names and {@link module:engine/model/range~Range ranges}
  31. * which will be set as Markers to {@link module:engine/model/model~Model#markers model markers collection}
  32. * when DocumentFragment will be inserted to the document.
  33. *
  34. * @member {Map<String,module:engine/model/range~Range>} module:engine/model/documentfragment~DocumentFragment#markers
  35. */
  36. this.markers = new Map();
  37. /**
  38. * List of nodes contained inside the document fragment.
  39. *
  40. * @private
  41. * @member {module:engine/model/nodelist~NodeList} module:engine/model/documentfragment~DocumentFragment#_children
  42. */
  43. this._children = new NodeList();
  44. if ( children ) {
  45. this.insertChildren( 0, children );
  46. }
  47. }
  48. /**
  49. * Returns an iterator that iterates over all nodes contained inside this document fragment.
  50. *
  51. * @returns {Iterable.<module:engine/model/node~Node>}
  52. */
  53. [ Symbol.iterator ]() {
  54. return this.getChildren();
  55. }
  56. /**
  57. * Number of this document fragment's children.
  58. *
  59. * @readonly
  60. * @type {Number}
  61. */
  62. get childCount() {
  63. return this._children.length;
  64. }
  65. /**
  66. * Sum of {module:engine/model/node~Node#offsetSize offset sizes} of all of this document fragment's children.
  67. *
  68. * @readonly
  69. * @type {Number}
  70. */
  71. get maxOffset() {
  72. return this._children.maxOffset;
  73. }
  74. /**
  75. * Is `true` if there are no nodes inside this document fragment, `false` otherwise.
  76. *
  77. * @readonly
  78. * @type {Boolean}
  79. */
  80. get isEmpty() {
  81. return this.childCount === 0;
  82. }
  83. /**
  84. * Artificial root of `DocumentFragment`. Returns itself. Added for compatibility reasons.
  85. *
  86. * @readonly
  87. * @type {module:engine/model/documentfragment~DocumentFragment}
  88. */
  89. get root() {
  90. return this;
  91. }
  92. /**
  93. * Artificial parent of `DocumentFragment`. Returns `null`. Added for compatibility reasons.
  94. *
  95. * @readonly
  96. * @type {null}
  97. */
  98. get parent() {
  99. return null;
  100. }
  101. /**
  102. * Checks whether given model tree object is of given type.
  103. *
  104. * Read more in {@link module:engine/model/node~Node#is}.
  105. *
  106. * @param {String} type
  107. * @returns {Boolean}
  108. */
  109. is( type ) {
  110. return type == 'documentFragment';
  111. }
  112. /**
  113. * Gets the child at the given index. Returns `null` if incorrect index was passed.
  114. *
  115. * @param {Number} index Index of child.
  116. * @returns {module:engine/model/node~Node|null} Child node.
  117. */
  118. getChild( index ) {
  119. return this._children.getNode( index );
  120. }
  121. /**
  122. * Returns an iterator that iterates over all of this document fragment's children.
  123. *
  124. * @returns {Iterable.<module:engine/model/node~Node>}
  125. */
  126. getChildren() {
  127. return this._children[ Symbol.iterator ]();
  128. }
  129. /**
  130. * Returns an index of the given child node. Returns `null` if given node is not a child of this document fragment.
  131. *
  132. * @param {module:engine/model/node~Node} node Child node to look for.
  133. * @returns {Number|null} Child node's index.
  134. */
  135. getChildIndex( node ) {
  136. return this._children.getNodeIndex( node );
  137. }
  138. /**
  139. * Returns the starting offset of given child. Starting offset is equal to the sum of
  140. * {module:engine/model/node~Node#offsetSize offset sizes} of all node's siblings that are before it. Returns `null` if
  141. * given node is not a child of this document fragment.
  142. *
  143. * @param {module:engine/model/node~Node} node Child node to look for.
  144. * @returns {Number|null} Child node's starting offset.
  145. */
  146. getChildStartOffset( node ) {
  147. return this._children.getNodeStartOffset( node );
  148. }
  149. /**
  150. * Returns path to a `DocumentFragment`, which is an empty array. Added for compatibility reasons.
  151. *
  152. * @returns {Array}
  153. */
  154. getPath() {
  155. return [];
  156. }
  157. /**
  158. * Returns a descendant node by its path relative to this element.
  159. *
  160. * // <this>a<b>c</b></this>
  161. * this.getNodeByPath( [ 0 ] ); // -> "a"
  162. * this.getNodeByPath( [ 1 ] ); // -> <b>
  163. * this.getNodeByPath( [ 1, 0 ] ); // -> "c"
  164. *
  165. * @param {Array.<Number>} relativePath Path of the node to find, relative to this element.
  166. * @returns {module:engine/model/node~Node|module:engine/model/documentfragment~DocumentFragment}
  167. */
  168. getNodeByPath( relativePath ) {
  169. let node = this; // eslint-disable-line consistent-this
  170. for ( const index of relativePath ) {
  171. node = node.getChild( node.offsetToIndex( index ) );
  172. }
  173. return node;
  174. }
  175. /**
  176. * Converts offset "position" to index "position".
  177. *
  178. * Returns index of a node that occupies given offset. If given offset is too low, returns `0`. If given offset is
  179. * too high, returns index after last child}.
  180. *
  181. * const textNode = new Text( 'foo' );
  182. * const pElement = new Element( 'p' );
  183. * const docFrag = new DocumentFragment( [ textNode, pElement ] );
  184. * docFrag.offsetToIndex( -1 ); // Returns 0, because offset is too low.
  185. * docFrag.offsetToIndex( 0 ); // Returns 0, because offset 0 is taken by `textNode` which is at index 0.
  186. * docFrag.offsetToIndex( 1 ); // Returns 0, because `textNode` has `offsetSize` equal to 3, so it occupies offset 1 too.
  187. * docFrag.offsetToIndex( 2 ); // Returns 0.
  188. * docFrag.offsetToIndex( 3 ); // Returns 1.
  189. * docFrag.offsetToIndex( 4 ); // Returns 2. There are no nodes at offset 4, so last available index is returned.
  190. *
  191. * @param {Number} offset Offset to look for.
  192. * @returns {Number} Index of a node that occupies given offset.
  193. */
  194. offsetToIndex( offset ) {
  195. return this._children.offsetToIndex( offset );
  196. }
  197. /**
  198. * {@link #insertChildren Inserts} one or more nodes at the end of this document fragment.
  199. *
  200. * @param {module:engine/model/item~Item|Iterable.<module:engine/model/item~Item>} items Items to be inserted.
  201. */
  202. appendChildren( items ) {
  203. this.insertChildren( this.childCount, items );
  204. }
  205. /**
  206. * Inserts one or more nodes at the given index and sets {@link module:engine/model/node~Node#parent parent} of these nodes
  207. * to this document fragment.
  208. *
  209. * @param {Number} index Index at which nodes should be inserted.
  210. * @param {module:engine/model/item~Item|Iterable.<module:engine/model/item~Item>} items Items to be inserted.
  211. */
  212. insertChildren( index, items ) {
  213. const nodes = normalize( items );
  214. for ( const node of nodes ) {
  215. // If node that is being added to this element is already inside another element, first remove it from the old parent.
  216. if ( node.parent !== null ) {
  217. node.remove();
  218. }
  219. node.parent = this;
  220. }
  221. this._children.insertNodes( index, nodes );
  222. }
  223. /**
  224. * Removes one or more nodes starting at the given index
  225. * and sets {@link module:engine/model/node~Node#parent parent} of these nodes to `null`.
  226. *
  227. * @param {Number} index Index of the first node to remove.
  228. * @param {Number} [howMany=1] Number of nodes to remove.
  229. * @returns {Array.<module:engine/model/node~Node>} Array containing removed nodes.
  230. */
  231. removeChildren( index, howMany = 1 ) {
  232. const nodes = this._children.removeNodes( index, howMany );
  233. for ( const node of nodes ) {
  234. node.parent = null;
  235. }
  236. return nodes;
  237. }
  238. /**
  239. * Converts `DocumentFragment` instance to plain object and returns it.
  240. * Takes care of converting all of this document fragment's children.
  241. *
  242. * @returns {Object} `DocumentFragment` instance converted to plain object.
  243. */
  244. toJSON() {
  245. const json = [];
  246. for ( const node of this._children ) {
  247. json.push( node.toJSON() );
  248. }
  249. return json;
  250. }
  251. /**
  252. * Creates a `DocumentFragment` instance from given plain object (i.e. parsed JSON string).
  253. * Converts `DocumentFragment` children to proper nodes.
  254. *
  255. * @param {Object} json Plain object to be converted to `DocumentFragment`.
  256. * @returns {module:engine/model/documentfragment~DocumentFragment} `DocumentFragment` instance created using given plain object.
  257. */
  258. static fromJSON( json ) {
  259. const children = [];
  260. for ( const child of json ) {
  261. if ( child.name ) {
  262. // If child has name property, it is an Element.
  263. children.push( Element.fromJSON( child ) );
  264. } else {
  265. // Otherwise, it is a Text node.
  266. children.push( Text.fromJSON( child ) );
  267. }
  268. }
  269. return new DocumentFragment( children );
  270. }
  271. }
  272. // Converts strings to Text and non-iterables to arrays.
  273. //
  274. // @param {String|module:engine/model/item~Item|Iterable.<module:engine/model/item~Item>}
  275. // @return {Iterable.<module:engine/model/node~Node>}
  276. function normalize( nodes ) {
  277. // Separate condition because string is iterable.
  278. if ( typeof nodes == 'string' ) {
  279. return [ new Text( nodes ) ];
  280. }
  281. if ( !isIterable( nodes ) ) {
  282. nodes = [ nodes ];
  283. }
  284. // Array.from to enable .map() on non-arrays.
  285. return Array.from( nodes )
  286. .map( node => {
  287. if ( typeof node == 'string' ) {
  288. return new Text( node );
  289. }
  290. if ( node instanceof TextProxy ) {
  291. return new Text( node.data, node.getAttributes() );
  292. }
  293. return node;
  294. } );
  295. }