selection.js 17 KB

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