| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502 |
- /**
- * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
- * For licensing, see LICENSE.md.
- */
- /**
- * @module utils/collection
- */
- import EmitterMixin from './emittermixin';
- import CKEditorError from './ckeditorerror';
- import uid from './uid';
- import mix from './mix';
- /**
- * Collections are ordered sets of objects. Items in the collection can be retrieved by their indexes
- * in the collection (like in an array) or by their ids.
- *
- * If an object without an `id` property is being added to the collection, the `id` property will be generated
- * automatically. Note that the automatically generated id is unique only within this single collection instance.
- *
- * By default an item in the collection is identified by its `id` property. The name of the identifier can be
- * configured through the constructor of the collection.
- *
- * @mixes EventEmitter
- */
- export default class Collection {
- /**
- * Creates a new Collection instance.
- *
- * @param {Object} options The options object.
- * @param {String} [options.idProperty='id'] The name of the property which is considered to identify an item.
- */
- constructor( options ) {
- /**
- * The internal list of items in the collection.
- *
- * @private
- * @member {Object[]}
- */
- this._items = [];
- /**
- * The internal map of items in the collection.
- *
- * @private
- * @member {Map}
- */
- this._itemMap = new Map();
- /**
- * The name of the property which is considered to identify an item.
- *
- * @private
- * @member {String}
- */
- this._idProperty = options && options.idProperty || 'id';
- /**
- * A helper mapping external items of a bound collection ({@link #bindTo})
- * and actual items of this collection.
- *
- * @protected
- * @member {Map}
- */
- this._bindToExternalToInternalMap = new Map();
- /**
- * A helper mapping items of this collection to external items of a bound collection
- * ({@link #bindTo}).
- *
- * @protected
- * @member {Map}
- */
- this._bindToInternalToExternalMap = new Map();
- /**
- * A collection instance this collection is bound to as a result
- * of calling {@link #bindTo} method.
- *
- * @protected
- * @member {module:utils/collection~Collection} #_bindToCollection
- */
- }
- /**
- * The number of items available in the collection.
- *
- * @member {Number} #length
- */
- get length() {
- return this._items.length;
- }
- /**
- * Adds an item into the collection.
- *
- * If the item does not have an id, then it will be automatically generated and set on the item.
- *
- * @chainable
- * @param {Object} item
- * @param {Number} [index] The position of the item in the collection. The item
- * is pushed to the collection when `index` not specified.
- * @fires add
- */
- add( item, index ) {
- let itemId;
- const idProperty = this._idProperty;
- if ( ( idProperty in item ) ) {
- itemId = item[ idProperty ];
- if ( typeof itemId != 'string' ) {
- /**
- * This item's id should be a string.
- *
- * @error collection-add-invalid-id
- */
- throw new CKEditorError( 'collection-add-invalid-id' );
- }
- if ( this.get( itemId ) ) {
- /**
- * This item already exists in the collection.
- *
- * @error collection-add-item-already-exists
- */
- throw new CKEditorError( 'collection-add-item-already-exists' );
- }
- } else {
- item[ idProperty ] = itemId = uid();
- }
- // TODO: Use ES6 default function argument.
- if ( index === undefined ) {
- index = this._items.length;
- } else if ( index > this._items.length || index < 0 ) {
- /**
- * The index number has invalid value.
- *
- * @error collection-add-item-bad-index
- */
- throw new CKEditorError( 'collection-add-item-invalid-index' );
- }
- this._items.splice( index, 0, item );
- this._itemMap.set( itemId, item );
- this.fire( 'add', item, index );
- return this;
- }
- /**
- * Gets item by its id or index.
- *
- * @param {String|Number} idOrIndex The item id or index in the collection.
- * @returns {Object} The requested item or `null` if such item does not exist.
- */
- get( idOrIndex ) {
- let item;
- if ( typeof idOrIndex == 'string' ) {
- item = this._itemMap.get( idOrIndex );
- } else if ( typeof idOrIndex == 'number' ) {
- item = this._items[ idOrIndex ];
- } else {
- /**
- * Index or id must be given.
- *
- * @error collection-get-invalid-arg
- */
- throw new CKEditorError( 'collection-get-invalid-arg: Index or id must be given.' );
- }
- return item || null;
- }
- /**
- * Gets index of item in the collection.
- * When item is not defined in the collection then index will be equal -1.
- *
- * @param {String|Object} idOrItem The item or its id in the collection.
- * @returns {Number} Index of given item.
- */
- getIndex( idOrItem ) {
- let item;
- if ( typeof idOrItem == 'string' ) {
- item = this._itemMap.get( idOrItem );
- } else {
- item = idOrItem;
- }
- return this._items.indexOf( item );
- }
- /**
- * Removes an item from the collection.
- *
- * @param {Object|Number|String} subject The item to remove, its id or index in the collection.
- * @returns {Object} The removed item.
- * @fires remove
- */
- remove( subject ) {
- let index, id, item;
- let itemDoesNotExist = false;
- const idProperty = this._idProperty;
- if ( typeof subject == 'string' ) {
- id = subject;
- item = this._itemMap.get( id );
- itemDoesNotExist = !item;
- if ( item ) {
- index = this._items.indexOf( item );
- }
- } else if ( typeof subject == 'number' ) {
- index = subject;
- item = this._items[ index ];
- itemDoesNotExist = !item;
- if ( item ) {
- id = item[ idProperty ];
- }
- } else {
- item = subject;
- id = item[ idProperty ];
- index = this._items.indexOf( item );
- itemDoesNotExist = ( index == -1 || !this._itemMap.get( id ) );
- }
- if ( itemDoesNotExist ) {
- /**
- * Item not found.
- *
- * @error collection-remove-404
- */
- throw new CKEditorError( 'collection-remove-404: Item not found.' );
- }
- this._items.splice( index, 1 );
- this._itemMap.delete( id );
- const externalItem = this._bindToInternalToExternalMap.get( item );
- this._bindToInternalToExternalMap.delete( item );
- this._bindToExternalToInternalMap.delete( externalItem );
- this.fire( 'remove', item );
- return item;
- }
- /**
- * Executes the callback for each item in the collection and composes an array or values returned by this callback.
- *
- * @param {Function} callback
- * @param {Object} callback.item
- * @param {Number} callback.index
- * @params {Object} ctx Context in which the `callback` will be called.
- * @returns {Array} The result of mapping.
- */
- map( callback, ctx ) {
- return this._items.map( callback, ctx );
- }
- /**
- * Finds the first item in the collection for which the `callback` returns a true value.
- *
- * @param {Function} callback
- * @param {Object} callback.item
- * @param {Number} callback.index
- * @returns {Object} The item for which `callback` returned a true value.
- * @params {Object} ctx Context in which the `callback` will be called.
- */
- find( callback, ctx ) {
- return this._items.find( callback, ctx );
- }
- /**
- * Returns an array with items for which the `callback` returned a true value.
- *
- * @param {Function} callback
- * @param {Object} callback.item
- * @param {Number} callback.index
- * @params {Object} ctx Context in which the `callback` will be called.
- * @returns {Object[]} The array with matching items.
- */
- filter( callback, ctx ) {
- return this._items.filter( callback, ctx );
- }
- /**
- * Removes all items from the collection and destroys the binding created using
- * {@link #bindTo}.
- */
- clear() {
- if ( this._bindToCollection ) {
- this.stopListening( this._bindToCollection );
- this._bindToCollection = null;
- }
- while ( this.length ) {
- this.remove( 0 );
- }
- }
- /**
- * Binds and synchronizes the collection with another one.
- *
- * The binding can be a simple factory:
- *
- * class FactoryClass {
- * constructor( data ) {
- * this.label = data.label;
- * }
- * }
- *
- * const source = new Collection( { idProperty: 'label' } );
- * const target = new Collection();
- *
- * target.bindTo( source ).as( FactoryClass );
- *
- * source.add( { label: 'foo' } );
- * source.add( { label: 'bar' } );
- *
- * console.log( target.length ); // 2
- * console.log( target.get( 1 ).label ); // 'bar'
- *
- * source.remove( 0 );
- * console.log( target.length ); // 1
- * console.log( target.get( 0 ).label ); // 'bar'
- *
- * or the factory driven by a custom callback:
- *
- * class FooClass {
- * constructor( data ) {
- * this.label = data.label;
- * }
- * }
- *
- * class BarClass {
- * constructor( data ) {
- * this.label = data.label;
- * }
- * }
- *
- * const source = new Collection( { idProperty: 'label' } );
- * const target = new Collection();
- *
- * target.bindTo( source ).using( ( item ) => {
- * if ( item.label == 'foo' ) {
- * return new FooClass( item );
- * } else {
- * return new BarClass( item );
- * }
- * } );
- *
- * source.add( { label: 'foo' } );
- * source.add( { label: 'bar' } );
- *
- * console.log( target.length ); // 2
- * console.log( target.get( 0 ) instanceof FooClass ); // true
- * console.log( target.get( 1 ) instanceof BarClass ); // true
- *
- * or the factory out of property name:
- *
- * const source = new Collection( { idProperty: 'label' } );
- * const target = new Collection();
- *
- * target.bindTo( source ).using( 'label' );
- *
- * source.add( { label: { value: 'foo' } } );
- * source.add( { label: { value: 'bar' } } );
- *
- * console.log( target.length ); // 2
- * console.log( target.get( 0 ).value ); // 'foo'
- * console.log( target.get( 1 ).value ); // 'bar'
- *
- * **Note**: {@link #clear} can be used to break the binding.
- *
- * @param {module:utils/collection~Collection} collection A collection to be bound.
- * @returns {Object}
- * @returns {module:utils/collection~Collection#bindTo#as} return.as
- * @returns {module:utils/collection~Collection#bindTo#using} return.using
- */
- bindTo( externalCollection ) {
- if ( this._bindToCollection ) {
- /**
- * The collection cannot be bound more than once.
- *
- * @error collection-bind-to-rebind
- */
- throw new CKEditorError( 'collection-bind-to-rebind: The collection cannot be bound more than once.' );
- }
- this._bindToCollection = externalCollection;
- return {
- /**
- * Creates the class factory binding.
- *
- * @static
- * @param {Function} Class Specifies which class factory is to be initialized.
- */
- as: ( Class ) => {
- this._setUpBindToBinding( item => new Class( item ) );
- },
- /**
- * Creates callback or property binding.
- *
- * @static
- * @param {Function|String} callbackOrProperty When the function is passed, it is used to
- * produce the items. When the string is provided, the property value is used to create
- * the bound collection items.
- */
- using: ( callbackOrProperty ) => {
- if ( typeof callbackOrProperty == 'function' ) {
- this._setUpBindToBinding( item => callbackOrProperty( item ) );
- } else {
- this._setUpBindToBinding( item => item[ callbackOrProperty ] );
- }
- }
- };
- }
- /**
- * Finalizes and activates a binding initiated by {#bindTo}.
- *
- * @protected
- * @param {Function} factory A function which produces collection items.
- */
- _setUpBindToBinding( factory ) {
- const externalCollection = this._bindToCollection;
- // Adds the item to the collection once a change has been done to the external collection.
- //
- // @private
- const addItem = ( evt, externalItem, index ) => {
- const isExternalBoundToThis = externalCollection._bindToCollection == this;
- const externalItemBound = externalCollection._bindToInternalToExternalMap.get( externalItem );
- // If an external collection is bound to this collection, which makes it a 2–way binding,
- // and the particular external collection item is already bound, don't add it here.
- // The external item has been created **out of this collection's item** and (re)adding it will
- // cause a loop.
- if ( isExternalBoundToThis && externalItemBound ) {
- this._bindToExternalToInternalMap.set( externalItem, externalItemBound );
- this._bindToInternalToExternalMap.set( externalItemBound, externalItem );
- } else {
- const item = factory( externalItem );
- this._bindToExternalToInternalMap.set( externalItem, item );
- this._bindToInternalToExternalMap.set( item, externalItem );
- this.add( item, index );
- }
- };
- // Load the initial content of the collection.
- for ( let externalItem of externalCollection ) {
- addItem( null, externalItem );
- }
- // Synchronize the with collection as new items are added.
- this.listenTo( externalCollection, 'add', addItem );
- // Synchronize the with collection as new items are removed.
- this.listenTo( externalCollection, 'remove', ( evt, externalItem ) => {
- const item = this._bindToExternalToInternalMap.get( externalItem );
- if ( item ) {
- this.remove( item );
- }
- } );
- }
- /**
- * Collection iterator.
- */
- [ Symbol.iterator ]() {
- return this._items[ Symbol.iterator ]();
- }
- /**
- * Fired when an item is added to the collection.
- *
- * @event add
- * @param {Object} item The added item.
- */
- /**
- * Fired when an item is removed from the collection.
- *
- * @event remove
- * @param {Object} item The removed item.
- */
- }
- mix( Collection, EmitterMixin );
|