position.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/view/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 EditableElement from './editableelement';
  12. /**
  13. * Position in the tree. Position is always located before or after a node.
  14. */
  15. export default class Position {
  16. /**
  17. * Creates a position.
  18. *
  19. * @param {module:engine/view/node~Node|module:engine/view/documentfragment~DocumentFragment} parent Position parent.
  20. * @param {Number} offset Position offset.
  21. */
  22. constructor( parent, offset ) {
  23. /**
  24. * Position parent.
  25. *
  26. * @member {module:engine/view/node~Node|module:engine/view/documentfragment~DocumentFragment}
  27. * module:engine/view/position~Position#parent
  28. */
  29. this.parent = parent;
  30. /**
  31. * Position offset.
  32. *
  33. * @member {Number} module:engine/view/position~Position#offset
  34. */
  35. this.offset = offset;
  36. }
  37. /**
  38. * Node directly after the position. Equals `null` when there is no node after position or position is located
  39. * inside text node.
  40. *
  41. * @readonly
  42. * @type {module:engine/view/node~Node|null}
  43. */
  44. get nodeAfter() {
  45. if ( this.parent.is( 'text' ) ) {
  46. return null;
  47. }
  48. return this.parent.getChild( this.offset ) || null;
  49. }
  50. /**
  51. * Node directly before the position. Equals `null` when there is no node before position or position is located
  52. * inside text node.
  53. *
  54. * @readonly
  55. * @type {module:engine/view/node~Node|null}
  56. */
  57. get nodeBefore() {
  58. if ( this.parent.is( 'text' ) ) {
  59. return null;
  60. }
  61. return this.parent.getChild( this.offset - 1 ) || null;
  62. }
  63. /**
  64. * Is `true` if position is at the beginning of its {@link module:engine/view/position~Position#parent parent}, `false` otherwise.
  65. *
  66. * @readonly
  67. * @type {Boolean}
  68. */
  69. get isAtStart() {
  70. return this.offset === 0;
  71. }
  72. /**
  73. * Is `true` if position is at the end of its {@link module:engine/view/position~Position#parent parent}, `false` otherwise.
  74. *
  75. * @readonly
  76. * @type {Boolean}
  77. */
  78. get isAtEnd() {
  79. const endOffset = this.parent.is( 'text' ) ? this.parent.data.length : this.parent.childCount;
  80. return this.offset === endOffset;
  81. }
  82. /**
  83. * Position's root, that is the root of the position's parent element.
  84. *
  85. * @readonly
  86. * @type {module:engine/view/node~Node|module:engine/view/documentfragment~DocumentFragment}
  87. */
  88. get root() {
  89. return this.parent.root;
  90. }
  91. /**
  92. * {@link module:engine/view/editableelement~EditableElement EditableElement} instance that contains this position, or `null` if
  93. * position is not inside an editable element.
  94. *
  95. * @type {module:engine/view/editableelement~EditableElement|null}
  96. */
  97. get editableElement() {
  98. let editable = this.parent;
  99. while ( !( editable instanceof EditableElement ) ) {
  100. if ( editable.parent ) {
  101. editable = editable.parent;
  102. } else {
  103. return null;
  104. }
  105. }
  106. return editable;
  107. }
  108. /**
  109. * Returns a new instance of Position with offset incremented by `shift` value.
  110. *
  111. * @param {Number} shift How position offset should get changed. Accepts negative values.
  112. * @returns {module:engine/view/position~Position} Shifted position.
  113. */
  114. getShiftedBy( shift ) {
  115. let shifted = Position.createFromPosition( this );
  116. let offset = shifted.offset + shift;
  117. shifted.offset = offset < 0 ? 0 : offset;
  118. return shifted;
  119. }
  120. /**
  121. * Gets the farthest position which matches the callback using
  122. * {@link module:engine/view/treewalker~TreeWalker TreeWalker}.
  123. *
  124. * For example:
  125. *
  126. * getLastMatchingPosition( value => value.type == 'text' ); // <p>{}foo</p> -> <p>foo[]</p>
  127. * getLastMatchingPosition( value => value.type == 'text', { direction: 'backward' } ); // <p>foo[]</p> -> <p>{}foo</p>
  128. * getLastMatchingPosition( value => false ); // Do not move the position.
  129. *
  130. * @param {Function} skip Callback function. Gets {@link module:engine/view/treewalker~TreeWalkerValue} and should
  131. * return `true` if the value should be skipped or `false` if not.
  132. * @param {Object} options Object with configuration options. See {@link module:engine/view/treewalker~TreeWalker}.
  133. *
  134. * @returns {module:engine/view/position~Position} The position after the last item which matches the `skip` callback test.
  135. */
  136. getLastMatchingPosition( skip, options = {} ) {
  137. options.startPosition = this;
  138. const treeWalker = new TreeWalker( options );
  139. treeWalker.skip( skip );
  140. return treeWalker.position;
  141. }
  142. /**
  143. * Returns ancestors array of this position, that is this position's parent and it's ancestors.
  144. *
  145. * @returns {Array} Array with ancestors.
  146. */
  147. getAncestors() {
  148. if ( this.parent.is( 'documentFragment' ) ) {
  149. return [ this.parent ];
  150. } else {
  151. return this.parent.getAncestors( { includeNode: true } );
  152. }
  153. }
  154. /**
  155. * Checks whether this position equals given position.
  156. *
  157. * @param {module:engine/view/position~Position} otherPosition Position to compare with.
  158. * @returns {Boolean} True if positions are same.
  159. */
  160. isEqual( otherPosition ) {
  161. return ( this.parent == otherPosition.parent && this.offset == otherPosition.offset );
  162. }
  163. /**
  164. * Checks whether this position is located before given position. When method returns `false` it does not mean that
  165. * this position is after give one. Two positions may be located inside separate roots and in that situation this
  166. * method will still return `false`.
  167. *
  168. * @see module:engine/view/position~Position#isAfter
  169. * @see module:engine/view/position~Position#compareWith
  170. * @param {module:engine/view/position~Position} otherPosition Position to compare with.
  171. * @returns {Boolean} Returns `true` if this position is before given position.
  172. */
  173. isBefore( otherPosition ) {
  174. return this.compareWith( otherPosition ) == 'before';
  175. }
  176. /**
  177. * Checks whether this position is located after given position. When method returns `false` it does not mean that
  178. * this position is before give one. Two positions may be located inside separate roots and in that situation this
  179. * method will still return `false`.
  180. *
  181. * @see module:engine/view/position~Position#isBefore
  182. * @see module:engine/view/position~Position#compareWith
  183. * @param {module:engine/view/position~Position} otherPosition Position to compare with.
  184. * @returns {Boolean} Returns `true` if this position is after given position.
  185. */
  186. isAfter( otherPosition ) {
  187. return this.compareWith( otherPosition ) == 'after';
  188. }
  189. /**
  190. * Checks whether this position is before, after or in same position that other position. Two positions may be also
  191. * different when they are located in separate roots.
  192. *
  193. * @param {module:engine/view/position~Position} otherPosition Position to compare with.
  194. * @returns {module:engine/view/position~PositionRelation}
  195. */
  196. compareWith( otherPosition ) {
  197. if ( this.isEqual( otherPosition ) ) {
  198. return 'same';
  199. }
  200. // If positions have same parent.
  201. if ( this.parent === otherPosition.parent ) {
  202. return this.offset - otherPosition.offset < 0 ? 'before' : 'after';
  203. }
  204. // Get path from root to position's parent element.
  205. const path = this.getAncestors();
  206. const otherPath = otherPosition.getAncestors();
  207. // Compare both path arrays to find common ancestor.
  208. const result = compareArrays( path, otherPath );
  209. let commonAncestorIndex;
  210. switch ( result ) {
  211. case 0:
  212. // No common ancestors found.
  213. return 'different';
  214. case 'prefix':
  215. commonAncestorIndex = path.length - 1;
  216. break;
  217. case 'extension':
  218. commonAncestorIndex = otherPath.length - 1;
  219. break;
  220. default:
  221. commonAncestorIndex = result - 1;
  222. }
  223. // Common ancestor of two positions.
  224. const commonAncestor = path[ commonAncestorIndex ];
  225. const nextAncestor1 = path[ commonAncestorIndex + 1 ];
  226. const nextAncestor2 = otherPath[ commonAncestorIndex + 1 ];
  227. // Check if common ancestor is not one of the parents.
  228. if ( commonAncestor === this.parent ) {
  229. const index = this.offset - nextAncestor2.index;
  230. return index <= 0 ? 'before' : 'after';
  231. } else if ( commonAncestor === otherPosition.parent ) {
  232. const index = nextAncestor1.index - otherPosition.offset;
  233. return index < 0 ? 'before' : 'after';
  234. }
  235. const index = nextAncestor1.index - nextAncestor2.index;
  236. // Compare indexes of next ancestors inside common one.
  237. return index < 0 ? 'before' : 'after';
  238. }
  239. /**
  240. * Creates position at the given location. The location can be specified as:
  241. *
  242. * * a {@link module:engine/view/position~Position position},
  243. * * parent element and offset (offset defaults to `0`),
  244. * * parent element and `'end'` (sets position at the end of that element),
  245. * * {@link module:engine/view/item~Item view item} and `'before'` or `'after'` (sets position before or after given view item).
  246. *
  247. * This method is a shortcut to other constructors such as:
  248. *
  249. * * {@link module:engine/view/position~Position.createBefore},
  250. * * {@link module:engine/view/position~Position.createAfter},
  251. * * {@link module:engine/view/position~Position.createFromPosition}.
  252. *
  253. * @param {module:engine/view/item~Item|module:engine/model/position~Position} itemOrPosition
  254. * @param {Number|'end'|'before'|'after'} [offset=0] Offset or one of the flags. Used only when
  255. * first parameter is a {@link module:engine/view/item~Item view item}.
  256. */
  257. static createAt( itemOrPosition, offset ) {
  258. if ( itemOrPosition instanceof Position ) {
  259. return this.createFromPosition( itemOrPosition );
  260. } else {
  261. let node = itemOrPosition;
  262. if ( offset == 'end' ) {
  263. offset = node.is( 'text' ) ? node.data.length : node.childCount;
  264. } else if ( offset == 'before' ) {
  265. return this.createBefore( node );
  266. } else if ( offset == 'after' ) {
  267. return this.createAfter( node );
  268. } else if ( !offset ) {
  269. offset = 0;
  270. }
  271. return new Position( node, offset );
  272. }
  273. }
  274. /**
  275. * Creates a new position after given view item.
  276. *
  277. * @param {module:engine/view/item~Item} item View item after which the position should be located.
  278. * @returns {module:engine/view/position~Position}
  279. */
  280. static createAfter( item ) {
  281. // TextProxy is not a instance of Node so we need do handle it in specific way.
  282. if ( item.is( 'textProxy' ) ) {
  283. return new Position( item.textNode, item.offsetInText + item.data.length );
  284. }
  285. if ( !item.parent ) {
  286. /**
  287. * You can not make a position after a root.
  288. *
  289. * @error position-after-root
  290. * @param {module:engine/view/node~Node} root
  291. */
  292. throw new CKEditorError( 'view-position-after-root: You can not make position after root.', { root: item } );
  293. }
  294. return new Position( item.parent, item.index + 1 );
  295. }
  296. /**
  297. * Creates a new position before given view item.
  298. *
  299. * @param {module:engine/view/item~Item} item View item before which the position should be located.
  300. * @returns {module:engine/view/position~Position}
  301. */
  302. static createBefore( item ) {
  303. // TextProxy is not a instance of Node so we need do handle it in specific way.
  304. if ( item.is( 'textProxy' ) ) {
  305. return new Position( item.textNode, item.offsetInText );
  306. }
  307. if ( !item.parent ) {
  308. /**
  309. * You cannot make a position before a root.
  310. *
  311. * @error position-before-root
  312. * @param {module:engine/view/node~Node} root
  313. */
  314. throw new CKEditorError( 'view-position-before-root: You can not make position before root.', { root: item } );
  315. }
  316. return new Position( item.parent, item.index );
  317. }
  318. /**
  319. * Creates and returns a new instance of `Position`, which is equal to the passed position.
  320. *
  321. * @param {module:engine/view/position~Position} position Position to be cloned.
  322. * @returns {module:engine/view/position~Position}
  323. */
  324. static createFromPosition( position ) {
  325. return new this( position.parent, position.offset );
  326. }
  327. }
  328. /**
  329. * A flag indicating whether this position is `'before'` or `'after'` or `'same'` as given position.
  330. * If positions are in different roots `'different'` flag is returned.
  331. *
  332. * @typedef {String} module:engine/view/position~PositionRelation
  333. */