range.js 36 KB

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