position.js 34 KB

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