8
0

position.js 12 KB

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