selection.js 30 KB

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