selection.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/model/selection
  7. */
  8. import Position from './position';
  9. import Element from './element';
  10. import Range from './range';
  11. import EmitterMixin from '@ckeditor/ckeditor5-utils/src/emittermixin';
  12. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  13. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  14. import toMap from '@ckeditor/ckeditor5-utils/src/tomap';
  15. import mapsEqual from '@ckeditor/ckeditor5-utils/src/mapsequal';
  16. import isIterable from '@ckeditor/ckeditor5-utils/src/isiterable';
  17. /**
  18. * `Selection` is a group of {@link module:engine/model/range~Range ranges} which has a direction specified by
  19. * {@link module:engine/model/selection~Selection#anchor anchor} and {@link module:engine/model/selection~Selection#focus focus}.
  20. * Additionally, `Selection` may have it's own attributes.
  21. */
  22. export default class Selection {
  23. /**
  24. * Creates new selection instance.
  25. *
  26. * @param {Iterable.<module:engine/view/range~Range>} [ranges] An optional iterable object of ranges to set.
  27. * @param {Boolean} [isLastBackward] An optional flag describing if last added range was selected forward - from start to end
  28. * (`false`) or backward - from end to start (`true`). Defaults to `false`.
  29. */
  30. constructor( ranges, isLastBackward ) {
  31. /**
  32. * Specifies whether the last added range was added as a backward or forward range.
  33. *
  34. * @private
  35. * @member {Boolean}
  36. */
  37. this._lastRangeBackward = false;
  38. /**
  39. * Stores selection ranges.
  40. *
  41. * @protected
  42. * @member {Array.<module:engine/model/range~Range>}
  43. */
  44. this._ranges = [];
  45. /**
  46. * List of attributes set on current selection.
  47. *
  48. * @protected
  49. * @member {Map} module:engine/model/selection~Selection#_attrs
  50. */
  51. this._attrs = new Map();
  52. if ( ranges ) {
  53. this.setRanges( ranges, isLastBackward );
  54. }
  55. }
  56. /**
  57. * Selection anchor. Anchor may be described as a position where the most recent part of the selection starts.
  58. * Together with {@link #focus} they define the direction of selection, which is important
  59. * when expanding/shrinking selection. Anchor is always {@link module:engine/model/range~Range#start start} or
  60. * {@link module:engine/model/range~Range#end end} position of the most recently added range.
  61. *
  62. * Is set to `null` if there are no ranges in selection.
  63. *
  64. * @see #focus
  65. * @readonly
  66. * @type {module:engine/model/position~Position|null}
  67. */
  68. get anchor() {
  69. if ( this._ranges.length > 0 ) {
  70. const range = this._ranges[ this._ranges.length - 1 ];
  71. return this._lastRangeBackward ? range.end : range.start;
  72. }
  73. return null;
  74. }
  75. /**
  76. * Selection focus. Focus is a position where the selection ends.
  77. *
  78. * Is set to `null` if there are no ranges in selection.
  79. *
  80. * @see #anchor
  81. * @readonly
  82. * @type {module:engine/model/position~Position|null}
  83. */
  84. get focus() {
  85. if ( this._ranges.length > 0 ) {
  86. const range = this._ranges[ this._ranges.length - 1 ];
  87. return this._lastRangeBackward ? range.start : range.end;
  88. }
  89. return null;
  90. }
  91. /**
  92. * Returns whether the selection is collapsed. Selection is collapsed when there is exactly one range which is
  93. * collapsed.
  94. *
  95. * @readonly
  96. * @type {Boolean}
  97. */
  98. get isCollapsed() {
  99. const length = this._ranges.length;
  100. if ( length === 1 ) {
  101. return this._ranges[ 0 ].isCollapsed;
  102. } else {
  103. return false;
  104. }
  105. }
  106. /**
  107. * Returns number of ranges in selection.
  108. *
  109. * @type {Number}
  110. */
  111. get rangeCount() {
  112. return this._ranges.length;
  113. }
  114. /**
  115. * Specifies whether the {@link #focus}
  116. * precedes {@link #anchor}.
  117. *
  118. * @type {Boolean}
  119. */
  120. get isBackward() {
  121. return !this.isCollapsed && this._lastRangeBackward;
  122. }
  123. /**
  124. * Checks whether this selection is equal to given selection. Selections are equal if they have same directions,
  125. * same number of ranges and all ranges from one selection equal to a range from other selection.
  126. *
  127. * @param {module:engine/model/selection~Selection} otherSelection Selection to compare with.
  128. * @returns {Boolean} `true` if selections are equal, `false` otherwise.
  129. */
  130. isEqual( otherSelection ) {
  131. if ( this.rangeCount != otherSelection.rangeCount ) {
  132. return false;
  133. } else if ( this.rangeCount === 0 ) {
  134. return true;
  135. }
  136. if ( !this.anchor.isEqual( otherSelection.anchor ) || !this.focus.isEqual( otherSelection.focus ) ) {
  137. return false;
  138. }
  139. for ( const thisRange of this._ranges ) {
  140. let found = false;
  141. for ( const otherRange of otherSelection._ranges ) {
  142. if ( thisRange.isEqual( otherRange ) ) {
  143. found = true;
  144. break;
  145. }
  146. }
  147. if ( !found ) {
  148. return false;
  149. }
  150. }
  151. return true;
  152. }
  153. /**
  154. * Returns an iterator that iterates over copies of selection ranges.
  155. *
  156. * @returns {Iterator.<module:engine/model/range~Range>}
  157. */
  158. * getRanges() {
  159. for ( const range of this._ranges ) {
  160. yield Range.createFromRange( range );
  161. }
  162. }
  163. /**
  164. * Returns a copy of the first range in the selection.
  165. * First range is the one which {@link module:engine/model/range~Range#start start} position
  166. * {@link module:engine/model/position~Position#isBefore is before} start position of all other ranges
  167. * (not to confuse with the first range added to the selection).
  168. *
  169. * Returns `null` if there are no ranges in selection.
  170. *
  171. * @returns {module:engine/model/range~Range|null}
  172. */
  173. getFirstRange() {
  174. let first = null;
  175. for ( const range of this._ranges ) {
  176. if ( !first || range.start.isBefore( first.start ) ) {
  177. first = range;
  178. }
  179. }
  180. return first ? Range.createFromRange( first ) : null;
  181. }
  182. /**
  183. * Returns a copy of the last range in the selection.
  184. * Last range is the one which {@link module:engine/model/range~Range#end end} position
  185. * {@link module:engine/model/position~Position#isAfter is after} end position of all other ranges (not to confuse with the range most
  186. * recently added to the selection).
  187. *
  188. * Returns `null` if there are no ranges in selection.
  189. *
  190. * @returns {module:engine/model/range~Range|null}
  191. */
  192. getLastRange() {
  193. let last = null;
  194. for ( const range of this._ranges ) {
  195. if ( !last || range.end.isAfter( last.end ) ) {
  196. last = range;
  197. }
  198. }
  199. return last ? Range.createFromRange( last ) : null;
  200. }
  201. /**
  202. * Returns the first position in the selection.
  203. * First position is the position that {@link module:engine/model/position~Position#isBefore is before}
  204. * any other position in the selection.
  205. *
  206. * Returns `null` if there are no ranges in selection.
  207. *
  208. * @returns {module:engine/model/position~Position|null}
  209. */
  210. getFirstPosition() {
  211. const first = this.getFirstRange();
  212. return first ? Position.createFromPosition( first.start ) : null;
  213. }
  214. /**
  215. * Returns the last position in the selection.
  216. * Last position is the position that {@link module:engine/model/position~Position#isAfter is after}
  217. * any other position in the selection.
  218. *
  219. * Returns `null` if there are no ranges in selection.
  220. *
  221. * @returns {module:engine/model/position~Position|null}
  222. */
  223. getLastPosition() {
  224. const lastRange = this.getLastRange();
  225. return lastRange ? Position.createFromPosition( lastRange.end ) : null;
  226. }
  227. /**
  228. * Adds a range to this selection. Added range is copied. This means that passed range is not saved in `Selection`
  229. * instance and operating on it will not change `Selection` state.
  230. *
  231. * Accepts a flag describing in which way the selection is made - passed range might be selected from
  232. * {@link module:engine/model/range~Range#start start} to {@link module:engine/model/range~Range#end end}
  233. * or from {@link module:engine/model/range~Range#end end}
  234. * to {@link module:engine/model/range~Range#start start}.
  235. * The flag is used to set {@link #anchor} and
  236. * {@link #focus} properties.
  237. *
  238. * @fires change:range
  239. * @param {module:engine/model/range~Range} range Range to add.
  240. * @param {Boolean} [isBackward=false] Flag describing if added range was selected forward - from start to end (`false`)
  241. * or backward - from end to start (`true`).
  242. */
  243. addRange( range, isBackward = false ) {
  244. this._pushRange( range );
  245. this._lastRangeBackward = !!isBackward;
  246. this.fire( 'change:range', { directChange: true } );
  247. }
  248. /**
  249. * Removes all ranges that were added to the selection.
  250. *
  251. * @fires change:range
  252. */
  253. removeAllRanges() {
  254. if ( this._ranges.length > 0 ) {
  255. this._removeAllRanges();
  256. this.fire( 'change:range', { directChange: true } );
  257. }
  258. }
  259. /**
  260. * Replaces all ranges that were added to the selection with given array of ranges. Last range of the array
  261. * is treated like the last added range and is used to set {@link module:engine/model/selection~Selection#anchor} and
  262. * {@link module:engine/model/selection~Selection#focus}. Accepts a flag describing in which direction the selection is made
  263. * (see {@link module:engine/model/selection~Selection#addRange}).
  264. *
  265. * @fires change:range
  266. * @param {Iterable.<module:engine/model/range~Range>} newRanges Ranges to set.
  267. * @param {Boolean} [isLastBackward=false] Flag describing if last added range was selected forward - from start to end (`false`)
  268. * or backward - from end to start (`true`).
  269. */
  270. setRanges( newRanges, isLastBackward = false ) {
  271. newRanges = Array.from( newRanges );
  272. // Check whether there is any range in new ranges set that is different than all already added ranges.
  273. const anyNewRange = newRanges.some( newRange => {
  274. if ( !( newRange instanceof Range ) ) {
  275. throw new CKEditorError( 'model-selection-added-not-range: Trying to add an object that is not an instance of Range.' );
  276. }
  277. return this._ranges.every( oldRange => {
  278. return !oldRange.isEqual( newRange );
  279. } );
  280. } );
  281. // Don't do anything if nothing changed.
  282. if ( newRanges.length === this._ranges.length && !anyNewRange ) {
  283. return;
  284. }
  285. this._removeAllRanges();
  286. for ( const range of newRanges ) {
  287. this._pushRange( range );
  288. }
  289. this._lastRangeBackward = !!isLastBackward;
  290. this.fire( 'change:range', { directChange: true } );
  291. }
  292. /**
  293. * Sets this selection's ranges and direction to the specified location based on the given
  294. * {@link module:engine/model/selection~Selection selection}, {@link module:engine/model/position~Position position},
  295. * {@link module:engine/model/range~Range range} or an iterable of {@link module:engine/model/range~Range ranges}.
  296. *
  297. * @param {module:engine/model/selection~Selection|module:engine/model/position~Position|
  298. * Iterable.<module:engine/model/range~Range>|module:engine/model/range~Range} selectable
  299. */
  300. setTo( selectable ) {
  301. if ( selectable instanceof Selection ) {
  302. this.setRanges( selectable.getRanges(), selectable.isBackward );
  303. } else if ( selectable instanceof Range ) {
  304. this.setRanges( [ selectable ] );
  305. } else if ( isIterable( selectable ) ) {
  306. // We assume that the selectable is an iterable of ranges.
  307. this.setRanges( selectable );
  308. } else {
  309. // We assume that the selectable is a position.
  310. this.setRanges( [ new Range( selectable ) ] );
  311. }
  312. }
  313. /**
  314. * Sets this selection in the provided element.
  315. *
  316. * @param {module:engine/model/element~Element} element
  317. */
  318. setIn( element ) {
  319. this.setRanges( [ Range.createIn( element ) ] );
  320. }
  321. /**
  322. * Sets this selection on the provided item.
  323. *
  324. * @param {module:engine/model/item~Item} item
  325. */
  326. setOn( item ) {
  327. this.setRanges( [ Range.createOn( item ) ] );
  328. }
  329. /**
  330. * Sets collapsed selection at the specified location.
  331. *
  332. * The location can be specified in the same form as {@link module:engine/model/position~Position.createAt} parameters.
  333. *
  334. * @fires change:range
  335. * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
  336. * @param {Number|'end'|'before'|'after'} [offset=0] Offset or one of the flags. Used only when
  337. * first parameter is a {@link module:engine/model/item~Item model item}.
  338. */
  339. setCollapsedAt( itemOrPosition, offset ) {
  340. const pos = Position.createAt( itemOrPosition, offset );
  341. const range = new Range( pos, pos );
  342. this.setRanges( [ range ] );
  343. }
  344. /**
  345. * Collapses selection to the selection's {@link module:engine/model/selection~Selection#getFirstPosition first position}.
  346. * All ranges, besides the collapsed one, will be removed. Nothing will change if there are no ranges stored
  347. * inside selection.
  348. *
  349. * @fires change
  350. */
  351. collapseToStart() {
  352. const startPosition = this.getFirstPosition();
  353. if ( startPosition !== null ) {
  354. this.setRanges( [ new Range( startPosition, startPosition ) ] );
  355. }
  356. }
  357. /**
  358. * Collapses selection to the selection's {@link module:engine/model/selection~Selection#getLastPosition last position}.
  359. * All ranges, besides the collapsed one, will be removed. Nothing will change if there are no ranges stored
  360. * inside selection.
  361. *
  362. * @fires change
  363. */
  364. collapseToEnd() {
  365. const endPosition = this.getLastPosition();
  366. if ( endPosition !== null ) {
  367. this.setRanges( [ new Range( endPosition, endPosition ) ] );
  368. }
  369. }
  370. /**
  371. * Moves {@link module:engine/model/selection~Selection#focus} to the specified location.
  372. *
  373. * The location can be specified in the same form as {@link module:engine/model/position~Position.createAt} parameters.
  374. *
  375. * @fires change:range
  376. * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
  377. * @param {Number|'end'|'before'|'after'} [offset=0] Offset or one of the flags. Used only when
  378. * first parameter is a {@link module:engine/model/item~Item model item}.
  379. */
  380. moveFocusTo( itemOrPosition, offset ) {
  381. if ( this.anchor === null ) {
  382. /**
  383. * Cannot set selection focus if there are no ranges in selection.
  384. *
  385. * @error model-selection-moveFocusTo-no-ranges
  386. */
  387. throw new CKEditorError(
  388. 'model-selection-moveFocusTo-no-ranges: Cannot set selection focus if there are no ranges in selection.'
  389. );
  390. }
  391. const newFocus = Position.createAt( itemOrPosition, offset );
  392. if ( newFocus.compareWith( this.focus ) == 'same' ) {
  393. return;
  394. }
  395. const anchor = this.anchor;
  396. if ( this._ranges.length ) {
  397. this._popRange();
  398. }
  399. if ( newFocus.compareWith( anchor ) == 'before' ) {
  400. this.addRange( new Range( newFocus, anchor ), true );
  401. } else {
  402. this.addRange( new Range( anchor, newFocus ) );
  403. }
  404. }
  405. /**
  406. * Gets an attribute value for given key or `undefined` if that attribute is not set on the selection.
  407. *
  408. * @param {String} key Key of attribute to look for.
  409. * @returns {*} Attribute value or `undefined`.
  410. */
  411. getAttribute( key ) {
  412. return this._attrs.get( key );
  413. }
  414. /**
  415. * Returns iterator that iterates over this selection's attributes.
  416. *
  417. * Attributes are returned as arrays containing two items. First one is attribute key and second is attribute value.
  418. * This format is accepted by native `Map` object and also can be passed in `Node` constructor.
  419. *
  420. * @returns {Iterable.<*>}
  421. */
  422. getAttributes() {
  423. return this._attrs.entries();
  424. }
  425. /**
  426. * Returns iterator that iterates over this selection's attribute keys.
  427. *
  428. * @returns {Iterator.<String>}
  429. */
  430. getAttributeKeys() {
  431. return this._attrs.keys();
  432. }
  433. /**
  434. * Checks if the selection has an attribute for given key.
  435. *
  436. * @param {String} key Key of attribute to check.
  437. * @returns {Boolean} `true` if attribute with given key is set on selection, `false` otherwise.
  438. */
  439. hasAttribute( key ) {
  440. return this._attrs.has( key );
  441. }
  442. /**
  443. * Removes all attributes from the selection.
  444. *
  445. * If there were any attributes in selection, fires the {@link #event:change} event with
  446. * removed attributes' keys.
  447. *
  448. * @fires change:attribute
  449. */
  450. clearAttributes() {
  451. if ( this._attrs.size > 0 ) {
  452. const attributeKeys = Array.from( this._attrs.keys() );
  453. this._attrs.clear();
  454. this.fire( 'change:attribute', { attributeKeys, directChange: true } );
  455. }
  456. }
  457. /**
  458. * Removes an attribute with given key from the selection.
  459. *
  460. * If given attribute was set on the selection, fires the {@link #event:change} event with
  461. * removed attribute key.
  462. *
  463. * @fires change:attribute
  464. * @param {String} key Key of attribute to remove.
  465. */
  466. removeAttribute( key ) {
  467. if ( this.hasAttribute( key ) ) {
  468. this._attrs.delete( key );
  469. this.fire( 'change:attribute', { attributeKeys: [ key ], directChange: true } );
  470. }
  471. }
  472. /**
  473. * Sets attribute on the selection. If attribute with the same key already is set, it's value is overwritten.
  474. *
  475. * If the attribute value has changed, fires the {@link #event:change} event with
  476. * the attribute key.
  477. *
  478. * @fires change:attribute
  479. * @param {String} key Key of attribute to set.
  480. * @param {*} value Attribute value.
  481. */
  482. setAttribute( key, value ) {
  483. if ( this.getAttribute( key ) !== value ) {
  484. this._attrs.set( key, value );
  485. this.fire( 'change:attribute', { attributeKeys: [ key ], directChange: true } );
  486. }
  487. }
  488. /**
  489. * Removes all attributes from the selection and sets given attributes.
  490. *
  491. * If given set of attributes is different than set of attributes already added to selection, fires
  492. * {@link #event:change change event} with keys of attributes that changed.
  493. *
  494. * @fires event:change:attribute
  495. * @param {Iterable|Object} attrs Iterable object containing attributes to be set.
  496. */
  497. setAttributesTo( attrs ) {
  498. attrs = toMap( attrs );
  499. if ( !mapsEqual( attrs, this._attrs ) ) {
  500. // Create a set from keys of old and new attributes.
  501. const changed = new Set( Array.from( attrs.keys() ).concat( Array.from( this._attrs.keys() ) ) );
  502. for ( const [ key, value ] of attrs ) {
  503. // If the attribute remains unchanged, remove it from changed set.
  504. if ( this._attrs.get( key ) === value ) {
  505. changed.delete( key );
  506. }
  507. }
  508. this._attrs = attrs;
  509. this.fire( 'change:attribute', { attributeKeys: Array.from( changed ), directChange: true } );
  510. }
  511. }
  512. /**
  513. * Returns the selected element. {@link module:engine/model/element~Element Element} is considered as selected if there is only
  514. * one range in the selection, and that range contains exactly one element.
  515. * Returns `null` if there is no selected element.
  516. *
  517. * @returns {module:engine/model/element~Element|null}
  518. */
  519. getSelectedElement() {
  520. if ( this.rangeCount !== 1 ) {
  521. return null;
  522. }
  523. const range = this.getFirstRange();
  524. const nodeAfterStart = range.start.nodeAfter;
  525. const nodeBeforeEnd = range.end.nodeBefore;
  526. return ( nodeAfterStart instanceof Element && nodeAfterStart == nodeBeforeEnd ) ? nodeAfterStart : null;
  527. }
  528. /**
  529. * Gets elements of type "block" touched by the selection.
  530. *
  531. * This method's result can be used for example to apply block styling to all blocks covered by this selection.
  532. *
  533. * **Note:** `getSelectedBlocks()` always returns the deepest block.
  534. *
  535. * In this case the function will return exactly all 3 paragraphs:
  536. *
  537. * <paragraph>[a</paragraph>
  538. * <quote>
  539. * <paragraph>b</paragraph>
  540. * </quote>
  541. * <paragraph>c]d</paragraph>
  542. *
  543. * In this case the paragraph will also be returned, despite the collapsed selection:
  544. *
  545. * <paragraph>[]a</paragraph>
  546. *
  547. * **Special case**: If a selection ends at the beginning of a block, that block is not returned as from user perspective
  548. * this block wasn't selected. See [#984](https://github.com/ckeditor/ckeditor5-engine/issues/984) for more details.
  549. *
  550. * <paragraph>[a</paragraph>
  551. * <paragraph>b</paragraph>
  552. * <paragraph>]c</paragraph> // this block will not be returned
  553. *
  554. * @returns {Iterator.<module:engine/model/element~Element>}
  555. */
  556. * getSelectedBlocks() {
  557. const visited = new WeakSet();
  558. for ( const range of this.getRanges() ) {
  559. const startBlock = getParentBlock( range.start, visited );
  560. if ( startBlock ) {
  561. yield startBlock;
  562. }
  563. for ( const value of range.getWalker() ) {
  564. if ( value.type == 'elementEnd' && isUnvisitedBlockContainer( value.item, visited ) ) {
  565. yield value.item;
  566. }
  567. }
  568. const endBlock = getParentBlock( range.end, visited );
  569. // #984. Don't return the end block if the range ends right at its beginning.
  570. if ( endBlock && !range.end.isTouching( Position.createAt( endBlock ) ) ) {
  571. yield endBlock;
  572. }
  573. }
  574. }
  575. /**
  576. * Checks whether the selection contains the entire content of the given element. This means that selection must start
  577. * at a position {@link module:engine/model/position~Position#isTouching touching} the element's start and ends at position
  578. * touching the element's end.
  579. *
  580. * By default, this method will check whether the entire content of the selection's current root is selected.
  581. * Useful to check if e.g. the user has just pressed <kbd>Ctrl</kbd> + <kbd>A</kbd>.
  582. *
  583. * @param {module:engine/model/element~Element} [element=this.anchor.root]
  584. * @returns {Boolean}
  585. */
  586. containsEntireContent( element = this.anchor.root ) {
  587. const limitStartPosition = Position.createAt( element );
  588. const limitEndPosition = Position.createAt( element, 'end' );
  589. return limitStartPosition.isTouching( this.getFirstPosition() ) &&
  590. limitEndPosition.isTouching( this.getLastPosition() );
  591. }
  592. /**
  593. * Creates and returns an instance of `Selection` that is a clone of given selection, meaning that it has same
  594. * ranges and same direction as this selection.
  595. *
  596. * @params {module:engine/model/selection~Selection} otherSelection Selection to be cloned.
  597. * @returns {module:engine/model/selection~Selection} `Selection` instance that is a clone of given selection.
  598. */
  599. static createFromSelection( otherSelection ) {
  600. const selection = new this();
  601. selection.setTo( otherSelection );
  602. return selection;
  603. }
  604. /**
  605. * Adds given range to internal {@link #_ranges ranges array}. Throws an error
  606. * if given range is intersecting with any range that is already stored in this selection.
  607. *
  608. * @protected
  609. * @param {module:engine/model/range~Range} range Range to add.
  610. */
  611. _pushRange( range ) {
  612. if ( !( range instanceof Range ) ) {
  613. throw new CKEditorError( 'model-selection-added-not-range: Trying to add an object that is not an instance of Range.' );
  614. }
  615. this._checkRange( range );
  616. this._ranges.push( Range.createFromRange( range ) );
  617. }
  618. /**
  619. * Checks if given range intersects with ranges that are already in the selection. Throws an error if it does.
  620. *
  621. * @protected
  622. * @param {module:engine/model/range~Range} range Range to check.
  623. */
  624. _checkRange( range ) {
  625. for ( let i = 0; i < this._ranges.length; i++ ) {
  626. if ( range.isIntersecting( this._ranges[ i ] ) ) {
  627. /**
  628. * Trying to add a range that intersects with another range from selection.
  629. *
  630. * @error model-selection-range-intersects
  631. * @param {module:engine/model/range~Range} addedRange Range that was added to the selection.
  632. * @param {module:engine/model/range~Range} intersectingRange Range from selection that intersects with `addedRange`.
  633. */
  634. throw new CKEditorError(
  635. 'model-selection-range-intersects: Trying to add a range that intersects with another range from selection.',
  636. { addedRange: range, intersectingRange: this._ranges[ i ] }
  637. );
  638. }
  639. }
  640. }
  641. /**
  642. * Removes most recently added range from the selection.
  643. *
  644. * @protected
  645. */
  646. _popRange() {
  647. this._ranges.pop();
  648. }
  649. /**
  650. * Deletes ranges from internal range array. Uses {@link #_popRange _popRange} to
  651. * ensure proper ranges removal.
  652. *
  653. * @private
  654. */
  655. _removeAllRanges() {
  656. while ( this._ranges.length > 0 ) {
  657. this._popRange();
  658. }
  659. }
  660. /**
  661. * @event change
  662. */
  663. /**
  664. * Fired whenever selection ranges are changed.
  665. *
  666. * @event change:range
  667. * @param {Boolean} directChange Specifies whether the range change was caused by direct usage of `Selection` API (`true`)
  668. * or by changes done to {@link module:engine/model/document~Document model document}
  669. * using {@link module:engine/model/batch~Batch Batch} API (`false`).
  670. */
  671. /**
  672. * Fired whenever selection attributes are changed.
  673. *
  674. * @event change:attribute
  675. * @param {Boolean} directChange Specifies whether the attributes changed by direct usage of the Selection API (`true`)
  676. * or by changes done to the {@link module:engine/model/document~Document model document}
  677. * using the {@link module:engine/model/batch~Batch Batch} API (`false`).
  678. * @param {Array.<String>} attributeKeys Array containing keys of attributes that changed.
  679. */
  680. }
  681. mix( Selection, EmitterMixin );
  682. // Checks whether the given element extends $block in the schema and has a parent (is not a root).
  683. // Marks it as already visited.
  684. function isUnvisitedBlockContainer( element, visited ) {
  685. if ( visited.has( element ) ) {
  686. return false;
  687. }
  688. visited.add( element );
  689. // TODO https://github.com/ckeditor/ckeditor5-engine/issues/532#issuecomment-278900072.
  690. // This should not be a `$block` check.
  691. return element.document.model.schema.itemExtends( element.name, '$block' ) && element.parent;
  692. }
  693. // Finds the lowest element in position's ancestors which is a block.
  694. // Marks all ancestors as already visited to not include any of them later on.
  695. function getParentBlock( position, visited ) {
  696. const ancestors = position.parent.getAncestors( { parentFirst: true, includeSelf: true } );
  697. const block = ancestors.find( element => isUnvisitedBlockContainer( element, visited ) );
  698. // Mark all ancestors of this position's parent, because find() might've stopped early and
  699. // the found block may be a child of another block.
  700. ancestors.forEach( element => visited.add( element ) );
  701. return block;
  702. }