8
0

selection.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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. /**
  15. * Class representing selection in tree view.
  16. *
  17. * Selection can consist of {@link module:engine/view/range~Range ranges} that can be added using
  18. * {@link module:engine/view/selection~Selection#addRange addRange}
  19. * and {@link module:engine/view/selection~Selection#setRanges setRanges} methods.
  20. * Both methods create copies of provided ranges and store those copies internally. Further modifications to passed
  21. * ranges will not change selection's state.
  22. * Selection's ranges can be obtained via {@link module:engine/view/selection~Selection#getRanges getRanges},
  23. * {@link module:engine/view/selection~Selection#getFirstRange getFirstRange}
  24. * and {@link module:engine/view/selection~Selection#getLastRange getLastRange}
  25. * methods, which return copies of ranges stored inside selection. Modifications made on these copies will not change
  26. * selection's state. Similar situation occurs when getting {@link module:engine/view/selection~Selection#anchor anchor},
  27. * {@link module:engine/view/selection~Selection#focus focus}, {@link module:engine/view/selection~Selection#getFirstPosition first} and
  28. * {@link module:engine/view/selection~Selection#getLastPosition last} positions - all will return copies of requested positions.
  29. */
  30. export default class Selection {
  31. /**
  32. * Creates new selection instance.
  33. *
  34. * @param {Iterable.<module:engine/view/range~Range>} [ranges] An optional array of ranges to set.
  35. * @param {Boolean} [isLastBackward] An optional flag describing if last added range was selected forward - from start to end
  36. * (`false`) or backward - from end to start (`true`). Defaults to `false`.
  37. */
  38. constructor( ranges, isLastBackward ) {
  39. /**
  40. * Stores all ranges that are selected.
  41. *
  42. * @protected
  43. * @member {Array.<module:engine/view/range~Range>}
  44. */
  45. this._ranges = [];
  46. /**
  47. * Specifies whether the last added range was added as a backward or forward range.
  48. *
  49. * @protected
  50. * @member {Boolean}
  51. */
  52. this._lastRangeBackward = false;
  53. /**
  54. * Specifies whether selection instance is fake.
  55. *
  56. * @private
  57. * @member {Boolean}
  58. */
  59. this._isFake = false;
  60. /**
  61. * Fake selection's label.
  62. *
  63. * @private
  64. * @member {String}
  65. */
  66. this._fakeSelectionLabel = '';
  67. if ( ranges ) {
  68. this.setRanges( ranges, isLastBackward );
  69. }
  70. }
  71. /**
  72. * Sets this selection instance to be marked as `fake`. A fake selection does not render as browser native selection
  73. * over selected elements and is hidden to the user. This way, no native selection UI artifacts are displayed to
  74. * the user and selection over elements can be represented in other way, for example by applying proper CSS class.
  75. *
  76. * Additionally fake's selection label can be provided. It will be used to describe fake selection in DOM (and be
  77. * properly handled by screen readers).
  78. *
  79. * @fires change
  80. * @param {Boolean} [value=true] If set to true selection will be marked as `fake`.
  81. * @param {Object} [options] Additional options.
  82. * @param {String} [options.label=''] Fake selection label.
  83. */
  84. setFake( value = true, options = {} ) {
  85. this._isFake = value;
  86. this._fakeSelectionLabel = value ? options.label || '' : '';
  87. this.fire( 'change' );
  88. }
  89. /**
  90. * Returns true if selection instance is marked as `fake`.
  91. *
  92. * @see #setFake
  93. * @returns {Boolean}
  94. */
  95. get isFake() {
  96. return this._isFake;
  97. }
  98. /**
  99. * Returns fake selection label.
  100. *
  101. * @see #setFake
  102. * @returns {String}
  103. */
  104. get fakeSelectionLabel() {
  105. return this._fakeSelectionLabel;
  106. }
  107. /**
  108. * Selection anchor. Anchor may be described as a position where the selection starts. Together with
  109. * {@link #focus focus} they define the direction of selection, which is important
  110. * when expanding/shrinking selection. Anchor is always the start or end of the most recent added range.
  111. * It may be a bit unintuitive when there are multiple ranges in selection.
  112. *
  113. * @see #focus
  114. * @type {module:engine/view/position~Position}
  115. */
  116. get anchor() {
  117. if ( !this._ranges.length ) {
  118. return null;
  119. }
  120. const range = this._ranges[ this._ranges.length - 1 ];
  121. const anchor = this._lastRangeBackward ? range.end : range.start;
  122. return Position.createFromPosition( anchor );
  123. }
  124. /**
  125. * Selection focus. Focus is a position where the selection ends.
  126. *
  127. * @see #anchor
  128. * @type {module:engine/view/position~Position}
  129. */
  130. get focus() {
  131. if ( !this._ranges.length ) {
  132. return null;
  133. }
  134. const range = this._ranges[ this._ranges.length - 1 ];
  135. const focus = this._lastRangeBackward ? range.start : range.end;
  136. return Position.createFromPosition( focus );
  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. */
  190. addRange( range, isBackward ) {
  191. if ( !( range instanceof Range ) ) {
  192. throw new CKEditorError( 'view-selection-invalid-range: Invalid Range.' );
  193. }
  194. this._pushRange( range );
  195. this._lastRangeBackward = !!isBackward;
  196. this.fire( 'change' );
  197. }
  198. /**
  199. * Returns an iterator that contains copies of all ranges added to the selection.
  200. *
  201. * @returns {Iterator.<module:engine/view/range~Range>}
  202. */
  203. * getRanges() {
  204. for ( const range of this._ranges ) {
  205. yield Range.createFromRange( range );
  206. }
  207. }
  208. /**
  209. * Returns copy of the first range in the selection. First range is the one which
  210. * {@link module:engine/view/range~Range#start start} position {@link module:engine/view/position~Position#isBefore is before} start
  211. * position of all other ranges (not to confuse with the first range added to the selection).
  212. * Returns `null` if no ranges are added to selection.
  213. *
  214. * @returns {module:engine/view/range~Range|null}
  215. */
  216. getFirstRange() {
  217. let first = null;
  218. for ( const range of this._ranges ) {
  219. if ( !first || range.start.isBefore( first.start ) ) {
  220. first = range;
  221. }
  222. }
  223. return first ? Range.createFromRange( first ) : null;
  224. }
  225. /**
  226. * Returns copy of the last range in the selection. Last range is the one which {@link module:engine/view/range~Range#end end}
  227. * position {@link module:engine/view/position~Position#isAfter is after} end position of all other ranges (not to confuse
  228. * with the last range added to the selection). Returns `null` if no ranges are added to selection.
  229. *
  230. * @returns {module:engine/view/range~Range|null}
  231. */
  232. getLastRange() {
  233. let last = null;
  234. for ( const range of this._ranges ) {
  235. if ( !last || range.end.isAfter( last.end ) ) {
  236. last = range;
  237. }
  238. }
  239. return last ? Range.createFromRange( last ) : null;
  240. }
  241. /**
  242. * Returns copy of the first position in the selection. First position is the position that
  243. * {@link module:engine/view/position~Position#isBefore is before} any other position in the selection ranges.
  244. * Returns `null` if no ranges are added to selection.
  245. *
  246. * @returns {module:engine/view/position~Position|null}
  247. */
  248. getFirstPosition() {
  249. const firstRange = this.getFirstRange();
  250. return firstRange ? Position.createFromPosition( firstRange.start ) : null;
  251. }
  252. /**
  253. * Returns copy of the last position in the selection. Last position is the position that
  254. * {@link module:engine/view/position~Position#isAfter is after} any other position in the selection ranges.
  255. * Returns `null` if no ranges are added to selection.
  256. *
  257. * @returns {module:engine/view/position~Position|null}
  258. */
  259. getLastPosition() {
  260. const lastRange = this.getLastRange();
  261. return lastRange ? Position.createFromPosition( lastRange.end ) : null;
  262. }
  263. /**
  264. * Checks whether, this selection is equal to given selection. Selections are equal if they have same directions,
  265. * same number of ranges and all ranges from one selection equal to a range from other selection.
  266. *
  267. * @param {module:engine/view/selection~Selection} otherSelection Selection to compare with.
  268. * @returns {Boolean} `true` if selections are equal, `false` otherwise.
  269. */
  270. isEqual( otherSelection ) {
  271. if ( this.isFake != otherSelection.isFake ) {
  272. return false;
  273. }
  274. if ( this.isFake && this.fakeSelectionLabel != otherSelection.fakeSelectionLabel ) {
  275. return false;
  276. }
  277. if ( this.rangeCount != otherSelection.rangeCount ) {
  278. return false;
  279. } else if ( this.rangeCount === 0 ) {
  280. return true;
  281. }
  282. if ( !this.anchor.isEqual( otherSelection.anchor ) || !this.focus.isEqual( otherSelection.focus ) ) {
  283. return false;
  284. }
  285. for ( const thisRange of this._ranges ) {
  286. let found = false;
  287. for ( const otherRange of otherSelection._ranges ) {
  288. if ( thisRange.isEqual( otherRange ) ) {
  289. found = true;
  290. break;
  291. }
  292. }
  293. if ( !found ) {
  294. return false;
  295. }
  296. }
  297. return true;
  298. }
  299. /**
  300. * Removes all ranges that were added to the selection.
  301. *
  302. * @fires change
  303. */
  304. removeAllRanges() {
  305. if ( this._ranges.length ) {
  306. this._ranges = [];
  307. this.fire( 'change' );
  308. }
  309. }
  310. /**
  311. * Replaces all ranges that were added to the selection with given array of ranges. Last range of the array
  312. * is treated like the last added range and is used to set {@link #anchor anchor} and {@link #focus focus}.
  313. * Accepts a flag describing in which way the selection is made (see {@link #addRange addRange}).
  314. *
  315. * @fires change
  316. * @param {Iterable.<module:engine/view/range~Range>} newRanges Iterable object of ranges to set.
  317. * @param {Boolean} [isLastBackward] Flag describing if last added range was selected forward - from start to end
  318. * (`false`) or backward - from end to start (`true`). Defaults to `false`.
  319. */
  320. setRanges( newRanges, isLastBackward ) {
  321. this._ranges = [];
  322. for ( const range of newRanges ) {
  323. if ( !( range instanceof Range ) ) {
  324. throw new CKEditorError( 'view-selection-invalid-range: Invalid Range.' );
  325. }
  326. this._pushRange( range );
  327. }
  328. this._lastRangeBackward = !!isLastBackward;
  329. this.fire( 'change' );
  330. }
  331. /**
  332. * Sets this selection's ranges and direction to the ranges and direction of the given selection.
  333. *
  334. * @param {module:engine/view/selection~Selection} otherSelection
  335. */
  336. setTo( otherSelection ) {
  337. this._isFake = otherSelection._isFake;
  338. this._fakeSelectionLabel = otherSelection._fakeSelectionLabel;
  339. this.setRanges( otherSelection.getRanges(), otherSelection.isBackward );
  340. }
  341. /**
  342. * Sets collapsed selection in the specified location.
  343. *
  344. * The location can be specified in the same form as {@link module:engine/view/position~Position.createAt} parameters.
  345. *
  346. * @fires change
  347. * @param {module:engine/view/item~Item|module:engine/view/position~Position} itemOrPosition
  348. * @param {Number|'end'|'before'|'after'} [offset=0] Offset or one of the flags. Used only when
  349. * first parameter is a {@link module:engine/view/item~Item view item}.
  350. */
  351. collapse( itemOrPosition, offset ) {
  352. const pos = Position.createAt( itemOrPosition, offset );
  353. const range = new Range( pos, pos );
  354. this.setRanges( [ range ] );
  355. }
  356. /**
  357. * Collapses selection to the selection's {@link #getFirstPosition first position}.
  358. * All ranges, besides the collapsed one, will be removed. Nothing will change if there are no ranges stored
  359. * inside selection.
  360. *
  361. * @fires change
  362. */
  363. collapseToStart() {
  364. const startPosition = this.getFirstPosition();
  365. if ( startPosition !== null ) {
  366. this.setRanges( [ new Range( startPosition, startPosition ) ] );
  367. }
  368. }
  369. /**
  370. * Collapses selection to the selection's {@link #getLastPosition last position}.
  371. * All ranges, besides the collapsed one, will be removed. Nothing will change if there are no ranges stored
  372. * inside selection.
  373. *
  374. * @fires change
  375. */
  376. collapseToEnd() {
  377. const endPosition = this.getLastPosition();
  378. if ( endPosition !== null ) {
  379. this.setRanges( [ new Range( endPosition, endPosition ) ] );
  380. }
  381. }
  382. /**
  383. * Sets {@link #focus} to the specified location.
  384. *
  385. * The location can be specified in the same form as {@link module:engine/view/position~Position.createAt} parameters.
  386. *
  387. * @fires change
  388. * @param {module:engine/view/item~Item|module:engine/view/position~Position} itemOrPosition
  389. * @param {Number|'end'|'before'|'after'} [offset=0] Offset or one of the flags. Used only when
  390. * first parameter is a {@link module:engine/view/item~Item view item}.
  391. */
  392. setFocus( itemOrPosition, offset ) {
  393. if ( this.anchor === null ) {
  394. /**
  395. * Cannot set selection focus if there are no ranges in selection.
  396. *
  397. * @error view-selection-setFocus-no-ranges
  398. */
  399. throw new CKEditorError( 'view-selection-setFocus-no-ranges: Cannot set selection focus if there are no ranges in selection.' );
  400. }
  401. const newFocus = Position.createAt( itemOrPosition, offset );
  402. if ( newFocus.compareWith( this.focus ) == 'same' ) {
  403. return;
  404. }
  405. const anchor = this.anchor;
  406. this._ranges.pop();
  407. if ( newFocus.compareWith( anchor ) == 'before' ) {
  408. this.addRange( new Range( newFocus, anchor ), true );
  409. } else {
  410. this.addRange( new Range( anchor, newFocus ) );
  411. }
  412. }
  413. /**
  414. * Returns the selected element. {@link module:engine/view/element~Element Element} is considered as selected if there is only
  415. * one range in the selection, and that range contains exactly one element.
  416. * Returns `null` if there is no selected element.
  417. *
  418. * @returns {module:engine/view/element~Element|null}
  419. */
  420. getSelectedElement() {
  421. if ( this.rangeCount !== 1 ) {
  422. return null;
  423. }
  424. const range = this.getFirstRange();
  425. const nodeAfterStart = range.start.nodeAfter;
  426. const nodeBeforeEnd = range.end.nodeBefore;
  427. return ( nodeAfterStart instanceof Element && nodeAfterStart == nodeBeforeEnd ) ? nodeAfterStart : null;
  428. }
  429. /**
  430. * Creates and returns an instance of `Selection` that is a clone of given selection, meaning that it has same
  431. * ranges and same direction as this selection.
  432. *
  433. * @params {module:engine/view/selection~Selection} otherSelection Selection to be cloned.
  434. * @returns {module:engine/view/selection~Selection} `Selection` instance that is a clone of given selection.
  435. */
  436. static createFromSelection( otherSelection ) {
  437. const selection = new Selection();
  438. selection.setTo( otherSelection );
  439. return selection;
  440. }
  441. /**
  442. * Adds range to selection - creates copy of given range so it can be safely used and modified.
  443. *
  444. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-selection-range-intersects` if added range intersects
  445. * with ranges already stored in selection instance.
  446. *
  447. * @private
  448. * @param {module:engine/view/range~Range} range
  449. */
  450. _pushRange( range ) {
  451. for ( const storedRange of this._ranges ) {
  452. if ( range.isIntersecting( storedRange ) ) {
  453. /**
  454. * Trying to add a range that intersects with another range from selection.
  455. *
  456. * @error selection-range-intersects
  457. * @param {module:engine/view/range~Range} addedRange Range that was added to the selection.
  458. * @param {module:engine/view/range~Range} intersectingRange Range from selection that intersects with `addedRange`.
  459. */
  460. throw new CKEditorError(
  461. 'view-selection-range-intersects: Trying to add a range that intersects with another range from selection.',
  462. { addedRange: range, intersectingRange: storedRange }
  463. );
  464. }
  465. }
  466. this._ranges.push( Range.createFromRange( range ) );
  467. }
  468. }
  469. mix( Selection, EmitterMixin );
  470. /**
  471. * Fired whenever selection ranges are changed through {@link ~Selection Selection API}.
  472. *
  473. * @event change
  474. */