8
0

selection.js 28 KB

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