| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527 |
- /**
- * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
- * For licensing, see LICENSE.md.
- */
- 'use strict';
- import Position from './position.js';
- import Range from './range.js';
- import LiveRange from './liverange.js';
- import EmitterMixin from '../../utils/emittermixin.js';
- import CharacterProxy from './characterproxy.js';
- import CKEditorError from '../../utils/ckeditorerror.js';
- import utils from '../../utils/utils.js';
- const storePrefix = 'selection:';
- /**
- * Represents a selection that is made on nodes in {@link core.treeModel.Document}. `Selection` instance is
- * created by {@link core.treeModel.Document}. You should not need to create an instance of `Selection`.
- *
- * Keep in mind that selection always contains at least one range. If no ranges has been added to selection or all ranges
- * got removed from selection, the selection will be reset to contain {@link core.treeModel.Selection#_getDefaultRange the default range}.
- *
- * @memberOf core.treeModel
- */
- export default class Selection {
- /**
- * Creates an empty selection.
- *
- * @param {core.treeModel.Document} document Document which owns this selection.
- */
- constructor( document ) {
- /**
- * List of attributes set on current selection.
- *
- * @protected
- * @member {Map} core.treeModel.Selection#_attrs
- */
- this._attrs = new Map();
- /**
- * Document which owns this selection.
- *
- * @private
- * @member {core.treeModel.Document} core.treeModel.Selection#_document
- */
- this._document = document;
- /**
- * Specifies whether the last added range was added as a backward or forward range.
- *
- * @private
- * @member {Boolean} core.treeModel.Selection#_lastRangeBackward
- */
- this._lastRangeBackward = false;
- /**
- * Stores all ranges that are selected.
- *
- * @private
- * @member {Array.<core.treeModel.LiveRange>} core.treeModel.Selection#_ranges
- */
- this._ranges = [];
- }
- /**
- * Selection anchor. Anchor may be described as a position where the selection starts. Together with
- * {@link core.treeModel.Selection#focus} they define the direction of selection, which is important
- * when expanding/shrinking selection. Anchor is always the start or end of the most recent added range.
- * It may be a bit unintuitive when there are multiple ranges in selection.
- *
- * @see core.treeModel.Selection#focus
- * @type {core.treeModel.LivePosition}
- */
- get anchor() {
- let range = this._ranges.length ? this._ranges[ this._ranges.length - 1 ] : this._getDefaultRange();
- return this._lastRangeBackward ? range.end : range.start;
- }
- /**
- * Selection focus. Focus is a position where the selection ends.
- *
- * @see core.treeModel.Selection#anchor
- * @type {core.treeModel.LivePosition}
- */
- get focus() {
- let range = this._ranges.length ? this._ranges[ this._ranges.length - 1 ] : this._getDefaultRange();
- return this._lastRangeBackward ? range.start : range.end;
- }
- /**
- * Returns whether the selection is collapsed. Selection is collapsed when all it's ranges are collapsed.
- *
- * @type {Boolean}
- */
- get isCollapsed() {
- for ( let i = 0; i < this._ranges.length; i++ ) {
- if ( !this._ranges[ i ].isCollapsed ) {
- return false;
- }
- }
- return true;
- }
- /**
- * Adds a range to the selection. Added range is copied and converted to {@link core.treeModel.LiveRange}. This means
- * that passed range is not saved in the Selection instance and you can safely operate on it.
- *
- * Accepts a flag describing in which way the selection is made - passed range might be selected from
- * {@link core.treeModel.Range#start} to {@link core.treeModel.Range#end} or from {@link core.treeModel.Range#end}
- * to {@link core.treeModel.Range#start}. The flag is used to set {@link core.treeModel.Selection#anchor} and
- * {@link core.treeModel.Selection#focus} properties.
- *
- * @fires {@link core.treeModel.Selection#change:range change:range}
- * @param {core.treeModel.Range} range Range to add.
- * @param {Boolean} [isBackward] Flag describing if added range was selected forward - from start to end (`false`)
- * or backward - from end to start (`true`). Defaults to `false`.
- */
- addRange( range, isBackward ) {
- this._pushRange( range );
- this._lastRangeBackward = !!isBackward;
- this.fire( 'change:range' );
- }
- /**
- * Unbinds all events previously bound by this selection or objects created by this selection.
- */
- destroy() {
- for ( let i = 0; i < this._ranges.length; i++ ) {
- this._ranges[ i ].detach();
- }
- }
- /**
- * Returns an array of ranges added to the selection. The method returns a copy of internal array, so
- * it will not change when ranges get added or removed from selection.
- *
- * @returns {Array.<LiveRange>}
- */
- getRanges() {
- return this._ranges.length ? this._ranges.slice() : [ this._getDefaultRange() ];
- }
- /**
- * Returns the first range in the selection. First range is the one which {@link core.treeModel.Range#start start} position
- * {@link core.treeModel.Position#isBefore is before} start position of all other ranges (not to confuse with the first range
- * added to the selection).
- *
- * @returns {core.treeModel.Range}
- */
- getFirstRange() {
- let first = null;
- for ( let i = 0; i < this._ranges.length; i++ ) {
- let range = this._ranges[ i ];
- if ( !first || range.start.isBefore( first.start ) ) {
- first = range;
- }
- }
- return first ? Range.createFromRange( first ) : this._getDefaultRange();
- }
- /**
- * Returns the first position in the selection. First position is the position that {@link core.treeModel.Position#isBefore is before}
- * any other position in the selection ranges.
- *
- * @returns {core.treeModel.Position}
- */
- getFirstPosition() {
- return Position.createFromPosition( this.getFirstRange().start );
- }
- /**
- * Removes all ranges that were added to the selection. Fires update event.
- *
- * @fires {@link core.treeModel.Selection#change:range change:range}
- */
- removeAllRanges() {
- this.destroy();
- this._ranges = [];
- this.fire( 'change:range' );
- }
- /**
- * Replaces all ranges that were added to the selection with given array of ranges. Last range of the array
- * is treated like the last added range and is used to set {@link #anchor} and {@link #focus}. Accepts a flag
- * describing in which way the selection is made (see {@link #addRange}).
- *
- * @fires {@link core.treeModel.Selection#change:range change:range}
- * @param {Array.<core.treeModel.Range>} newRanges Array of ranges to set.
- * @param {Boolean} [isLastBackward] Flag describing if last added range was selected forward - from start to end (`false`)
- * or backward - from end to start (`true`). Defaults to `false`.
- */
- setRanges( newRanges, isLastBackward ) {
- this.destroy();
- this._ranges = [];
- for ( let i = 0; i < newRanges.length; i++ ) {
- this._pushRange( newRanges[ i ] );
- }
- this._lastRangeBackward = !!isLastBackward;
- this.fire( 'change:range' );
- }
- /**
- * Removes all attributes from the selection.
- *
- * @fires {@link core.treeModel.Selection#change:range change:range}
- */
- clearAttributes() {
- this._attrs.clear();
- this._setStoredAttributesTo( new Map() );
- this.fire( 'change:attribute' );
- }
- /**
- * Gets an attribute value for given key or undefined it that attribute is not set on selection.
- *
- * @param {String} key Key of attribute to look for.
- * @returns {*} Attribute value or null.
- */
- getAttribute( key ) {
- return this._attrs.get( key );
- }
- /**
- * Returns iterator that iterates over this selection attributes.
- *
- * @returns {Iterable.<*>}
- */
- getAttributes() {
- return this._attrs[ Symbol.iterator ]();
- }
- /**
- * Checks if the selection has an attribute for given key.
- *
- * @param {String} key Key of attribute to check.
- * @returns {Boolean} `true` if attribute with given key is set on selection, `false` otherwise.
- */
- hasAttribute( key ) {
- return this._attrs.has( key );
- }
- /**
- * Removes an attribute with given key from the selection.
- *
- * @fires {@link core.treeModel.Selection#change:range change:range}
- * @param {String} key Key of attribute to remove.
- */
- removeAttribute( key ) {
- this._attrs.delete( key );
- this._removeStoredAttribute( key );
- this.fire( 'change:attribute' );
- }
- /**
- * Sets attribute on the selection. If attribute with the same key already is set, it overwrites its values.
- *
- * @fires {@link core.treeModel.Selection#change:range change:range}
- * @param {String} key Key of attribute to set.
- * @param {*} value Attribute value.
- */
- setAttribute( key, value ) {
- this._attrs.set( key, value );
- this._storeAttribute( key, value );
- this.fire( 'change:attribute' );
- }
- /**
- * Removes all attributes from the selection and sets given attributes.
- *
- * @fires {@link core.treeModel.Selection#change:range change:range}
- * @param {Iterable|Object} attrs Iterable object containing attributes to be set.
- */
- setAttributesTo( attrs ) {
- this._attrs = utils.toMap( attrs );
- this._setStoredAttributesTo( this._attrs );
- this.fire( 'change:attribute' );
- }
- /**
- * Converts given range to {@link core.treeModel.LiveRange} and adds it to internal ranges array. Throws an error
- * if given range is intersecting with any range that is already stored in this selection.
- *
- * @private
- * @param {core.treeModel.Range} range Range to add.
- */
- _pushRange( range ) {
- for ( let i = 0; i < this._ranges.length ; i++ ) {
- if ( range.isIntersecting( this._ranges[ i ] ) ) {
- /**
- * Trying to add a range that intersects with another range from selection.
- *
- * @error selection-range-intersects
- * @param {core.treeModel.Range} addedRange Range that was added to the selection.
- * @param {core.treeModel.Range} intersectingRange Range from selection that intersects with `addedRange`.
- */
- throw new CKEditorError(
- 'selection-range-intersects: Trying to add a range that intersects with another range from selection.',
- { addedRange: range, intersectingRange: this._ranges[ i ] }
- );
- }
- }
- this._ranges.push( LiveRange.createFromRange( range ) );
- }
- /**
- * Iterates through all attributes stored in current selection's parent.
- *
- * @returns {Iterable.<*>}
- */
- *_getStoredAttributes() {
- const selectionParent = this.getFirstPosition().parent;
- if ( this.isCollapsed && selectionParent.getChildCount() === 0 ) {
- for ( let attr of selectionParent.getAttributes() ) {
- if ( attr[ 0 ].indexOf( storePrefix ) === 0 ) {
- const realKey = attr[ 0 ].substr( storePrefix.length );
- yield [ realKey, attr[ 1 ] ];
- }
- }
- }
- }
- /**
- * Removes attribute with given key from attributes stored in current selection's parent node.
- *
- * @private
- * @param {String} key Key of attribute to remove.
- */
- _removeStoredAttribute( key ) {
- const selectionParent = this.getFirstPosition().parent;
- if ( this.isCollapsed && selectionParent.getChildCount() === 0 ) {
- const storeKey = Selection._getStoreAttributeKey( key );
- this._document.enqueueChanges( () => {
- this._document.batch().removeAttr( storeKey, selectionParent );
- } );
- }
- }
- /**
- * Stores given attribute key and value in current selection's parent node if the selection is collapsed and
- * the parent node is empty.
- *
- * @private
- * @param {String} key Key of attribute to set.
- * @param {*} value Attribute value.
- */
- _storeAttribute( key, value ) {
- const selectionParent = this.getFirstPosition().parent;
- if ( this.isCollapsed && selectionParent.getChildCount() === 0 ) {
- const storeKey = Selection._getStoreAttributeKey( key );
- this._document.enqueueChanges( () => {
- this._document.batch().setAttr( storeKey, value, selectionParent );
- } );
- }
- }
- /**
- * Sets selection attributes stored in current selection's parent node to given set of attributes.
- *
- * @param {Iterable|Object} attrs Iterable object containing attributes to be set.
- * @private
- */
- _setStoredAttributesTo( attrs ) {
- const selectionParent = this.getFirstPosition().parent;
- if ( this.isCollapsed && selectionParent.getChildCount() === 0 ) {
- this._document.enqueueChanges( () => {
- const batch = this._document.batch();
- for ( let attr of this._getStoredAttributes() ) {
- const storeKey = Selection._getStoreAttributeKey( attr[ 0 ] );
- batch.removeAttr( storeKey, selectionParent );
- }
- for ( let attr of attrs ) {
- const storeKey = Selection._getStoreAttributeKey( attr[ 0 ] );
- batch.setAttr( storeKey, attr[ 1 ], selectionParent );
- }
- } );
- }
- }
- /**
- * Updates this selection attributes based on it's position in the Tree Model.
- *
- * @protected
- */
- _updateAttributes() {
- const position = this.getFirstPosition();
- const positionParent = position.parent;
- let attrs = null;
- if ( this.isCollapsed === false ) {
- // 1. If selection is a range...
- const range = this.getFirstRange();
- // ...look for a first character node in that range and take attributes from it.
- for ( let item of range ) {
- if ( item.type == 'TEXT' ) {
- attrs = item.item.getAttributes();
- break;
- }
- }
- }
- // 2. If the selection is a caret or the range does not contain a character node...
- if ( !attrs && this.isCollapsed === true ) {
- const nodeBefore = positionParent.getChild( position.offset - 1 );
- const nodeAfter = positionParent.getChild( position.offset );
- // ...look at the node before caret and take attributes from it if it is a character node.
- attrs = getAttrsIfCharacter( nodeBefore );
- // 3. If not, look at the node after caret...
- if ( !attrs ) {
- attrs = getAttrsIfCharacter( nodeAfter );
- }
- // 4. If not, try to find the first character on the left, that is in the same node.
- if ( !attrs ) {
- let node = nodeBefore;
- while ( node && !attrs ) {
- node = node.previousSibling;
- attrs = getAttrsIfCharacter( node );
- }
- }
- // 5. If not found, try to find the first character on the right, that is in the same node.
- if ( !attrs ) {
- let node = nodeAfter;
- while ( node && !attrs ) {
- node = node.nextSibling;
- attrs = getAttrsIfCharacter( node );
- }
- }
- // 6. If not found, selection should retrieve attributes from parent.
- if ( !attrs ) {
- attrs = this._getStoredAttributes();
- }
- }
- if ( attrs ) {
- this._attrs = new Map( attrs );
- } else {
- this.clearAttributes();
- }
- function getAttrsIfCharacter( node ) {
- if ( node instanceof CharacterProxy ) {
- return node.getAttributes();
- }
- return null;
- }
- this.fire( 'change:attribute' );
- }
- /**
- * Returns a default range for this selection. The default range is a collapsed range that starts and ends
- * at the beginning of this selection's document {@link core.treeModel.Document#_getDefaultRoot default root}.
- * This "artificial" range is important for algorithms that base on selection, so they won't break or need
- * special logic if there are no real ranges in the selection.
- *
- * @private
- * @returns {core.treeModel.Range}
- */
- _getDefaultRange() {
- const defaultRoot = this._document._getDefaultRoot();
- return new Range( new Position( defaultRoot, [ 0 ] ), new Position( defaultRoot, [ 0 ] ) );
- }
- /**
- * Generates and returns an attribute key for selection attributes store, basing on original attribute key.
- *
- * @param {String} key Attribute key to convert.
- * @returns {String} Converted attribute key, applicable for selection store.
- */
- static _getStoreAttributeKey( key ) {
- return storePrefix + key;
- }
- }
- utils.mix( Selection, EmitterMixin );
- /**
- * Fired whenever selection ranges are changed through {@link core.treeModel.Selection Selection API}. Not fired when
- * {@link core.treeModel.LiveRange live ranges} inserted in selection change because of Tree Model changes.
- *
- * @event core.treeModel.Selection#change:range
- */
- /**
- * Fired whenever selection attributes are changed.
- *
- * @event core.treeModel.Selection#change:attribute
- */
|