position.js 38 KB

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