range.js 36 KB

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