8
0

selection.js 16 KB

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