position.js 14 KB

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