position.js 41 KB

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