selection.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. 'use strict';
  6. import Position from './position.js';
  7. import Range from './range.js';
  8. import LiveRange from './liverange.js';
  9. import EmitterMixin from '../../utils/emittermixin.js';
  10. import CharacterProxy from './characterproxy.js';
  11. import CKEditorError from '../../utils/ckeditorerror.js';
  12. import toMap from '../../utils/tomap.js';
  13. import mix from '../../utils/mix.js';
  14. const storePrefix = 'selection:';
  15. /**
  16. * Represents a selection that is made on nodes in {@link engine.treeModel.Document}. `Selection` instance is
  17. * created by {@link engine.treeModel.Document}. You should not need to create an instance of `Selection`.
  18. *
  19. * Keep in mind that selection always contains at least one range. If no ranges has been added to selection or all ranges
  20. * got removed from selection, the selection will be reset to contain {@link engine.treeModel.Selection#_getDefaultRange the default range}.
  21. *
  22. * @memberOf engine.treeModel
  23. */
  24. export default class Selection {
  25. /**
  26. * Creates an empty selection.
  27. *
  28. * @param {engine.treeModel.Document} document Document which owns this selection.
  29. */
  30. constructor( document ) {
  31. /**
  32. * List of attributes set on current selection.
  33. *
  34. * @protected
  35. * @member {Map} engine.treeModel.Selection#_attrs
  36. */
  37. this._attrs = new Map();
  38. /**
  39. * Document which owns this selection.
  40. *
  41. * @private
  42. * @member {engine.treeModel.Document} engine.treeModel.Selection#_document
  43. */
  44. this._document = document;
  45. /**
  46. * Specifies whether the last added range was added as a backward or forward range.
  47. *
  48. * @private
  49. * @member {Boolean} engine.treeModel.Selection#_lastRangeBackward
  50. */
  51. this._lastRangeBackward = false;
  52. /**
  53. * Stores all ranges that are selected.
  54. *
  55. * @private
  56. * @member {Array.<engine.treeModel.LiveRange>} engine.treeModel.Selection#_ranges
  57. */
  58. this._ranges = [];
  59. }
  60. /**
  61. * Selection anchor. Anchor may be described as a position where the selection starts. Together with
  62. * {@link engine.treeModel.Selection#focus} they define the direction of selection, which is important
  63. * when expanding/shrinking selection. Anchor is always the start or end of the most recent added range.
  64. * It may be a bit unintuitive when there are multiple ranges in selection.
  65. *
  66. * @see engine.treeModel.Selection#focus
  67. * @type {engine.treeModel.LivePosition}
  68. */
  69. get anchor() {
  70. let range = this._ranges.length ? this._ranges[ this._ranges.length - 1 ] : this._getDefaultRange();
  71. return this._lastRangeBackward ? range.end : range.start;
  72. }
  73. /**
  74. * Selection focus. Focus is a position where the selection ends.
  75. *
  76. * @see engine.treeModel.Selection#anchor
  77. * @type {engine.treeModel.LivePosition}
  78. */
  79. get focus() {
  80. let range = this._ranges.length ? this._ranges[ this._ranges.length - 1 ] : this._getDefaultRange();
  81. return this._lastRangeBackward ? range.start : range.end;
  82. }
  83. /**
  84. * Returns whether the selection is collapsed. Selection is collapsed when there is exactly one range which is
  85. * collapsed.
  86. *
  87. * @type {Boolean}
  88. */
  89. get isCollapsed() {
  90. const length = this._ranges.length;
  91. if ( length === 0 ) {
  92. // Default range is collapsed.
  93. return true;
  94. } else if ( length === 1 ) {
  95. return this._ranges[ 0 ].isCollapsed;
  96. } else {
  97. return false;
  98. }
  99. }
  100. /**
  101. * Returns number of ranges in selection.
  102. *
  103. * @type {Number}
  104. */
  105. get rangeCount() {
  106. return this._ranges.length ? this._ranges.length : 1;
  107. }
  108. /**
  109. * Specifies whether the {@link engine.treeModel.Selection#focus} precedes {@link engine.treeModel.Selection#anchor}.
  110. *
  111. * @type {Boolean}
  112. */
  113. get isBackward() {
  114. return !this.isCollapsed && this._lastRangeBackward;
  115. }
  116. /**
  117. * Adds a range to the selection. Added range is copied and converted to {@link engine.treeModel.LiveRange}. This means
  118. * that passed range is not saved in the Selection instance and you can safely operate on it.
  119. *
  120. * Accepts a flag describing in which way the selection is made - passed range might be selected from
  121. * {@link engine.treeModel.Range#start} to {@link engine.treeModel.Range#end} or from {@link engine.treeModel.Range#end}
  122. * to {@link engine.treeModel.Range#start}. The flag is used to set {@link engine.treeModel.Selection#anchor} and
  123. * {@link engine.treeModel.Selection#focus} properties.
  124. *
  125. * @fires engine.treeModel.Selection#change:range
  126. * @param {engine.treeModel.Range} range Range to add.
  127. * @param {Boolean} [isBackward] Flag describing if added range was selected forward - from start to end (`false`)
  128. * or backward - from end to start (`true`). Defaults to `false`.
  129. */
  130. addRange( range, isBackward ) {
  131. this._pushRange( range );
  132. this._lastRangeBackward = !!isBackward;
  133. this.fire( 'change:range' );
  134. }
  135. /**
  136. * Unbinds all events previously bound by this selection or objects created by this selection.
  137. */
  138. destroy() {
  139. for ( let i = 0; i < this._ranges.length; i++ ) {
  140. this._ranges[ i ].detach();
  141. }
  142. }
  143. /**
  144. * Returns an iterator that contains copies of all ranges added to the selection.
  145. *
  146. * @returns {Iterator.<engine.treeModel.Range>}
  147. */
  148. *getRanges() {
  149. if ( this._ranges.length ) {
  150. for ( let range of this._ranges ) {
  151. yield Range.createFromRange( range );
  152. }
  153. } else {
  154. yield this._getDefaultRange();
  155. }
  156. }
  157. /**
  158. * Returns the first range in the selection. First range is the one which {@link engine.treeModel.Range#start start} position
  159. * {@link engine.treeModel.Position#isBefore is before} start position of all other ranges (not to confuse with the first range
  160. * added to the selection).
  161. *
  162. * @returns {engine.treeModel.Range}
  163. */
  164. getFirstRange() {
  165. let first = null;
  166. for ( let i = 0; i < this._ranges.length; i++ ) {
  167. let range = this._ranges[ i ];
  168. if ( !first || range.start.isBefore( first.start ) ) {
  169. first = range;
  170. }
  171. }
  172. return first ? Range.createFromRange( first ) : this._getDefaultRange();
  173. }
  174. /**
  175. * Returns the first position in the selection. First position is the position that {@link engine.treeModel.Position#isBefore is before}
  176. * any other position in the selection ranges.
  177. *
  178. * @returns {engine.treeModel.Position}
  179. */
  180. getFirstPosition() {
  181. return Position.createFromPosition( this.getFirstRange().start );
  182. }
  183. /**
  184. * Removes all ranges that were added to the selection. Fires update event.
  185. *
  186. * @fires engine.treeModel.Selection#change:range
  187. */
  188. removeAllRanges() {
  189. this.destroy();
  190. this._ranges = [];
  191. this.fire( 'change:range' );
  192. }
  193. /**
  194. * Replaces all ranges that were added to the selection with given array of ranges. Last range of the array
  195. * is treated like the last added range and is used to set {@link #anchor} and {@link #focus}. Accepts a flag
  196. * describing in which way the selection is made (see {@link #addRange}).
  197. *
  198. * @fires engine.treeModel.Selection#change:range
  199. * @param {Array.<engine.treeModel.Range>} newRanges Array of ranges to set.
  200. * @param {Boolean} [isLastBackward] Flag describing if last added range was selected forward - from start to end (`false`)
  201. * or backward - from end to start (`true`). Defaults to `false`.
  202. */
  203. setRanges( newRanges, isLastBackward ) {
  204. this.destroy();
  205. this._ranges = [];
  206. for ( let i = 0; i < newRanges.length; i++ ) {
  207. this._pushRange( newRanges[ i ] );
  208. }
  209. this._lastRangeBackward = !!isLastBackward;
  210. this.fire( 'change:range' );
  211. }
  212. /**
  213. * Sets collapsed selection in the specified location.
  214. *
  215. * The location can be specified in the same form as {@link engine.treeModel.Position.createAt} parameters.
  216. *
  217. * @fires engine.treeModel.Selection#change:range
  218. * @param {engine.treeModel.Node|engine.treeModel.Position} nodeOrPosition
  219. * @param {Number|'END'|'BEFORE'|'AFTER'} [offset=0] Offset or one of the flags. Used only when
  220. * first parameter is a node.
  221. */
  222. collapse( nodeOrPosition, offset ) {
  223. const pos = Position.createAt( nodeOrPosition, offset );
  224. const range = new Range( pos, pos );
  225. this.setRanges( [ range ] );
  226. }
  227. /**
  228. * Sets {@link engine.treeModel.Selection#focus} in the specified location.
  229. *
  230. * The location can be specified in the same form as {@link engine.treeModel.Position.createAt} parameters.
  231. *
  232. * @fires engine.treeModel.Selection#change:range
  233. * @param {engine.treeModel.Node|engine.treeModel.Position} nodeOrPosition
  234. * @param {Number|'END'|'BEFORE'|'AFTER'} [offset=0] Offset or one of the flags. Used only when
  235. * first parameter is a node.
  236. */
  237. setFocus( nodeOrPosition, offset ) {
  238. const newFocus = Position.createAt( nodeOrPosition, offset );
  239. if ( newFocus.compareWith( this.focus ) == 'SAME' ) {
  240. return;
  241. }
  242. const anchor = this.anchor;
  243. if ( this._ranges.length ) {
  244. // TODO Replace with _popRange, so child classes can override this (needed for #329).
  245. this._ranges.pop().detach();
  246. }
  247. if ( newFocus.compareWith( anchor ) == 'BEFORE' ) {
  248. this.addRange( new Range( newFocus, anchor ), true );
  249. } else {
  250. this.addRange( new Range( anchor, newFocus ) );
  251. }
  252. }
  253. /**
  254. * Removes all attributes from the selection.
  255. *
  256. * @fires engine.treeModel.Selection#change:attribute
  257. */
  258. clearAttributes() {
  259. this._attrs.clear();
  260. this._setStoredAttributesTo( new Map() );
  261. this.fire( 'change:attribute' );
  262. }
  263. /**
  264. * Gets an attribute value for given key or undefined it that attribute is not set on selection.
  265. *
  266. * @param {String} key Key of attribute to look for.
  267. * @returns {*} Attribute value or null.
  268. */
  269. getAttribute( key ) {
  270. return this._attrs.get( key );
  271. }
  272. /**
  273. * Returns iterator that iterates over this selection attributes.
  274. *
  275. * @returns {Iterable.<*>}
  276. */
  277. getAttributes() {
  278. return this._attrs[ Symbol.iterator ]();
  279. }
  280. /**
  281. * Checks if the selection has an attribute for given key.
  282. *
  283. * @param {String} key Key of attribute to check.
  284. * @returns {Boolean} `true` if attribute with given key is set on selection, `false` otherwise.
  285. */
  286. hasAttribute( key ) {
  287. return this._attrs.has( key );
  288. }
  289. /**
  290. * Removes an attribute with given key from the selection.
  291. *
  292. * @fires engine.treeModel.Selection#change:attribute
  293. * @param {String} key Key of attribute to remove.
  294. */
  295. removeAttribute( key ) {
  296. this._attrs.delete( key );
  297. this._removeStoredAttribute( key );
  298. this.fire( 'change:attribute' );
  299. }
  300. /**
  301. * Sets attribute on the selection. If attribute with the same key already is set, it overwrites its values.
  302. *
  303. * @fires engine.treeModel.Selection#change:attribute
  304. * @param {String} key Key of attribute to set.
  305. * @param {*} value Attribute value.
  306. */
  307. setAttribute( key, value ) {
  308. this._attrs.set( key, value );
  309. this._storeAttribute( key, value );
  310. this.fire( 'change:attribute' );
  311. }
  312. /**
  313. * Removes all attributes from the selection and sets given attributes.
  314. *
  315. * @fires engine.treeModel.Selection#change:attribute
  316. * @param {Iterable|Object} attrs Iterable object containing attributes to be set.
  317. */
  318. setAttributesTo( attrs ) {
  319. this._attrs = toMap( attrs );
  320. this._setStoredAttributesTo( this._attrs );
  321. this.fire( 'change:attribute' );
  322. }
  323. /**
  324. * Converts given range to {@link engine.treeModel.LiveRange} and adds it to internal ranges array. Throws an error
  325. * if given range is intersecting with any range that is already stored in this selection.
  326. *
  327. * @private
  328. * @param {engine.treeModel.Range} range Range to add.
  329. */
  330. _pushRange( range ) {
  331. for ( let i = 0; i < this._ranges.length ; i++ ) {
  332. if ( range.isIntersecting( this._ranges[ i ] ) ) {
  333. /**
  334. * Trying to add a range that intersects with another range from selection.
  335. *
  336. * @error selection-range-intersects
  337. * @param {engine.treeModel.Range} addedRange Range that was added to the selection.
  338. * @param {engine.treeModel.Range} intersectingRange Range from selection that intersects with `addedRange`.
  339. */
  340. throw new CKEditorError(
  341. 'selection-range-intersects: Trying to add a range that intersects with another range from selection.',
  342. { addedRange: range, intersectingRange: this._ranges[ i ] }
  343. );
  344. }
  345. }
  346. this._ranges.push( LiveRange.createFromRange( range ) );
  347. }
  348. /**
  349. * Iterates through all attributes stored in current selection's parent.
  350. *
  351. * @returns {Iterable.<*>}
  352. */
  353. *_getStoredAttributes() {
  354. const selectionParent = this.getFirstPosition().parent;
  355. if ( this.isCollapsed && selectionParent.getChildCount() === 0 ) {
  356. for ( let attr of selectionParent.getAttributes() ) {
  357. if ( attr[ 0 ].indexOf( storePrefix ) === 0 ) {
  358. const realKey = attr[ 0 ].substr( storePrefix.length );
  359. yield [ realKey, attr[ 1 ] ];
  360. }
  361. }
  362. }
  363. }
  364. /**
  365. * Removes attribute with given key from attributes stored in current selection's parent node.
  366. *
  367. * @private
  368. * @param {String} key Key of attribute to remove.
  369. */
  370. _removeStoredAttribute( key ) {
  371. const selectionParent = this.getFirstPosition().parent;
  372. if ( this.isCollapsed && selectionParent.getChildCount() === 0 ) {
  373. const storeKey = Selection._getStoreAttributeKey( key );
  374. this._document.enqueueChanges( () => {
  375. this._document.batch().removeAttr( storeKey, selectionParent );
  376. } );
  377. }
  378. }
  379. /**
  380. * Stores given attribute key and value in current selection's parent node if the selection is collapsed and
  381. * the parent node is empty.
  382. *
  383. * @private
  384. * @param {String} key Key of attribute to set.
  385. * @param {*} value Attribute value.
  386. */
  387. _storeAttribute( key, value ) {
  388. const selectionParent = this.getFirstPosition().parent;
  389. if ( this.isCollapsed && selectionParent.getChildCount() === 0 ) {
  390. const storeKey = Selection._getStoreAttributeKey( key );
  391. this._document.enqueueChanges( () => {
  392. this._document.batch().setAttr( storeKey, value, selectionParent );
  393. } );
  394. }
  395. }
  396. /**
  397. * Sets selection attributes stored in current selection's parent node to given set of attributes.
  398. *
  399. * @param {Iterable|Object} attrs Iterable object containing attributes to be set.
  400. * @private
  401. */
  402. _setStoredAttributesTo( attrs ) {
  403. const selectionParent = this.getFirstPosition().parent;
  404. if ( this.isCollapsed && selectionParent.getChildCount() === 0 ) {
  405. this._document.enqueueChanges( () => {
  406. const batch = this._document.batch();
  407. for ( let attr of this._getStoredAttributes() ) {
  408. const storeKey = Selection._getStoreAttributeKey( attr[ 0 ] );
  409. batch.removeAttr( storeKey, selectionParent );
  410. }
  411. for ( let attr of attrs ) {
  412. const storeKey = Selection._getStoreAttributeKey( attr[ 0 ] );
  413. batch.setAttr( storeKey, attr[ 1 ], selectionParent );
  414. }
  415. } );
  416. }
  417. }
  418. /**
  419. * Updates this selection attributes based on it's position in the model.
  420. *
  421. * @protected
  422. */
  423. _updateAttributes() {
  424. const position = this.getFirstPosition();
  425. const positionParent = position.parent;
  426. let attrs = null;
  427. if ( !this.isCollapsed ) {
  428. // 1. If selection is a range...
  429. const range = this.getFirstRange();
  430. // ...look for a first character node in that range and take attributes from it.
  431. for ( let item of range ) {
  432. if ( item.type == 'TEXT' ) {
  433. attrs = item.item.getAttributes();
  434. break;
  435. }
  436. }
  437. } else {
  438. // 2. If the selection is a caret or the range does not contain a character node...
  439. const nodeBefore = positionParent.getChild( position.offset - 1 );
  440. const nodeAfter = positionParent.getChild( position.offset );
  441. // ...look at the node before caret and take attributes from it if it is a character node.
  442. attrs = getAttrsIfCharacter( nodeBefore );
  443. // 3. If not, look at the node after caret...
  444. if ( !attrs ) {
  445. attrs = getAttrsIfCharacter( nodeAfter );
  446. }
  447. // 4. If not, try to find the first character on the left, that is in the same node.
  448. if ( !attrs ) {
  449. let node = nodeBefore;
  450. while ( node && !attrs ) {
  451. node = node.previousSibling;
  452. attrs = getAttrsIfCharacter( node );
  453. }
  454. }
  455. // 5. If not found, try to find the first character on the right, that is in the same node.
  456. if ( !attrs ) {
  457. let node = nodeAfter;
  458. while ( node && !attrs ) {
  459. node = node.nextSibling;
  460. attrs = getAttrsIfCharacter( node );
  461. }
  462. }
  463. // 6. If not found, selection should retrieve attributes from parent.
  464. if ( !attrs ) {
  465. attrs = this._getStoredAttributes();
  466. }
  467. }
  468. if ( attrs ) {
  469. this._attrs = new Map( attrs );
  470. } else {
  471. this.clearAttributes();
  472. }
  473. function getAttrsIfCharacter( node ) {
  474. if ( node instanceof CharacterProxy ) {
  475. return node.getAttributes();
  476. }
  477. return null;
  478. }
  479. this.fire( 'change:attribute' );
  480. }
  481. /**
  482. * Returns a default range for this selection. The default range is a collapsed range that starts and ends
  483. * at the beginning of this selection's document {@link engine.treeModel.Document#_getDefaultRoot default root}.
  484. * This "artificial" range is important for algorithms that base on selection, so they won't break or need
  485. * special logic if there are no real ranges in the selection.
  486. *
  487. * @private
  488. * @returns {engine.treeModel.Range}
  489. */
  490. _getDefaultRange() {
  491. const defaultRoot = this._document._getDefaultRoot();
  492. const pos = new Position( defaultRoot, [ 0 ] );
  493. return new Range( pos, pos );
  494. }
  495. /**
  496. * Generates and returns an attribute key for selection attributes store, basing on original attribute key.
  497. *
  498. * @param {String} key Attribute key to convert.
  499. * @returns {String} Converted attribute key, applicable for selection store.
  500. */
  501. static _getStoreAttributeKey( key ) {
  502. return storePrefix + key;
  503. }
  504. }
  505. mix( Selection, EmitterMixin );
  506. /**
  507. * Fired whenever selection ranges are changed through {@link engine.treeModel.Selection Selection API}. Not fired when
  508. * {@link engine.treeModel.LiveRange live ranges} inserted in selection change because of Tree Model changes.
  509. *
  510. * @event engine.treeModel.Selection#change:range
  511. */
  512. /**
  513. * Fired whenever selection attributes are changed.
  514. *
  515. * @event engine.treeModel.Selection#change:attribute
  516. */