range.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  1. /**
  2. * @license Copyright (c) 2003-2018, 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. import compareArrays from '@ckeditor/ckeditor5-utils/src/comparearrays';
  12. /**
  13. * Range class. Range is iterable.
  14. */
  15. export default class Range {
  16. /**
  17. * Creates a range spanning from `start` position to `end` position.
  18. *
  19. * **Note:** Constructor creates it's own {@link module:engine/model/position~Position Position} instances basing on passed values.
  20. *
  21. * @param {module:engine/model/position~Position} start Start position.
  22. * @param {module:engine/model/position~Position} [end] End position. If not set, range will be collapsed at `start` position.
  23. */
  24. constructor( start, end = null ) {
  25. /**
  26. * Start position.
  27. *
  28. * @readonly
  29. * @member {module:engine/model/position~Position}
  30. */
  31. this.start = Position.createFromPosition( start );
  32. /**
  33. * End position.
  34. *
  35. * @readonly
  36. * @member {module:engine/model/position~Position}
  37. */
  38. this.end = end ? Position.createFromPosition( end ) : Position.createFromPosition( start );
  39. // If the range is collapsed, treat in a similar way as a position and set its boundaries stickiness to 'toNone'.
  40. // In other case, make the boundaries stick to the "inside" of the range.
  41. this.start.stickiness = this.isCollapsed ? 'toNone' : 'toNext';
  42. this.end.stickiness = this.isCollapsed ? 'toNone' : 'toPrevious';
  43. }
  44. /**
  45. * Iterable interface.
  46. *
  47. * Iterates over all {@link module:engine/model/item~Item items} that are in this range and returns
  48. * them together with additional information like length or {@link module:engine/model/position~Position positions},
  49. * grouped as {@link module:engine/model/treewalker~TreeWalkerValue}.
  50. * It iterates over all {@link module:engine/model/textproxy~TextProxy text contents} that are inside the range
  51. * and all the {@link module:engine/model/element~Element}s that are entered into when iterating over this range.
  52. *
  53. * This iterator uses {@link module:engine/model/treewalker~TreeWalker} with `boundaries` set to this range
  54. * and `ignoreElementEnd` option set to `true`.
  55. *
  56. * @returns {Iterable.<module:engine/model/treewalker~TreeWalkerValue>}
  57. */
  58. * [ Symbol.iterator ]() {
  59. yield* new TreeWalker( { boundaries: this, ignoreElementEnd: true } );
  60. }
  61. /**
  62. * Returns whether the range is collapsed, that is if {@link #start} and
  63. * {@link #end} positions are equal.
  64. *
  65. * @type {Boolean}
  66. */
  67. get isCollapsed() {
  68. return this.start.isEqual( this.end );
  69. }
  70. /**
  71. * Returns whether this range is flat, that is if {@link #start} position and
  72. * {@link #end} position are in the same {@link module:engine/model/position~Position#parent}.
  73. *
  74. * @type {Boolean}
  75. */
  76. get isFlat() {
  77. const startParentPath = this.start.getParentPath();
  78. const endParentPath = this.end.getParentPath();
  79. return compareArrays( startParentPath, endParentPath ) == 'same';
  80. }
  81. /**
  82. * Range root element.
  83. *
  84. * @type {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment}
  85. */
  86. get root() {
  87. return this.start.root;
  88. }
  89. /**
  90. * Checks whether this range contains given {@link module:engine/model/position~Position position}.
  91. *
  92. * @param {module:engine/model/position~Position} position Position to check.
  93. * @returns {Boolean} `true` if given {@link module:engine/model/position~Position position} is contained
  94. * in this range,`false` otherwise.
  95. */
  96. containsPosition( position ) {
  97. return position.isAfter( this.start ) && position.isBefore( this.end );
  98. }
  99. /**
  100. * Checks whether this range contains given {@link ~Range range}.
  101. *
  102. * @param {module:engine/model/range~Range} otherRange Range to check.
  103. * @param {Boolean} [loose=false] Whether the check is loose or strict. If the check is strict (`false`), compared range cannot
  104. * start or end at the same position as this range boundaries. If the check is loose (`true`), compared range can start, end or
  105. * even be equal to this range. Note that collapsed ranges are always compared in strict mode.
  106. * @returns {Boolean} `true` if given {@link ~Range range} boundaries are contained by this range, `false` otherwise.
  107. */
  108. containsRange( otherRange, loose = false ) {
  109. if ( otherRange.isCollapsed ) {
  110. loose = false;
  111. }
  112. const containsStart = this.containsPosition( otherRange.start ) || ( loose && this.start.isEqual( otherRange.start ) );
  113. const containsEnd = this.containsPosition( otherRange.end ) || ( loose && this.end.isEqual( otherRange.end ) );
  114. return containsStart && containsEnd;
  115. }
  116. /**
  117. * Checks whether given {@link module:engine/model/item~Item} is inside this range.
  118. *
  119. * @param {module:engine/model/item~Item} item Model item to check.
  120. */
  121. containsItem( item ) {
  122. const pos = Position.createBefore( item );
  123. return this.containsPosition( pos ) || this.start.isEqual( pos );
  124. }
  125. /**
  126. * Two ranges are equal if their {@link #start} and {@link #end} positions are equal.
  127. *
  128. * @param {module:engine/model/range~Range} otherRange Range to compare with.
  129. * @returns {Boolean} `true` if ranges are equal, `false` otherwise.
  130. */
  131. isEqual( otherRange ) {
  132. return this.start.isEqual( otherRange.start ) && this.end.isEqual( otherRange.end );
  133. }
  134. /**
  135. * Checks and returns whether this range intersects with given range.
  136. *
  137. * @param {module:engine/model/range~Range} otherRange Range to compare with.
  138. * @returns {Boolean} `true` if ranges intersect, `false` otherwise.
  139. */
  140. isIntersecting( otherRange ) {
  141. return this.start.isBefore( otherRange.end ) && this.end.isAfter( otherRange.start );
  142. }
  143. /**
  144. * Computes which part(s) of this {@link ~Range range} is not a part of given {@link ~Range range}.
  145. * Returned array contains zero, one or two {@link ~Range ranges}.
  146. *
  147. * Examples:
  148. *
  149. * let range = new Range( new Position( root, [ 2, 7 ] ), new Position( root, [ 4, 0, 1 ] ) );
  150. * let otherRange = new Range( new Position( root, [ 1 ] ), new Position( root, [ 5 ] ) );
  151. * let transformed = range.getDifference( otherRange );
  152. * // transformed array has no ranges because `otherRange` contains `range`
  153. *
  154. * otherRange = new Range( new Position( root, [ 1 ] ), new Position( root, [ 3 ] ) );
  155. * transformed = range.getDifference( otherRange );
  156. * // transformed array has one range: from [ 3 ] to [ 4, 0, 1 ]
  157. *
  158. * otherRange = new Range( new Position( root, [ 3 ] ), new Position( root, [ 4 ] ) );
  159. * transformed = range.getDifference( otherRange );
  160. * // transformed array has two ranges: from [ 2, 7 ] to [ 3 ] and from [ 4 ] to [ 4, 0, 1 ]
  161. *
  162. * @param {module:engine/model/range~Range} otherRange Range to differentiate against.
  163. * @returns {Array.<module:engine/model/range~Range>} The difference between ranges.
  164. */
  165. getDifference( otherRange ) {
  166. const ranges = [];
  167. if ( this.isIntersecting( otherRange ) ) {
  168. // Ranges intersect.
  169. if ( this.containsPosition( otherRange.start ) ) {
  170. // Given range start is inside this range. This means that we have to
  171. // add shrunken range - from the start to the middle of this range.
  172. ranges.push( new Range( this.start, otherRange.start ) );
  173. }
  174. if ( this.containsPosition( otherRange.end ) ) {
  175. // Given range end is inside this range. This means that we have to
  176. // add shrunken range - from the middle of this range to the end.
  177. ranges.push( new Range( otherRange.end, this.end ) );
  178. }
  179. } else {
  180. // Ranges do not intersect, return the original range.
  181. ranges.push( Range.createFromRange( this ) );
  182. }
  183. return ranges;
  184. }
  185. /**
  186. * Returns an intersection of this {@link ~Range range} and given {@link ~Range range}.
  187. * Intersection is a common part of both of those ranges. If ranges has no common part, returns `null`.
  188. *
  189. * Examples:
  190. *
  191. * let range = new Range( new Position( root, [ 2, 7 ] ), new Position( root, [ 4, 0, 1 ] ) );
  192. * let otherRange = new Range( new Position( root, [ 1 ] ), new Position( root, [ 2 ] ) );
  193. * let transformed = range.getIntersection( otherRange ); // null - ranges have no common part
  194. *
  195. * otherRange = new Range( new Position( root, [ 3 ] ), new Position( root, [ 5 ] ) );
  196. * transformed = range.getIntersection( otherRange ); // range from [ 3 ] to [ 4, 0, 1 ]
  197. *
  198. * @param {module:engine/model/range~Range} otherRange Range to check for intersection.
  199. * @returns {module:engine/model/range~Range|null} A common part of given ranges or `null` if ranges have no common part.
  200. */
  201. getIntersection( otherRange ) {
  202. if ( this.isIntersecting( otherRange ) ) {
  203. // Ranges intersect, so a common range will be returned.
  204. // At most, it will be same as this range.
  205. let commonRangeStart = this.start;
  206. let commonRangeEnd = this.end;
  207. if ( this.containsPosition( otherRange.start ) ) {
  208. // Given range start is inside this range. This means thaNt we have to
  209. // shrink common range to the given range start.
  210. commonRangeStart = otherRange.start;
  211. }
  212. if ( this.containsPosition( otherRange.end ) ) {
  213. // Given range end is inside this range. This means that we have to
  214. // shrink common range to the given range end.
  215. commonRangeEnd = otherRange.end;
  216. }
  217. return new Range( commonRangeStart, commonRangeEnd );
  218. }
  219. // Ranges do not intersect, so they do not have common part.
  220. return null;
  221. }
  222. /**
  223. * Computes and returns the smallest set of {@link #isFlat flat} ranges, that covers this range in whole.
  224. *
  225. * See an example of a model structure (`[` and `]` are range boundaries):
  226. *
  227. * root root
  228. * |- element DIV DIV P2 P3 DIV
  229. * | |- element H H P1 f o o b a r H P4
  230. * | | |- "fir[st" fir[st lorem se]cond ipsum
  231. * | |- element P1
  232. * | | |- "lorem" ||
  233. * |- element P2 ||
  234. * | |- "foo" VV
  235. * |- element P3
  236. * | |- "bar" root
  237. * |- element DIV DIV [P2 P3] DIV
  238. * | |- element H H [P1] f o o b a r H P4
  239. * | | |- "se]cond" fir[st] lorem [se]cond ipsum
  240. * | |- element P4
  241. * | | |- "ipsum"
  242. *
  243. * As it can be seen, letters contained in the range are: `stloremfoobarse`, spread across different parents.
  244. * We are looking for minimal set of flat ranges that contains the same nodes.
  245. *
  246. * Minimal flat ranges for above range `( [ 0, 0, 3 ], [ 3, 0, 2 ] )` will be:
  247. *
  248. * ( [ 0, 0, 3 ], [ 0, 0, 5 ] ) = "st"
  249. * ( [ 0, 1 ], [ 0, 2 ] ) = element P1 ("lorem")
  250. * ( [ 1 ], [ 3 ] ) = element P2, element P3 ("foobar")
  251. * ( [ 3, 0, 0 ], [ 3, 0, 2 ] ) = "se"
  252. *
  253. * **Note:** if an {@link module:engine/model/element~Element element} is not wholly contained in this range, it won't be returned
  254. * in any of the returned flat ranges. See in the example how `H` elements at the beginning and at the end of the range
  255. * were omitted. Only their parts that were wholly in the range were returned.
  256. *
  257. * **Note:** this method is not returning flat ranges that contain no nodes.
  258. *
  259. * @returns {Array.<module:engine/model/range~Range>} Array of flat ranges covering this range.
  260. */
  261. getMinimalFlatRanges() {
  262. const ranges = [];
  263. const diffAt = this.start.getCommonPath( this.end ).length;
  264. const pos = Position.createFromPosition( this.start );
  265. let posParent = pos.parent;
  266. // Go up.
  267. while ( pos.path.length > diffAt + 1 ) {
  268. const howMany = posParent.maxOffset - pos.offset;
  269. if ( howMany !== 0 ) {
  270. ranges.push( new Range( pos, pos.getShiftedBy( howMany ) ) );
  271. }
  272. pos.path = pos.path.slice( 0, -1 );
  273. pos.offset++;
  274. posParent = posParent.parent;
  275. }
  276. // Go down.
  277. while ( pos.path.length <= this.end.path.length ) {
  278. const offset = this.end.path[ pos.path.length - 1 ];
  279. const howMany = offset - pos.offset;
  280. if ( howMany !== 0 ) {
  281. ranges.push( new Range( pos, pos.getShiftedBy( howMany ) ) );
  282. }
  283. pos.offset = offset;
  284. pos.path.push( 0 );
  285. }
  286. return ranges;
  287. }
  288. /**
  289. * Creates a {@link module:engine/model/treewalker~TreeWalker TreeWalker} instance with this range as a boundary.
  290. *
  291. * @param {Object} options Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
  292. * @param {module:engine/model/position~Position} [options.startPosition]
  293. * @param {Boolean} [options.singleCharacters=false]
  294. * @param {Boolean} [options.shallow=false]
  295. * @param {Boolean} [options.ignoreElementEnd=false]
  296. */
  297. getWalker( options = {} ) {
  298. options.boundaries = this;
  299. return new TreeWalker( options );
  300. }
  301. /**
  302. * Returns an iterator that iterates over all {@link module:engine/model/item~Item items} that are in this range and returns
  303. * them.
  304. *
  305. * This method uses {@link module:engine/model/treewalker~TreeWalker} with `boundaries` set to this range and `ignoreElementEnd` option
  306. * set to `true`. However it returns only {@link module:engine/model/item~Item model items},
  307. * not {@link module:engine/model/treewalker~TreeWalkerValue}.
  308. *
  309. * You may specify additional options for the tree walker. See {@link module:engine/model/treewalker~TreeWalker} for
  310. * a full list of available options.
  311. *
  312. * @method getItems
  313. * @param {Object} options Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
  314. * @returns {Iterable.<module:engine/model/item~Item>}
  315. */
  316. * getItems( options = {} ) {
  317. options.boundaries = this;
  318. options.ignoreElementEnd = true;
  319. const treeWalker = new TreeWalker( options );
  320. for ( const value of treeWalker ) {
  321. yield value.item;
  322. }
  323. }
  324. /**
  325. * Returns an iterator that iterates over all {@link module:engine/model/position~Position positions} that are boundaries or
  326. * contained in this range.
  327. *
  328. * This method uses {@link module:engine/model/treewalker~TreeWalker} with `boundaries` set to this range. However it returns only
  329. * {@link module:engine/model/position~Position positions}, not {@link module:engine/model/treewalker~TreeWalkerValue}.
  330. *
  331. * You may specify additional options for the tree walker. See {@link module:engine/model/treewalker~TreeWalker} for
  332. * a full list of available options.
  333. *
  334. * @param {Object} options Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
  335. * @returns {Iterable.<module:engine/model/position~Position>}
  336. */
  337. * getPositions( options = {} ) {
  338. options.boundaries = this;
  339. const treeWalker = new TreeWalker( options );
  340. yield treeWalker.position;
  341. for ( const value of treeWalker ) {
  342. yield value.nextPosition;
  343. }
  344. }
  345. /**
  346. * Returns a range that is a result of transforming this range by given `operation`.
  347. *
  348. * **Note:** transformation may break one range into multiple ranges (for example, when a part of the range is
  349. * moved to a different part of document tree). For this reason, an array is returned by this method and it
  350. * may contain one or more `Range` instances.
  351. *
  352. * @param {module:engine/model/operation/operation~Operation} operation Operation to transform range by.
  353. * @returns {Array.<module:engine/model/range~Range>} Range which is the result of transformation.
  354. */
  355. getTransformedByOperation( operation ) {
  356. switch ( operation.type ) {
  357. case 'insert':
  358. return this._getTransformedByInsertOperation( operation );
  359. case 'move':
  360. case 'remove':
  361. case 'reinsert':
  362. return this._getTransformedByMoveOperation( operation );
  363. case 'split':
  364. return [ this._getTransformedBySplitOperation( operation ) ];
  365. case 'merge':
  366. return [ this._getTransformedByMergeOperation( operation ) ];
  367. }
  368. return [ Range.createFromRange( this ) ];
  369. }
  370. /**
  371. * Returns a range that is a result of transforming this range by multiple `operations`.
  372. *
  373. * @see ~Range#getTransformedByOperation
  374. * @param {Iterable.<module:engine/model/operation/operation~Operation>} operations Operations to transform the range by.
  375. * @returns {Array.<module:engine/model/range~Range>} Range which is the result of transformation.
  376. */
  377. getTransformedByOperations( operations ) {
  378. const ranges = [ Range.createFromRange( this ) ];
  379. for ( const operation of operations ) {
  380. for ( let i = 0; i < ranges.length; i++ ) {
  381. const result = ranges[ i ].getTransformedByOperation( operation );
  382. ranges.splice( i, 1, ...result );
  383. i += result.length - 1;
  384. }
  385. }
  386. // It may happen that a range is split into two, and then the part of second "piece" is moved into first
  387. // "piece". In this case we will have incorrect third range, which should not be included in the result --
  388. // because it is already included in the first "piece". In this loop we are looking for all such ranges that
  389. // are inside other ranges and we simply remove them.
  390. for ( let i = 0; i < ranges.length; i++ ) {
  391. const range = ranges[ i ];
  392. for ( let j = i + 1; j < ranges.length; j++ ) {
  393. const next = ranges[ j ];
  394. if ( range.containsRange( next ) || next.containsRange( range ) || range.isEqual( next ) ) {
  395. ranges.splice( j, 1 );
  396. }
  397. }
  398. }
  399. return ranges;
  400. }
  401. /**
  402. * Returns an {@link module:engine/model/element~Element} or {@link module:engine/model/documentfragment~DocumentFragment}
  403. * which is a common ancestor of the range's both ends (in which the entire range is contained).
  404. *
  405. * @returns {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment|null}
  406. */
  407. getCommonAncestor() {
  408. return this.start.getCommonAncestor( this.end );
  409. }
  410. /**
  411. * Converts `Range` to plain object and returns it.
  412. *
  413. * @returns {Object} `Node` converted to plain object.
  414. */
  415. toJSON() {
  416. return {
  417. start: this.start.toJSON(),
  418. end: this.end.toJSON()
  419. };
  420. }
  421. /**
  422. * Returns a result of transforming a copy of this range by insert operation.
  423. *
  424. * One or more ranges may be returned as a result of this transformation.
  425. *
  426. * @protected
  427. * @param {module:engine/model/operation/insertoperation~InsertOperation} operation
  428. * @returns {Array.<module:engine/model/range~Range>}
  429. */
  430. _getTransformedByInsertOperation( operation, spread = false ) {
  431. return this._getTransformedByInsertion( operation.position, operation.howMany, spread );
  432. }
  433. /**
  434. * Returns a result of transforming a copy of this range by move operation.
  435. *
  436. * One or more ranges may be returned as a result of this transformation.
  437. *
  438. * @protected
  439. * @param {module:engine/model/operation/moveoperation~MoveOperation} operation
  440. * @returns {Array.<module:engine/model/range~Range>}
  441. */
  442. _getTransformedByMoveOperation( operation, spread = false ) {
  443. const sourcePosition = operation.sourcePosition;
  444. const howMany = operation.howMany;
  445. const targetPosition = operation.targetPosition;
  446. return this._getTransformedByMove( sourcePosition, targetPosition, howMany, spread );
  447. }
  448. /**
  449. * Returns a result of transforming a copy of this range by split operation.
  450. *
  451. * Always one range is returned. The transformation is done in a way to not break the range.
  452. *
  453. * @protected
  454. * @param {module:engine/model/operation/splitoperation~SplitOperation} operation
  455. * @returns {module:engine/model/range~Range}
  456. */
  457. _getTransformedBySplitOperation( operation ) {
  458. const start = this.start._getTransformedBySplitOperation( operation );
  459. let end = this.end._getTransformedBySplitOperation( operation );
  460. if ( this.end.isEqual( operation.insertionPosition ) ) {
  461. end = this.end.getShiftedBy( 1 );
  462. }
  463. // Below may happen when range contains graveyard element used by split operation.
  464. if ( start.root != end.root ) {
  465. // End position was next to the moved graveyard element and was moved with it.
  466. // Fix it by using old `end` which has proper `root`.
  467. end = this.end.getShiftedBy( -1 );
  468. }
  469. return new Range( start, end );
  470. }
  471. /**
  472. * Returns a result of transforming a copy of this range by merge operation.
  473. *
  474. * Always one range is returned. The transformation is done in a way to not break the range.
  475. *
  476. * @protected
  477. * @param {module:engine/model/operation/mergeoperation~MergeOperation} operation
  478. * @returns {module:engine/model/range~Range}
  479. */
  480. _getTransformedByMergeOperation( operation ) {
  481. let start = this.start._getTransformedByMergeOperation( operation );
  482. let end = this.end._getTransformedByMergeOperation( operation );
  483. if ( start.root != end.root ) {
  484. // This happens when the end position was next to the merged (deleted) element.
  485. // Then, the end position was moved to the graveyard root. In this case we need to fix
  486. // the range cause its boundaries would be in different roots.
  487. end = this.end.getShiftedBy( -1 );
  488. }
  489. if ( start.isAfter( end ) ) {
  490. // This happens in three following cases:
  491. //
  492. // Case 1: Merge operation source position is before the target position (due to some transformations, OT, etc.)
  493. // This means that start can be moved before the end of the range.
  494. //
  495. // Before: <p>a{a</p><p>b}b</p><p>cc</p>
  496. // Merge: <p>b}b</p><p>cca{a</p>
  497. // Fix: <p>{b}b</p><p>ccaa</p>
  498. //
  499. // Case 2: Range start is before merged node but not directly.
  500. // Result should include all nodes that were in the original range.
  501. //
  502. // Before: <p>aa</p>{<p>cc</p><p>b}b</p>
  503. // Merge: <p>aab}b</p>{<p>cc</p>
  504. // Fix: <p>aa{bb</p><p>cc</p>}
  505. //
  506. // The range is expanded by an additional `b` letter but it is better than dropping the whole `cc` paragraph.
  507. //
  508. // Case 3: Range start is directly before merged node.
  509. // Resulting range should include only nodes from the merged element:
  510. //
  511. // Before: <p>aa</p>{<p>b}b</p><p>cc</p>
  512. // Merge: <p>aab}b</p>{<p>cc</p>
  513. // Fix: <p>aa{b}b</p><p>cc</p>
  514. //
  515. if ( operation.sourcePosition.isBefore( operation.targetPosition ) ) {
  516. // Case 1.
  517. start = Position.createFromPosition( end );
  518. start.offset = 0;
  519. } else {
  520. if ( !operation.deletionPosition.isEqual( start ) ) {
  521. // Case 2.
  522. end = operation.deletionPosition;
  523. }
  524. // In both case 2 and 3 start is at the end of the merge-to element.
  525. start = operation.targetPosition;
  526. }
  527. return new Range( start, end );
  528. }
  529. return new Range( start, end );
  530. }
  531. /**
  532. * Returns an array containing one or two {@link ~Range ranges} that are a result of transforming this
  533. * {@link ~Range range} by inserting `howMany` nodes at `insertPosition`. Two {@link ~Range ranges} are
  534. * returned if the insertion was inside this {@link ~Range range} and `spread` is set to `true`.
  535. *
  536. * Examples:
  537. *
  538. * let range = new Range( new Position( root, [ 2, 7 ] ), new Position( root, [ 4, 0, 1 ] ) );
  539. * let transformed = range._getTransformedByInsertion( new Position( root, [ 1 ] ), 2 );
  540. * // transformed array has one range from [ 4, 7 ] to [ 6, 0, 1 ]
  541. *
  542. * transformed = range._getTransformedByInsertion( new Position( root, [ 4, 0, 0 ] ), 4 );
  543. * // transformed array has one range from [ 2, 7 ] to [ 4, 0, 5 ]
  544. *
  545. * transformed = range._getTransformedByInsertion( new Position( root, [ 3, 2 ] ), 4 );
  546. * // transformed array has one range, which is equal to original range
  547. *
  548. * transformed = range._getTransformedByInsertion( new Position( root, [ 3, 2 ] ), 4, true );
  549. * // transformed array has two ranges: from [ 2, 7 ] to [ 3, 2 ] and from [ 3, 6 ] to [ 4, 0, 1 ]
  550. *
  551. * @protected
  552. * @param {module:engine/model/position~Position} insertPosition Position where nodes are inserted.
  553. * @param {Number} howMany How many nodes are inserted.
  554. * @param {Boolean} [spread] Flag indicating whether this {~Range range} should be spread if insertion
  555. * was inside the range. Defaults to `false`.
  556. * @returns {Array.<module:engine/model/range~Range>} Result of the transformation.
  557. */
  558. _getTransformedByInsertion( insertPosition, howMany, spread = false ) {
  559. if ( spread && this.containsPosition( insertPosition ) ) {
  560. // Range has to be spread. The first part is from original start to the spread point.
  561. // The other part is from spread point to the original end, but transformed by
  562. // insertion to reflect insertion changes.
  563. return [
  564. new Range( this.start, insertPosition ),
  565. new Range(
  566. insertPosition.getShiftedBy( howMany ),
  567. this.end._getTransformedByInsertion( insertPosition, howMany )
  568. )
  569. ];
  570. } else {
  571. const range = Range.createFromRange( this );
  572. range.start = range.start._getTransformedByInsertion( insertPosition, howMany );
  573. range.end = range.end._getTransformedByInsertion( insertPosition, howMany );
  574. return [ range ];
  575. }
  576. }
  577. /**
  578. * Returns an array containing {@link ~Range ranges} that are a result of transforming this
  579. * {@link ~Range range} by moving `howMany` nodes from `sourcePosition` to `targetPosition`.
  580. *
  581. * @protected
  582. * @param {module:engine/model/position~Position} sourcePosition Position from which nodes are moved.
  583. * @param {module:engine/model/position~Position} targetPosition Position to where nodes are moved.
  584. * @param {Number} howMany How many nodes are moved.
  585. * @param {Boolean} [spread=false] Whether the range should be spread if the move points inside the range.
  586. * @returns {Array.<module:engine/model/range~Range>} Result of the transformation.
  587. */
  588. _getTransformedByMove( sourcePosition, targetPosition, howMany, spread = false ) {
  589. // Special case for transforming a collapsed range. Just transform it like a position.
  590. if ( this.isCollapsed ) {
  591. const newPos = this.start._getTransformedByMove( sourcePosition, targetPosition, howMany );
  592. return [ new Range( newPos ) ];
  593. }
  594. // Special case for transformation when a part of the range is moved towards the range.
  595. //
  596. // Examples:
  597. //
  598. // <div><p>ab</p><p>c[d</p></div><p>e]f</p> --> <div><p>ab</p></div><p>c[d</p><p>e]f</p>
  599. // <p>e[f</p><div><p>a]b</p><p>cd</p></div> --> <p>e[f</p><p>a]b</p><div><p>cd</p></div>
  600. //
  601. // Without this special condition, the default algorithm leaves an "artifact" range from one of `differenceSet` parts:
  602. //
  603. // <div><p>ab</p><p>c[d</p></div><p>e]f</p> --> <div><p>ab</p>{</div>}<p>c[d</p><p>e]f</p>
  604. //
  605. // This special case is applied only if the range is to be kept together (not spread).
  606. const moveRange = Range.createFromPositionAndShift( sourcePosition, howMany );
  607. const insertPosition = targetPosition._getTransformedByDeletion( sourcePosition, howMany );
  608. if ( this.containsPosition( targetPosition ) && !spread ) {
  609. if ( moveRange.containsPosition( this.start ) || moveRange.containsPosition( this.end ) ) {
  610. const start = this.start._getTransformedByMove( sourcePosition, targetPosition, howMany );
  611. const end = this.end._getTransformedByMove( sourcePosition, targetPosition, howMany );
  612. return [ new Range( start, end ) ];
  613. }
  614. }
  615. // Default algorithm.
  616. let result;
  617. const differenceSet = this.getDifference( moveRange );
  618. let difference = null;
  619. const common = this.getIntersection( moveRange );
  620. if ( differenceSet.length == 1 ) {
  621. // `moveRange` and this range may intersect but may be separate.
  622. difference = new Range(
  623. differenceSet[ 0 ].start._getTransformedByDeletion( sourcePosition, howMany ),
  624. differenceSet[ 0 ].end._getTransformedByDeletion( sourcePosition, howMany )
  625. );
  626. } else if ( differenceSet.length == 2 ) {
  627. // `moveRange` is inside this range.
  628. difference = new Range(
  629. this.start,
  630. this.end._getTransformedByDeletion( sourcePosition, howMany )
  631. );
  632. } // else, `moveRange` contains this range.
  633. if ( difference ) {
  634. result = difference._getTransformedByInsertion( insertPosition, howMany, common !== null || spread );
  635. } else {
  636. result = [];
  637. }
  638. if ( common ) {
  639. const transformedCommon = new Range(
  640. common.start._getCombined( moveRange.start, insertPosition ),
  641. common.end._getCombined( moveRange.start, insertPosition )
  642. );
  643. if ( result.length == 2 ) {
  644. result.splice( 1, 0, transformedCommon );
  645. } else {
  646. result.push( transformedCommon );
  647. }
  648. }
  649. return result;
  650. }
  651. /**
  652. * Returns a copy of this range that is transformed by deletion of `howMany` nodes from `deletePosition`.
  653. *
  654. * If the deleted range is intersecting with the transformed range, the transformed range will be shrank.
  655. *
  656. * If the deleted range contains transformed range, `null` will be returned.
  657. *
  658. * @protected
  659. * @param {module:engine/model/position~Position} deletionPosition Position from which nodes are removed.
  660. * @param {Number} howMany How many nodes are removed.
  661. * @returns {module:engine/model/range~Range|null} Result of the transformation.
  662. */
  663. _getTransformedByDeletion( deletePosition, howMany ) {
  664. let newStart = this.start._getTransformedByDeletion( deletePosition, howMany );
  665. let newEnd = this.end._getTransformedByDeletion( deletePosition, howMany );
  666. if ( newStart == null && newEnd == null ) {
  667. return null;
  668. }
  669. if ( newStart == null ) {
  670. newStart = deletePosition;
  671. }
  672. if ( newEnd == null ) {
  673. newEnd = deletePosition;
  674. }
  675. return new Range( newStart, newEnd );
  676. }
  677. /**
  678. * Creates a new range, spreading from specified {@link module:engine/model/position~Position position} to a position moved by
  679. * given `shift`. If `shift` is a negative value, shifted position is treated as the beginning of the range.
  680. *
  681. * @param {module:engine/model/position~Position} position Beginning of the range.
  682. * @param {Number} shift How long the range should be.
  683. * @returns {module:engine/model/range~Range}
  684. */
  685. static createFromPositionAndShift( position, shift ) {
  686. const start = position;
  687. const end = position.getShiftedBy( shift );
  688. return shift > 0 ? new this( start, end ) : new this( end, start );
  689. }
  690. /**
  691. * Creates a range from given parents and offsets.
  692. *
  693. * @param {module:engine/model/element~Element} startElement Start position parent element.
  694. * @param {Number} startOffset Start position offset.
  695. * @param {module:engine/model/element~Element} endElement End position parent element.
  696. * @param {Number} endOffset End position offset.
  697. * @returns {module:engine/model/range~Range}
  698. */
  699. static createFromParentsAndOffsets( startElement, startOffset, endElement, endOffset ) {
  700. return new this(
  701. Position.createFromParentAndOffset( startElement, startOffset ),
  702. Position.createFromParentAndOffset( endElement, endOffset )
  703. );
  704. }
  705. /**
  706. * Creates a new instance of `Range` which is equal to passed range.
  707. *
  708. * @param {module:engine/model/range~Range} range Range to clone.
  709. * @returns {module:engine/model/range~Range}
  710. */
  711. static createFromRange( range ) {
  712. return new this( range.start, range.end );
  713. }
  714. /**
  715. * Creates a range inside an {@link module:engine/model/element~Element element} which starts before the first child of
  716. * that element and ends after the last child of that element.
  717. *
  718. * @param {module:engine/model/element~Element} element Element which is a parent for the range.
  719. * @returns {module:engine/model/range~Range}
  720. */
  721. static createIn( element ) {
  722. return this.createFromParentsAndOffsets( element, 0, element, element.maxOffset );
  723. }
  724. /**
  725. * Creates a range that starts before given {@link module:engine/model/item~Item model item} and ends after it.
  726. *
  727. * @param {module:engine/model/item~Item} item
  728. * @returns {module:engine/model/range~Range}
  729. */
  730. static createOn( item ) {
  731. return this.createFromPositionAndShift( Position.createBefore( item ), item.offsetSize );
  732. }
  733. /**
  734. * Creates a collapsed range at given {@link module:engine/model/position~Position position}
  735. * or on the given {@link module:engine/model/item~Item item}.
  736. *
  737. * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
  738. * @param {Number|'end'|'before'|'after'} [offset] Offset or one of the flags. Used only when
  739. * first parameter is a {@link module:engine/model/item~Item model item}.
  740. */
  741. static createCollapsedAt( itemOrPosition, offset ) {
  742. const start = Position.createAt( itemOrPosition, offset );
  743. const end = Position.createFromPosition( start );
  744. return new Range( start, end );
  745. }
  746. /**
  747. * Combines all ranges from the passed array into a one range. At least one range has to be passed.
  748. * Passed ranges must not have common parts.
  749. *
  750. * The first range from the array is a reference range. If other ranges start or end on the exactly same position where
  751. * the reference range, they get combined into one range.
  752. *
  753. * [ ][] [ ][ ][ ][ ][] [ ] // Passed ranges, shown sorted
  754. * [ ] // The result of the function if the first range was a reference range.
  755. * [ ] // The result of the function if the third-to-seventh range was a reference range.
  756. * [ ] // The result of the function if the last range was a reference range.
  757. *
  758. * @param {Array.<module:engine/model/range~Range>} ranges Ranges to combine.
  759. * @returns {module:engine/model/range~Range} Combined range.
  760. */
  761. static createFromRanges( ranges ) {
  762. if ( ranges.length === 0 ) {
  763. /**
  764. * At least one range has to be passed to
  765. * {@link module:engine/model/range~Range.createFromRanges `Range.createFromRanges()`}.
  766. *
  767. * @error range-create-from-ranges-empty-array
  768. */
  769. throw new CKEditorError( 'range-create-from-ranges-empty-array: At least one range has to be passed.' );
  770. } else if ( ranges.length == 1 ) {
  771. return this.createFromRange( ranges[ 0 ] );
  772. }
  773. // 1. Set the first range in `ranges` array as a reference range.
  774. // If we are going to return just a one range, one of the ranges need to be the reference one.
  775. // Other ranges will be stuck to that range, if possible.
  776. const ref = ranges[ 0 ];
  777. // 2. Sort all the ranges so it's easier to process them.
  778. ranges.sort( ( a, b ) => {
  779. return a.start.isAfter( b.start ) ? 1 : -1;
  780. } );
  781. // 3. Check at which index the reference range is now.
  782. const refIndex = ranges.indexOf( ref );
  783. // 4. At this moment we don't need the original range.
  784. // We are going to modify the result and we need to return a new instance of Range.
  785. // We have to create a copy of the reference range.
  786. const result = new this( ref.start, ref.end );
  787. // 5. Ranges should be checked and glued starting from the range that is closest to the reference range.
  788. // Since ranges are sorted, start with the range with index that is closest to reference range index.
  789. if ( refIndex > 0 ) {
  790. for ( let i = refIndex - 1; true; i++ ) {
  791. if ( ranges[ i ].end.isEqual( result.start ) ) {
  792. result.start = Position.createFromPosition( ranges[ i ].start );
  793. } else {
  794. // If ranges are not starting/ending at the same position there is no point in looking further.
  795. break;
  796. }
  797. }
  798. }
  799. // 6. Ranges should be checked and glued starting from the range that is closest to the reference range.
  800. // Since ranges are sorted, start with the range with index that is closest to reference range index.
  801. for ( let i = refIndex + 1; i < ranges.length; i++ ) {
  802. if ( ranges[ i ].start.isEqual( result.end ) ) {
  803. result.end = Position.createFromPosition( ranges[ i ].end );
  804. } else {
  805. // If ranges are not starting/ending at the same position there is no point in looking further.
  806. break;
  807. }
  808. }
  809. return result;
  810. }
  811. /**
  812. * Creates a `Range` instance from given plain object (i.e. parsed JSON string).
  813. *
  814. * @param {Object} json Plain object to be converted to `Range`.
  815. * @param {module:engine/model/document~Document} doc Document object that will be range owner.
  816. * @returns {module:engine/model/element~Element} `Range` instance created using given plain object.
  817. */
  818. static fromJSON( json, doc ) {
  819. return new this( Position.fromJSON( json.start, doc ), Position.fromJSON( json.end, doc ) );
  820. }
  821. }