8
0

position.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  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/position
  7. */
  8. import TreeWalker from './treewalker';
  9. import compareArrays from '@ckeditor/ckeditor5-utils/src/comparearrays';
  10. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  11. import Text from './text';
  12. import { last } from 'lodash-es';
  13. /**
  14. * Represents a position in the model tree.
  15. *
  16. * A position is represented by its {@link module:engine/model/position~Position#root} and
  17. * a {@link module:engine/model/position~Position#path} in that root.
  18. *
  19. * You can create position instances via its constructor or the `createPosition*()` factory methods of
  20. * {@link module:engine/model/model~Model} and {@link module:engine/model/writer~Writer}.
  21. *
  22. * **Note:** Position is based on offsets, not indexes. This means that a position between two text nodes
  23. * `foo` and `bar` has offset `3`, not `1`. See {@link module:engine/model/position~Position#path} for more information.
  24. *
  25. * Since a position in the model is represented by a {@link module:engine/model/position~Position#root position root} and
  26. * {@link module:engine/model/position~Position#path position path} it is possible to create positions placed in non-existing places.
  27. * This requirement is important for operational transformation algorithms.
  28. *
  29. * Also, {@link module:engine/model/operation/operation~Operation operations}
  30. * kept in the {@link module:engine/model/document~Document#history document history}
  31. * are storing positions (and ranges) which were correct when those operations were applied, but may not be correct
  32. * after the document has changed.
  33. *
  34. * When changes are applied to the model, it may also happen that {@link module:engine/model/position~Position#parent position parent}
  35. * will change even if position path has not changed. Keep in mind, that if a position leads to non-existing element,
  36. * {@link module:engine/model/position~Position#parent} and some other properties and methods will throw errors.
  37. *
  38. * In most cases, position with wrong path is caused by an error in code, but it is sometimes needed, as described above.
  39. */
  40. export default class Position {
  41. /**
  42. * Creates a position.
  43. *
  44. * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} root Root of the position.
  45. * @param {Array.<Number>} path Position path. See {@link module:engine/model/position~Position#path}.
  46. * @param {module:engine/model/position~PositionStickiness} [stickiness='toNone'] Position stickiness.
  47. * See {@link module:engine/model/position~PositionStickiness}.
  48. */
  49. constructor( root, path, stickiness = 'toNone' ) {
  50. if ( !root.is( 'element' ) && !root.is( 'documentFragment' ) ) {
  51. /**
  52. * Position root is invalid.
  53. *
  54. * Positions can only be anchored in elements or document fragments.
  55. *
  56. * @error model-position-root-invalid
  57. */
  58. throw new CKEditorError( 'model-position-root-invalid: Position root invalid.' );
  59. }
  60. if ( !( path instanceof Array ) || path.length === 0 ) {
  61. /**
  62. * Position path must be an array with at least one item.
  63. *
  64. * @error model-position-path-incorrect
  65. * @param path
  66. */
  67. throw new CKEditorError( 'model-position-path-incorrect: Position path must be an array with at least one item.', { path } );
  68. }
  69. // Normalize the root and path (if element was passed).
  70. path = root.getPath().concat( path );
  71. root = root.root;
  72. /**
  73. * Root of the position path.
  74. *
  75. * @readonly
  76. * @member {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment}
  77. * module:engine/model/position~Position#root
  78. */
  79. this.root = root;
  80. /**
  81. * Position of the node in the tree. **Path contains offsets, not indexes.**
  82. *
  83. * Position can be placed before, after or in a {@link module:engine/model/node~Node node} if that node has
  84. * {@link module:engine/model/node~Node#offsetSize} greater than `1`. Items in position path are
  85. * {@link module:engine/model/node~Node#startOffset starting offsets} of position ancestors, starting from direct root children,
  86. * down to the position offset in it's parent.
  87. *
  88. * ROOT
  89. * |- P before: [ 0 ] after: [ 1 ]
  90. * |- UL before: [ 1 ] after: [ 2 ]
  91. * |- LI before: [ 1, 0 ] after: [ 1, 1 ]
  92. * | |- foo before: [ 1, 0, 0 ] after: [ 1, 0, 3 ]
  93. * |- LI before: [ 1, 1 ] after: [ 1, 2 ]
  94. * |- bar before: [ 1, 1, 0 ] after: [ 1, 1, 3 ]
  95. *
  96. * `foo` and `bar` are representing {@link module:engine/model/text~Text text nodes}. Since text nodes has offset size
  97. * greater than `1` you can place position offset between their start and end:
  98. *
  99. * ROOT
  100. * |- P
  101. * |- UL
  102. * |- LI
  103. * | |- f^o|o ^ has path: [ 1, 0, 1 ] | has path: [ 1, 0, 2 ]
  104. * |- LI
  105. * |- b^a|r ^ has path: [ 1, 1, 1 ] | has path: [ 1, 1, 2 ]
  106. *
  107. * @readonly
  108. * @member {Array.<Number>} module:engine/model/position~Position#path
  109. */
  110. this.path = path;
  111. /**
  112. * Position stickiness. See {@link module:engine/model/position~PositionStickiness}.
  113. *
  114. * @member {module:engine/model/position~PositionStickiness} module:engine/model/position~Position#stickiness
  115. */
  116. this.stickiness = stickiness;
  117. }
  118. /**
  119. * Offset at which this position is located in its {@link module:engine/model/position~Position#parent parent}. It is equal
  120. * to the last item in position {@link module:engine/model/position~Position#path path}.
  121. *
  122. * @type {Number}
  123. */
  124. get offset() {
  125. return last( this.path );
  126. }
  127. /**
  128. * @param {Number} newOffset
  129. */
  130. set offset( newOffset ) {
  131. this.path[ this.path.length - 1 ] = newOffset;
  132. }
  133. /**
  134. * Parent element of this position.
  135. *
  136. * Keep in mind that `parent` value is calculated when the property is accessed.
  137. * If {@link module:engine/model/position~Position#path position path}
  138. * leads to a non-existing element, `parent` property will throw error.
  139. *
  140. * Also it is a good idea to cache `parent` property if it is used frequently in an algorithm (i.e. in a long loop).
  141. *
  142. * @readonly
  143. * @type {module:engine/model/element~Element}
  144. */
  145. get parent() {
  146. let parent = this.root;
  147. for ( let i = 0; i < this.path.length - 1; i++ ) {
  148. parent = parent.getChild( parent.offsetToIndex( this.path[ i ] ) );
  149. }
  150. return parent;
  151. }
  152. /**
  153. * Position {@link module:engine/model/position~Position#offset offset} converted to an index in position's parent node. It is
  154. * equal to the {@link module:engine/model/node~Node#index index} of a node after this position. If position is placed
  155. * in text node, position index is equal to the index of that text node.
  156. *
  157. * @readonly
  158. * @type {Number}
  159. */
  160. get index() {
  161. return this.parent.offsetToIndex( this.offset );
  162. }
  163. /**
  164. * Returns {@link module:engine/model/text~Text text node} instance in which this position is placed or `null` if this
  165. * position is not in a text node.
  166. *
  167. * @readonly
  168. * @type {module:engine/model/text~Text|null}
  169. */
  170. get textNode() {
  171. const node = this.parent.getChild( this.index );
  172. return ( node instanceof Text && node.startOffset < this.offset ) ? node : null;
  173. }
  174. /**
  175. * Node directly after this position or `null` if this position is in text node.
  176. *
  177. * @readonly
  178. * @type {module:engine/model/node~Node|null}
  179. */
  180. get nodeAfter() {
  181. return this.textNode === null ? this.parent.getChild( this.index ) : null;
  182. }
  183. /**
  184. * Node directly before this position or `null` if this position is in text node.
  185. *
  186. * @readonly
  187. * @type {Node}
  188. */
  189. get nodeBefore() {
  190. return this.textNode === null ? this.parent.getChild( this.index - 1 ) : null;
  191. }
  192. /**
  193. * Is `true` if position is at the beginning of its {@link module:engine/model/position~Position#parent parent}, `false` otherwise.
  194. *
  195. * @readonly
  196. * @type {Boolean}
  197. */
  198. get isAtStart() {
  199. return this.offset === 0;
  200. }
  201. /**
  202. * Is `true` if position is at the end of its {@link module:engine/model/position~Position#parent parent}, `false` otherwise.
  203. *
  204. * @readonly
  205. * @type {Boolean}
  206. */
  207. get isAtEnd() {
  208. return this.offset == this.parent.maxOffset;
  209. }
  210. /**
  211. * Checks whether this position is before or after given position.
  212. *
  213. * This method is safe to use it on non-existing positions (for example during operational transformation).
  214. *
  215. * @param {module:engine/model/position~Position} otherPosition Position to compare with.
  216. * @returns {module:engine/model/position~PositionRelation}
  217. */
  218. compareWith( otherPosition ) {
  219. if ( this.root != otherPosition.root ) {
  220. return 'different';
  221. }
  222. const result = compareArrays( this.path, otherPosition.path );
  223. switch ( result ) {
  224. case 'same':
  225. return 'same';
  226. case 'prefix':
  227. return 'before';
  228. case 'extension':
  229. return 'after';
  230. default:
  231. return this.path[ result ] < otherPosition.path[ result ] ? 'before' : 'after';
  232. }
  233. }
  234. /**
  235. * Gets the farthest position which matches the callback using
  236. * {@link module:engine/model/treewalker~TreeWalker TreeWalker}.
  237. *
  238. * For example:
  239. *
  240. * getLastMatchingPosition( value => value.type == 'text' );
  241. * // <paragraph>[]foo</paragraph> -> <paragraph>foo[]</paragraph>
  242. *
  243. * getLastMatchingPosition( value => value.type == 'text', { direction: 'backward' } );
  244. * // <paragraph>foo[]</paragraph> -> <paragraph>[]foo</paragraph>
  245. *
  246. * getLastMatchingPosition( value => false );
  247. * // Do not move the position.
  248. *
  249. * @param {Function} skip Callback function. Gets {@link module:engine/model/treewalker~TreeWalkerValue} and should
  250. * return `true` if the value should be skipped or `false` if not.
  251. * @param {Object} options Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
  252. *
  253. * @returns {module:engine/model/position~Position} The position after the last item which matches the `skip` callback test.
  254. */
  255. getLastMatchingPosition( skip, options = {} ) {
  256. options.startPosition = this;
  257. const treeWalker = new TreeWalker( options );
  258. treeWalker.skip( skip );
  259. return treeWalker.position;
  260. }
  261. /**
  262. * Returns a path to this position's parent. Parent path is equal to position {@link module:engine/model/position~Position#path path}
  263. * but without the last item.
  264. *
  265. * This method is safe to use it on non-existing positions (for example during operational transformation).
  266. *
  267. * @returns {Array.<Number>} Path to the parent.
  268. */
  269. getParentPath() {
  270. return this.path.slice( 0, -1 );
  271. }
  272. /**
  273. * Returns ancestors array of this position, that is this position's parent and its ancestors.
  274. *
  275. * @returns {Array.<module:engine/model/item~Item>} Array with ancestors.
  276. */
  277. getAncestors() {
  278. if ( this.parent.is( 'documentFragment' ) ) {
  279. return [ this.parent ];
  280. } else {
  281. return this.parent.getAncestors( { includeSelf: true } );
  282. }
  283. }
  284. /**
  285. * Returns the slice of two position {@link #path paths} which is identical. The {@link #root roots}
  286. * of these two paths must be identical.
  287. *
  288. * This method is safe to use it on non-existing positions (for example during operational transformation).
  289. *
  290. * @param {module:engine/model/position~Position} position The second position.
  291. * @returns {Array.<Number>} The common path.
  292. */
  293. getCommonPath( position ) {
  294. if ( this.root != position.root ) {
  295. return [];
  296. }
  297. // We find on which tree-level start and end have the lowest common ancestor
  298. const cmp = compareArrays( this.path, position.path );
  299. // If comparison returned string it means that arrays are same.
  300. const diffAt = ( typeof cmp == 'string' ) ? Math.min( this.path.length, position.path.length ) : cmp;
  301. return this.path.slice( 0, diffAt );
  302. }
  303. /**
  304. * Returns an {@link module:engine/model/element~Element} or {@link module:engine/model/documentfragment~DocumentFragment}
  305. * which is a common ancestor of both positions. The {@link #root roots} of these two positions must be identical.
  306. *
  307. * @param {module:engine/model/position~Position} position The second position.
  308. * @returns {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment|null}
  309. */
  310. getCommonAncestor( position ) {
  311. const ancestorsA = this.getAncestors();
  312. const ancestorsB = position.getAncestors();
  313. let i = 0;
  314. while ( ancestorsA[ i ] == ancestorsB[ i ] && ancestorsA[ i ] ) {
  315. i++;
  316. }
  317. return i === 0 ? null : ancestorsA[ i - 1 ];
  318. }
  319. /**
  320. * Returns a new instance of `Position`, that has same {@link #parent parent} but it's offset
  321. * is shifted by `shift` value (can be a negative value).
  322. *
  323. * This method is safe to use it on non-existing positions (for example during operational transformation).
  324. *
  325. * @param {Number} shift Offset shift. Can be a negative value.
  326. * @returns {module:engine/model/position~Position} Shifted position.
  327. */
  328. getShiftedBy( shift ) {
  329. const shifted = this.clone();
  330. const offset = shifted.offset + shift;
  331. shifted.offset = offset < 0 ? 0 : offset;
  332. return shifted;
  333. }
  334. /**
  335. * Checks whether this position is after given position.
  336. *
  337. * This method is safe to use it on non-existing positions (for example during operational transformation).
  338. *
  339. * @see module:engine/model/position~Position#isBefore
  340. * @param {module:engine/model/position~Position} otherPosition Position to compare with.
  341. * @returns {Boolean} True if this position is after given position.
  342. */
  343. isAfter( otherPosition ) {
  344. return this.compareWith( otherPosition ) == 'after';
  345. }
  346. /**
  347. * Checks whether this position is before given position.
  348. *
  349. * **Note:** watch out when using negation of the value returned by this method, because the negation will also
  350. * be `true` if positions are in different roots and you might not expect this. You should probably use
  351. * `a.isAfter( b ) || a.isEqual( b )` or `!a.isBefore( p ) && a.root == b.root` in most scenarios. If your
  352. * condition uses multiple `isAfter` and `isBefore` checks, build them so they do not use negated values, i.e.:
  353. *
  354. * if ( a.isBefore( b ) && c.isAfter( d ) ) {
  355. * // do A.
  356. * } else {
  357. * // do B.
  358. * }
  359. *
  360. * or, if you have only one if-branch:
  361. *
  362. * if ( !( a.isBefore( b ) && c.isAfter( d ) ) {
  363. * // do B.
  364. * }
  365. *
  366. * rather than:
  367. *
  368. * if ( !a.isBefore( b ) || && !c.isAfter( d ) ) {
  369. * // do B.
  370. * } else {
  371. * // do A.
  372. * }
  373. *
  374. * This method is safe to use it on non-existing positions (for example during operational transformation).
  375. *
  376. * @param {module:engine/model/position~Position} otherPosition Position to compare with.
  377. * @returns {Boolean} True if this position is before given position.
  378. */
  379. isBefore( otherPosition ) {
  380. return this.compareWith( otherPosition ) == 'before';
  381. }
  382. /**
  383. * Checks whether this position is equal to given position.
  384. *
  385. * This method is safe to use it on non-existing positions (for example during operational transformation).
  386. *
  387. * @param {module:engine/model/position~Position} otherPosition Position to compare with.
  388. * @returns {Boolean} True if positions are same.
  389. */
  390. isEqual( otherPosition ) {
  391. return this.compareWith( otherPosition ) == 'same';
  392. }
  393. /**
  394. * Checks whether this position is touching given position. Positions touch when there are no text nodes
  395. * or empty nodes in a range between them. Technically, those positions are not equal but in many cases
  396. * they are very similar or even indistinguishable.
  397. *
  398. * @param {module:engine/model/position~Position} otherPosition Position to compare with.
  399. * @returns {Boolean} True if positions touch.
  400. */
  401. isTouching( otherPosition ) {
  402. let left = null;
  403. let right = null;
  404. const compare = this.compareWith( otherPosition );
  405. switch ( compare ) {
  406. case 'same':
  407. return true;
  408. case 'before':
  409. left = Position._createAt( this );
  410. right = Position._createAt( otherPosition );
  411. break;
  412. case 'after':
  413. left = Position._createAt( otherPosition );
  414. right = Position._createAt( this );
  415. break;
  416. default:
  417. return false;
  418. }
  419. // Cached for optimization purposes.
  420. let leftParent = left.parent;
  421. while ( left.path.length + right.path.length ) {
  422. if ( left.isEqual( right ) ) {
  423. return true;
  424. }
  425. if ( left.path.length > right.path.length ) {
  426. if ( left.offset !== leftParent.maxOffset ) {
  427. return false;
  428. }
  429. left.path = left.path.slice( 0, -1 );
  430. leftParent = leftParent.parent;
  431. left.offset++;
  432. } else {
  433. if ( right.offset !== 0 ) {
  434. return false;
  435. }
  436. right.path = right.path.slice( 0, -1 );
  437. }
  438. }
  439. }
  440. /**
  441. * Checks if two positions are in the same parent.
  442. *
  443. * This method is safe to use it on non-existing positions (for example during operational transformation).
  444. *
  445. * @param {module:engine/model/position~Position} position Position to compare with.
  446. * @returns {Boolean} `true` if positions have the same parent, `false` otherwise.
  447. */
  448. hasSameParentAs( position ) {
  449. if ( this.root !== position.root ) {
  450. return false;
  451. }
  452. const thisParentPath = this.getParentPath();
  453. const posParentPath = position.getParentPath();
  454. return compareArrays( thisParentPath, posParentPath ) == 'same';
  455. }
  456. /**
  457. * Returns a copy of this position that is transformed by given `operation`.
  458. *
  459. * The new position's parameters are updated accordingly to the effect of the `operation`.
  460. *
  461. * For example, if `n` nodes are inserted before the position, the returned position {@link ~Position#offset} will be
  462. * increased by `n`. If the position was in a merged element, it will be accordingly moved to the new element, etc.
  463. *
  464. * This method is safe to use it on non-existing positions (for example during operational transformation).
  465. *
  466. * @param {module:engine/model/operation/operation~Operation} operation Operation to transform by.
  467. * @returns {module:engine/model/position~Position} Transformed position.
  468. */
  469. getTransformedByOperation( operation ) {
  470. let result;
  471. switch ( operation.type ) {
  472. case 'insert':
  473. result = this._getTransformedByInsertOperation( operation );
  474. break;
  475. case 'move':
  476. case 'remove':
  477. case 'reinsert':
  478. result = this._getTransformedByMoveOperation( operation );
  479. break;
  480. case 'split':
  481. result = this._getTransformedBySplitOperation( operation );
  482. break;
  483. case 'merge':
  484. result = this._getTransformedByMergeOperation( operation );
  485. break;
  486. default:
  487. result = Position._createAt( this );
  488. break;
  489. }
  490. return result;
  491. }
  492. /**
  493. * Returns a copy of this position transformed by an insert operation.
  494. *
  495. * @protected
  496. * @param {module:engine/model/operation/insertoperation~InsertOperation} operation
  497. * @returns {module:engine/model/position~Position}
  498. */
  499. _getTransformedByInsertOperation( operation ) {
  500. return this._getTransformedByInsertion( operation.position, operation.howMany );
  501. }
  502. /**
  503. * Returns a copy of this position transformed by a move operation.
  504. *
  505. * @protected
  506. * @param {module:engine/model/operation/moveoperation~MoveOperation} operation
  507. * @returns {module:engine/model/position~Position}
  508. */
  509. _getTransformedByMoveOperation( operation ) {
  510. return this._getTransformedByMove( operation.sourcePosition, operation.targetPosition, operation.howMany );
  511. }
  512. /**
  513. * Returns a copy of this position transformed by a split operation.
  514. *
  515. * @protected
  516. * @param {module:engine/model/operation/splitoperation~SplitOperation} operation
  517. * @returns {module:engine/model/position~Position}
  518. */
  519. _getTransformedBySplitOperation( operation ) {
  520. const movedRange = operation.movedRange;
  521. const isContained = movedRange.containsPosition( this ) ||
  522. ( movedRange.start.isEqual( this ) && this.stickiness == 'toNext' );
  523. if ( isContained ) {
  524. return this._getCombined( operation.splitPosition, operation.moveTargetPosition );
  525. } else {
  526. if ( operation.graveyardPosition ) {
  527. return this._getTransformedByMove( operation.graveyardPosition, operation.insertionPosition, 1 );
  528. } else {
  529. return this._getTransformedByInsertion( operation.insertionPosition, 1 );
  530. }
  531. }
  532. }
  533. /**
  534. * Returns a copy of this position transformed by merge operation.
  535. *
  536. * @protected
  537. * @param {module:engine/model/operation/mergeoperation~MergeOperation} operation
  538. * @returns {module:engine/model/position~Position}
  539. */
  540. _getTransformedByMergeOperation( operation ) {
  541. const movedRange = operation.movedRange;
  542. const isContained = movedRange.containsPosition( this ) || movedRange.start.isEqual( this );
  543. let pos;
  544. if ( isContained ) {
  545. pos = this._getCombined( operation.sourcePosition, operation.targetPosition );
  546. if ( operation.sourcePosition.isBefore( operation.targetPosition ) ) {
  547. // Above happens during OT when the merged element is moved before the merged-to element.
  548. pos = pos._getTransformedByDeletion( operation.deletionPosition, 1 );
  549. }
  550. } else if ( this.isEqual( operation.deletionPosition ) ) {
  551. pos = Position._createAt( operation.deletionPosition );
  552. } else {
  553. pos = this._getTransformedByMove( operation.deletionPosition, operation.graveyardPosition, 1 );
  554. }
  555. return pos;
  556. }
  557. /**
  558. * Returns a copy of this position that is updated by removing `howMany` nodes starting from `deletePosition`.
  559. * It may happen that this position is in a removed node. If that is the case, `null` is returned instead.
  560. *
  561. * @protected
  562. * @param {module:engine/model/position~Position} deletePosition Position before the first removed node.
  563. * @param {Number} howMany How many nodes are removed.
  564. * @returns {module:engine/model/position~Position|null} Transformed position or `null`.
  565. */
  566. _getTransformedByDeletion( deletePosition, howMany ) {
  567. const transformed = Position._createAt( this );
  568. // This position can't be affected if deletion was in a different root.
  569. if ( this.root != deletePosition.root ) {
  570. return transformed;
  571. }
  572. if ( compareArrays( deletePosition.getParentPath(), this.getParentPath() ) == 'same' ) {
  573. // If nodes are removed from the node that is pointed by this position...
  574. if ( deletePosition.offset < this.offset ) {
  575. // And are removed from before an offset of that position...
  576. if ( deletePosition.offset + howMany > this.offset ) {
  577. // Position is in removed range, it's no longer in the tree.
  578. return null;
  579. } else {
  580. // Decrement the offset accordingly.
  581. transformed.offset -= howMany;
  582. }
  583. }
  584. } else if ( compareArrays( deletePosition.getParentPath(), this.getParentPath() ) == 'prefix' ) {
  585. // If nodes are removed from a node that is on a path to this position...
  586. const i = deletePosition.path.length - 1;
  587. if ( deletePosition.offset <= this.path[ i ] ) {
  588. // And are removed from before next node of that path...
  589. if ( deletePosition.offset + howMany > this.path[ i ] ) {
  590. // If the next node of that path is removed return null
  591. // because the node containing this position got removed.
  592. return null;
  593. } else {
  594. // Otherwise, decrement index on that path.
  595. transformed.path[ i ] -= howMany;
  596. }
  597. }
  598. }
  599. return transformed;
  600. }
  601. /**
  602. * Returns a copy of this position that is updated by inserting `howMany` nodes at `insertPosition`.
  603. *
  604. * @protected
  605. * @param {module:engine/model/position~Position} insertPosition Position where nodes are inserted.
  606. * @param {Number} howMany How many nodes are inserted.
  607. * @returns {module:engine/model/position~Position} Transformed position.
  608. */
  609. _getTransformedByInsertion( insertPosition, howMany ) {
  610. const transformed = Position._createAt( this );
  611. // This position can't be affected if insertion was in a different root.
  612. if ( this.root != insertPosition.root ) {
  613. return transformed;
  614. }
  615. if ( compareArrays( insertPosition.getParentPath(), this.getParentPath() ) == 'same' ) {
  616. // If nodes are inserted in the node that is pointed by this position...
  617. if ( insertPosition.offset < this.offset || ( insertPosition.offset == this.offset && this.stickiness != 'toPrevious' ) ) {
  618. // And are inserted before an offset of that position...
  619. // "Push" this positions offset.
  620. transformed.offset += howMany;
  621. }
  622. } else if ( compareArrays( insertPosition.getParentPath(), this.getParentPath() ) == 'prefix' ) {
  623. // If nodes are inserted in a node that is on a path to this position...
  624. const i = insertPosition.path.length - 1;
  625. if ( insertPosition.offset <= this.path[ i ] ) {
  626. // And are inserted before next node of that path...
  627. // "Push" the index on that path.
  628. transformed.path[ i ] += howMany;
  629. }
  630. }
  631. return transformed;
  632. }
  633. /**
  634. * Returns a copy of this position that is updated by moving `howMany` nodes from `sourcePosition` to `targetPosition`.
  635. *
  636. * @protected
  637. * @param {module:engine/model/position~Position} sourcePosition Position before the first element to move.
  638. * @param {module:engine/model/position~Position} targetPosition Position where moved elements will be inserted.
  639. * @param {Number} howMany How many consecutive nodes to move, starting from `sourcePosition`.
  640. * @returns {module:engine/model/position~Position} Transformed position.
  641. */
  642. _getTransformedByMove( sourcePosition, targetPosition, howMany ) {
  643. // Update target position, as it could be affected by nodes removal.
  644. targetPosition = targetPosition._getTransformedByDeletion( sourcePosition, howMany );
  645. if ( sourcePosition.isEqual( targetPosition ) ) {
  646. // If `targetPosition` is equal to `sourcePosition` this isn't really any move. Just return position as it is.
  647. return Position._createAt( this );
  648. }
  649. // Moving a range removes nodes from their original position. We acknowledge this by proper transformation.
  650. const transformed = this._getTransformedByDeletion( sourcePosition, howMany );
  651. const isMoved = transformed === null ||
  652. ( sourcePosition.isEqual( this ) && this.stickiness == 'toNext' ) ||
  653. ( sourcePosition.getShiftedBy( howMany ).isEqual( this ) && this.stickiness == 'toPrevious' );
  654. if ( isMoved ) {
  655. // This position is inside moved range (or sticks to it).
  656. // In this case, we calculate a combination of this position, move source position and target position.
  657. return this._getCombined( sourcePosition, targetPosition );
  658. } else {
  659. // This position is not inside a removed range.
  660. //
  661. // In next step, we simply reflect inserting `howMany` nodes, which might further affect the position.
  662. return transformed._getTransformedByInsertion( targetPosition, howMany );
  663. }
  664. }
  665. /**
  666. * Returns a new position that is a combination of this position and given positions.
  667. *
  668. * The combined position is a copy of this position transformed by moving a range starting at `source` position
  669. * to the `target` position. It is expected that this position is inside the moved range.
  670. *
  671. * Example:
  672. *
  673. * let original = model.createPositionFromPath( root, [ 2, 3, 1 ] );
  674. * let source = model.createPositionFromPath( root, [ 2, 2 ] );
  675. * let target = model.createPositionFromPath( otherRoot, [ 1, 1, 3 ] );
  676. * original._getCombined( source, target ); // path is [ 1, 1, 4, 1 ], root is `otherRoot`
  677. *
  678. * Explanation:
  679. *
  680. * We have a position `[ 2, 3, 1 ]` and move some nodes from `[ 2, 2 ]` to `[ 1, 1, 3 ]`. The original position
  681. * was inside moved nodes and now should point to the new place. The moved nodes will be after
  682. * positions `[ 1, 1, 3 ]`, `[ 1, 1, 4 ]`, `[ 1, 1, 5 ]`. Since our position was in the second moved node,
  683. * the transformed position will be in a sub-tree of a node at `[ 1, 1, 4 ]`. Looking at original path, we
  684. * took care of `[ 2, 3 ]` part of it. Now we have to add the rest of the original path to the transformed path.
  685. * Finally, the transformed position will point to `[ 1, 1, 4, 1 ]`.
  686. *
  687. * @protected
  688. * @param {module:engine/model/position~Position} source Beginning of the moved range.
  689. * @param {module:engine/model/position~Position} target Position where the range is moved.
  690. * @returns {module:engine/model/position~Position} Combined position.
  691. */
  692. _getCombined( source, target ) {
  693. const i = source.path.length - 1;
  694. // The first part of a path to combined position is a path to the place where nodes were moved.
  695. const combined = Position._createAt( target );
  696. combined.stickiness = this.stickiness;
  697. // Then we have to update the rest of the path.
  698. // Fix the offset because this position might be after `from` position and we have to reflect that.
  699. combined.offset = combined.offset + this.path[ i ] - source.offset;
  700. // Then, add the rest of the path.
  701. // If this position is at the same level as `from` position nothing will get added.
  702. combined.path = combined.path.concat( this.path.slice( i + 1 ) );
  703. return combined;
  704. }
  705. /**
  706. * @inheritDoc
  707. */
  708. toJSON() {
  709. return {
  710. root: this.root.toJSON(),
  711. path: Array.from( this.path ),
  712. stickiness: this.stickiness
  713. };
  714. }
  715. /**
  716. * Returns a new position that is equal to current position.
  717. *
  718. * @returns {module:engine/model/position~Position}
  719. */
  720. clone() {
  721. return new this.constructor( this.root, this.path, this.stickiness );
  722. }
  723. /**
  724. * Creates position at the given location. The location can be specified as:
  725. *
  726. * * a {@link module:engine/model/position~Position position},
  727. * * parent element and offset (offset defaults to `0`),
  728. * * parent element and `'end'` (sets position at the end of that element),
  729. * * {@link module:engine/model/item~Item model item} and `'before'` or `'after'` (sets position before or after given model item).
  730. *
  731. * This method is a shortcut to other factory methods such as:
  732. *
  733. * * {@link module:engine/model/position~Position._createBefore},
  734. * * {@link module:engine/model/position~Position._createAfter}.
  735. *
  736. * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
  737. * @param {Number|'end'|'before'|'after'} [offset] Offset or one of the flags. Used only when the
  738. * first parameter is a {@link module:engine/model/item~Item model item}.
  739. * @param {module:engine/model/position~PositionStickiness} [stickiness='toNone'] Position stickiness. Used only when the
  740. * first parameter is a {@link module:engine/model/item~Item model item}.
  741. * @protected
  742. */
  743. static _createAt( itemOrPosition, offset, stickiness = 'toNone' ) {
  744. if ( itemOrPosition instanceof Position ) {
  745. return new Position( itemOrPosition.root, itemOrPosition.path, itemOrPosition.stickiness );
  746. } else {
  747. const node = itemOrPosition;
  748. if ( offset == 'end' ) {
  749. offset = node.maxOffset;
  750. } else if ( offset == 'before' ) {
  751. return this._createBefore( node, stickiness );
  752. } else if ( offset == 'after' ) {
  753. return this._createAfter( node, stickiness );
  754. } else if ( offset !== 0 && !offset ) {
  755. /**
  756. * {@link module:engine/model/model~Model#createPositionAt `Model#createPositionAt()`}
  757. * requires the offset to be specified when the first parameter is a model item.
  758. *
  759. * @error model-createPositionAt-offset-required
  760. */
  761. throw new CKEditorError(
  762. 'model-createPositionAt-offset-required: ' +
  763. 'Model#createPositionAt() requires the offset when the first parameter is a model item.' );
  764. }
  765. if ( !node.is( 'element' ) && !node.is( 'documentFragment' ) ) {
  766. /**
  767. * Position parent have to be a model element or model document fragment.
  768. *
  769. * @error model-position-parent-incorrect
  770. */
  771. throw new CKEditorError( 'model-position-parent-incorrect: Position parent have to be a element or document fragment.' );
  772. }
  773. const path = node.getPath();
  774. path.push( offset );
  775. return new this( node.root, path, stickiness );
  776. }
  777. }
  778. /**
  779. * Creates a new position, after given {@link module:engine/model/item~Item model item}.
  780. *
  781. * @param {module:engine/model/item~Item} item Item after which the position should be placed.
  782. * @param {module:engine/model/position~PositionStickiness} [stickiness='toNone'] Position stickiness.
  783. * @returns {module:engine/model/position~Position}
  784. * @protected
  785. */
  786. static _createAfter( item, stickiness ) {
  787. if ( !item.parent ) {
  788. /**
  789. * You can not make a position after a root element.
  790. *
  791. * @error model-position-after-root
  792. * @param {module:engine/model/item~Item} root
  793. */
  794. throw new CKEditorError( 'model-position-after-root: You cannot make a position after root.', { root: item } );
  795. }
  796. return this._createAt( item.parent, item.endOffset, stickiness );
  797. }
  798. /**
  799. * Creates a new position, before the given {@link module:engine/model/item~Item model item}.
  800. *
  801. * @param {module:engine/model/item~Item} item Item before which the position should be placed.
  802. * @param {module:engine/model/position~PositionStickiness} [stickiness='toNone'] Position stickiness.
  803. * @returns {module:engine/model/position~Position}
  804. * @protected
  805. */
  806. static _createBefore( item, stickiness ) {
  807. if ( !item.parent ) {
  808. /**
  809. * You can not make a position before a root element.
  810. *
  811. * @error model-position-before-root
  812. * @param {module:engine/model/item~Item} root
  813. */
  814. throw new CKEditorError( 'model-position-before-root: You cannot make a position before root.', { root: item } );
  815. }
  816. return this._createAt( item.parent, item.startOffset, stickiness );
  817. }
  818. /**
  819. * Creates a `Position` instance from given plain object (i.e. parsed JSON string).
  820. *
  821. * @param {Object} json Plain object to be converted to `Position`.
  822. * @param {module:engine/model/document~Document} doc Document object that will be position owner.
  823. * @returns {module:engine/model/position~Position} `Position` instance created using given plain object.
  824. */
  825. static fromJSON( json, doc ) {
  826. if ( json.root === '$graveyard' ) {
  827. const pos = new Position( doc.graveyard, json.path );
  828. pos.stickiness = json.stickiness;
  829. return pos;
  830. }
  831. if ( !doc.getRoot( json.root ) ) {
  832. /**
  833. * Cannot create position for document. Root with specified name does not exist.
  834. *
  835. * @error model-position-fromjson-no-root
  836. * @param {String} rootName
  837. */
  838. throw new CKEditorError(
  839. 'model-position-fromjson-no-root: Cannot create position for document. Root with specified name does not exist.',
  840. { rootName: json.root }
  841. );
  842. }
  843. return new Position( doc.getRoot( json.root ), json.path, json.stickiness );
  844. }
  845. }
  846. /**
  847. * A flag indicating whether this position is `'before'` or `'after'` or `'same'` as given position.
  848. * If positions are in different roots `'different'` flag is returned.
  849. *
  850. * @typedef {String} module:engine/model/position~PositionRelation
  851. */
  852. /**
  853. * Represents how position is "sticking" with neighbour nodes. Used to define how position should be transformed (moved)
  854. * in edge cases. Possible values: `'toNone'`, `'toNext'`, `'toPrevious'`.
  855. *
  856. * Examples:
  857. *
  858. * Insert. Position is at | and nodes are inserted at the same position, marked as ^:
  859. *
  860. * - sticks to none: <p>f^|oo</p> -> <p>fbar|oo</p>
  861. * - sticks to next node: <p>f^|oo</p> -> <p>fbar|oo</p>
  862. * - sticks to previous node: <p>f|^oo</p> -> <p>f|baroo</p>
  863. *
  864. *
  865. * Move. Position is at | and range [oo] is moved to position ^:
  866. *
  867. * - sticks to none: <p>f|[oo]</p><p>b^ar</p> -> <p>f|</p><p>booar</p>
  868. * - sticks to none: <p>f[oo]|</p><p>b^ar</p> -> <p>f|</p><p>booar</p>
  869. *
  870. * - sticks to next node: <p>f|[oo]</p><p>b^ar</p> -> <p>f</p><p>b|ooar</p>
  871. * - sticks to next node: <p>f[oo]|</p><p>b^ar</p> -> <p>f|</p><p>booar</p>
  872. *
  873. * - sticks to previous node: <p>f|[oo]</p><p>b^ar</p> -> <p>f|</p><p>booar</p>
  874. * - sticks to previous node: <p>f[oo]|</p><p>b^ar</p> -> <p>f</p><p>boo|ar</p>
  875. *
  876. * @typedef {String} module:engine/model/position~PositionStickiness
  877. */