8
0

selection.js 31 KB

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