8
0

range.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/model/range
  7. */
  8. import Position from './position';
  9. import TreeWalker from './treewalker';
  10. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  11. import compareArrays from '@ckeditor/ckeditor5-utils/src/comparearrays';
  12. /**
  13. * 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. * @param {Object} options Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
  302. * @param {module:engine/model/position~Position} [options.startPosition]
  303. * @param {Boolean} [options.singleCharacters=false]
  304. * @param {Boolean} [options.shallow=false]
  305. * @param {Boolean} [options.ignoreElementEnd=false]
  306. */
  307. getWalker( options = {} ) {
  308. options.boundaries = this;
  309. return new TreeWalker( options );
  310. }
  311. /**
  312. * Returns an iterator that iterates over all {@link module:engine/model/item~Item items} that are in this range and returns
  313. * them.
  314. *
  315. * This method uses {@link module:engine/model/treewalker~TreeWalker} with `boundaries` set to this range and `ignoreElementEnd` option
  316. * set to `true`. However it returns only {@link module:engine/model/item~Item model items},
  317. * not {@link module:engine/model/treewalker~TreeWalkerValue}.
  318. *
  319. * You may specify additional options for the tree walker. See {@link module:engine/model/treewalker~TreeWalker} for
  320. * a full list of available options.
  321. *
  322. * @method getItems
  323. * @param {Object} options Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
  324. * @returns {Iterable.<module:engine/model/item~Item>}
  325. */
  326. * getItems( options = {} ) {
  327. options.boundaries = this;
  328. options.ignoreElementEnd = true;
  329. const treeWalker = new TreeWalker( options );
  330. for ( const value of treeWalker ) {
  331. yield value.item;
  332. }
  333. }
  334. /**
  335. * Returns an iterator that iterates over all {@link module:engine/model/position~Position positions} that are boundaries or
  336. * contained in this range.
  337. *
  338. * This method uses {@link module:engine/model/treewalker~TreeWalker} with `boundaries` set to this range. However it returns only
  339. * {@link module:engine/model/position~Position positions}, not {@link module:engine/model/treewalker~TreeWalkerValue}.
  340. *
  341. * You may specify additional options for the tree walker. See {@link module:engine/model/treewalker~TreeWalker} for
  342. * a full list of available options.
  343. *
  344. * @param {Object} options Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
  345. * @returns {Iterable.<module:engine/model/position~Position>}
  346. */
  347. * getPositions( options = {} ) {
  348. options.boundaries = this;
  349. const treeWalker = new TreeWalker( options );
  350. yield treeWalker.position;
  351. for ( const value of treeWalker ) {
  352. yield value.nextPosition;
  353. }
  354. }
  355. /**
  356. * Returns a range that is a result of transforming this range by given `operation`.
  357. *
  358. * **Note:** transformation may break one range into multiple ranges (for example, when a part of the range is
  359. * moved to a different part of document tree). For this reason, an array is returned by this method and it
  360. * may contain one or more `Range` instances.
  361. *
  362. * @param {module:engine/model/operation/operation~Operation} operation Operation to transform range by.
  363. * @returns {Array.<module:engine/model/range~Range>} Range which is the result of transformation.
  364. */
  365. getTransformedByOperation( operation ) {
  366. switch ( operation.type ) {
  367. case 'insert':
  368. return this._getTransformedByInsertOperation( operation );
  369. case 'move':
  370. case 'remove':
  371. case 'reinsert':
  372. return this._getTransformedByMoveOperation( operation );
  373. case 'split':
  374. return [ this._getTransformedBySplitOperation( operation ) ];
  375. case 'merge':
  376. return [ this._getTransformedByMergeOperation( operation ) ];
  377. }
  378. return [ new Range( this.start, this.end ) ];
  379. }
  380. /**
  381. * Returns a range that is a result of transforming this range by multiple `operations`.
  382. *
  383. * @see ~Range#getTransformedByOperation
  384. * @param {Iterable.<module:engine/model/operation/operation~Operation>} operations Operations to transform the range by.
  385. * @returns {Array.<module:engine/model/range~Range>} Range which is the result of transformation.
  386. */
  387. getTransformedByOperations( operations ) {
  388. const ranges = [ new Range( this.start, this.end ) ];
  389. for ( const operation of operations ) {
  390. for ( let i = 0; i < ranges.length; i++ ) {
  391. const result = ranges[ i ].getTransformedByOperation( operation );
  392. ranges.splice( i, 1, ...result );
  393. i += result.length - 1;
  394. }
  395. }
  396. // It may happen that a range is split into two, and then the part of second "piece" is moved into first
  397. // "piece". In this case we will have incorrect third range, which should not be included in the result --
  398. // because it is already included in the first "piece". In this loop we are looking for all such ranges that
  399. // are inside other ranges and we simply remove them.
  400. for ( let i = 0; i < ranges.length; i++ ) {
  401. const range = ranges[ i ];
  402. for ( let j = i + 1; j < ranges.length; j++ ) {
  403. const next = ranges[ j ];
  404. if ( range.containsRange( next ) || next.containsRange( range ) || range.isEqual( next ) ) {
  405. ranges.splice( j, 1 );
  406. }
  407. }
  408. }
  409. return ranges;
  410. }
  411. /**
  412. * Returns an {@link module:engine/model/element~Element} or {@link module:engine/model/documentfragment~DocumentFragment}
  413. * which is a common ancestor of the range's both ends (in which the entire range is contained).
  414. *
  415. * @returns {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment|null}
  416. */
  417. getCommonAncestor() {
  418. return this.start.getCommonAncestor( this.end );
  419. }
  420. /**
  421. * Converts `Range` to plain object and returns it.
  422. *
  423. * @returns {Object} `Node` converted to plain object.
  424. */
  425. toJSON() {
  426. return {
  427. start: this.start.toJSON(),
  428. end: this.end.toJSON()
  429. };
  430. }
  431. /**
  432. * Returns a new range that is equal to current range.
  433. *
  434. * @returns {module:engine/model/range~Range}
  435. */
  436. clone() {
  437. return new this.constructor( this.start, this.end );
  438. }
  439. /**
  440. * Returns a result of transforming a copy of this range by insert operation.
  441. *
  442. * One or more ranges may be returned as a result of this transformation.
  443. *
  444. * @protected
  445. * @param {module:engine/model/operation/insertoperation~InsertOperation} operation
  446. * @returns {Array.<module:engine/model/range~Range>}
  447. */
  448. _getTransformedByInsertOperation( operation, spread = false ) {
  449. return this._getTransformedByInsertion( operation.position, operation.howMany, spread );
  450. }
  451. /**
  452. * Returns a result of transforming a copy of this range by move operation.
  453. *
  454. * One or more ranges may be returned as a result of this transformation.
  455. *
  456. * @protected
  457. * @param {module:engine/model/operation/moveoperation~MoveOperation} operation
  458. * @returns {Array.<module:engine/model/range~Range>}
  459. */
  460. _getTransformedByMoveOperation( operation, spread = false ) {
  461. const sourcePosition = operation.sourcePosition;
  462. const howMany = operation.howMany;
  463. const targetPosition = operation.targetPosition;
  464. return this._getTransformedByMove( sourcePosition, targetPosition, howMany, spread );
  465. }
  466. /**
  467. * Returns a result of transforming a copy of this range by split operation.
  468. *
  469. * Always one range is returned. The transformation is done in a way to not break the range.
  470. *
  471. * @protected
  472. * @param {module:engine/model/operation/splitoperation~SplitOperation} operation
  473. * @returns {module:engine/model/range~Range}
  474. */
  475. _getTransformedBySplitOperation( operation ) {
  476. const start = this.start._getTransformedBySplitOperation( operation );
  477. let end = this.end._getTransformedBySplitOperation( operation );
  478. if ( this.end.isEqual( operation.insertionPosition ) ) {
  479. end = this.end.getShiftedBy( 1 );
  480. }
  481. // Below may happen when range contains graveyard element used by split operation.
  482. if ( start.root != end.root ) {
  483. // End position was next to the moved graveyard element and was moved with it.
  484. // Fix it by using old `end` which has proper `root`.
  485. end = this.end.getShiftedBy( -1 );
  486. }
  487. return new Range( start, end );
  488. }
  489. /**
  490. * Returns a result of transforming a copy of this range by merge operation.
  491. *
  492. * Always one range is returned. The transformation is done in a way to not break the range.
  493. *
  494. * @protected
  495. * @param {module:engine/model/operation/mergeoperation~MergeOperation} operation
  496. * @returns {module:engine/model/range~Range}
  497. */
  498. _getTransformedByMergeOperation( operation ) {
  499. // Special case when the marker is set on "the closing tag" of an element. Marker can be set like that during
  500. // transformations, especially when a content of a few block elements were removed. For example:
  501. //
  502. // {} is the transformed range, [] is the removed range.
  503. // <p>F[o{o</p><p>B}ar</p><p>Xy]z</p>
  504. //
  505. // <p>Fo{o</p><p>B}ar</p><p>z</p>
  506. // <p>F{</p><p>B}ar</p><p>z</p>
  507. // <p>F{</p>}<p>z</p>
  508. // <p>F{}z</p>
  509. //
  510. if ( this.start.isEqual( operation.targetPosition ) && this.end.isEqual( operation.deletionPosition ) ) {
  511. return new Range( this.start );
  512. }
  513. let start = this.start._getTransformedByMergeOperation( operation );
  514. let end = this.end._getTransformedByMergeOperation( operation );
  515. if ( start.root != end.root ) {
  516. // This happens when the end position was next to the merged (deleted) element.
  517. // Then, the end position was moved to the graveyard root. In this case we need to fix
  518. // the range cause its boundaries would be in different roots.
  519. end = this.end.getShiftedBy( -1 );
  520. }
  521. if ( start.isAfter( end ) ) {
  522. // This happens in three following cases:
  523. //
  524. // Case 1: Merge operation source position is before the target position (due to some transformations, OT, etc.)
  525. // This means that start can be moved before the end of the range.
  526. //
  527. // Before: <p>a{a</p><p>b}b</p><p>cc</p>
  528. // Merge: <p>b}b</p><p>cca{a</p>
  529. // Fix: <p>{b}b</p><p>ccaa</p>
  530. //
  531. // Case 2: Range start is before merged node but not directly.
  532. // Result should include all nodes that were in the original range.
  533. //
  534. // Before: <p>aa</p>{<p>cc</p><p>b}b</p>
  535. // Merge: <p>aab}b</p>{<p>cc</p>
  536. // Fix: <p>aa{bb</p><p>cc</p>}
  537. //
  538. // The range is expanded by an additional `b` letter but it is better than dropping the whole `cc` paragraph.
  539. //
  540. // Case 3: Range start is directly before merged node.
  541. // Resulting range should include only nodes from the merged element:
  542. //
  543. // Before: <p>aa</p>{<p>b}b</p><p>cc</p>
  544. // Merge: <p>aab}b</p>{<p>cc</p>
  545. // Fix: <p>aa{b}b</p><p>cc</p>
  546. //
  547. if ( operation.sourcePosition.isBefore( operation.targetPosition ) ) {
  548. // Case 1.
  549. start = Position._createAt( end );
  550. start.offset = 0;
  551. } else {
  552. if ( !operation.deletionPosition.isEqual( start ) ) {
  553. // Case 2.
  554. end = operation.deletionPosition;
  555. }
  556. // In both case 2 and 3 start is at the end of the merge-to element.
  557. start = operation.targetPosition;
  558. }
  559. return new Range( start, end );
  560. }
  561. return new Range( start, end );
  562. }
  563. /**
  564. * Returns an array containing one or two {@link ~Range ranges} that are a result of transforming this
  565. * {@link ~Range range} by inserting `howMany` nodes at `insertPosition`. Two {@link ~Range ranges} are
  566. * returned if the insertion was inside this {@link ~Range range} and `spread` is set to `true`.
  567. *
  568. * Examples:
  569. *
  570. * let range = model.createRange(
  571. * model.createPositionFromPath( root, [ 2, 7 ] ),
  572. * model.createPositionFromPath( root, [ 4, 0, 1 ] )
  573. * );
  574. * let transformed = range._getTransformedByInsertion( model.createPositionFromPath( root, [ 1 ] ), 2 );
  575. * // transformed array has one range from [ 4, 7 ] to [ 6, 0, 1 ]
  576. *
  577. * transformed = range._getTransformedByInsertion( model.createPositionFromPath( root, [ 4, 0, 0 ] ), 4 );
  578. * // transformed array has one range from [ 2, 7 ] to [ 4, 0, 5 ]
  579. *
  580. * transformed = range._getTransformedByInsertion( model.createPositionFromPath( root, [ 3, 2 ] ), 4 );
  581. * // transformed array has one range, which is equal to original range
  582. *
  583. * transformed = range._getTransformedByInsertion( model.createPositionFromPath( root, [ 3, 2 ] ), 4, true );
  584. * // transformed array has two ranges: from [ 2, 7 ] to [ 3, 2 ] and from [ 3, 6 ] to [ 4, 0, 1 ]
  585. *
  586. * @protected
  587. * @param {module:engine/model/position~Position} insertPosition Position where nodes are inserted.
  588. * @param {Number} howMany How many nodes are inserted.
  589. * @param {Boolean} [spread] Flag indicating whether this {~Range range} should be spread if insertion
  590. * was inside the range. Defaults to `false`.
  591. * @returns {Array.<module:engine/model/range~Range>} Result of the transformation.
  592. */
  593. _getTransformedByInsertion( insertPosition, howMany, spread = false ) {
  594. if ( spread && this.containsPosition( insertPosition ) ) {
  595. // Range has to be spread. The first part is from original start to the spread point.
  596. // The other part is from spread point to the original end, but transformed by
  597. // insertion to reflect insertion changes.
  598. return [
  599. new Range( this.start, insertPosition ),
  600. new Range(
  601. insertPosition.getShiftedBy( howMany ),
  602. this.end._getTransformedByInsertion( insertPosition, howMany )
  603. )
  604. ];
  605. } else {
  606. const range = new Range( this.start, this.end );
  607. range.start = range.start._getTransformedByInsertion( insertPosition, howMany );
  608. range.end = range.end._getTransformedByInsertion( insertPosition, howMany );
  609. return [ range ];
  610. }
  611. }
  612. /**
  613. * Returns an array containing {@link ~Range ranges} that are a result of transforming this
  614. * {@link ~Range range} by moving `howMany` nodes from `sourcePosition` to `targetPosition`.
  615. *
  616. * @protected
  617. * @param {module:engine/model/position~Position} sourcePosition Position from which nodes are moved.
  618. * @param {module:engine/model/position~Position} targetPosition Position to where nodes are moved.
  619. * @param {Number} howMany How many nodes are moved.
  620. * @param {Boolean} [spread=false] Whether the range should be spread if the move points inside the range.
  621. * @returns {Array.<module:engine/model/range~Range>} Result of the transformation.
  622. */
  623. _getTransformedByMove( sourcePosition, targetPosition, howMany, spread = false ) {
  624. // Special case for transforming a collapsed range. Just transform it like a position.
  625. if ( this.isCollapsed ) {
  626. const newPos = this.start._getTransformedByMove( sourcePosition, targetPosition, howMany );
  627. return [ new Range( newPos ) ];
  628. }
  629. // Special case for transformation when a part of the range is moved towards the range.
  630. //
  631. // Examples:
  632. //
  633. // <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>
  634. // <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>
  635. //
  636. // Without this special condition, the default algorithm leaves an "artifact" range from one of `differenceSet` parts:
  637. //
  638. // <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>
  639. //
  640. // This special case is applied only if the range is to be kept together (not spread).
  641. const moveRange = Range._createFromPositionAndShift( sourcePosition, howMany );
  642. const insertPosition = targetPosition._getTransformedByDeletion( sourcePosition, howMany );
  643. if ( this.containsPosition( targetPosition ) && !spread ) {
  644. if ( moveRange.containsPosition( this.start ) || moveRange.containsPosition( this.end ) ) {
  645. const start = this.start._getTransformedByMove( sourcePosition, targetPosition, howMany );
  646. const end = this.end._getTransformedByMove( sourcePosition, targetPosition, howMany );
  647. return [ new Range( start, end ) ];
  648. }
  649. }
  650. // Default algorithm.
  651. let result;
  652. const differenceSet = this.getDifference( moveRange );
  653. let difference = null;
  654. const common = this.getIntersection( moveRange );
  655. if ( differenceSet.length == 1 ) {
  656. // `moveRange` and this range may intersect but may be separate.
  657. difference = new Range(
  658. differenceSet[ 0 ].start._getTransformedByDeletion( sourcePosition, howMany ),
  659. differenceSet[ 0 ].end._getTransformedByDeletion( sourcePosition, howMany )
  660. );
  661. } else if ( differenceSet.length == 2 ) {
  662. // `moveRange` is inside this range.
  663. difference = new Range(
  664. this.start,
  665. this.end._getTransformedByDeletion( sourcePosition, howMany )
  666. );
  667. } // else, `moveRange` contains this range.
  668. if ( difference ) {
  669. result = difference._getTransformedByInsertion( insertPosition, howMany, common !== null || spread );
  670. } else {
  671. result = [];
  672. }
  673. if ( common ) {
  674. const transformedCommon = new Range(
  675. common.start._getCombined( moveRange.start, insertPosition ),
  676. common.end._getCombined( moveRange.start, insertPosition )
  677. );
  678. if ( result.length == 2 ) {
  679. result.splice( 1, 0, transformedCommon );
  680. } else {
  681. result.push( transformedCommon );
  682. }
  683. }
  684. return result;
  685. }
  686. /**
  687. * Returns a copy of this range that is transformed by deletion of `howMany` nodes from `deletePosition`.
  688. *
  689. * If the deleted range is intersecting with the transformed range, the transformed range will be shrank.
  690. *
  691. * If the deleted range contains transformed range, `null` will be returned.
  692. *
  693. * @protected
  694. * @param {module:engine/model/position~Position} deletionPosition Position from which nodes are removed.
  695. * @param {Number} howMany How many nodes are removed.
  696. * @returns {module:engine/model/range~Range|null} Result of the transformation.
  697. */
  698. _getTransformedByDeletion( deletePosition, howMany ) {
  699. let newStart = this.start._getTransformedByDeletion( deletePosition, howMany );
  700. let newEnd = this.end._getTransformedByDeletion( deletePosition, howMany );
  701. if ( newStart == null && newEnd == null ) {
  702. return null;
  703. }
  704. if ( newStart == null ) {
  705. newStart = deletePosition;
  706. }
  707. if ( newEnd == null ) {
  708. newEnd = deletePosition;
  709. }
  710. return new Range( newStart, newEnd );
  711. }
  712. /**
  713. * Creates a new range, spreading from specified {@link module:engine/model/position~Position position} to a position moved by
  714. * given `shift`. If `shift` is a negative value, shifted position is treated as the beginning of the range.
  715. *
  716. * @protected
  717. * @param {module:engine/model/position~Position} position Beginning of the range.
  718. * @param {Number} shift How long the range should be.
  719. * @returns {module:engine/model/range~Range}
  720. */
  721. static _createFromPositionAndShift( position, shift ) {
  722. const start = position;
  723. const end = position.getShiftedBy( shift );
  724. return shift > 0 ? new this( start, end ) : new this( end, start );
  725. }
  726. /**
  727. * Creates a range inside an {@link module:engine/model/element~Element element} which starts before the first child of
  728. * that element and ends after the last child of that element.
  729. *
  730. * @protected
  731. * @param {module:engine/model/element~Element} element Element which is a parent for the range.
  732. * @returns {module:engine/model/range~Range}
  733. */
  734. static _createIn( element ) {
  735. return new this( Position._createAt( element, 0 ), Position._createAt( element, element.maxOffset ) );
  736. }
  737. /**
  738. * Creates a range that starts before given {@link module:engine/model/item~Item model item} and ends after it.
  739. *
  740. * @protected
  741. * @param {module:engine/model/item~Item} item
  742. * @returns {module:engine/model/range~Range}
  743. */
  744. static _createOn( item ) {
  745. return this._createFromPositionAndShift( Position._createBefore( item ), item.offsetSize );
  746. }
  747. /**
  748. * Combines all ranges from the passed array into a one range. At least one range has to be passed.
  749. * Passed ranges must not have common parts.
  750. *
  751. * The first range from the array is a reference range. If other ranges start or end on the exactly same position where
  752. * the reference range, they get combined into one range.
  753. *
  754. * [ ][] [ ][ ][ ][ ][] [ ] // Passed ranges, shown sorted
  755. * [ ] // The result of the function if the first range was a reference range.
  756. * [ ] // The result of the function if the third-to-seventh range was a reference range.
  757. * [ ] // The result of the function if the last range was a reference range.
  758. *
  759. * @param {Array.<module:engine/model/range~Range>} ranges Ranges to combine.
  760. * @returns {module:engine/model/range~Range} Combined range.
  761. */
  762. static _createFromRanges( ranges ) {
  763. if ( ranges.length === 0 ) {
  764. /**
  765. * At least one range has to be passed to
  766. * {@link module:engine/model/range~Range._createFromRanges `Range._createFromRanges()`}.
  767. *
  768. * @error range-create-from-ranges-empty-array
  769. */
  770. throw new CKEditorError( 'range-create-from-ranges-empty-array: At least one range has to be passed.' );
  771. } else if ( ranges.length == 1 ) {
  772. return ranges[ 0 ].clone();
  773. }
  774. // 1. Set the first range in `ranges` array as a reference range.
  775. // If we are going to return just a one range, one of the ranges need to be the reference one.
  776. // Other ranges will be stuck to that range, if possible.
  777. const ref = ranges[ 0 ];
  778. // 2. Sort all the ranges so it's easier to process them.
  779. ranges.sort( ( a, b ) => {
  780. return a.start.isAfter( b.start ) ? 1 : -1;
  781. } );
  782. // 3. Check at which index the reference range is now.
  783. const refIndex = ranges.indexOf( ref );
  784. // 4. At this moment we don't need the original range.
  785. // We are going to modify the result and we need to return a new instance of Range.
  786. // We have to create a copy of the reference range.
  787. const result = new this( ref.start, ref.end );
  788. // 5. Ranges should be checked and glued starting from the range that is closest to the reference range.
  789. // Since ranges are sorted, start with the range with index that is closest to reference range index.
  790. if ( refIndex > 0 ) {
  791. for ( let i = refIndex - 1; true; i++ ) {
  792. if ( ranges[ i ].end.isEqual( result.start ) ) {
  793. result.start = Position._createAt( ranges[ i ].start );
  794. } else {
  795. // If ranges are not starting/ending at the same position there is no point in looking further.
  796. break;
  797. }
  798. }
  799. }
  800. // 6. Ranges should be checked and glued starting from the range that is closest to the reference range.
  801. // Since ranges are sorted, start with the range with index that is closest to reference range index.
  802. for ( let i = refIndex + 1; i < ranges.length; i++ ) {
  803. if ( ranges[ i ].start.isEqual( result.end ) ) {
  804. result.end = Position._createAt( ranges[ i ].end );
  805. } else {
  806. // If ranges are not starting/ending at the same position there is no point in looking further.
  807. break;
  808. }
  809. }
  810. return result;
  811. }
  812. /**
  813. * Creates a `Range` instance from given plain object (i.e. parsed JSON string).
  814. *
  815. * @param {Object} json Plain object to be converted to `Range`.
  816. * @param {module:engine/model/document~Document} doc Document object that will be range owner.
  817. * @returns {module:engine/model/element~Element} `Range` instance created using given plain object.
  818. */
  819. static fromJSON( json, doc ) {
  820. return new this( Position.fromJSON( json.start, doc ), Position.fromJSON( json.end, doc ) );
  821. }
  822. }