8
0

range.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/model/range
  7. */
  8. import Position from './position';
  9. import TreeWalker from './treewalker';
  10. import CKEditorError from 'ckeditor5-utils/src/ckeditorerror';
  11. /**
  12. * Range class. Range is iterable.
  13. */
  14. export default class Range {
  15. /**
  16. * Creates a range spanning from `start` position to `end` position.
  17. *
  18. * **Note:** Constructor creates it's own {@link module:engine/model/position~Position Position} instances basing on passed values.
  19. *
  20. * @param {module:engine/model/position~Position} start Start position.
  21. * @param {module:engine/model/position~Position} [end] End position. If not set, range will be collapsed at `start` position.
  22. */
  23. constructor( start, end = null ) {
  24. /**
  25. * Start position.
  26. *
  27. * @readonly
  28. * @member {module:engine/model/position~Position}
  29. */
  30. this.start = Position.createFromPosition( start );
  31. /**
  32. * End position.
  33. *
  34. * @readonly
  35. * @member {module:engine/model/position~Position}
  36. */
  37. this.end = end ? Position.createFromPosition( end ) : Position.createFromPosition( start );
  38. }
  39. /**
  40. * Returns an iterator that iterates over all {@link module:engine/model/item~Item items} that are in this range and returns
  41. * them together with additional information like length or {@link module:engine/model/position~Position positions},
  42. * grouped as {@link module:engine/model/treewalker~TreeWalkerValue}.
  43. * It iterates over all {@link module:engine/model/textproxy~TextProxy text contents} that are inside the range
  44. * and all the {@link module:engine/model/element~Element}s that are entered into when iterating over this range.
  45. *
  46. * This iterator uses {@link module:engine/model/treewalker~TreeWalker} with `boundaries` set to this range
  47. * and `ignoreElementEnd` option set to `true`.
  48. *
  49. * @returns {Iterable.<module:engine/model/treewalker~TreeWalkerValue>}
  50. */
  51. *[ Symbol.iterator ]() {
  52. yield* new TreeWalker( { boundaries: this, ignoreElementEnd: true } );
  53. }
  54. /**
  55. * Returns whether the range is collapsed, that is if {@link #start start} and
  56. * {@link #end end} positions are equal.
  57. *
  58. * @type {Boolean}
  59. */
  60. get isCollapsed() {
  61. return this.start.isEqual( this.end );
  62. }
  63. /**
  64. * Returns whether this range is flat, that is if {@link #start start} position and
  65. * {@link #end end} position are in the same {@link module:engine/model/position~Position#parent parent}.
  66. *
  67. * @type {Boolean}
  68. */
  69. get isFlat() {
  70. return this.start.parent === this.end.parent;
  71. }
  72. /**
  73. * Returns whether this range has no nodes in it, that is if {@link #start start} position and
  74. * {@link #end end} position are {@link module:engine/model/position~Position#isTouching touching}.
  75. *
  76. * **Note:** A range may be empty, but not {@link #isCollapsed collapsed}.
  77. *
  78. * @type {Boolean}
  79. */
  80. get isEmpty() {
  81. return this.start.isTouching( this.end );
  82. }
  83. /**
  84. * Range root element.
  85. *
  86. * @type {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment}
  87. */
  88. get root() {
  89. return this.start.root;
  90. }
  91. /**
  92. * Checks whether this range contains given {@link module:engine/model/position~Position position}.
  93. *
  94. * @param {module:engine/model/position~Position} position Position to check.
  95. * @returns {Boolean} `true` if given {@link module:engine/model/position~Position position} is contained in this range, `false` otherwise.
  96. */
  97. containsPosition( position ) {
  98. return position.isAfter( this.start ) && position.isBefore( this.end );
  99. }
  100. /**
  101. * Checks whether this range contains given {@link ~Range range}.
  102. *
  103. * @param {module:engine/model/range~Range} otherRange Range to check.
  104. * @returns {Boolean} `true` if given {@link ~Range range} boundaries are contained by this range, `false` otherwise.
  105. */
  106. containsRange( otherRange ) {
  107. return this.containsPosition( otherRange.start ) && this.containsPosition( otherRange.end );
  108. }
  109. /**
  110. * Two ranges are equal if their {@link #start start} and
  111. * {@link #end end} positions are equal.
  112. *
  113. * @param {module:engine/model/range~Range} otherRange Range to compare with.
  114. * @returns {Boolean} `true` if ranges are equal, `false` otherwise.
  115. */
  116. isEqual( otherRange ) {
  117. return this.start.isEqual( otherRange.start ) && this.end.isEqual( otherRange.end );
  118. }
  119. /**
  120. * Checks and returns whether this range intersects with given range.
  121. *
  122. * @param {module:engine/model/range~Range} otherRange Range to compare with.
  123. * @returns {Boolean} `true` if ranges intersect, `false` otherwise.
  124. */
  125. isIntersecting( otherRange ) {
  126. return this.start.isBefore( otherRange.end ) && this.end.isAfter( otherRange.start );
  127. }
  128. /**
  129. * Computes which part(s) of this {@link ~Range range} is not a part of given {@link ~Range range}.
  130. * Returned array contains zero, one or two {@link ~Range ranges}.
  131. *
  132. * Examples:
  133. *
  134. * let range = new Range( new Position( root, [ 2, 7 ] ), new Position( root, [ 4, 0, 1 ] ) );
  135. * let otherRange = new Range( new Position( root, [ 1 ] ), new Position( root, [ 5 ] ) );
  136. * let transformed = range.getDifference( otherRange );
  137. * // transformed array has no ranges because `otherRange` contains `range`
  138. *
  139. * otherRange = new Range( new Position( root, [ 1 ] ), new Position( root, [ 3 ] ) );
  140. * transformed = range.getDifference( otherRange );
  141. * // transformed array has one range: from [ 3 ] to [ 4, 0, 1 ]
  142. *
  143. * otherRange = new Range( new Position( root, [ 3 ] ), new Position( root, [ 4 ] ) );
  144. * transformed = range.getDifference( otherRange );
  145. * // transformed array has two ranges: from [ 2, 7 ] to [ 3 ] and from [ 4 ] to [ 4, 0, 1 ]
  146. *
  147. * @param {module:engine/model/range~Range} otherRange Range to differentiate against.
  148. * @returns {Array.<module:engine/model/range~Range>} The difference between ranges.
  149. */
  150. getDifference( otherRange ) {
  151. const ranges = [];
  152. if ( this.isIntersecting( otherRange ) ) {
  153. // Ranges intersect.
  154. if ( this.containsPosition( otherRange.start ) ) {
  155. // Given range start is inside this range. This means that we have to
  156. // add shrunken range - from the start to the middle of this range.
  157. ranges.push( new Range( this.start, otherRange.start ) );
  158. }
  159. if ( this.containsPosition( otherRange.end ) ) {
  160. // Given range end is inside this range. This means that we have to
  161. // add shrunken range - from the middle of this range to the end.
  162. ranges.push( new Range( otherRange.end, this.end ) );
  163. }
  164. } else {
  165. // Ranges do not intersect, return the original range.
  166. ranges.push( Range.createFromRange( this ) );
  167. }
  168. return ranges;
  169. }
  170. /**
  171. * Returns an intersection of this {@link ~Range range} and given {@link ~Range range}.
  172. * Intersection is a common part of both of those ranges. If ranges has no common part, returns `null`.
  173. *
  174. * Examples:
  175. *
  176. * let range = new Range( new Position( root, [ 2, 7 ] ), new Position( root, [ 4, 0, 1 ] ) );
  177. * let otherRange = new Range( new Position( root, [ 1 ] ), new Position( root, [ 2 ] ) );
  178. * let transformed = range.getIntersection( otherRange ); // null - ranges have no common part
  179. *
  180. * otherRange = new Range( new Position( root, [ 3 ] ), new Position( root, [ 5 ] ) );
  181. * transformed = range.getIntersection( otherRange ); // range from [ 3 ] to [ 4, 0, 1 ]
  182. *
  183. * @param {module:engine/model/range~Range} otherRange Range to check for intersection.
  184. * @returns {module:engine/model/range~Range|null} A common part of given ranges or `null` if ranges have no common part.
  185. */
  186. getIntersection( otherRange ) {
  187. if ( this.isIntersecting( otherRange ) ) {
  188. // Ranges intersect, so a common range will be returned.
  189. // At most, it will be same as this range.
  190. let commonRangeStart = this.start;
  191. let commonRangeEnd = this.end;
  192. if ( this.containsPosition( otherRange.start ) ) {
  193. // Given range start is inside this range. This means thaNt we have to
  194. // shrink common range to the given range start.
  195. commonRangeStart = otherRange.start;
  196. }
  197. if ( this.containsPosition( otherRange.end ) ) {
  198. // Given range end is inside this range. This means that we have to
  199. // shrink common range to the given range end.
  200. commonRangeEnd = otherRange.end;
  201. }
  202. return new Range( commonRangeStart, commonRangeEnd );
  203. }
  204. // Ranges do not intersect, so they do not have common part.
  205. return null;
  206. }
  207. /**
  208. * Computes and returns the smallest set of {@link #isFlat flat} ranges, that covers this range in whole.
  209. *
  210. * See an example of a model structure (`[` and `]` are range boundaries):
  211. *
  212. * root root
  213. * |- element DIV DIV P2 P3 DIV
  214. * | |- element H H P1 f o o b a r H P4
  215. * | | |- "fir[st" fir[st lorem se]cond ipsum
  216. * | |- element P1
  217. * | | |- "lorem" ||
  218. * |- element P2 ||
  219. * | |- "foo" VV
  220. * |- element P3
  221. * | |- "bar" root
  222. * |- element DIV DIV [P2 P3] DIV
  223. * | |- element H H [P1] f o o b a r H P4
  224. * | | |- "se]cond" fir[st] lorem [se]cond ipsum
  225. * | |- element P4
  226. * | | |- "ipsum"
  227. *
  228. * As it can be seen, letters contained in the range are: `stloremfoobarse`, spread across different parents.
  229. * We are looking for minimal set of flat ranges that contains the same nodes.
  230. *
  231. * Minimal flat ranges for above range `( [ 0, 0, 3 ], [ 3, 0, 2 ] )` will be:
  232. *
  233. * ( [ 0, 0, 3 ], [ 0, 0, 5 ] ) = "st"
  234. * ( [ 0, 1 ], [ 0, 2 ] ) = element P1 ("lorem")
  235. * ( [ 1 ], [ 3 ] ) = element P2, element P3 ("foobar")
  236. * ( [ 3, 0, 0 ], [ 3, 0, 2 ] ) = "se"
  237. *
  238. * **Note:** if an {@link module:engine/model/element~Element element} is not wholly contained in this range, it won't be returned
  239. * in any of the returned flat ranges. See in the example how `H` elements at the beginning and at the end of the range
  240. * were omitted. Only their parts that were wholly in the range were returned.
  241. *
  242. * **Note:** this method is not returning flat ranges that contain no nodes.
  243. *
  244. * @returns {Array.<module:engine/model/range~Range>} Array of flat ranges covering this range.
  245. */
  246. getMinimalFlatRanges() {
  247. const ranges = [];
  248. const diffAt = this.start.getCommonPath( this.end ).length;
  249. let pos = Position.createFromPosition( this.start );
  250. let posParent = pos.parent;
  251. // Go up.
  252. while ( pos.path.length > diffAt + 1 ) {
  253. let howMany = posParent.maxOffset - pos.offset;
  254. if ( howMany !== 0 ) {
  255. ranges.push( new Range( pos, pos.getShiftedBy( howMany ) ) );
  256. }
  257. pos.path = pos.path.slice( 0, -1 );
  258. pos.offset++;
  259. posParent = posParent.parent;
  260. }
  261. // Go down.
  262. while ( pos.path.length <= this.end.path.length ) {
  263. let offset = this.end.path[ pos.path.length - 1 ];
  264. let howMany = offset - pos.offset;
  265. if ( howMany !== 0 ) {
  266. ranges.push( new Range( pos, pos.getShiftedBy( howMany ) ) );
  267. }
  268. pos.offset = offset;
  269. pos.path.push( 0 );
  270. }
  271. return ranges;
  272. }
  273. /**
  274. * Creates a {@link module:engine/model/treewalker~TreeWalker TreeWalker} instance with this range as a boundary.
  275. *
  276. * @param {Object} options Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
  277. * @param {module:engine/model/position~Position} [options.startPosition]
  278. * @param {Boolean} [options.singleCharacters=false]
  279. * @param {Boolean} [options.shallow=false]
  280. * @param {Boolean} [options.ignoreElementEnd=false]
  281. */
  282. getWalker( options = {} ) {
  283. options.boundaries = this;
  284. return new TreeWalker( options );
  285. }
  286. /**
  287. * Returns an iterator that iterates over all {@link module:engine/model/item~Item items} that are in this range and returns
  288. * them.
  289. *
  290. * This method uses {@link module:engine/model/treewalker~TreeWalker} with `boundaries` set to this range and `ignoreElementEnd` option
  291. * set to `true`. However it returns only {@link module:engine/model/item~Item model items},
  292. * not {@link module:engine/model/treewalker~TreeWalkerValue}.
  293. *
  294. * You may specify additional options for the tree walker. See {@link module:engine/model/treewalker~TreeWalker} for
  295. * a full list of available options.
  296. *
  297. * @method getItems
  298. * @param {Object} options Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
  299. * @returns {Iterable.<module:engine/model/item~Item>}
  300. */
  301. *getItems( options = {} ) {
  302. options.boundaries = this;
  303. options.ignoreElementEnd = true;
  304. const treeWalker = new TreeWalker( options );
  305. for ( let value of treeWalker ) {
  306. yield value.item;
  307. }
  308. }
  309. /**
  310. * Returns an iterator that iterates over all {@link module:engine/model/position~Position positions} that are boundaries or
  311. * contained in this range.
  312. *
  313. * This method uses {@link module:engine/model/treewalker~TreeWalker} with `boundaries` set to this range. However it returns only
  314. * {@link module:engine/model/position~Position positions}, not {@link module:engine/model/treewalker~TreeWalkerValue}.
  315. *
  316. * You may specify additional options for the tree walker. See {@link module:engine/model/treewalker~TreeWalker} for
  317. * a full list of available options.
  318. *
  319. * @param {Object} options Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
  320. * @returns {Iterable.<module:engine/model/position~Position>}
  321. */
  322. *getPositions( options = {} ) {
  323. options.boundaries = this;
  324. const treeWalker = new TreeWalker( options );
  325. yield treeWalker.position;
  326. for ( let value of treeWalker ) {
  327. yield value.nextPosition;
  328. }
  329. }
  330. /**
  331. * Returns a range that is a result of transforming this range by given `delta`.
  332. *
  333. * @param {module:engine/model/delta~Delta} delta Delta to transform range by.
  334. * @returns {Array.<module:engine/model/range~Range>} Range which is the result of transformation.
  335. */
  336. getTransformedByDelta( delta ) {
  337. let ranges = [ Range.createFromRange( this ) ];
  338. // Operation types that a range can be transformed by.
  339. const supportedTypes = new Set( [ 'insert', 'move', 'remove', 'reinsert' ] );
  340. for ( let operation of delta.operations ) {
  341. if ( supportedTypes.has( operation.type ) ) {
  342. for ( let i = 0; i < ranges.length; i++ ) {
  343. const result = ranges[ i ]._getTransformedByDocumentChange(
  344. operation.type,
  345. operation.targetPosition || operation.position,
  346. operation.howMany || operation.nodes.maxOffset,
  347. operation.sourcePosition
  348. );
  349. ranges.splice( i, 1, ...result );
  350. i += result.length - 1;
  351. }
  352. }
  353. }
  354. return ranges;
  355. }
  356. /**
  357. * Returns a range that is a result of transforming this range by a change in the model document.
  358. *
  359. * @protected
  360. * @param {'insert'|'move'|'remove'|'reinsert'} type Change type.
  361. * @param {module:engine/model/position~Position} targetPosition Position before the first changed node.
  362. * @param {Number} howMany How many nodes has been changed.
  363. * @param {module:engine/model/position~Position} sourcePosition Source position of changes.
  364. * @returns {Array.<module:engine/model/range~Range>}
  365. */
  366. _getTransformedByDocumentChange( type, targetPosition, howMany, sourcePosition ) {
  367. if ( type == 'insert' ) {
  368. return this._getTransformedByInsertion( targetPosition, howMany, false, false );
  369. } else {
  370. return this._getTransformedByMove( sourcePosition, targetPosition, howMany );
  371. }
  372. }
  373. /**
  374. * Returns an array containing one or two {@link ~Range ranges} that are a result of transforming this
  375. * {@link ~Range range} by inserting `howMany` nodes at `insertPosition`. Two {@link ~Range ranges} are
  376. * returned if the insertion was inside this {@link ~Range range} and `spread` is set to `true`.
  377. *
  378. * Examples:
  379. *
  380. * let range = new Range( new Position( root, [ 2, 7 ] ), new Position( root, [ 4, 0, 1 ] ) );
  381. * let transformed = range._getTransformedByInsertion( new Position( root, [ 1 ] ), 2 );
  382. * // transformed array has one range from [ 4, 7 ] to [ 6, 0, 1 ]
  383. *
  384. * transformed = range._getTransformedByInsertion( new Position( root, [ 4, 0, 0 ] ), 4 );
  385. * // transformed array has one range from [ 2, 7 ] to [ 4, 0, 5 ]
  386. *
  387. * transformed = range._getTransformedByInsertion( new Position( root, [ 3, 2 ] ), 4 );
  388. * // transformed array has one range, which is equal to original range
  389. *
  390. * transformed = range._getTransformedByInsertion( new Position( root, [ 3, 2 ] ), 4, true );
  391. * // transformed array has two ranges: from [ 2, 7 ] to [ 3, 2 ] and from [ 3, 6 ] to [ 4, 0, 1 ]
  392. *
  393. * transformed = range._getTransformedByInsertion( new Position( root, [ 4, 0, 1 ] ), 4, false, false );
  394. * // transformed array has one range which is equal to original range because insertion is after the range boundary
  395. *
  396. * transformed = range._getTransformedByInsertion( new Position( root, [ 4, 0, 1 ] ), 4, false, true );
  397. * // transformed array has one range: from [ 2, 7 ] to [ 4, 0, 5 ] because range was expanded
  398. *
  399. * @protected
  400. * @param {module:engine/model/position~Position} insertPosition Position where nodes are inserted.
  401. * @param {Number} howMany How many nodes are inserted.
  402. * @param {Boolean} [spread] Flag indicating whether this {~Range range} should be spread if insertion
  403. * was inside the range. Defaults to `false`.
  404. * @param {Boolean} [isSticky] Flag indicating whether insertion should expand a range if it is in a place of
  405. * range boundary. Defaults to `false`.
  406. * @returns {Array.<module:engine/model/range~Range>} Result of the transformation.
  407. */
  408. _getTransformedByInsertion( insertPosition, howMany, spread = false, isSticky = false ) {
  409. if ( spread && this.containsPosition( insertPosition ) ) {
  410. // Range has to be spread. The first part is from original start to the spread point.
  411. // The other part is from spread point to the original end, but transformed by
  412. // insertion to reflect insertion changes.
  413. return [
  414. new Range( this.start, insertPosition ),
  415. new Range(
  416. insertPosition._getTransformedByInsertion( insertPosition, howMany, true ),
  417. this.end._getTransformedByInsertion( insertPosition, howMany, this.isCollapsed )
  418. )
  419. ];
  420. } else {
  421. const range = Range.createFromRange( this );
  422. let insertBeforeStart = range.isCollapsed ? true : !isSticky;
  423. let insertBeforeEnd = range.isCollapsed ? true : isSticky;
  424. range.start = range.start._getTransformedByInsertion( insertPosition, howMany, insertBeforeStart );
  425. range.end = range.end._getTransformedByInsertion( insertPosition, howMany, insertBeforeEnd );
  426. return [ range ];
  427. }
  428. }
  429. /**
  430. * Returns an array containing {@link ~Range ranges} that are a result of transforming this
  431. * {@link ~Range range} by moving `howMany` nodes from `sourcePosition` to `targetPosition`.
  432. *
  433. * @protected
  434. * @param {module:engine/model/position~Position} sourcePosition Position from which nodes are moved.
  435. * @param {module:engine/model/position~Position} targetPosition Position to where nodes are moved.
  436. * @param {Number} howMany How many nodes are moved.
  437. * @param {Boolean} [spread] Flag indicating whether this {~Range range} should be spread if insertion
  438. * was inside the range. Defaults to `false`.
  439. * @returns {Array.<module:engine/model/range~Range>} Result of the transformation.
  440. */
  441. _getTransformedByMove( sourcePosition, targetPosition, howMany ) {
  442. if ( this.isCollapsed ) {
  443. const newPos = this.start._getTransformedByMove( sourcePosition, targetPosition, howMany, true, true );
  444. return [ new Range( newPos ) ];
  445. }
  446. let result;
  447. const moveRange = new Range( sourcePosition, sourcePosition.getShiftedBy( howMany ) );
  448. const differenceSet = this.getDifference( moveRange );
  449. let difference = null;
  450. const common = this.getIntersection( moveRange );
  451. if ( differenceSet.length == 1 ) {
  452. // `moveRange` and this range intersects.
  453. difference = new Range(
  454. differenceSet[ 0 ].start._getTransformedByDeletion( sourcePosition, howMany ),
  455. differenceSet[ 0 ].end._getTransformedByDeletion( sourcePosition, howMany )
  456. );
  457. } else if ( differenceSet.length == 2 ) {
  458. // `moveRange` is inside this range.
  459. difference = new Range(
  460. this.start,
  461. this.end._getTransformedByDeletion( sourcePosition, howMany )
  462. );
  463. } // else, `moveRange` wholly contains this range.
  464. const insertPosition = targetPosition._getTransformedByDeletion( sourcePosition, howMany );
  465. if ( difference ) {
  466. result = difference._getTransformedByInsertion( insertPosition, howMany, common !== null );
  467. } else {
  468. result = [];
  469. }
  470. if ( common ) {
  471. result.push( new Range(
  472. common.start._getCombined( moveRange.start, insertPosition ),
  473. common.end._getCombined( moveRange.start, insertPosition )
  474. ) );
  475. }
  476. return result;
  477. }
  478. /**
  479. * Creates a new range, spreading from specified {@link module:engine/model/position~Position position} to a position moved by
  480. * given `shift`. If `shift` is a negative value, shifted position is treated as the beginning of the range.
  481. *
  482. * @param {module:engine/model/position~Position} position Beginning of the range.
  483. * @param {Number} shift How long the range should be.
  484. * @returns {module:engine/model/range~Range}
  485. */
  486. static createFromPositionAndShift( position, shift ) {
  487. const start = position;
  488. const end = position.getShiftedBy( shift );
  489. return shift > 0 ? new this( start, end ) : new this( end, start );
  490. }
  491. /**
  492. * Creates a range from given parents and offsets.
  493. *
  494. * @param {module:engine/model/element~Element} startElement Start position parent element.
  495. * @param {Number} startOffset Start position offset.
  496. * @param {module:engine/model/element~Element} endElement End position parent element.
  497. * @param {Number} endOffset End position offset.
  498. * @returns {module:engine/model/range~Range}
  499. */
  500. static createFromParentsAndOffsets( startElement, startOffset, endElement, endOffset ) {
  501. return new this(
  502. Position.createFromParentAndOffset( startElement, startOffset ),
  503. Position.createFromParentAndOffset( endElement, endOffset )
  504. );
  505. }
  506. /**
  507. * Creates a new instance of `Range` which is equal to passed range.
  508. *
  509. * @param {module:engine/model/range~Range} range Range to clone.
  510. * @returns {module:engine/model/range~Range}
  511. */
  512. static createFromRange( range ) {
  513. return new this( range.start, range.end );
  514. }
  515. /**
  516. * Creates a range inside an {@link module:engine/model/element~Element element} which starts before the first child of
  517. * that element and ends after the last child of that element.
  518. *
  519. * @param {module:engine/model/element~Element} element Element which is a parent for the range.
  520. * @returns {module:engine/model/range~Range}
  521. */
  522. static createIn( element ) {
  523. return this.createFromParentsAndOffsets( element, 0, element, element.maxOffset );
  524. }
  525. /**
  526. * Creates a range that starts before given {@link module:engine/model/item~Item model item} and ends after it.
  527. *
  528. * @param {module:engine/model/item~Item} item
  529. * @returns {module:engine/model/range~Range}
  530. */
  531. static createOn( item ) {
  532. return this.createFromPositionAndShift( Position.createBefore( item ), item.offsetSize );
  533. }
  534. /**
  535. * Combines all ranges from the passed array into a one range. At least one range has to be passed.
  536. * Passed ranges must not have common parts.
  537. *
  538. * The first range from the array is a reference range. If other ranges
  539. * {@link module:engine/model/position~Position#isTouching are touching} the reference range, they will get combined into one range.
  540. *
  541. * [ ][] [ ][ ][ ref range ][ ][] [ ] // Passed ranges, shown sorted. "Ref range" was the first range in original array.
  542. * [ returned range ] [ ] // The combined range.
  543. * [ ] // The result of the function if the first range was a reference range.
  544. * [ ] // The result of the function if the third-to-seventh range was a reference range.
  545. * [ ] // The result of the function if the last range was a reference range.
  546. *
  547. * @param {Array.<module:engine/model/range~Range>} ranges Ranges to combine.
  548. * @returns {module:engine/model/range~Range} Combined range.
  549. */
  550. static createFromRanges( ranges ) {
  551. if ( ranges.length === 0 ) {
  552. /**
  553. * At least one range has to be passed.
  554. *
  555. * @error range-create-from-ranges-empty-array
  556. */
  557. throw new CKEditorError( 'range-create-from-ranges-empty-array: At least one range has to be passed.' );
  558. } else if ( ranges.length == 1 ) {
  559. return Range.createFromRange( ranges[ 0 ] );
  560. }
  561. // 1. Set the first range in `ranges` array as a reference range.
  562. // If we are going to return just a one range, one of the ranges need to be the reference one.
  563. // Other ranges will be stuck to that range, if possible.
  564. const ref = ranges[ 0 ];
  565. // 2. Sort all the ranges so it's easier to process them.
  566. ranges.sort( ( a, b ) => a.start.isAfter( b.start ) );
  567. // 3. Check at which index the reference range is now.
  568. const refIndex = ranges.indexOf( ref );
  569. // 4. At this moment we don't need the original range.
  570. // We are going to modify the result and we need to return a new instance of Range.
  571. // We have to create a copy of the reference range.
  572. const result = new this( ref.start, ref.end );
  573. // 5. Ranges before reference range should be glued starting from the "last one", that is the range
  574. // that is closest to the reference range.
  575. for ( let i = refIndex - 1; i >= 0; i++ ) {
  576. if ( ranges[ i ].end.isTouching( result.start ) ) {
  577. result.start = Position.createFromPosition( ranges[ i ].start );
  578. } else {
  579. // If range do not touch with reference range there is no point in looking further.
  580. break;
  581. }
  582. }
  583. // 5. Ranges after reference range should be glued starting from the "first one", that is the range
  584. // that is closest to the reference range.
  585. for ( let i = refIndex + 1; i < ranges.length; i++ ) {
  586. if ( ranges[ i ].start.isTouching( result.end ) ) {
  587. result.end = Position.createFromPosition( ranges[ i ].end );
  588. } else {
  589. // If range do not touch with reference range there is no point in looking further.
  590. break;
  591. }
  592. }
  593. return result;
  594. }
  595. /**
  596. * Creates a `Range` instance from given plain object (i.e. parsed JSON string).
  597. *
  598. * @param {Object} json Plain object to be converted to `Range`.
  599. * @param {module:engine/model/document~Document} doc Document object that will be range owner.
  600. * @returns {module:engine/model/element~Element} `Range` instance created using given plain object.
  601. */
  602. static fromJSON( json, doc ) {
  603. return new this( Position.fromJSON( json.start, doc ), Position.fromJSON( json.end, doc ) );
  604. }
  605. }