selection.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module engine/view/selection
  7. */
  8. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  9. import Range from './range';
  10. import Position from './position';
  11. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  12. import EmitterMixin from '@ckeditor/ckeditor5-utils/src/emittermixin';
  13. import Node from './node';
  14. import Element from './element';
  15. import count from '@ckeditor/ckeditor5-utils/src/count';
  16. import isIterable from '@ckeditor/ckeditor5-utils/src/isiterable';
  17. import DocumentSelection from './documentselection';
  18. /**
  19. * Class representing an arbirtary selection in the view.
  20. * See also {@link module:engine/view/documentselection~DocumentSelection}.
  21. *
  22. * New selection instances can be created via the constructor or one these methods:
  23. *
  24. * * {@link module:engine/view/view~View#createSelection `View#createSelection()`},
  25. * * {@link module:engine/view/upcastwriter~UpcastWriter#createSelection `UpcastWriter#createSelection()`}.
  26. *
  27. * A selection can consist of {@link module:engine/view/range~Range ranges} that can be set by using
  28. * the {@link module:engine/view/selection~Selection#setTo `Selection#setTo()`} method.
  29. */
  30. export default class Selection {
  31. /**
  32. * Creates new selection instance.
  33. *
  34. * **Note**: The selection constructor is available as a factory method:
  35. *
  36. * * {@link module:engine/view/view~View#createSelection `View#createSelection()`},
  37. * * {@link module:engine/view/upcastwriter~UpcastWriter#createSelection `UpcastWriter#createSelection()`}.
  38. *
  39. * // Creates empty selection without ranges.
  40. * const selection = writer.createSelection();
  41. *
  42. * // Creates selection at the given range.
  43. * const range = writer.createRange( start, end );
  44. * const selection = writer.createSelection( range );
  45. *
  46. * // Creates selection at the given ranges
  47. * const ranges = [ writer.createRange( start1, end2 ), writer.createRange( star2, end2 ) ];
  48. * const selection = writer.createSelection( ranges );
  49. *
  50. * // Creates selection from the other selection.
  51. * const otherSelection = writer.createSelection();
  52. * const selection = writer.createSelection( otherSelection );
  53. *
  54. * // Creates selection from the document selection.
  55. * const selection = writer.createSelection( editor.editing.view.document.selection );
  56. *
  57. * // Creates selection at the given position.
  58. * const position = writer.createPositionFromPath( root, path );
  59. * const selection = writer.createSelection( position );
  60. *
  61. * // Creates collapsed selection at the position of given item and offset.
  62. * const paragraph = writer.createContainerElement( 'paragraph' );
  63. * const selection = writer.createSelection( paragraph, offset );
  64. *
  65. * // Creates a range inside an {@link module:engine/view/element~Element element} which starts before the
  66. * // first child of that element and ends after the last child of that element.
  67. * const selection = writer.createSelection( paragraph, 'in' );
  68. *
  69. * // Creates a range on an {@link module:engine/view/item~Item item} which starts before the item and ends
  70. * // just after the item.
  71. * const selection = writer.createSelection( paragraph, 'on' );
  72. *
  73. * `Selection`'s constructor allow passing additional options (`backward`, `fake` and `label`) as the last argument.
  74. *
  75. * // Creates backward selection.
  76. * const selection = writer.createSelection( range, { backward: true } );
  77. *
  78. * Fake selection does not render as browser native selection over selected elements and is hidden to the user.
  79. * This way, no native selection UI artifacts are displayed to the user and selection over elements can be
  80. * represented in other way, for example by applying proper CSS class.
  81. *
  82. * Additionally fake's selection label can be provided. It will be used to describe fake selection in DOM
  83. * (and be properly handled by screen readers).
  84. *
  85. * // Creates fake selection with label.
  86. * const selection = writer.createSelection( range, { fake: true, label: 'foo' } );
  87. *
  88. * @param {module:engine/view/selection~Selectable} [selectable=null]
  89. * @param {Number|'before'|'end'|'after'|'on'|'in'} [placeOrOffset] Offset or place when selectable is an `Item`.
  90. * @param {Object} [options]
  91. * @param {Boolean} [options.backward] Sets this selection instance to be backward.
  92. * @param {Boolean} [options.fake] Sets this selection instance to be marked as `fake`.
  93. * @param {String} [options.label] Label for the fake selection.
  94. */
  95. constructor( selectable = null, placeOrOffset, options ) {
  96. /**
  97. * Stores all ranges that are selected.
  98. *
  99. * @protected
  100. * @member {Array.<module:engine/view/range~Range>}
  101. */
  102. this._ranges = [];
  103. /**
  104. * Specifies whether the last added range was added as a backward or forward range.
  105. *
  106. * @protected
  107. * @member {Boolean}
  108. */
  109. this._lastRangeBackward = false;
  110. /**
  111. * Specifies whether selection instance is fake.
  112. *
  113. * @private
  114. * @member {Boolean}
  115. */
  116. this._isFake = false;
  117. /**
  118. * Fake selection's label.
  119. *
  120. * @private
  121. * @member {String}
  122. */
  123. this._fakeSelectionLabel = '';
  124. this.setTo( selectable, placeOrOffset, options );
  125. }
  126. /**
  127. * Returns true if selection instance is marked as `fake`.
  128. *
  129. * @see #setTo
  130. * @returns {Boolean}
  131. */
  132. get isFake() {
  133. return this._isFake;
  134. }
  135. /**
  136. * Returns fake selection label.
  137. *
  138. * @see #setTo
  139. * @returns {String}
  140. */
  141. get fakeSelectionLabel() {
  142. return this._fakeSelectionLabel;
  143. }
  144. /**
  145. * Selection anchor. Anchor may be described as a position where the selection starts. Together with
  146. * {@link #focus focus} they define the direction of selection, which is important
  147. * when expanding/shrinking selection. Anchor is always the start or end of the most recent added range.
  148. * It may be a bit unintuitive when there are multiple ranges in selection.
  149. *
  150. * @see #focus
  151. * @type {module:engine/view/position~Position}
  152. */
  153. get anchor() {
  154. if ( !this._ranges.length ) {
  155. return null;
  156. }
  157. const range = this._ranges[ this._ranges.length - 1 ];
  158. const anchor = this._lastRangeBackward ? range.end : range.start;
  159. return anchor.clone();
  160. }
  161. /**
  162. * Selection focus. Focus is a position where the selection ends.
  163. *
  164. * @see #anchor
  165. * @type {module:engine/view/position~Position}
  166. */
  167. get focus() {
  168. if ( !this._ranges.length ) {
  169. return null;
  170. }
  171. const range = this._ranges[ this._ranges.length - 1 ];
  172. const focus = this._lastRangeBackward ? range.start : range.end;
  173. return focus.clone();
  174. }
  175. /**
  176. * Returns whether the selection is collapsed. Selection is collapsed when there is exactly one range which is
  177. * collapsed.
  178. *
  179. * @type {Boolean}
  180. */
  181. get isCollapsed() {
  182. return this.rangeCount === 1 && this._ranges[ 0 ].isCollapsed;
  183. }
  184. /**
  185. * Returns number of ranges in selection.
  186. *
  187. * @type {Number}
  188. */
  189. get rangeCount() {
  190. return this._ranges.length;
  191. }
  192. /**
  193. * Specifies whether the {@link #focus} precedes {@link #anchor}.
  194. *
  195. * @type {Boolean}
  196. */
  197. get isBackward() {
  198. return !this.isCollapsed && this._lastRangeBackward;
  199. }
  200. /**
  201. * {@link module:engine/view/editableelement~EditableElement EditableElement} instance that contains this selection, or `null`
  202. * if the selection is not inside an editable element.
  203. *
  204. * @type {module:engine/view/editableelement~EditableElement|null}
  205. */
  206. get editableElement() {
  207. if ( this.anchor ) {
  208. return this.anchor.editableElement;
  209. }
  210. return null;
  211. }
  212. /**
  213. * Returns an iterable that contains copies of all ranges added to the selection.
  214. *
  215. * @returns {Iterable.<module:engine/view/range~Range>}
  216. */
  217. * getRanges() {
  218. for ( const range of this._ranges ) {
  219. yield range.clone();
  220. }
  221. }
  222. /**
  223. * Returns copy of the first range in the selection. First range is the one which
  224. * {@link module:engine/view/range~Range#start start} position {@link module:engine/view/position~Position#isBefore is before} start
  225. * position of all other ranges (not to confuse with the first range added to the selection).
  226. * Returns `null` if no ranges are added to selection.
  227. *
  228. * @returns {module:engine/view/range~Range|null}
  229. */
  230. getFirstRange() {
  231. let first = null;
  232. for ( const range of this._ranges ) {
  233. if ( !first || range.start.isBefore( first.start ) ) {
  234. first = range;
  235. }
  236. }
  237. return first ? first.clone() : null;
  238. }
  239. /**
  240. * Returns copy of the last range in the selection. Last range is the one which {@link module:engine/view/range~Range#end end}
  241. * position {@link module:engine/view/position~Position#isAfter is after} end position of all other ranges (not to confuse
  242. * with the last range added to the selection). Returns `null` if no ranges are added to selection.
  243. *
  244. * @returns {module:engine/view/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 ? last.clone() : null;
  254. }
  255. /**
  256. * Returns copy of the first position in the selection. First position is the position that
  257. * {@link module:engine/view/position~Position#isBefore is before} any other position in the selection ranges.
  258. * Returns `null` if no ranges are added to selection.
  259. *
  260. * @returns {module:engine/view/position~Position|null}
  261. */
  262. getFirstPosition() {
  263. const firstRange = this.getFirstRange();
  264. return firstRange ? firstRange.start.clone() : null;
  265. }
  266. /**
  267. * Returns copy of the last position in the selection. Last position is the position that
  268. * {@link module:engine/view/position~Position#isAfter is after} any other position in the selection ranges.
  269. * Returns `null` if no ranges are added to selection.
  270. *
  271. * @returns {module:engine/view/position~Position|null}
  272. */
  273. getLastPosition() {
  274. const lastRange = this.getLastRange();
  275. return lastRange ? lastRange.end.clone() : null;
  276. }
  277. /**
  278. * Checks whether, this selection is equal to given selection. Selections are equal if they have same directions,
  279. * same number of ranges and all ranges from one selection equal to a range from other selection.
  280. *
  281. * @param {module:engine/view/selection~Selection|module:engine/view/documentselection~DocumentSelection} otherSelection
  282. * Selection to compare with.
  283. * @returns {Boolean} `true` if selections are equal, `false` otherwise.
  284. */
  285. isEqual( otherSelection ) {
  286. if ( this.isFake != otherSelection.isFake ) {
  287. return false;
  288. }
  289. if ( this.isFake && this.fakeSelectionLabel != otherSelection.fakeSelectionLabel ) {
  290. return false;
  291. }
  292. if ( this.rangeCount != otherSelection.rangeCount ) {
  293. return false;
  294. } else if ( this.rangeCount === 0 ) {
  295. return true;
  296. }
  297. if ( !this.anchor.isEqual( otherSelection.anchor ) || !this.focus.isEqual( otherSelection.focus ) ) {
  298. return false;
  299. }
  300. for ( const thisRange of this._ranges ) {
  301. let found = false;
  302. for ( const otherRange of otherSelection._ranges ) {
  303. if ( thisRange.isEqual( otherRange ) ) {
  304. found = true;
  305. break;
  306. }
  307. }
  308. if ( !found ) {
  309. return false;
  310. }
  311. }
  312. return true;
  313. }
  314. /**
  315. * Checks whether this selection is similar to given selection. Selections are similar if they have same directions, same
  316. * number of ranges, and all {@link module:engine/view/range~Range#getTrimmed trimmed} ranges from one selection are
  317. * equal to any trimmed range from other selection.
  318. *
  319. * @param {module:engine/view/selection~Selection|module:engine/view/documentselection~DocumentSelection} otherSelection
  320. * Selection to compare with.
  321. * @returns {Boolean} `true` if selections are similar, `false` otherwise.
  322. */
  323. isSimilar( otherSelection ) {
  324. if ( this.isBackward != otherSelection.isBackward ) {
  325. return false;
  326. }
  327. const numOfRangesA = count( this.getRanges() );
  328. const numOfRangesB = count( otherSelection.getRanges() );
  329. // If selections have different number of ranges, they cannot be similar.
  330. if ( numOfRangesA != numOfRangesB ) {
  331. return false;
  332. }
  333. // If both selections have no ranges, they are similar.
  334. if ( numOfRangesA == 0 ) {
  335. return true;
  336. }
  337. // Check if each range in one selection has a similar range in other selection.
  338. for ( let rangeA of this.getRanges() ) {
  339. rangeA = rangeA.getTrimmed();
  340. let found = false;
  341. for ( let rangeB of otherSelection.getRanges() ) {
  342. rangeB = rangeB.getTrimmed();
  343. if ( rangeA.start.isEqual( rangeB.start ) && rangeA.end.isEqual( rangeB.end ) ) {
  344. found = true;
  345. break;
  346. }
  347. }
  348. // For `rangeA`, neither range in `otherSelection` was similar. So selections are not similar.
  349. if ( !found ) {
  350. return false;
  351. }
  352. }
  353. // There were no ranges that weren't matched. Selections are similar.
  354. return true;
  355. }
  356. /**
  357. * Returns the selected element. {@link module:engine/view/element~Element Element} is considered as selected if there is only
  358. * one range in the selection, and that range contains exactly one element.
  359. * Returns `null` if there is no selected element.
  360. *
  361. * @returns {module:engine/view/element~Element|null}
  362. */
  363. getSelectedElement() {
  364. if ( this.rangeCount !== 1 ) {
  365. return null;
  366. }
  367. const range = this.getFirstRange();
  368. let nodeAfterStart = range.start.nodeAfter;
  369. let nodeBeforeEnd = range.end.nodeBefore;
  370. // Handle the situation when selection position is at the beginning / at the end of a text node.
  371. // In such situation `.nodeAfter` and `.nodeBefore` are `null` but the selection still might be spanning
  372. // over one element.
  373. //
  374. // <p>Foo{<span class="widget"></span>}bar</p> vs <p>Foo[<span class="widget"></span>]bar</p>
  375. //
  376. // These are basically the same selections, only the difference is if the selection position is at
  377. // at the end/at the beginning of a text node or just before/just after the text node.
  378. //
  379. if ( range.start.parent.is( 'text' ) && range.start.isAtEnd && range.start.parent.nextSibling ) {
  380. nodeAfterStart = range.start.parent.nextSibling;
  381. }
  382. if ( range.end.parent.is( 'text' ) && range.end.isAtStart && range.end.parent.previousSibling ) {
  383. nodeBeforeEnd = range.end.parent.previousSibling;
  384. }
  385. return ( nodeAfterStart instanceof Element && nodeAfterStart == nodeBeforeEnd ) ? nodeAfterStart : null;
  386. }
  387. /**
  388. * Sets this selection's ranges and direction to the specified location based on the given
  389. * {@link module:engine/view/selection~Selectable selectable}.
  390. *
  391. * // Sets selection to the given range.
  392. * const range = writer.createRange( start, end );
  393. * selection.setTo( range );
  394. *
  395. * // Sets selection to given ranges.
  396. * const ranges = [ writer.createRange( start1, end2 ), writer.createRange( star2, end2 ) ];
  397. * selection.setTo( range );
  398. *
  399. * // Sets selection to the other selection.
  400. * const otherSelection = writer.createSelection();
  401. * selection.setTo( otherSelection );
  402. *
  403. * // Sets selection to contents of DocumentSelection.
  404. * selection.setTo( editor.editing.view.document.selection );
  405. *
  406. * // Sets collapsed selection at the given position.
  407. * const position = writer.createPositionAt( root, path );
  408. * selection.setTo( position );
  409. *
  410. * // Sets collapsed selection at the position of given item and offset.
  411. * selection.setTo( paragraph, offset );
  412. *
  413. * Creates a range inside an {@link module:engine/view/element~Element element} which starts before the first child of
  414. * that element and ends after the last child of that element.
  415. *
  416. * selection.setTo( paragraph, 'in' );
  417. *
  418. * Creates a range on an {@link module:engine/view/item~Item item} which starts before the item and ends just after the item.
  419. *
  420. * selection.setTo( paragraph, 'on' );
  421. *
  422. * // Clears selection. Removes all ranges.
  423. * selection.setTo( null );
  424. *
  425. * `Selection#setTo()` method allow passing additional options (`backward`, `fake` and `label`) as the last argument.
  426. *
  427. * // Sets selection as backward.
  428. * selection.setTo( range, { backward: true } );
  429. *
  430. * Fake selection does not render as browser native selection over selected elements and is hidden to the user.
  431. * This way, no native selection UI artifacts are displayed to the user and selection over elements can be
  432. * represented in other way, for example by applying proper CSS class.
  433. *
  434. * Additionally fake's selection label can be provided. It will be used to describe fake selection in DOM
  435. * (and be properly handled by screen readers).
  436. *
  437. * // Creates fake selection with label.
  438. * selection.setTo( range, { fake: true, label: 'foo' } );
  439. *
  440. * @fires change
  441. * @param {module:engine/view/selection~Selectable} selectable
  442. * @param {Number|'before'|'end'|'after'|'on'|'in'} [placeOrOffset] Sets place or offset of the selection.
  443. * @param {Object} [options]
  444. * @param {Boolean} [options.backward] Sets this selection instance to be backward.
  445. * @param {Boolean} [options.fake] Sets this selection instance to be marked as `fake`.
  446. * @param {String} [options.label] Label for the fake selection.
  447. */
  448. setTo( selectable, placeOrOffset, options ) {
  449. if ( selectable === null ) {
  450. this._setRanges( [] );
  451. this._setFakeOptions( placeOrOffset );
  452. } else if ( selectable instanceof Selection || selectable instanceof DocumentSelection ) {
  453. this._setRanges( selectable.getRanges(), selectable.isBackward );
  454. this._setFakeOptions( { fake: selectable.isFake, label: selectable.fakeSelectionLabel } );
  455. } else if ( selectable instanceof Range ) {
  456. this._setRanges( [ selectable ], placeOrOffset && placeOrOffset.backward );
  457. this._setFakeOptions( placeOrOffset );
  458. } else if ( selectable instanceof Position ) {
  459. this._setRanges( [ new Range( selectable ) ] );
  460. this._setFakeOptions( placeOrOffset );
  461. } else if ( selectable instanceof Node ) {
  462. const backward = !!options && !!options.backward;
  463. let range;
  464. if ( placeOrOffset === undefined ) {
  465. /**
  466. * selection.setTo requires the second parameter when the first parameter is a node.
  467. *
  468. * @error view-selection-setTo-required-second-parameter
  469. */
  470. throw new CKEditorError(
  471. 'view-selection-setTo-required-second-parameter: ' +
  472. 'selection.setTo requires the second parameter when the first parameter is a node.',
  473. this
  474. );
  475. } else if ( placeOrOffset == 'in' ) {
  476. range = Range._createIn( selectable );
  477. } else if ( placeOrOffset == 'on' ) {
  478. range = Range._createOn( selectable );
  479. } else {
  480. range = new Range( Position._createAt( selectable, placeOrOffset ) );
  481. }
  482. this._setRanges( [ range ], backward );
  483. this._setFakeOptions( options );
  484. } else if ( isIterable( selectable ) ) {
  485. // We assume that the selectable is an iterable of ranges.
  486. // Array.from() is used to prevent setting ranges to the old iterable
  487. this._setRanges( selectable, placeOrOffset && placeOrOffset.backward );
  488. this._setFakeOptions( placeOrOffset );
  489. } else {
  490. /**
  491. * Cannot set selection to given place.
  492. *
  493. * @error view-selection-setTo-not-selectable
  494. */
  495. throw new CKEditorError( 'view-selection-setTo-not-selectable: Cannot set selection to given place.', this );
  496. }
  497. this.fire( 'change' );
  498. }
  499. /**
  500. * Moves {@link #focus} to the specified location.
  501. *
  502. * The location can be specified in the same form as {@link module:engine/view/view~View#createPositionAt view.createPositionAt()}
  503. * parameters.
  504. *
  505. * @fires change
  506. * @param {module:engine/view/item~Item|module:engine/view/position~Position} itemOrPosition
  507. * @param {Number|'end'|'before'|'after'} [offset] Offset or one of the flags. Used only when
  508. * first parameter is a {@link module:engine/view/item~Item view item}.
  509. */
  510. setFocus( itemOrPosition, offset ) {
  511. if ( this.anchor === null ) {
  512. /**
  513. * Cannot set selection focus if there are no ranges in selection.
  514. *
  515. * @error view-selection-setFocus-no-ranges
  516. */
  517. throw new CKEditorError(
  518. 'view-selection-setFocus-no-ranges: Cannot set selection focus if there are no ranges in selection.',
  519. this
  520. );
  521. }
  522. const newFocus = Position._createAt( itemOrPosition, offset );
  523. if ( newFocus.compareWith( this.focus ) == 'same' ) {
  524. return;
  525. }
  526. const anchor = this.anchor;
  527. this._ranges.pop();
  528. if ( newFocus.compareWith( anchor ) == 'before' ) {
  529. this._addRange( new Range( newFocus, anchor ), true );
  530. } else {
  531. this._addRange( new Range( anchor, newFocus ) );
  532. }
  533. this.fire( 'change' );
  534. }
  535. /**
  536. * Method verifies if the checked object belongs to a given a type. Type's name might be prefixed with a `view:` string,
  537. * for example `view:selection`. Type is a string which usually equal to a name of the class written in camelCase convention.
  538. * If the object is a class instance, which has a parent class with `is()` method, then type verification returns `true`
  539. * for any type match for an entire child-parent chain.
  540. *
  541. * const selection = new Selection( ... );
  542. *
  543. * selection.is( 'selection' ); // true
  544. * selection.is( 'view:selection' ); // true
  545. * selection.is( 'node' ); // false
  546. * selection.is( 'element' ); // false
  547. *
  548. * Acceptable type for this class is `selection` and its prefixed version.
  549. *
  550. * See also: {@link module:engine/view/node~Node#is `Node#is()`}.
  551. *
  552. * @param {String} type
  553. * @returns {Boolean}
  554. */
  555. is( type ) {
  556. return type == 'selection' || type == 'view:selection';
  557. }
  558. /**
  559. * Replaces all ranges that were added to the selection with given array of ranges. Last range of the array
  560. * is treated like the last added range and is used to set {@link #anchor anchor} and {@link #focus focus}.
  561. * Accepts a flag describing in which way the selection is made.
  562. *
  563. * @private
  564. * @param {Iterable.<module:engine/view/range~Range>} newRanges Iterable object of ranges to set.
  565. * @param {Boolean} [isLastBackward=false] Flag describing if last added range was selected forward - from start to end
  566. * (`false`) or backward - from end to start (`true`). Defaults to `false`.
  567. */
  568. _setRanges( newRanges, isLastBackward = false ) {
  569. // New ranges should be copied to prevent removing them by setting them to `[]` first.
  570. // Only applies to situations when selection is set to the same selection or same selection's ranges.
  571. newRanges = Array.from( newRanges );
  572. this._ranges = [];
  573. for ( const range of newRanges ) {
  574. this._addRange( range );
  575. }
  576. this._lastRangeBackward = !!isLastBackward;
  577. }
  578. /**
  579. * Sets this selection instance to be marked as `fake`. A fake selection does not render as browser native selection
  580. * over selected elements and is hidden to the user. This way, no native selection UI artifacts are displayed to
  581. * the user and selection over elements can be represented in other way, for example by applying proper CSS class.
  582. *
  583. * Additionally fake's selection label can be provided. It will be used to describe fake selection in DOM (and be
  584. * properly handled by screen readers).
  585. *
  586. * @private
  587. * @param {Object} [options] Options.
  588. * @param {Boolean} [options.fake] If set to true selection will be marked as `fake`.
  589. * @param {String} [options.label=''] Fake selection label.
  590. */
  591. _setFakeOptions( options = {} ) {
  592. this._isFake = !!options.fake;
  593. this._fakeSelectionLabel = options.fake ? options.label || '' : '';
  594. }
  595. /**
  596. * Adds a range to the selection. Added range is copied. This means that passed range is not saved in the
  597. * selection instance and you can safely operate on it.
  598. *
  599. * Accepts a flag describing in which way the selection is made - passed range might be selected from
  600. * {@link module:engine/view/range~Range#start start} to {@link module:engine/view/range~Range#end end}
  601. * or from {@link module:engine/view/range~Range#end end} to {@link module:engine/view/range~Range#start start}.
  602. * The flag is used to set {@link #anchor anchor} and {@link #focus focus} properties.
  603. *
  604. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-selection-range-intersects` if added range intersects
  605. * with ranges already stored in Selection instance.
  606. *
  607. * @private
  608. * @fires change
  609. * @param {module:engine/view/range~Range} range
  610. * @param {Boolean} [isBackward]
  611. */
  612. _addRange( range, isBackward = false ) {
  613. if ( !( range instanceof Range ) ) {
  614. /**
  615. * Selection range set to an object that is not an instance of {@link module:engine/view/range~Range}.
  616. *
  617. * @error view-selection-add-range-not-range
  618. */
  619. throw new CKEditorError(
  620. 'view-selection-add-range-not-range: ' +
  621. 'Selection range set to an object that is not an instance of view.Range',
  622. this
  623. );
  624. }
  625. this._pushRange( range );
  626. this._lastRangeBackward = !!isBackward;
  627. }
  628. /**
  629. * Adds range to selection - creates copy of given range so it can be safely used and modified.
  630. *
  631. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-selection-range-intersects` if added range intersects
  632. * with ranges already stored in selection instance.
  633. *
  634. * @private
  635. * @param {module:engine/view/range~Range} range
  636. */
  637. _pushRange( range ) {
  638. for ( const storedRange of this._ranges ) {
  639. if ( range.isIntersecting( storedRange ) ) {
  640. /**
  641. * Trying to add a range that intersects with another range from selection.
  642. *
  643. * @error view-selection-range-intersects
  644. * @param {module:engine/view/range~Range} addedRange Range that was added to the selection.
  645. * @param {module:engine/view/range~Range} intersectingRange Range from selection that intersects with `addedRange`.
  646. */
  647. throw new CKEditorError(
  648. 'view-selection-range-intersects: Trying to add a range that intersects with another range from selection.',
  649. this,
  650. { addedRange: range, intersectingRange: storedRange }
  651. );
  652. }
  653. }
  654. this._ranges.push( new Range( range.start, range.end ) );
  655. }
  656. /**
  657. * Fired whenever selection ranges are changed through {@link ~Selection Selection API}.
  658. *
  659. * @event change
  660. */
  661. }
  662. mix( Selection, EmitterMixin );
  663. /**
  664. * An entity that is used to set selection.
  665. *
  666. * See also {@link module:engine/view/selection~Selection#setTo}
  667. *
  668. * @typedef {
  669. * module:engine/view/selection~Selection|
  670. * module:engine/view/documentselection~DocumentSelection|
  671. * module:engine/view/position~Position|
  672. * Iterable.<module:engine/view/range~Range>|
  673. * module:engine/view/range~Range|
  674. * module:engine/view/item~Item|
  675. * null
  676. * } module:engine/view/selection~Selectable
  677. */