8
0

range.js 36 KB

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