selection.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  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 Element from './element';
  14. import count from '@ckeditor/ckeditor5-utils/src/count';
  15. import isIterable from '@ckeditor/ckeditor5-utils/src/isiterable';
  16. /**
  17. * Class representing selection in tree view.
  18. *
  19. * Selection can consist of {@link module:engine/view/range~Range ranges} that can be added using
  20. * {@link module:engine/view/selection~Selection#addRange addRange}
  21. * and {@link module:engine/view/selection~Selection#setRanges setRanges} methods.
  22. * Both methods create copies of provided ranges and store those copies internally. Further modifications to passed
  23. * ranges will not change selection's state.
  24. * Selection's ranges can be obtained via {@link module:engine/view/selection~Selection#getRanges getRanges},
  25. * {@link module:engine/view/selection~Selection#getFirstRange getFirstRange}
  26. * and {@link module:engine/view/selection~Selection#getLastRange getLastRange}
  27. * methods, which return copies of ranges stored inside selection. Modifications made on these copies will not change
  28. * selection's state. Similar situation occurs when getting {@link module:engine/view/selection~Selection#anchor anchor},
  29. * {@link module:engine/view/selection~Selection#focus focus}, {@link module:engine/view/selection~Selection#getFirstPosition first} and
  30. * {@link module:engine/view/selection~Selection#getLastPosition last} positions - all will return copies of requested positions.
  31. */
  32. export default class Selection {
  33. /**
  34. * Creates new selection instance.
  35. *
  36. * @param {Iterable.<module:engine/view/range~Range>} [ranges] An optional array of ranges to set.
  37. * @param {Boolean} [isLastBackward] An optional flag describing if last added range was selected forward - from start to end
  38. * (`false`) or backward - from end to start (`true`). Defaults to `false`.
  39. */
  40. constructor( ranges, isLastBackward ) {
  41. /**
  42. * Stores all ranges that are selected.
  43. *
  44. * @protected
  45. * @member {Array.<module:engine/view/range~Range>}
  46. */
  47. this._ranges = [];
  48. /**
  49. * Specifies whether the last added range was added as a backward or forward range.
  50. *
  51. * @protected
  52. * @member {Boolean}
  53. */
  54. this._lastRangeBackward = false;
  55. /**
  56. * Specifies whether selection instance is fake.
  57. *
  58. * @private
  59. * @member {Boolean}
  60. */
  61. this._isFake = false;
  62. /**
  63. * Fake selection's label.
  64. *
  65. * @private
  66. * @member {String}
  67. */
  68. this._fakeSelectionLabel = '';
  69. if ( ranges ) {
  70. this.setRanges( ranges, isLastBackward );
  71. }
  72. }
  73. /**
  74. * Sets this selection instance to be marked as `fake`. A fake selection does not render as browser native selection
  75. * over selected elements and is hidden to the user. This way, no native selection UI artifacts are displayed to
  76. * the user and selection over elements can be represented in other way, for example by applying proper CSS class.
  77. *
  78. * Additionally fake's selection label can be provided. It will be used to describe fake selection in DOM (and be
  79. * properly handled by screen readers).
  80. *
  81. * @fires change
  82. * @param {Boolean} [value=true] If set to true selection will be marked as `fake`.
  83. * @param {Object} [options] Additional options.
  84. * @param {String} [options.label=''] Fake selection label.
  85. */
  86. setFake( value = true, options = {} ) {
  87. this._isFake = value;
  88. this._fakeSelectionLabel = value ? options.label || '' : '';
  89. this.fire( 'change' );
  90. }
  91. /**
  92. * Returns true if selection instance is marked as `fake`.
  93. *
  94. * @see #setFake
  95. * @returns {Boolean}
  96. */
  97. get isFake() {
  98. return this._isFake;
  99. }
  100. /**
  101. * Returns fake selection label.
  102. *
  103. * @see #setFake
  104. * @returns {String}
  105. */
  106. get fakeSelectionLabel() {
  107. return this._fakeSelectionLabel;
  108. }
  109. /**
  110. * Selection anchor. Anchor may be described as a position where the selection starts. Together with
  111. * {@link #focus focus} they define the direction of selection, which is important
  112. * when expanding/shrinking selection. Anchor is always the start or end of the most recent added range.
  113. * It may be a bit unintuitive when there are multiple ranges in selection.
  114. *
  115. * @see #focus
  116. * @type {module:engine/view/position~Position}
  117. */
  118. get anchor() {
  119. if ( !this._ranges.length ) {
  120. return null;
  121. }
  122. const range = this._ranges[ this._ranges.length - 1 ];
  123. return this._lastRangeBackward ? range.end : range.start;
  124. }
  125. /**
  126. * Selection focus. Focus is a position where the selection ends.
  127. *
  128. * @see #anchor
  129. * @type {module:engine/view/position~Position}
  130. */
  131. get focus() {
  132. if ( !this._ranges.length ) {
  133. return null;
  134. }
  135. const range = this._ranges[ this._ranges.length - 1 ];
  136. return this._lastRangeBackward ? range.start : range.end;
  137. }
  138. /**
  139. * Returns whether the selection is collapsed. Selection is collapsed when there is exactly one range which is
  140. * collapsed.
  141. *
  142. * @type {Boolean}
  143. */
  144. get isCollapsed() {
  145. return this.rangeCount === 1 && this._ranges[ 0 ].isCollapsed;
  146. }
  147. /**
  148. * Returns number of ranges in selection.
  149. *
  150. * @type {Number}
  151. */
  152. get rangeCount() {
  153. return this._ranges.length;
  154. }
  155. /**
  156. * Specifies whether the {@link #focus} precedes {@link #anchor}.
  157. *
  158. * @type {Boolean}
  159. */
  160. get isBackward() {
  161. return !this.isCollapsed && this._lastRangeBackward;
  162. }
  163. /**
  164. * {@link module:engine/view/editableelement~EditableElement EditableElement} instance that contains this selection, or `null`
  165. * if the selection is not inside an editable element.
  166. *
  167. * @type {module:engine/view/editableelement~EditableElement|null}
  168. */
  169. get editableElement() {
  170. if ( this.anchor ) {
  171. return this.anchor.editableElement;
  172. }
  173. return null;
  174. }
  175. /**
  176. * Adds a range to the selection. Added range is copied. This means that passed range is not saved in the
  177. * selection instance and you can safely operate on it.
  178. *
  179. * Accepts a flag describing in which way the selection is made - passed range might be selected from
  180. * {@link module:engine/view/range~Range#start start} to {@link module:engine/view/range~Range#end end}
  181. * or from {@link module:engine/view/range~Range#end end} to {@link module:engine/view/range~Range#start start}.
  182. * The flag is used to set {@link #anchor anchor} and {@link #focus focus} properties.
  183. *
  184. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-selection-range-intersects` if added range intersects
  185. * with ranges already stored in Selection instance.
  186. *
  187. * @fires change
  188. * @param {module:engine/view/range~Range} range
  189. * @param {Boolean} isBackward
  190. */
  191. addRange( range, isBackward ) {
  192. if ( !( range instanceof Range ) ) {
  193. throw new CKEditorError( 'view-selection-invalid-range: Invalid Range.' );
  194. }
  195. this._pushRange( range );
  196. this._lastRangeBackward = !!isBackward;
  197. this.fire( 'change' );
  198. }
  199. /**
  200. * Returns an iterator that contains all ranges added to the selection.
  201. *
  202. * @returns {Iterator.<module:engine/view/range~Range>}
  203. */
  204. getRanges() {
  205. return this._ranges[ Symbol.iterator ]();
  206. }
  207. /**
  208. * Returns first range in the selection. First range is the one which
  209. * {@link module:engine/view/range~Range#start start} position {@link module:engine/view/position~Position#isBefore is before} start
  210. * position of all other ranges (not to confuse with the first range added to the selection).
  211. * Returns `null` if no ranges are added to selection.
  212. *
  213. * @returns {module:engine/view/range~Range|null}
  214. */
  215. getFirstRange() {
  216. let first = null;
  217. for ( const range of this._ranges ) {
  218. if ( !first || range.start.isBefore( first.start ) ) {
  219. first = range;
  220. }
  221. }
  222. return first;
  223. }
  224. /**
  225. * Returns last range in the selection. Last range is the one which {@link module:engine/view/range~Range#end end}
  226. * position {@link module:engine/view/position~Position#isAfter is after} end position of all other ranges (not to confuse
  227. * with the last range added to the selection). Returns `null` if no ranges are added to selection.
  228. *
  229. * @returns {module:engine/view/range~Range|null}
  230. */
  231. getLastRange() {
  232. let last = null;
  233. for ( const range of this._ranges ) {
  234. if ( !last || range.end.isAfter( last.end ) ) {
  235. last = range;
  236. }
  237. }
  238. return last;
  239. }
  240. /**
  241. * Returns copy of the first position in the selection. First position is the position that
  242. * {@link module:engine/view/position~Position#isBefore is before} any other position in the selection ranges.
  243. * Returns `null` if no ranges are added to selection.
  244. *
  245. * @returns {module:engine/view/position~Position|null}
  246. */
  247. getFirstPosition() {
  248. const firstRange = this.getFirstRange();
  249. return firstRange ? firstRange.start : null;
  250. }
  251. /**
  252. * Returns copy of the last position in the selection. Last position is the position that
  253. * {@link module:engine/view/position~Position#isAfter is after} any other position in the selection ranges.
  254. * Returns `null` if no ranges are added to selection.
  255. *
  256. * @returns {module:engine/view/position~Position|null}
  257. */
  258. getLastPosition() {
  259. const lastRange = this.getLastRange();
  260. return lastRange ? lastRange.end : null;
  261. }
  262. /**
  263. * Checks whether, this selection is equal to given selection. Selections are equal if they have same directions,
  264. * same number of ranges and all ranges from one selection equal to a range from other selection.
  265. *
  266. * @param {module:engine/view/selection~Selection} otherSelection Selection to compare with.
  267. * @returns {Boolean} `true` if selections are equal, `false` otherwise.
  268. */
  269. isEqual( otherSelection ) {
  270. if ( this.isFake != otherSelection.isFake ) {
  271. return false;
  272. }
  273. if ( this.isFake && this.fakeSelectionLabel != otherSelection.fakeSelectionLabel ) {
  274. return false;
  275. }
  276. if ( this.rangeCount != otherSelection.rangeCount ) {
  277. return false;
  278. } else if ( this.rangeCount === 0 ) {
  279. return true;
  280. }
  281. if ( !this.anchor.isEqual( otherSelection.anchor ) || !this.focus.isEqual( otherSelection.focus ) ) {
  282. return false;
  283. }
  284. for ( const thisRange of this._ranges ) {
  285. let found = false;
  286. for ( const otherRange of otherSelection._ranges ) {
  287. if ( thisRange.isEqual( otherRange ) ) {
  288. found = true;
  289. break;
  290. }
  291. }
  292. if ( !found ) {
  293. return false;
  294. }
  295. }
  296. return true;
  297. }
  298. /**
  299. * Checks whether this selection is similar to given selection. Selections are similar if they have same directions, same
  300. * number of ranges, and all {@link module:engine/view/range~Range#getTrimmed trimmed} ranges from one selection are
  301. * equal to any trimmed range from other selection.
  302. *
  303. * @param {module:engine/view/selection~Selection} otherSelection Selection to compare with.
  304. * @returns {Boolean} `true` if selections are similar, `false` otherwise.
  305. */
  306. isSimilar( otherSelection ) {
  307. if ( this.isBackward != otherSelection.isBackward ) {
  308. return false;
  309. }
  310. const numOfRangesA = count( this.getRanges() );
  311. const numOfRangesB = count( otherSelection.getRanges() );
  312. // If selections have different number of ranges, they cannot be similar.
  313. if ( numOfRangesA != numOfRangesB ) {
  314. return false;
  315. }
  316. // If both selections have no ranges, they are similar.
  317. if ( numOfRangesA == 0 ) {
  318. return true;
  319. }
  320. // Check if each range in one selection has a similar range in other selection.
  321. for ( let rangeA of this.getRanges() ) {
  322. rangeA = rangeA.getTrimmed();
  323. let found = false;
  324. for ( let rangeB of otherSelection.getRanges() ) {
  325. rangeB = rangeB.getTrimmed();
  326. if ( rangeA.start.isEqual( rangeB.start ) && rangeA.end.isEqual( rangeB.end ) ) {
  327. found = true;
  328. break;
  329. }
  330. }
  331. // For `rangeA`, neither range in `otherSelection` was similar. So selections are not similar.
  332. if ( !found ) {
  333. return false;
  334. }
  335. }
  336. // There were no ranges that weren't matched. Selections are similar.
  337. return true;
  338. }
  339. /**
  340. * Removes all ranges that were added to the selection.
  341. *
  342. * @fires change
  343. */
  344. removeAllRanges() {
  345. if ( this._ranges.length ) {
  346. this._ranges = [];
  347. this.fire( 'change' );
  348. }
  349. }
  350. /**
  351. * Replaces all ranges that were added to the selection with given array of ranges. Last range of the array
  352. * is treated like the last added range and is used to set {@link #anchor anchor} and {@link #focus focus}.
  353. * Accepts a flag describing in which way the selection is made (see {@link #addRange addRange}).
  354. *
  355. * @fires change
  356. * @param {Iterable.<module:engine/view/range~Range>} newRanges Iterable object of ranges to set.
  357. * @param {Boolean} [isLastBackward] Flag describing if last added range was selected forward - from start to end
  358. * (`false`) or backward - from end to start (`true`). Defaults to `false`.
  359. */
  360. setRanges( newRanges, isLastBackward ) {
  361. this._ranges = [];
  362. for ( const range of newRanges ) {
  363. if ( !( range instanceof Range ) ) {
  364. throw new CKEditorError( 'view-selection-invalid-range: Invalid Range.' );
  365. }
  366. this._pushRange( range );
  367. }
  368. this._lastRangeBackward = !!isLastBackward;
  369. this.fire( 'change' );
  370. }
  371. /**
  372. * Sets this selection's ranges and direction to the specified location based on the given
  373. * {@link module:engine/view/selection~Selection selection}, {@link module:engine/view/position~Position position},
  374. * {@link module:engine/view/range~Range range} or an iterable of {@link module:engine/view/range~Range ranges}.
  375. *
  376. * @param {module:engine/view/selection~Selection|module:engine/view/position~Position|
  377. * Iterable.<module:engine/view/range~Range>|module:engine/view/range~Range} selectable
  378. */
  379. setTo( selectable ) {
  380. if ( selectable instanceof Selection ) {
  381. this._isFake = selectable._isFake;
  382. this._fakeSelectionLabel = selectable._fakeSelectionLabel;
  383. this.setRanges( selectable.getRanges(), selectable.isBackward );
  384. } else if ( selectable instanceof Range ) {
  385. this.setRanges( [ selectable ] );
  386. } else if ( isIterable( selectable ) ) {
  387. // We assume that the selectable is an iterable of ranges.
  388. this.setRanges( selectable );
  389. } else {
  390. // We assume that the selectable is a position.
  391. this.setRanges( [ new Range( selectable ) ] );
  392. }
  393. }
  394. /**
  395. * Sets this selection in the provided element.
  396. *
  397. * @param {module:engine/view/element~Element} element
  398. */
  399. setIn( element ) {
  400. this.setRanges( [ Range.createIn( element ) ] );
  401. }
  402. /**
  403. * Sets this selection on the provided item.
  404. *
  405. * @param {module:engine/view/item~Item} item
  406. */
  407. setOn( item ) {
  408. this.setRanges( [ Range.createOn( item ) ] );
  409. }
  410. /**
  411. * Sets collapsed selection at the specified location.
  412. *
  413. * The location can be specified in the same form as {@link module:engine/view/position~Position.createAt} parameters.
  414. *
  415. * @fires change
  416. * @param {module:engine/view/item~Item|module:engine/view/position~Position} itemOrPosition
  417. * @param {Number|'end'|'before'|'after'} [offset=0] Offset or one of the flags. Used only when
  418. * first parameter is a {@link module:engine/view/item~Item view item}.
  419. */
  420. setCollapsedAt( itemOrPosition, offset ) {
  421. const pos = Position.createAt( itemOrPosition, offset );
  422. const range = new Range( pos, pos );
  423. this.setRanges( [ range ] );
  424. }
  425. /**
  426. * Collapses selection to the selection's {@link #getFirstPosition first position}.
  427. * All ranges, besides the collapsed one, will be removed. Nothing will change if there are no ranges stored
  428. * inside selection.
  429. *
  430. * @fires change
  431. */
  432. collapseToStart() {
  433. const startPosition = this.getFirstPosition();
  434. if ( startPosition !== null ) {
  435. this.setRanges( [ new Range( startPosition, startPosition ) ] );
  436. }
  437. }
  438. /**
  439. * Collapses selection to the selection's {@link #getLastPosition last position}.
  440. * All ranges, besides the collapsed one, will be removed. Nothing will change if there are no ranges stored
  441. * inside selection.
  442. *
  443. * @fires change
  444. */
  445. collapseToEnd() {
  446. const endPosition = this.getLastPosition();
  447. if ( endPosition !== null ) {
  448. this.setRanges( [ new Range( endPosition, endPosition ) ] );
  449. }
  450. }
  451. /**
  452. * Moves {@link #focus} to the specified location.
  453. *
  454. * The location can be specified in the same form as {@link module:engine/view/position~Position.createAt} parameters.
  455. *
  456. * @fires change
  457. * @param {module:engine/view/item~Item|module:engine/view/position~Position} itemOrPosition
  458. * @param {Number|'end'|'before'|'after'} [offset=0] Offset or one of the flags. Used only when
  459. * first parameter is a {@link module:engine/view/item~Item view item}.
  460. */
  461. moveFocusTo( itemOrPosition, offset ) {
  462. if ( this.anchor === null ) {
  463. /**
  464. * Cannot set selection focus if there are no ranges in selection.
  465. *
  466. * @error view-selection-moveFocusTo-no-ranges
  467. */
  468. throw new CKEditorError(
  469. 'view-selection-moveFocusTo-no-ranges: Cannot set selection focus if there are no ranges in selection.'
  470. );
  471. }
  472. const newFocus = Position.createAt( itemOrPosition, offset );
  473. if ( newFocus.compareWith( this.focus ) == 'same' ) {
  474. return;
  475. }
  476. const anchor = this.anchor;
  477. this._ranges.pop();
  478. if ( newFocus.compareWith( anchor ) == 'before' ) {
  479. this.addRange( new Range( newFocus, anchor ), true );
  480. } else {
  481. this.addRange( new Range( anchor, newFocus ) );
  482. }
  483. }
  484. /**
  485. * Returns the selected element. {@link module:engine/view/element~Element Element} is considered as selected if there is only
  486. * one range in the selection, and that range contains exactly one element.
  487. * Returns `null` if there is no selected element.
  488. *
  489. * @returns {module:engine/view/element~Element|null}
  490. */
  491. getSelectedElement() {
  492. if ( this.rangeCount !== 1 ) {
  493. return null;
  494. }
  495. const range = this.getFirstRange();
  496. const nodeAfterStart = range.start.nodeAfter;
  497. const nodeBeforeEnd = range.end.nodeBefore;
  498. return ( nodeAfterStart instanceof Element && nodeAfterStart == nodeBeforeEnd ) ? nodeAfterStart : null;
  499. }
  500. /**
  501. * Creates and returns an instance of `Selection` that is a clone of given selection, meaning that it has same
  502. * ranges and same direction as this selection.
  503. *
  504. * @params {module:engine/view/selection~Selection} otherSelection Selection to be cloned.
  505. * @returns {module:engine/view/selection~Selection} `Selection` instance that is a clone of given selection.
  506. */
  507. static createFromSelection( otherSelection ) {
  508. const selection = new Selection();
  509. selection.setTo( otherSelection );
  510. return selection;
  511. }
  512. /**
  513. * Adds range to selection - creates copy of given range so it can be safely used and modified.
  514. *
  515. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-selection-range-intersects` if added range intersects
  516. * with ranges already stored in selection instance.
  517. *
  518. * @private
  519. * @param {module:engine/view/range~Range} range
  520. */
  521. _pushRange( range ) {
  522. for ( const storedRange of this._ranges ) {
  523. if ( range.isIntersecting( storedRange ) ) {
  524. /**
  525. * Trying to add a range that intersects with another range from selection.
  526. *
  527. * @error view-selection-range-intersects
  528. * @param {module:engine/view/range~Range} addedRange Range that was added to the selection.
  529. * @param {module:engine/view/range~Range} intersectingRange Range from selection that intersects with `addedRange`.
  530. */
  531. throw new CKEditorError(
  532. 'view-selection-range-intersects: Trying to add a range that intersects with another range from selection.',
  533. { addedRange: range, intersectingRange: storedRange }
  534. );
  535. }
  536. }
  537. this._ranges.push( Range.createFromRange( range ) );
  538. }
  539. }
  540. mix( Selection, EmitterMixin );
  541. /**
  542. * Fired whenever selection ranges are changed through {@link ~Selection Selection API}.
  543. *
  544. * @event change
  545. */