position.js 37 KB

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