8
0

range.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  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/range
  7. */
  8. import Position from './position';
  9. import TreeWalker from './treewalker';
  10. import CKEditorError from '@ckeditor/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. * Range root element.
  74. *
  75. * @type {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment}
  76. */
  77. get root() {
  78. return this.start.root;
  79. }
  80. /**
  81. * Checks whether this range contains given {@link module:engine/model/position~Position position}.
  82. *
  83. * @param {module:engine/model/position~Position} position Position to check.
  84. * @returns {Boolean} `true` if given {@link module:engine/model/position~Position position} is contained
  85. * in this range,`false` otherwise.
  86. */
  87. containsPosition( position ) {
  88. return position.isAfter( this.start ) && position.isBefore( this.end );
  89. }
  90. /**
  91. * Checks whether this range contains given {@link ~Range range}.
  92. *
  93. * @param {module:engine/model/range~Range} otherRange Range to check.
  94. * @param {Boolean} [loose=false] Whether the check is loose or strict. If the check is strict (`false`), compared range cannot
  95. * start or end at the same position as this range boundaries. If the check is loose (`true`), compared range can start, end or
  96. * even be equal to this range. Note that collapsed ranges are always compared in strict mode.
  97. * @returns {Boolean} `true` if given {@link ~Range range} boundaries are contained by this range, `false` otherwise.
  98. */
  99. containsRange( otherRange, loose = false ) {
  100. if ( otherRange.isCollapsed ) {
  101. loose = false;
  102. }
  103. const containsStart = this.containsPosition( otherRange.start ) || ( loose && this.start.isEqual( otherRange.start ) );
  104. const containsEnd = this.containsPosition( otherRange.end ) || ( loose && this.end.isEqual( otherRange.end ) );
  105. return containsStart && containsEnd;
  106. }
  107. /**
  108. * Two ranges are equal if their {@link #start start} and {@link #end end} positions are equal.
  109. *
  110. * @param {module:engine/model/range~Range} otherRange Range to compare with.
  111. * @returns {Boolean} `true` if ranges are equal, `false` otherwise.
  112. */
  113. isEqual( otherRange ) {
  114. return this.start.isEqual( otherRange.start ) && this.end.isEqual( otherRange.end );
  115. }
  116. /**
  117. * Checks and returns whether this range intersects with given range.
  118. *
  119. * @param {module:engine/model/range~Range} otherRange Range to compare with.
  120. * @returns {Boolean} `true` if ranges intersect, `false` otherwise.
  121. */
  122. isIntersecting( otherRange ) {
  123. return this.start.isBefore( otherRange.end ) && this.end.isAfter( otherRange.start );
  124. }
  125. /**
  126. * Computes which part(s) of this {@link ~Range range} is not a part of given {@link ~Range range}.
  127. * Returned array contains zero, one or two {@link ~Range ranges}.
  128. *
  129. * Examples:
  130. *
  131. * let range = new Range( new Position( root, [ 2, 7 ] ), new Position( root, [ 4, 0, 1 ] ) );
  132. * let otherRange = new Range( new Position( root, [ 1 ] ), new Position( root, [ 5 ] ) );
  133. * let transformed = range.getDifference( otherRange );
  134. * // transformed array has no ranges because `otherRange` contains `range`
  135. *
  136. * otherRange = new Range( new Position( root, [ 1 ] ), new Position( root, [ 3 ] ) );
  137. * transformed = range.getDifference( otherRange );
  138. * // transformed array has one range: from [ 3 ] to [ 4, 0, 1 ]
  139. *
  140. * otherRange = new Range( new Position( root, [ 3 ] ), new Position( root, [ 4 ] ) );
  141. * transformed = range.getDifference( otherRange );
  142. * // transformed array has two ranges: from [ 2, 7 ] to [ 3 ] and from [ 4 ] to [ 4, 0, 1 ]
  143. *
  144. * @param {module:engine/model/range~Range} otherRange Range to differentiate against.
  145. * @returns {Array.<module:engine/model/range~Range>} The difference between ranges.
  146. */
  147. getDifference( otherRange ) {
  148. const ranges = [];
  149. if ( this.isIntersecting( otherRange ) ) {
  150. // Ranges intersect.
  151. if ( this.containsPosition( otherRange.start ) ) {
  152. // Given range start is inside this range. This means that we have to
  153. // add shrunken range - from the start to the middle of this range.
  154. ranges.push( new Range( this.start, otherRange.start ) );
  155. }
  156. if ( this.containsPosition( otherRange.end ) ) {
  157. // Given range end is inside this range. This means that we have to
  158. // add shrunken range - from the middle of this range to the end.
  159. ranges.push( new Range( otherRange.end, this.end ) );
  160. }
  161. } else {
  162. // Ranges do not intersect, return the original range.
  163. ranges.push( Range.createFromRange( this ) );
  164. }
  165. return ranges;
  166. }
  167. /**
  168. * Returns an intersection of this {@link ~Range range} and given {@link ~Range range}.
  169. * Intersection is a common part of both of those ranges. If ranges has no common part, returns `null`.
  170. *
  171. * Examples:
  172. *
  173. * let range = new Range( new Position( root, [ 2, 7 ] ), new Position( root, [ 4, 0, 1 ] ) );
  174. * let otherRange = new Range( new Position( root, [ 1 ] ), new Position( root, [ 2 ] ) );
  175. * let transformed = range.getIntersection( otherRange ); // null - ranges have no common part
  176. *
  177. * otherRange = new Range( new Position( root, [ 3 ] ), new Position( root, [ 5 ] ) );
  178. * transformed = range.getIntersection( otherRange ); // range from [ 3 ] to [ 4, 0, 1 ]
  179. *
  180. * @param {module:engine/model/range~Range} otherRange Range to check for intersection.
  181. * @returns {module:engine/model/range~Range|null} A common part of given ranges or `null` if ranges have no common part.
  182. */
  183. getIntersection( otherRange ) {
  184. if ( this.isIntersecting( otherRange ) ) {
  185. // Ranges intersect, so a common range will be returned.
  186. // At most, it will be same as this range.
  187. let commonRangeStart = this.start;
  188. let commonRangeEnd = this.end;
  189. if ( this.containsPosition( otherRange.start ) ) {
  190. // Given range start is inside this range. This means thaNt we have to
  191. // shrink common range to the given range start.
  192. commonRangeStart = otherRange.start;
  193. }
  194. if ( this.containsPosition( otherRange.end ) ) {
  195. // Given range end is inside this range. This means that we have to
  196. // shrink common range to the given range end.
  197. commonRangeEnd = otherRange.end;
  198. }
  199. return new Range( commonRangeStart, commonRangeEnd );
  200. }
  201. // Ranges do not intersect, so they do not have common part.
  202. return null;
  203. }
  204. /**
  205. * Computes and returns the smallest set of {@link #isFlat flat} ranges, that covers this range in whole.
  206. *
  207. * See an example of a model structure (`[` and `]` are range boundaries):
  208. *
  209. * root root
  210. * |- element DIV DIV P2 P3 DIV
  211. * | |- element H H P1 f o o b a r H P4
  212. * | | |- "fir[st" fir[st lorem se]cond ipsum
  213. * | |- element P1
  214. * | | |- "lorem" ||
  215. * |- element P2 ||
  216. * | |- "foo" VV
  217. * |- element P3
  218. * | |- "bar" root
  219. * |- element DIV DIV [P2 P3] DIV
  220. * | |- element H H [P1] f o o b a r H P4
  221. * | | |- "se]cond" fir[st] lorem [se]cond ipsum
  222. * | |- element P4
  223. * | | |- "ipsum"
  224. *
  225. * As it can be seen, letters contained in the range are: `stloremfoobarse`, spread across different parents.
  226. * We are looking for minimal set of flat ranges that contains the same nodes.
  227. *
  228. * Minimal flat ranges for above range `( [ 0, 0, 3 ], [ 3, 0, 2 ] )` will be:
  229. *
  230. * ( [ 0, 0, 3 ], [ 0, 0, 5 ] ) = "st"
  231. * ( [ 0, 1 ], [ 0, 2 ] ) = element P1 ("lorem")
  232. * ( [ 1 ], [ 3 ] ) = element P2, element P3 ("foobar")
  233. * ( [ 3, 0, 0 ], [ 3, 0, 2 ] ) = "se"
  234. *
  235. * **Note:** if an {@link module:engine/model/element~Element element} is not wholly contained in this range, it won't be returned
  236. * in any of the returned flat ranges. See in the example how `H` elements at the beginning and at the end of the range
  237. * were omitted. Only their parts that were wholly in the range were returned.
  238. *
  239. * **Note:** this method is not returning flat ranges that contain no nodes.
  240. *
  241. * @returns {Array.<module:engine/model/range~Range>} Array of flat ranges covering this range.
  242. */
  243. getMinimalFlatRanges() {
  244. const ranges = [];
  245. const diffAt = this.start.getCommonPath( this.end ).length;
  246. const pos = Position.createFromPosition( this.start );
  247. let posParent = pos.parent;
  248. // Go up.
  249. while ( pos.path.length > diffAt + 1 ) {
  250. const howMany = posParent.maxOffset - pos.offset;
  251. if ( howMany !== 0 ) {
  252. ranges.push( new Range( pos, pos.getShiftedBy( howMany ) ) );
  253. }
  254. pos.path = pos.path.slice( 0, -1 );
  255. pos.offset++;
  256. posParent = posParent.parent;
  257. }
  258. // Go down.
  259. while ( pos.path.length <= this.end.path.length ) {
  260. const offset = this.end.path[ pos.path.length - 1 ];
  261. const howMany = offset - pos.offset;
  262. if ( howMany !== 0 ) {
  263. ranges.push( new Range( pos, pos.getShiftedBy( howMany ) ) );
  264. }
  265. pos.offset = offset;
  266. pos.path.push( 0 );
  267. }
  268. return ranges;
  269. }
  270. /**
  271. * Creates a {@link module:engine/model/treewalker~TreeWalker TreeWalker} instance with this range as a boundary.
  272. *
  273. * @param {Object} options Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
  274. * @param {module:engine/model/position~Position} [options.startPosition]
  275. * @param {Boolean} [options.singleCharacters=false]
  276. * @param {Boolean} [options.shallow=false]
  277. * @param {Boolean} [options.ignoreElementEnd=false]
  278. */
  279. getWalker( options = {} ) {
  280. options.boundaries = this;
  281. return new TreeWalker( options );
  282. }
  283. /**
  284. * Returns an iterator that iterates over all {@link module:engine/model/item~Item items} that are in this range and returns
  285. * them.
  286. *
  287. * This method uses {@link module:engine/model/treewalker~TreeWalker} with `boundaries` set to this range and `ignoreElementEnd` option
  288. * set to `true`. However it returns only {@link module:engine/model/item~Item model items},
  289. * not {@link module:engine/model/treewalker~TreeWalkerValue}.
  290. *
  291. * You may specify additional options for the tree walker. See {@link module:engine/model/treewalker~TreeWalker} for
  292. * a full list of available options.
  293. *
  294. * @method getItems
  295. * @param {Object} options Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
  296. * @returns {Iterable.<module:engine/model/item~Item>}
  297. */
  298. * getItems( options = {} ) {
  299. options.boundaries = this;
  300. options.ignoreElementEnd = true;
  301. const treeWalker = new TreeWalker( options );
  302. for ( const value of treeWalker ) {
  303. yield value.item;
  304. }
  305. }
  306. /**
  307. * Returns an iterator that iterates over all {@link module:engine/model/position~Position positions} that are boundaries or
  308. * contained in this range.
  309. *
  310. * This method uses {@link module:engine/model/treewalker~TreeWalker} with `boundaries` set to this range. However it returns only
  311. * {@link module:engine/model/position~Position positions}, not {@link module:engine/model/treewalker~TreeWalkerValue}.
  312. *
  313. * You may specify additional options for the tree walker. See {@link module:engine/model/treewalker~TreeWalker} for
  314. * a full list of available options.
  315. *
  316. * @param {Object} options Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
  317. * @returns {Iterable.<module:engine/model/position~Position>}
  318. */
  319. * getPositions( options = {} ) {
  320. options.boundaries = this;
  321. const treeWalker = new TreeWalker( options );
  322. yield treeWalker.position;
  323. for ( const value of treeWalker ) {
  324. yield value.nextPosition;
  325. }
  326. }
  327. /**
  328. * Returns a range that is a result of transforming this range by given `delta`.
  329. *
  330. * **Note:** transformation may break one range into multiple ranges (e.g. when a part of the range is
  331. * moved to a different part of document tree). For this reason, an array is returned by this method and it
  332. * may contain one or more `Range` instances.
  333. *
  334. * @param {module:engine/model/delta/delta~Delta} delta Delta to transform range by.
  335. * @returns {Array.<module:engine/model/range~Range>} Range which is the result of transformation.
  336. */
  337. getTransformedByDelta( delta ) {
  338. const ranges = [ Range.createFromRange( this ) ];
  339. // Operation types that a range can be transformed by.
  340. const supportedTypes = new Set( [ 'insert', 'move', 'remove', 'reinsert' ] );
  341. for ( const operation of delta.operations ) {
  342. if ( supportedTypes.has( operation.type ) ) {
  343. for ( let i = 0; i < ranges.length; i++ ) {
  344. const result = ranges[ i ]._getTransformedByDocumentChange(
  345. operation.type,
  346. delta.type,
  347. operation.targetPosition || operation.position,
  348. operation.howMany || operation.nodes.maxOffset,
  349. operation.sourcePosition
  350. );
  351. ranges.splice( i, 1, ...result );
  352. i += result.length - 1;
  353. }
  354. }
  355. }
  356. return ranges;
  357. }
  358. /**
  359. * Returns a range that is a result of transforming this range by multiple `deltas`.
  360. *
  361. * **Note:** transformation may break one range into multiple ranges (e.g. when a part of the range is
  362. * moved to a different part of document tree). For this reason, an array is returned by this method and it
  363. * may contain one or more `Range` instances.
  364. *
  365. * @param {Iterable.<module:engine/model/delta/delta~Delta>} deltas Deltas to transform the range by.
  366. * @returns {Array.<module:engine/model/range~Range>} Range which is the result of transformation.
  367. */
  368. getTransformedByDeltas( deltas ) {
  369. const ranges = [ Range.createFromRange( this ) ];
  370. for ( const delta of deltas ) {
  371. for ( let i = 0; i < ranges.length; i++ ) {
  372. const result = ranges[ i ].getTransformedByDelta( delta );
  373. ranges.splice( i, 1, ...result );
  374. i += result.length - 1;
  375. }
  376. }
  377. // It may happen that a range is split into two, and then the part of second "piece" is moved into first
  378. // "piece". In this case we will have incorrect third range, which should not be included in the result --
  379. // because it is already included in the first "piece". In this loop we are looking for all such ranges that
  380. // are inside other ranges and we simply remove them.
  381. for ( let i = 0; i < ranges.length; i++ ) {
  382. const range = ranges[ i ];
  383. for ( let j = i + 1; j < ranges.length; j++ ) {
  384. const next = ranges[ j ];
  385. if ( range.containsRange( next ) || next.containsRange( range ) || range.isEqual( next ) ) {
  386. ranges.splice( j, 1 );
  387. }
  388. }
  389. }
  390. return ranges;
  391. }
  392. /**
  393. * Returns a range that is a result of transforming this range by a change in the model document.
  394. *
  395. * @protected
  396. * @param {'insert'|'move'|'remove'|'reinsert'} type Change type.
  397. * @param {String} deltaType Type of delta that introduced the change.
  398. * @param {module:engine/model/position~Position} targetPosition Position before the first changed node.
  399. * @param {Number} howMany How many nodes has been changed.
  400. * @param {module:engine/model/position~Position} sourcePosition Source position of changes.
  401. * @returns {Array.<module:engine/model/range~Range>}
  402. */
  403. _getTransformedByDocumentChange( type, deltaType, targetPosition, howMany, sourcePosition ) {
  404. if ( type == 'insert' ) {
  405. return this._getTransformedByInsertion( targetPosition, howMany, false, false );
  406. } else {
  407. const sourceRange = Range.createFromPositionAndShift( sourcePosition, howMany );
  408. if (
  409. deltaType == 'merge' &&
  410. this.isCollapsed &&
  411. ( this.start.isEqual( sourceRange.start ) || this.start.isEqual( sourceRange.end ) )
  412. ) {
  413. // Collapsed range is in merged element.
  414. // Without fix, the range would end up in the graveyard, together with removed element.
  415. // <p>foo</p><p>[]bar</p> -> <p>foobar</p><p>[]</p> -> <p>foobar</p> -> <p>foo[]bar</p>
  416. return [ new Range( targetPosition.getShiftedBy( this.start.offset ) ) ];
  417. } else if ( type == 'move' ) {
  418. // In all examples `[]` is `this` and `{}` is `sourceRange`, while `^` is move target position.
  419. //
  420. // Example:
  421. // <p>xx</p>^<w>{<p>a[b</p>}</w><p>c]d</p> --> <p>xx</p><p>a[b</p><w></w><p>c]d</p>
  422. // ^<p>xx</p><w>{<p>a[b</p>}</w><p>c]d</p> --> <p>a[b</p><p>xx</p><w></w><p>c]d</p> // Note <p>xx</p> inclusion.
  423. // <w>{<p>a[b</p>}</w>^<p>c]d</p> --> <w></w><p>a[b</p><p>c]d</p>
  424. if (
  425. sourceRange.containsPosition( this.start ) &&
  426. this.containsPosition( sourceRange.end ) &&
  427. this.end.isAfter( targetPosition )
  428. ) {
  429. const start = this.start._getCombined(
  430. sourcePosition,
  431. targetPosition._getTransformedByDeletion( sourcePosition, howMany )
  432. );
  433. const end = this.end._getTransformedByMove( sourcePosition, targetPosition, howMany, false, false );
  434. return [ new Range( start, end ) ];
  435. }
  436. // Example:
  437. // <p>c[d</p><w>{<p>a]b</p>}</w>^<p>xx</p> --> <p>c[d</p><w></w><p>a]b</p><p>xx</p>
  438. // <p>c[d</p><w>{<p>a]b</p>}</w><p>xx</p>^ --> <p>c[d</p><w></w><p>xx</p><p>a]b</p> // Note <p>xx</p> inclusion.
  439. // <p>c[d</p>^<w>{<p>a]b</p>}</w> --> <p>c[d</p><p>a]b</p><w></w>
  440. if (
  441. sourceRange.containsPosition( this.end ) &&
  442. this.containsPosition( sourceRange.start ) &&
  443. this.start.isBefore( targetPosition )
  444. ) {
  445. const start = this.start._getTransformedByMove(
  446. sourcePosition,
  447. targetPosition,
  448. howMany,
  449. true,
  450. false
  451. );
  452. const end = this.end._getCombined(
  453. sourcePosition,
  454. targetPosition._getTransformedByDeletion( sourcePosition, howMany )
  455. );
  456. return [ new Range( start, end ) ];
  457. }
  458. }
  459. return this._getTransformedByMove( sourcePosition, targetPosition, howMany );
  460. }
  461. }
  462. /**
  463. * Returns an array containing one or two {@link ~Range ranges} that are a result of transforming this
  464. * {@link ~Range range} by inserting `howMany` nodes at `insertPosition`. Two {@link ~Range ranges} are
  465. * returned if the insertion was inside this {@link ~Range range} and `spread` is set to `true`.
  466. *
  467. * Examples:
  468. *
  469. * let range = new Range( new Position( root, [ 2, 7 ] ), new Position( root, [ 4, 0, 1 ] ) );
  470. * let transformed = range._getTransformedByInsertion( new Position( root, [ 1 ] ), 2 );
  471. * // transformed array has one range from [ 4, 7 ] to [ 6, 0, 1 ]
  472. *
  473. * transformed = range._getTransformedByInsertion( new Position( root, [ 4, 0, 0 ] ), 4 );
  474. * // transformed array has one range from [ 2, 7 ] to [ 4, 0, 5 ]
  475. *
  476. * transformed = range._getTransformedByInsertion( new Position( root, [ 3, 2 ] ), 4 );
  477. * // transformed array has one range, which is equal to original range
  478. *
  479. * transformed = range._getTransformedByInsertion( new Position( root, [ 3, 2 ] ), 4, true );
  480. * // transformed array has two ranges: from [ 2, 7 ] to [ 3, 2 ] and from [ 3, 6 ] to [ 4, 0, 1 ]
  481. *
  482. * transformed = range._getTransformedByInsertion( new Position( root, [ 4, 0, 1 ] ), 4, false, false );
  483. * // transformed array has one range which is equal to original range because insertion is after the range boundary
  484. *
  485. * transformed = range._getTransformedByInsertion( new Position( root, [ 4, 0, 1 ] ), 4, false, true );
  486. * // transformed array has one range: from [ 2, 7 ] to [ 4, 0, 5 ] because range was expanded
  487. *
  488. * @protected
  489. * @param {module:engine/model/position~Position} insertPosition Position where nodes are inserted.
  490. * @param {Number} howMany How many nodes are inserted.
  491. * @param {Boolean} [spread] Flag indicating whether this {~Range range} should be spread if insertion
  492. * was inside the range. Defaults to `false`.
  493. * @param {Boolean} [isSticky] Flag indicating whether insertion should expand a range if it is in a place of
  494. * range boundary. Defaults to `false`.
  495. * @returns {Array.<module:engine/model/range~Range>} Result of the transformation.
  496. */
  497. _getTransformedByInsertion( insertPosition, howMany, spread = false, isSticky = false ) {
  498. if ( spread && this.containsPosition( insertPosition ) ) {
  499. // Range has to be spread. The first part is from original start to the spread point.
  500. // The other part is from spread point to the original end, but transformed by
  501. // insertion to reflect insertion changes.
  502. return [
  503. new Range( this.start, insertPosition ),
  504. new Range(
  505. insertPosition._getTransformedByInsertion( insertPosition, howMany, true ),
  506. this.end._getTransformedByInsertion( insertPosition, howMany, this.isCollapsed )
  507. )
  508. ];
  509. } else {
  510. const range = Range.createFromRange( this );
  511. const insertBeforeStart = range.isCollapsed ? true : !isSticky;
  512. const insertBeforeEnd = range.isCollapsed ? true : isSticky;
  513. range.start = range.start._getTransformedByInsertion( insertPosition, howMany, insertBeforeStart );
  514. range.end = range.end._getTransformedByInsertion( insertPosition, howMany, insertBeforeEnd );
  515. return [ range ];
  516. }
  517. }
  518. /**
  519. * Returns an array containing {@link ~Range ranges} that are a result of transforming this
  520. * {@link ~Range range} by moving `howMany` nodes from `sourcePosition` to `targetPosition`.
  521. *
  522. * @protected
  523. * @param {module:engine/model/position~Position} sourcePosition Position from which nodes are moved.
  524. * @param {module:engine/model/position~Position} targetPosition Position to where nodes are moved.
  525. * @param {Number} howMany How many nodes are moved.
  526. * @returns {Array.<module:engine/model/range~Range>} Result of the transformation.
  527. */
  528. _getTransformedByMove( sourcePosition, targetPosition, howMany ) {
  529. if ( this.isCollapsed ) {
  530. const newPos = this.start._getTransformedByMove( sourcePosition, targetPosition, howMany, true, false );
  531. return [ new Range( newPos ) ];
  532. }
  533. let result;
  534. const moveRange = new Range( sourcePosition, sourcePosition.getShiftedBy( howMany ) );
  535. const differenceSet = this.getDifference( moveRange );
  536. let difference = null;
  537. const common = this.getIntersection( moveRange );
  538. if ( differenceSet.length == 1 ) {
  539. // `moveRange` and this range may intersect.
  540. difference = new Range(
  541. differenceSet[ 0 ].start._getTransformedByDeletion( sourcePosition, howMany ),
  542. differenceSet[ 0 ].end._getTransformedByDeletion( sourcePosition, howMany )
  543. );
  544. } else if ( differenceSet.length == 2 ) {
  545. // `moveRange` is inside this range.
  546. difference = new Range(
  547. this.start,
  548. this.end._getTransformedByDeletion( sourcePosition, howMany )
  549. );
  550. } // else, `moveRange` contains this range.
  551. const insertPosition = targetPosition._getTransformedByDeletion( sourcePosition, howMany );
  552. if ( difference ) {
  553. result = difference._getTransformedByInsertion( insertPosition, howMany, common !== null );
  554. } else {
  555. result = [];
  556. }
  557. if ( common ) {
  558. result.push( new Range(
  559. common.start._getCombined( moveRange.start, insertPosition ),
  560. common.end._getCombined( moveRange.start, insertPosition )
  561. ) );
  562. }
  563. return result;
  564. }
  565. /**
  566. * Creates a new range, spreading from specified {@link module:engine/model/position~Position position} to a position moved by
  567. * given `shift`. If `shift` is a negative value, shifted position is treated as the beginning of the range.
  568. *
  569. * @param {module:engine/model/position~Position} position Beginning of the range.
  570. * @param {Number} shift How long the range should be.
  571. * @returns {module:engine/model/range~Range}
  572. */
  573. static createFromPositionAndShift( position, shift ) {
  574. const start = position;
  575. const end = position.getShiftedBy( shift );
  576. return shift > 0 ? new this( start, end ) : new this( end, start );
  577. }
  578. /**
  579. * Creates a range from given parents and offsets.
  580. *
  581. * @param {module:engine/model/element~Element} startElement Start position parent element.
  582. * @param {Number} startOffset Start position offset.
  583. * @param {module:engine/model/element~Element} endElement End position parent element.
  584. * @param {Number} endOffset End position offset.
  585. * @returns {module:engine/model/range~Range}
  586. */
  587. static createFromParentsAndOffsets( startElement, startOffset, endElement, endOffset ) {
  588. return new this(
  589. Position.createFromParentAndOffset( startElement, startOffset ),
  590. Position.createFromParentAndOffset( endElement, endOffset )
  591. );
  592. }
  593. /**
  594. * Creates a new instance of `Range` which is equal to passed range.
  595. *
  596. * @param {module:engine/model/range~Range} range Range to clone.
  597. * @returns {module:engine/model/range~Range}
  598. */
  599. static createFromRange( range ) {
  600. return new this( range.start, range.end );
  601. }
  602. /**
  603. * Creates a range inside an {@link module:engine/model/element~Element element} which starts before the first child of
  604. * that element and ends after the last child of that element.
  605. *
  606. * @param {module:engine/model/element~Element} element Element which is a parent for the range.
  607. * @returns {module:engine/model/range~Range}
  608. */
  609. static createIn( element ) {
  610. return this.createFromParentsAndOffsets( element, 0, element, element.maxOffset );
  611. }
  612. /**
  613. * Creates a range that starts before given {@link module:engine/model/item~Item model item} and ends after it.
  614. *
  615. * @param {module:engine/model/item~Item} item
  616. * @returns {module:engine/model/range~Range}
  617. */
  618. static createOn( item ) {
  619. return this.createFromPositionAndShift( Position.createBefore( item ), item.offsetSize );
  620. }
  621. /**
  622. * Combines all ranges from the passed array into a one range. At least one range has to be passed.
  623. * Passed ranges must not have common parts.
  624. *
  625. * The first range from the array is a reference range. If other ranges start or end on the exactly same position where
  626. * the reference range, they get combined into one range.
  627. *
  628. * [ ][] [ ][ ][ ][ ][] [ ] // Passed ranges, shown sorted
  629. * [ ] // The result of the function if the first range was a reference range.
  630. * [ ] // The result of the function if the third-to-seventh range was a reference range.
  631. * [ ] // The result of the function if the last range was a reference range.
  632. *
  633. * @param {Array.<module:engine/model/range~Range>} ranges Ranges to combine.
  634. * @returns {module:engine/model/range~Range} Combined range.
  635. */
  636. static createFromRanges( ranges ) {
  637. if ( ranges.length === 0 ) {
  638. /**
  639. * At least one range has to be passed.
  640. *
  641. * @error range-create-from-ranges-empty-array
  642. */
  643. throw new CKEditorError( 'range-create-from-ranges-empty-array: At least one range has to be passed.' );
  644. } else if ( ranges.length == 1 ) {
  645. return this.createFromRange( ranges[ 0 ] );
  646. }
  647. // 1. Set the first range in `ranges` array as a reference range.
  648. // If we are going to return just a one range, one of the ranges need to be the reference one.
  649. // Other ranges will be stuck to that range, if possible.
  650. const ref = ranges[ 0 ];
  651. // 2. Sort all the ranges so it's easier to process them.
  652. ranges.sort( ( a, b ) => {
  653. return a.start.isAfter( b.start ) ? 1 : -1;
  654. } );
  655. // 3. Check at which index the reference range is now.
  656. const refIndex = ranges.indexOf( ref );
  657. // 4. At this moment we don't need the original range.
  658. // We are going to modify the result and we need to return a new instance of Range.
  659. // We have to create a copy of the reference range.
  660. const result = new this( ref.start, ref.end );
  661. // 5. Ranges should be checked and glued starting from the range that is closest to the reference range.
  662. // Since ranges are sorted, start with the range with index that is closest to reference range index.
  663. for ( let i = refIndex - 1; i >= 0; i++ ) {
  664. if ( ranges[ i ].end.isEqual( result.start ) ) {
  665. result.start = Position.createFromPosition( ranges[ i ].start );
  666. } else {
  667. // If ranges are not starting/ending at the same position there is no point in looking further.
  668. break;
  669. }
  670. }
  671. // 6. Ranges should be checked and glued starting from the range that is closest to the reference range.
  672. // Since ranges are sorted, start with the range with index that is closest to reference range index.
  673. for ( let i = refIndex + 1; i < ranges.length; i++ ) {
  674. if ( ranges[ i ].start.isEqual( result.end ) ) {
  675. result.end = Position.createFromPosition( ranges[ i ].end );
  676. } else {
  677. // If ranges are not starting/ending at the same position there is no point in looking further.
  678. break;
  679. }
  680. }
  681. return result;
  682. }
  683. /**
  684. * Creates a `Range` instance from given plain object (i.e. parsed JSON string).
  685. *
  686. * @param {Object} json Plain object to be converted to `Range`.
  687. * @param {module:engine/model/document~Document} doc Document object that will be range owner.
  688. * @returns {module:engine/model/element~Element} `Range` instance created using given plain object.
  689. */
  690. static fromJSON( json, doc ) {
  691. return new this( Position.fromJSON( json.start, doc ), Position.fromJSON( json.end, doc ) );
  692. }
  693. }