8
0

position.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. import DocumentFragment from './documentfragment.js';
  6. import Element from './element.js';
  7. import last from '../../utils/lib/lodash/last.js';
  8. import compareArrays from '../../utils/comparearrays';
  9. import CKEditorError from '../../utils/ckeditorerror.js';
  10. import Text from './text.js';
  11. /**
  12. * Represents a position in the model tree.
  13. *
  14. * **Note:** Position is based on offsets, not indexes. This means that position in element containing two text nodes
  15. * with data `foo` and `bar`, position between them has offset `3`, not `1`. See {@link engine.model.Position#path} for more.
  16. *
  17. * Since position in a model is represented by a {@link engine.model.Position#root position root} and
  18. * {@link engine.model.Position#path position path} it is possible to create positions placed in non-existing elements.
  19. * This requirement is important for {@link engine.model.operation.transfrom operational transformation}.
  20. *
  21. * Also, {@link engine.model.operation.Operation operations} kept in {@link engine.model.Document#history document history}
  22. * are storing positions (and ranges) which were correct when those operations were applied, but may not be correct
  23. * after document got changed.
  24. *
  25. * When changes are applied to model, it may also happen that {@link engine.model.Position#parent position parent} will change
  26. * even if position path has not changed. Keep in mind, that if a position leads to non-existing element,
  27. * {@link engine.model.Position#parent} and some other properties and methods will throw errors.
  28. *
  29. * In most cases, position with wrong path is caused by an error in code, but it is sometimes needed, as described above.
  30. *
  31. * @memberOf engine.model
  32. */
  33. export default class Position {
  34. /**
  35. * Creates a position.
  36. *
  37. * @param {engine.model.Element|engine.model.DocumentFragment} root Root of the position.
  38. * @param {Array.<Number>} path Position path. See {@link engine.model.Position#path}.
  39. */
  40. constructor( root, path ) {
  41. if ( !( root instanceof Element ) && !( root instanceof DocumentFragment ) ) {
  42. /**
  43. * Position root invalid.
  44. *
  45. * @error position-root-invalid.
  46. */
  47. throw new CKEditorError( 'position-root-invalid: Position root invalid.' );
  48. }
  49. if ( !( path instanceof Array ) || path.length === 0 ) {
  50. /**
  51. * Position path must be an Array with at least one item.
  52. *
  53. * @error position-path-incorrect
  54. * @param path
  55. */
  56. throw new CKEditorError( 'position-path-incorrect: Position path must be an Array with at least one item.', { path: path } );
  57. }
  58. // Normalize the root and path (if element was passed).
  59. path = root.getPath().concat( path );
  60. root = root.root;
  61. /**
  62. * Root of the position path.
  63. *
  64. * @readonly
  65. * @member {engine.model.Element|engine.model.DocumentFragment} engine.model.Position#root
  66. */
  67. this.root = root;
  68. /**
  69. * Position of the node it the tree. Path is described through offsets, not indexes.
  70. *
  71. * Position can be placed before, after or in a {@link engine.model.Node node} if that node has
  72. * {@link engine.model.Node#offsetSize} greater than `1`. Items in position path are
  73. * {@link engine.model.Node#startOffset starting offsets} of position ancestors, starting from direct root children,
  74. * down to the position offset in it's parent.
  75. *
  76. * ROOT
  77. * |- P before: [ 0 ] after: [ 1 ]
  78. * |- UL before: [ 1 ] after: [ 2 ]
  79. * |- LI before: [ 1, 0 ] after: [ 1, 1 ]
  80. * | |- foo before: [ 1, 0, 0 ] after: [ 1, 0, 3 ]
  81. * |- LI before: [ 1, 1 ] after: [ 1, 2 ]
  82. * |- bar before: [ 1, 1, 0 ] after: [ 1, 1, 3 ]
  83. *
  84. * `foo` and `bar` are representing {@link engine.model.Text text nodes}. Since text nodes has offset size
  85. * greater than `1` you can place position offset between their start and end:
  86. *
  87. * ROOT
  88. * |- P
  89. * |- UL
  90. * |- LI
  91. * | |- f^o|o ^ has path: [ 1, 0, 1 ] | has path: [ 1, 0, 2 ]
  92. * |- LI
  93. * |- b^a|r ^ has path: [ 1, 1, 1 ] | has path: [ 1, 1, 2 ]
  94. *
  95. * @member {Array.<Number>} engine.model.Position#path
  96. */
  97. this.path = path;
  98. }
  99. /**
  100. * Position {@link engine.model.Position#offset offset} converted to an index in position's parent node. It is
  101. * equal to the {@link engine.model.Node#getIndex index} of a node after this position. If position is placed
  102. * in text node, position index is equal to the index of that text node.
  103. *
  104. * @readonly
  105. * @type {Number}
  106. */
  107. get index() {
  108. return this.parent.offsetToIndex( this.offset );
  109. }
  110. /**
  111. * Returns {@link engine.model.Text text node} instance in which this position is placed or `null` if this
  112. * position is not in a text node.
  113. *
  114. * @readonly
  115. * @type {engine.model.Text|null}
  116. */
  117. get textNode() {
  118. let node = this.parent.getChild( this.index );
  119. return ( node instanceof Text && node.startOffset < this.offset ) ? node : null;
  120. }
  121. /**
  122. * Node directly after this position or `null` if this position is in text node.
  123. *
  124. * @readonly
  125. * @type {engine.model.Node|null}
  126. */
  127. get nodeAfter() {
  128. return this.textNode === null ? this.parent.getChild( this.index ) : null;
  129. }
  130. /**
  131. * Node directly before this position or `null` if this position is in text node.
  132. *
  133. * @readonly
  134. * @type {Node}
  135. */
  136. get nodeBefore() {
  137. return this.textNode === null ? this.parent.getChild( this.index - 1 ) : null;
  138. }
  139. /**
  140. * Offset at which this position is located in it's {@link engine.model.Position#parent parent}. It is equal
  141. * to the last item in position {@link engine.model.Position#path path}.
  142. *
  143. * @type {Number}
  144. */
  145. get offset() {
  146. return last( this.path );
  147. }
  148. /**
  149. * @param {Number} newOffset
  150. */
  151. set offset( newOffset ) {
  152. this.path[ this.path.length - 1 ] = newOffset;
  153. }
  154. /**
  155. * Parent element of this position.
  156. *
  157. * Keep in mind that `parent` value is calculated when the property is accessed. If {@link engine.model.Position#path position path}
  158. * leads to a non-existing element, `parent` property will throw error.
  159. *
  160. * Also it is a good idea to cache `parent` property if it is used frequently in an algorithm (i.e. in a long loop).
  161. *
  162. * @readonly
  163. * @type {engine.model.Element}
  164. */
  165. get parent() {
  166. let parent = this.root;
  167. for ( let i = 0; i < this.path.length - 1; i++ ) {
  168. parent = parent.getChild( parent.offsetToIndex( this.path[ i ] ) );
  169. }
  170. return parent;
  171. }
  172. /**
  173. * Checks whether this position is before or after given position.
  174. *
  175. * @param {engine.model.Position} otherPosition Position to compare with.
  176. * @returns {engine.model.PositionRelation}
  177. */
  178. compareWith( otherPosition ) {
  179. if ( this.root != otherPosition.root ) {
  180. return 'different';
  181. }
  182. const result = compareArrays( this.path, otherPosition.path );
  183. switch ( result ) {
  184. case 'same':
  185. return 'same';
  186. case 'prefix':
  187. return 'before';
  188. case 'extension':
  189. return 'after';
  190. default:
  191. if ( this.path[ result ] < otherPosition.path[ result ] ) {
  192. return 'before';
  193. } else {
  194. return 'after';
  195. }
  196. }
  197. }
  198. /**
  199. * Returns a path to this position's parent. Parent path is equal to position {@link engine.model.Position#path path}
  200. * but without the last item.
  201. *
  202. * This method returns the parent path even if the parent does not exists.
  203. *
  204. * @returns {Array.<Number>} Path to the parent.
  205. */
  206. getParentPath() {
  207. return this.path.slice( 0, -1 );
  208. }
  209. /**
  210. * Returns a new instance of `Position`, that has same {@link engine.model.Position#parent parent} but it's offset
  211. * is shifted by `shift` value (can be a negative value).
  212. *
  213. * @param {Number} shift Offset shift. Can be a negative value.
  214. * @returns {engine.model.Position} Shifted position.
  215. */
  216. getShiftedBy( shift ) {
  217. let shifted = Position.createFromPosition( this );
  218. let offset = shifted.offset + shift;
  219. shifted.offset = offset < 0 ? 0 : offset;
  220. return shifted;
  221. }
  222. /**
  223. * Checks whether this position is after given position.
  224. *
  225. * @see engine.model.Position#isBefore
  226. *
  227. * @param {engine.model.Position} otherPosition Position to compare with.
  228. * @returns {Boolean} True if this position is after given position.
  229. */
  230. isAfter( otherPosition ) {
  231. return this.compareWith( otherPosition ) == 'after';
  232. }
  233. /**
  234. * Checks whether this position is before given position.
  235. *
  236. * **Note:** watch out when using negation of the value returned by this method, because the negation will also
  237. * be `true` if positions are in different roots and you might not expect this. You should probably use
  238. * `a.isAfter( b ) || a.isEqual( b )` or `!a.isBefore( p ) && a.root == b.root` in most scenarios. If your
  239. * condition uses multiple `isAfter` and `isBefore` checks, build them so they do not use negated values, i.e.:
  240. *
  241. * if ( a.isBefore( b ) && c.isAfter( d ) ) {
  242. * // do A.
  243. * } else {
  244. * // do B.
  245. * }
  246. *
  247. * or, if you have only one if-branch:
  248. *
  249. * if ( !( a.isBefore( b ) && c.isAfter( d ) ) {
  250. * // do B.
  251. * }
  252. *
  253. * rather than:
  254. *
  255. * if ( !a.isBefore( b ) || && !c.isAfter( d ) ) {
  256. * // do B.
  257. * } else {
  258. * // do A.
  259. * }
  260. *
  261. * @param {engine.model.Position} otherPosition Position to compare with.
  262. * @returns {Boolean} True if this position is before given position.
  263. */
  264. isBefore( otherPosition ) {
  265. return this.compareWith( otherPosition ) == 'before';
  266. }
  267. /**
  268. * Checks whether this position is equal to given position.
  269. *
  270. * @param {engine.model.Position} otherPosition Position to compare with.
  271. * @returns {Boolean} True if positions are same.
  272. */
  273. isEqual( otherPosition ) {
  274. return this.compareWith( otherPosition ) == 'same';
  275. }
  276. /**
  277. * Checks whether this position is touching given position. Positions touch when there are no text nodes
  278. * or empty nodes in a range between them. Technically, those positions are not equal but in many cases
  279. * they are very similar or even indistinguishable.
  280. *
  281. * @param {engine.model.Position} otherPosition Position to compare with.
  282. * @returns {Boolean} True if positions touch.
  283. */
  284. isTouching( otherPosition ) {
  285. let left = null;
  286. let right = null;
  287. let compare = this.compareWith( otherPosition );
  288. switch ( compare ) {
  289. case 'same':
  290. return true;
  291. case 'before':
  292. left = Position.createFromPosition( this );
  293. right = Position.createFromPosition( otherPosition );
  294. break;
  295. case 'after':
  296. left = Position.createFromPosition( otherPosition );
  297. right = Position.createFromPosition( this );
  298. break;
  299. default:
  300. return false;
  301. }
  302. // Cached for optimization purposes.
  303. let leftParent = left.parent;
  304. while ( left.path.length + right.path.length ) {
  305. if ( left.isEqual( right ) ) {
  306. return true;
  307. }
  308. if ( left.path.length > right.path.length ) {
  309. if ( left.offset !== leftParent.getMaxOffset() ) {
  310. return false;
  311. }
  312. left.path = left.path.slice( 0, -1 );
  313. leftParent = leftParent.parent;
  314. left.offset++;
  315. } else {
  316. if ( right.offset !== 0 ) {
  317. return false;
  318. }
  319. right.path = right.path.slice( 0, -1 );
  320. }
  321. }
  322. }
  323. /**
  324. * Returns `true` if position is at the beginning of its {@link engine.model.Position#parent parent}, `false` otherwise.
  325. *
  326. * @returns {Boolean}
  327. */
  328. isAtStart() {
  329. return this.offset === 0;
  330. }
  331. /**
  332. * Returns `true` if position is at the end of its {@link engine.model.Position#parent parent}, `false` otherwise.
  333. *
  334. * @returns {Boolean}
  335. */
  336. isAtEnd() {
  337. return this.offset == this.parent.getMaxOffset();
  338. }
  339. /**
  340. * Returns a copy of this position that is updated by removing `howMany` nodes starting from `deletePosition`.
  341. * It may happen that this position is in a removed node. If that is the case, `null` is returned instead.
  342. *
  343. * @protected
  344. * @param {engine.model.Position} deletePosition Position before the first removed node.
  345. * @param {Number} howMany How many nodes are removed.
  346. * @returns {engine.model.Position|null} Transformed position or `null`.
  347. */
  348. _getTransformedByDeletion( deletePosition, howMany ) {
  349. let transformed = Position.createFromPosition( this );
  350. // This position can't be affected if deletion was in a different root.
  351. if ( this.root != deletePosition.root ) {
  352. return transformed;
  353. }
  354. if ( compareArrays( deletePosition.getParentPath(), this.getParentPath() ) == 'same' ) {
  355. // If nodes are removed from the node that is pointed by this position...
  356. if ( deletePosition.offset < this.offset ) {
  357. // And are removed from before an offset of that position...
  358. if ( deletePosition.offset + howMany > this.offset ) {
  359. // Position is in removed range, it's no longer in the tree.
  360. return null;
  361. } else {
  362. // Decrement the offset accordingly.
  363. transformed.offset -= howMany;
  364. }
  365. }
  366. } else if ( compareArrays( deletePosition.getParentPath(), this.getParentPath() ) == 'prefix' ) {
  367. // If nodes are removed from a node that is on a path to this position...
  368. const i = deletePosition.path.length - 1;
  369. if ( deletePosition.offset <= this.path[ i ] ) {
  370. // And are removed from before next node of that path...
  371. if ( deletePosition.offset + howMany > this.path[ i ] ) {
  372. // If the next node of that path is removed return null
  373. // because the node containing this position got removed.
  374. return null;
  375. } else {
  376. // Otherwise, decrement index on that path.
  377. transformed.path[ i ] -= howMany;
  378. }
  379. }
  380. }
  381. return transformed;
  382. }
  383. /**
  384. * Returns a copy of this position that is updated by inserting `howMany` nodes at `insertPosition`.
  385. *
  386. * @protected
  387. * @param {engine.model.Position} insertPosition Position where nodes are inserted.
  388. * @param {Number} howMany How many nodes are inserted.
  389. * @param {Boolean} insertBefore Flag indicating whether nodes are inserted before or after `insertPosition`.
  390. * This is important only when `insertPosition` and this position are same. If that is the case and the flag is
  391. * set to `true`, this position will get transformed. If the flag is set to `false`, it won't.
  392. * @returns {engine.model.Position} Transformed position.
  393. */
  394. _getTransformedByInsertion( insertPosition, howMany, insertBefore ) {
  395. let transformed = Position.createFromPosition( this );
  396. // This position can't be affected if insertion was in a different root.
  397. if ( this.root != insertPosition.root ) {
  398. return transformed;
  399. }
  400. if ( compareArrays( insertPosition.getParentPath(), this.getParentPath() ) == 'same' ) {
  401. // If nodes are inserted in the node that is pointed by this position...
  402. if ( insertPosition.offset < this.offset || ( insertPosition.offset == this.offset && insertBefore ) ) {
  403. // And are inserted before an offset of that position...
  404. // "Push" this positions offset.
  405. transformed.offset += howMany;
  406. }
  407. } else if ( compareArrays( insertPosition.getParentPath(), this.getParentPath() ) == 'prefix' ) {
  408. // If nodes are inserted in a node that is on a path to this position...
  409. const i = insertPosition.path.length - 1;
  410. if ( insertPosition.offset <= this.path[ i ] ) {
  411. // And are inserted before next node of that path...
  412. // "Push" the index on that path.
  413. transformed.path[ i ] += howMany;
  414. }
  415. }
  416. return transformed;
  417. }
  418. /**
  419. * Returns a copy of this position that is updated by moving `howMany` nodes from `sourcePosition` to `targetPosition`.
  420. *
  421. * @protected
  422. * @param {engine.model.Position} sourcePosition Position before the first element to move.
  423. * @param {engine.model.Position} targetPosition Position where moved elements will be inserted.
  424. * @param {Number} howMany How many consecutive nodes to move, starting from `sourcePosition`.
  425. * @param {Boolean} insertBefore Flag indicating whether moved nodes are pasted before or after `insertPosition`.
  426. * This is important only when `targetPosition` and this position are same. If that is the case and the flag is
  427. * set to `true`, this position will get transformed by range insertion. If the flag is set to `false`, it won't.
  428. * @param {Boolean} [sticky] Flag indicating whether this position "sticks" to range, that is if it should be moved
  429. * with the moved range if it is equal to one of range's boundaries.
  430. * @returns {engine.model.Position} Transformed position.
  431. */
  432. _getTransformedByMove( sourcePosition, targetPosition, howMany, insertBefore, sticky ) {
  433. // Moving a range removes nodes from their original position. We acknowledge this by proper transformation.
  434. let transformed = this._getTransformedByDeletion( sourcePosition, howMany );
  435. // Then we update target position, as it could be affected by nodes removal too.
  436. targetPosition = targetPosition._getTransformedByDeletion( sourcePosition, howMany );
  437. if ( transformed === null || ( sticky && transformed.isEqual( sourcePosition ) ) ) {
  438. // This position is inside moved range (or sticks to it).
  439. // In this case, we calculate a combination of this position, move source position and target position.
  440. transformed = this._getCombined( sourcePosition, targetPosition );
  441. } else {
  442. // This position is not inside a removed range.
  443. // In next step, we simply reflect inserting `howMany` nodes, which might further affect the position.
  444. transformed = transformed._getTransformedByInsertion( targetPosition, howMany, insertBefore );
  445. }
  446. return transformed;
  447. }
  448. /**
  449. * Returns a new position that is a combination of this position and given positions.
  450. *
  451. * The combined position is a copy of this position transformed by moving a range starting at `source` position
  452. * to the `target` position. It is expected that this position is inside the moved range.
  453. *
  454. * Example:
  455. *
  456. * let original = new Position( root, [ 2, 3, 1 ] );
  457. * let source = new Position( root, [ 2, 2 ] );
  458. * let target = new Position( otherRoot, [ 1, 1, 3 ] );
  459. * original._getCombined( source, target ); // path is [ 1, 1, 4, 1 ], root is `otherRoot`
  460. *
  461. * Explanation:
  462. *
  463. * We have a position `[ 2, 3, 1 ]` and move some nodes from `[ 2, 2 ]` to `[ 1, 1, 3 ]`. The original position
  464. * was inside moved nodes and now should point to the new place. The moved nodes will be after
  465. * positions `[ 1, 1, 3 ]`, `[ 1, 1, 4 ]`, `[ 1, 1, 5 ]`. Since our position was in the second moved node,
  466. * the transformed position will be in a sub-tree of a node at `[ 1, 1, 4 ]`. Looking at original path, we
  467. * took care of `[ 2, 3 ]` part of it. Now we have to add the rest of the original path to the transformed path.
  468. * Finally, the transformed position will point to `[ 1, 1, 4, 1 ]`.
  469. *
  470. * @protected
  471. * @param {engine.model.Position} source Beginning of the moved range.
  472. * @param {engine.model.Position} target Position where the range is moved.
  473. * @returns {engine.model.Position} Combined position.
  474. */
  475. _getCombined( source, target ) {
  476. const i = source.path.length - 1;
  477. // The first part of a path to combined position is a path to the place where nodes were moved.
  478. let combined = Position.createFromPosition( target );
  479. // Then we have to update the rest of the path.
  480. // Fix the offset because this position might be after `from` position and we have to reflect that.
  481. combined.offset = combined.offset + this.path[ i ] - source.offset;
  482. // Then, add the rest of the path.
  483. // If this position is at the same level as `from` position nothing will get added.
  484. combined.path = combined.path.concat( this.path.slice( i + 1 ) );
  485. return combined;
  486. }
  487. /**
  488. * Creates position at the given location. The location can be specified as:
  489. *
  490. * * a {@link engine.model.Position position},
  491. * * parent element and offset (offset defaults to `0`),
  492. * * parent element and `'end'` (sets position at the end of that element),
  493. * * {@link engine.model.Item model item} and `'before'` or `'after'` (sets position before or after given model item).
  494. *
  495. * This method is a shortcut to other constructors such as:
  496. *
  497. * * {@link engine.model.Position.createBefore},
  498. * * {@link engine.model.Position.createAfter},
  499. * * {@link engine.model.Position.createFromParentAndOffset},
  500. * * {@link engine.model.Position.createFromPosition}.
  501. *
  502. * @param {engine.model.Item|engine.model.Position} itemOrPosition
  503. * @param {Number|'end'|'before'|'after'} [offset=0] Offset or one of the flags. Used only when
  504. * first parameter is a {@link engine.model.Item model item}.
  505. */
  506. static createAt( itemOrPosition, offset ) {
  507. if ( itemOrPosition instanceof Position ) {
  508. return this.createFromPosition( itemOrPosition );
  509. } else {
  510. const node = itemOrPosition;
  511. if ( offset == 'end' ) {
  512. offset = node.getMaxOffset();
  513. } else if ( offset == 'before' ) {
  514. return this.createBefore( node );
  515. } else if ( offset == 'after' ) {
  516. return this.createAfter( node );
  517. } else if ( !offset ) {
  518. offset = 0;
  519. }
  520. return this.createFromParentAndOffset( node, offset );
  521. }
  522. }
  523. /**
  524. * Creates a new position, after given {@link engine.model.Item model item}.
  525. *
  526. * @param {engine.model.Item} item Item after which the position should be placed.
  527. * @returns {engine.model.Position}
  528. */
  529. static createAfter( item ) {
  530. if ( !item.parent ) {
  531. /**
  532. * You can not make position after root.
  533. *
  534. * @error position-after-root
  535. * @param {engine.model.Item} root
  536. */
  537. throw new CKEditorError( 'position-after-root: You can not make position after root.', { root: item } );
  538. }
  539. return this.createFromParentAndOffset( item.parent, item.endOffset );
  540. }
  541. /**
  542. * Creates a new position, before the given {@link engine.model.Item model item}.
  543. *
  544. * @param {engine.model.Item} item Item before which the position should be placed.
  545. * @returns {engine.model.Position}
  546. */
  547. static createBefore( item ) {
  548. if ( !item.parent ) {
  549. /**
  550. * You can not make position before root.
  551. *
  552. * @error position-before-root
  553. * @param {engine.model.Item} root
  554. */
  555. throw new CKEditorError( 'position-before-root: You can not make position before root.', { root: item } );
  556. }
  557. return this.createFromParentAndOffset( item.parent, item.startOffset );
  558. }
  559. /**
  560. * Creates a new position from the parent element and an offset in that element.
  561. *
  562. * @param {engine.model.Element|engine.model.DocumentFragment} parent Position's parent.
  563. * @param {Number} offset Position's offset.
  564. * @returns {engine.model.Position}
  565. */
  566. static createFromParentAndOffset( parent, offset ) {
  567. if ( !( parent instanceof Element || parent instanceof DocumentFragment ) ) {
  568. /**
  569. * Position parent have to be a model element or model document fragment.
  570. *
  571. * @error position-parent-incorrect
  572. */
  573. throw new CKEditorError( 'position-parent-incorrect: Position parent have to be a element or document fragment.' );
  574. }
  575. const path = parent.getPath();
  576. path.push( offset );
  577. return new this( parent.root, path );
  578. }
  579. /**
  580. * Creates a new position, which is equal to passed position.
  581. *
  582. * @param {engine.model.Position} position Position to be cloned.
  583. * @returns {engine.model.Position}
  584. */
  585. static createFromPosition( position ) {
  586. return new this( position.root, position.path.slice() );
  587. }
  588. /**
  589. * Creates a `Position` instance from given plain object (i.e. parsed JSON string).
  590. *
  591. * @param {Object} json Plain object to be converted to `Position`.
  592. * @returns {engine.model.Position} `Position` instance created using given plain object.
  593. */
  594. static fromJSON( json, doc ) {
  595. if ( json.root === '$graveyard' ) {
  596. return new Position( doc.graveyard, json.path );
  597. }
  598. if ( !doc.hasRoot( json.root ) ) {
  599. /**
  600. * Cannot create position for document. Root with specified name does not exist.
  601. *
  602. * @error position-fromjson-no-root
  603. * @param {String} rootName
  604. */
  605. throw new CKEditorError(
  606. 'position-fromjson-no-root: Cannot create position for document. Root with specified name does not exist.',
  607. { rootName: json.root }
  608. );
  609. }
  610. return new Position( doc.getRoot( json.root ), json.path );
  611. }
  612. }
  613. /**
  614. * A flag indicating whether this position is `'before'` or `'after'` or `'same'` as given position.
  615. * If positions are in different roots `'different'` flag is returned.
  616. *
  617. * @typedef {String} engine.model.PositionRelation
  618. */