collection.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module utils/collection
  7. */
  8. import EmitterMixin from './emittermixin';
  9. import CKEditorError from './ckeditorerror';
  10. import uid from './uid';
  11. import mix from './mix';
  12. /**
  13. * Collections are ordered sets of objects. Items in the collection can be retrieved by their indexes
  14. * in the collection (like in an array) or by their ids.
  15. *
  16. * If an object without an `id` property is being added to the collection, the `id` property will be generated
  17. * automatically. Note that the automatically generated id is unique only within this single collection instance.
  18. *
  19. * By default an item in the collection is identified by its `id` property. The name of the identifier can be
  20. * configured through the constructor of the collection.
  21. *
  22. * @mixes module:utils/emittermixin~EmitterMixin
  23. */
  24. export default class Collection {
  25. /**
  26. * Creates a new Collection instance.
  27. *
  28. * @param {Object} [options={}] The options object.
  29. * @param {String} [options.idProperty='id'] The name of the property which is considered to identify an item.
  30. */
  31. constructor( options = {} ) {
  32. /**
  33. * The internal list of items in the collection.
  34. *
  35. * @private
  36. * @member {Object[]}
  37. */
  38. this._items = [];
  39. /**
  40. * The internal map of items in the collection.
  41. *
  42. * @private
  43. * @member {Map}
  44. */
  45. this._itemMap = new Map();
  46. /**
  47. * The name of the property which is considered to identify an item.
  48. *
  49. * @private
  50. * @member {String}
  51. */
  52. this._idProperty = options.idProperty || 'id';
  53. /**
  54. * A helper mapping external items of a bound collection ({@link #bindTo})
  55. * and actual items of this collection. It provides information
  56. * necessary to properly remove items bound to another collection.
  57. *
  58. * See {@link #_bindToInternalToExternalMap}.
  59. *
  60. * @protected
  61. * @member {WeakMap}
  62. */
  63. this._bindToExternalToInternalMap = new WeakMap();
  64. /**
  65. * A helper mapping items of this collection to external items of a bound collection
  66. * ({@link #bindTo}). It provides information necessary to manage the bindings, e.g.
  67. * to avoid loops in two–way bindings.
  68. *
  69. * See {@link #_bindToExternalToInternalMap}.
  70. *
  71. * @protected
  72. * @member {WeakMap}
  73. */
  74. this._bindToInternalToExternalMap = new WeakMap();
  75. /**
  76. * Stores indexes of skipped items from bound external collection.
  77. *
  78. * @private
  79. * @member {Array}
  80. */
  81. this._skippedIndexesFromExternal = [];
  82. /**
  83. * A collection instance this collection is bound to as a result
  84. * of calling {@link #bindTo} method.
  85. *
  86. * @protected
  87. * @member {module:utils/collection~Collection} #_bindToCollection
  88. */
  89. }
  90. /**
  91. * The number of items available in the collection.
  92. *
  93. * @member {Number} #length
  94. */
  95. get length() {
  96. return this._items.length;
  97. }
  98. /**
  99. * Returns the first item from the collection or null when collection is empty.
  100. *
  101. * @returns {Object|null} The first item or `null` if collection is empty.
  102. */
  103. get first() {
  104. return this._items[ 0 ] || null;
  105. }
  106. /**
  107. * Returns the last item from the collection or null when collection is empty.
  108. *
  109. * @returns {Object|null} The last item or `null` if collection is empty.
  110. */
  111. get last() {
  112. return this._items[ this.length - 1 ] || null;
  113. }
  114. /**
  115. * Adds an item into the collection.
  116. *
  117. * If the item does not have an id, then it will be automatically generated and set on the item.
  118. *
  119. * @chainable
  120. * @param {Object} item
  121. * @param {Number} [index] The position of the item in the collection. The item
  122. * is pushed to the collection when `index` not specified.
  123. * @fires add
  124. */
  125. add( item, index ) {
  126. let itemId;
  127. const idProperty = this._idProperty;
  128. if ( ( idProperty in item ) ) {
  129. itemId = item[ idProperty ];
  130. if ( typeof itemId != 'string' ) {
  131. /**
  132. * This item's id should be a string.
  133. *
  134. * @error collection-add-invalid-id
  135. */
  136. throw new CKEditorError( 'collection-add-invalid-id' );
  137. }
  138. if ( this.get( itemId ) ) {
  139. /**
  140. * This item already exists in the collection.
  141. *
  142. * @error collection-add-item-already-exists
  143. */
  144. throw new CKEditorError( 'collection-add-item-already-exists' );
  145. }
  146. } else {
  147. item[ idProperty ] = itemId = uid();
  148. }
  149. // TODO: Use ES6 default function argument.
  150. if ( index === undefined ) {
  151. index = this._items.length;
  152. } else if ( index > this._items.length || index < 0 ) {
  153. /**
  154. * The index number has invalid value.
  155. *
  156. * @error collection-add-item-bad-index
  157. */
  158. throw new CKEditorError( 'collection-add-item-invalid-index' );
  159. }
  160. this._items.splice( index, 0, item );
  161. this._itemMap.set( itemId, item );
  162. this.fire( 'add', item, index );
  163. return this;
  164. }
  165. /**
  166. * Gets item by its id or index.
  167. *
  168. * @param {String|Number} idOrIndex The item id or index in the collection.
  169. * @returns {Object|null} The requested item or `null` if such item does not exist.
  170. */
  171. get( idOrIndex ) {
  172. let item;
  173. if ( typeof idOrIndex == 'string' ) {
  174. item = this._itemMap.get( idOrIndex );
  175. } else if ( typeof idOrIndex == 'number' ) {
  176. item = this._items[ idOrIndex ];
  177. } else {
  178. /**
  179. * Index or id must be given.
  180. *
  181. * @error collection-get-invalid-arg
  182. */
  183. throw new CKEditorError( 'collection-get-invalid-arg: Index or id must be given.' );
  184. }
  185. return item || null;
  186. }
  187. /**
  188. * Returns a boolean indicating whether the collection contains an item. Item id or index can be used instead of the
  189. * item.
  190. *
  191. * @param {Object|String|Number} itemOrIdOrIndex The item, item id or item index in the collection.
  192. * @returns {Boolean} `true` if the collection contains the item, `false` otherwise.
  193. */
  194. has( itemOrIdOrIndex ) {
  195. if ( typeof itemOrIdOrIndex == 'number' ) {
  196. return !!this._items[ itemOrIdOrIndex ];
  197. } else if ( typeof itemOrIdOrIndex == 'string' ) {
  198. return this._itemMap.has( itemOrIdOrIndex );
  199. } else { // Object
  200. const idProperty = this._idProperty;
  201. const id = itemOrIdOrIndex[ idProperty ];
  202. if ( typeof id != 'string' ) {
  203. /**
  204. * This item's id should be a string.
  205. *
  206. * @error collection-has-invalid-id
  207. */
  208. throw new CKEditorError( 'collection-has-invalid-id: This item\'s id should be a string.' );
  209. }
  210. return this._itemMap.has( id );
  211. }
  212. }
  213. /**
  214. * Gets index of item in the collection.
  215. * When item is not defined in the collection then index will be equal -1.
  216. *
  217. * @param {String|Object} idOrItem The item or its id in the collection.
  218. * @returns {Number} Index of given item.
  219. */
  220. getIndex( idOrItem ) {
  221. let item;
  222. if ( typeof idOrItem == 'string' ) {
  223. item = this._itemMap.get( idOrItem );
  224. } else {
  225. item = idOrItem;
  226. }
  227. return this._items.indexOf( item );
  228. }
  229. /**
  230. * Removes an item from the collection.
  231. *
  232. * @param {Object|Number|String} subject The item to remove, its id or index in the collection.
  233. * @returns {Object} The removed item.
  234. * @fires remove
  235. */
  236. remove( subject ) {
  237. let index, id, item;
  238. let itemDoesNotExist = false;
  239. const idProperty = this._idProperty;
  240. if ( typeof subject == 'string' ) {
  241. id = subject;
  242. item = this._itemMap.get( id );
  243. itemDoesNotExist = !item;
  244. if ( item ) {
  245. index = this._items.indexOf( item );
  246. }
  247. } else if ( typeof subject == 'number' ) {
  248. index = subject;
  249. item = this._items[ index ];
  250. itemDoesNotExist = !item;
  251. if ( item ) {
  252. id = item[ idProperty ];
  253. }
  254. } else {
  255. item = subject;
  256. id = item[ idProperty ];
  257. index = this._items.indexOf( item );
  258. itemDoesNotExist = ( index == -1 || !this._itemMap.get( id ) );
  259. }
  260. if ( itemDoesNotExist ) {
  261. /**
  262. * Item not found.
  263. *
  264. * @error collection-remove-404
  265. */
  266. throw new CKEditorError( 'collection-remove-404: Item not found.' );
  267. }
  268. this._items.splice( index, 1 );
  269. this._itemMap.delete( id );
  270. const externalItem = this._bindToInternalToExternalMap.get( item );
  271. this._bindToInternalToExternalMap.delete( item );
  272. this._bindToExternalToInternalMap.delete( externalItem );
  273. this.fire( 'remove', item, index );
  274. return item;
  275. }
  276. /**
  277. * Executes the callback for each item in the collection and composes an array or values returned by this callback.
  278. *
  279. * @param {Function} callback
  280. * @param {Object} callback.item
  281. * @param {Number} callback.index
  282. * @param {Object} ctx Context in which the `callback` will be called.
  283. * @returns {Array} The result of mapping.
  284. */
  285. map( callback, ctx ) {
  286. return this._items.map( callback, ctx );
  287. }
  288. /**
  289. * Finds the first item in the collection for which the `callback` returns a true value.
  290. *
  291. * @param {Function} callback
  292. * @param {Object} callback.item
  293. * @param {Number} callback.index
  294. * @param {Object} ctx Context in which the `callback` will be called.
  295. * @returns {Object} The item for which `callback` returned a true value.
  296. */
  297. find( callback, ctx ) {
  298. return this._items.find( callback, ctx );
  299. }
  300. /**
  301. * Returns an array with items for which the `callback` returned a true value.
  302. *
  303. * @param {Function} callback
  304. * @param {Object} callback.item
  305. * @param {Number} callback.index
  306. * @param {Object} ctx Context in which the `callback` will be called.
  307. * @returns {Object[]} The array with matching items.
  308. */
  309. filter( callback, ctx ) {
  310. return this._items.filter( callback, ctx );
  311. }
  312. /**
  313. * Removes all items from the collection and destroys the binding created using
  314. * {@link #bindTo}.
  315. */
  316. clear() {
  317. if ( this._bindToCollection ) {
  318. this.stopListening( this._bindToCollection );
  319. this._bindToCollection = null;
  320. }
  321. while ( this.length ) {
  322. this.remove( 0 );
  323. }
  324. }
  325. /**
  326. * Binds and synchronizes the collection with another one.
  327. *
  328. * The binding can be a simple factory:
  329. *
  330. * class FactoryClass {
  331. * constructor( data ) {
  332. * this.label = data.label;
  333. * }
  334. * }
  335. *
  336. * const source = new Collection( { idProperty: 'label' } );
  337. * const target = new Collection();
  338. *
  339. * target.bindTo( source ).as( FactoryClass );
  340. *
  341. * source.add( { label: 'foo' } );
  342. * source.add( { label: 'bar' } );
  343. *
  344. * console.log( target.length ); // 2
  345. * console.log( target.get( 1 ).label ); // 'bar'
  346. *
  347. * source.remove( 0 );
  348. * console.log( target.length ); // 1
  349. * console.log( target.get( 0 ).label ); // 'bar'
  350. *
  351. * or the factory driven by a custom callback:
  352. *
  353. * class FooClass {
  354. * constructor( data ) {
  355. * this.label = data.label;
  356. * }
  357. * }
  358. *
  359. * class BarClass {
  360. * constructor( data ) {
  361. * this.label = data.label;
  362. * }
  363. * }
  364. *
  365. * const source = new Collection( { idProperty: 'label' } );
  366. * const target = new Collection();
  367. *
  368. * target.bindTo( source ).using( ( item ) => {
  369. * if ( item.label == 'foo' ) {
  370. * return new FooClass( item );
  371. * } else {
  372. * return new BarClass( item );
  373. * }
  374. * } );
  375. *
  376. * source.add( { label: 'foo' } );
  377. * source.add( { label: 'bar' } );
  378. *
  379. * console.log( target.length ); // 2
  380. * console.log( target.get( 0 ) instanceof FooClass ); // true
  381. * console.log( target.get( 1 ) instanceof BarClass ); // true
  382. *
  383. * or the factory out of property name:
  384. *
  385. * const source = new Collection( { idProperty: 'label' } );
  386. * const target = new Collection();
  387. *
  388. * target.bindTo( source ).using( 'label' );
  389. *
  390. * source.add( { label: { value: 'foo' } } );
  391. * source.add( { label: { value: 'bar' } } );
  392. *
  393. * console.log( target.length ); // 2
  394. * console.log( target.get( 0 ).value ); // 'foo'
  395. * console.log( target.get( 1 ).value ); // 'bar'
  396. *
  397. * It's possible to skip specified items by returning falsy value:
  398. *
  399. * const source = new Collection();
  400. * const target = new Collection();
  401. *
  402. * target.bindTo( source ).using( item => {
  403. * if ( item.hidden ) {
  404. * return null;
  405. * }
  406. *
  407. * return item;
  408. * } );
  409. *
  410. * source.add( { hidden: true } );
  411. * source.add( { hidden: false } );
  412. *
  413. * console.log( source.length ); // 2
  414. * console.log( target.length ); // 1
  415. *
  416. * **Note**: {@link #clear} can be used to break the binding.
  417. *
  418. * @param {module:utils/collection~Collection} externalCollection A collection to be bound.
  419. * @returns {Object}
  420. * @returns {module:utils/collection~CollectionBindToChain} The binding chain object.
  421. */
  422. bindTo( externalCollection ) {
  423. if ( this._bindToCollection ) {
  424. /**
  425. * The collection cannot be bound more than once.
  426. *
  427. * @error collection-bind-to-rebind
  428. */
  429. throw new CKEditorError( 'collection-bind-to-rebind: The collection cannot be bound more than once.' );
  430. }
  431. this._bindToCollection = externalCollection;
  432. return {
  433. as: Class => {
  434. this._setUpBindToBinding( item => new Class( item ) );
  435. },
  436. using: callbackOrProperty => {
  437. if ( typeof callbackOrProperty == 'function' ) {
  438. this._setUpBindToBinding( item => callbackOrProperty( item ) );
  439. } else {
  440. this._setUpBindToBinding( item => item[ callbackOrProperty ] );
  441. }
  442. }
  443. };
  444. }
  445. /**
  446. * Finalizes and activates a binding initiated by {#bindTo}.
  447. *
  448. * @protected
  449. * @param {Function} factory A function which produces collection items.
  450. */
  451. _setUpBindToBinding( factory ) {
  452. const externalCollection = this._bindToCollection;
  453. // Adds the item to the collection once a change has been done to the external collection.
  454. //
  455. // @private
  456. const addItem = ( evt, externalItem, index ) => {
  457. const isExternalBoundToThis = externalCollection._bindToCollection == this;
  458. const externalItemBound = externalCollection._bindToInternalToExternalMap.get( externalItem );
  459. // If an external collection is bound to this collection, which makes it a 2–way binding,
  460. // and the particular external collection item is already bound, don't add it here.
  461. // The external item has been created **out of this collection's item** and (re)adding it will
  462. // cause a loop.
  463. if ( isExternalBoundToThis && externalItemBound ) {
  464. this._bindToExternalToInternalMap.set( externalItem, externalItemBound );
  465. this._bindToInternalToExternalMap.set( externalItemBound, externalItem );
  466. } else {
  467. const item = factory( externalItem );
  468. // When there is no item we need to remember skipped index first and then we can skip this item.
  469. if ( !item ) {
  470. this._skippedIndexesFromExternal.push( index );
  471. return;
  472. }
  473. // Lets try to put item at the same index as index in external collection
  474. // but when there are a skipped items in one or both collections we need to recalculate this index.
  475. let finalIndex = index;
  476. // When we try to insert item after some skipped items from external collection we need
  477. // to include this skipped items and decrease index.
  478. //
  479. // For the following example:
  480. // external -> [ 'A', 'B - skipped for internal', 'C - skipped for internal' ]
  481. // internal -> [ A ]
  482. //
  483. // Another item is been added at the end of external collection:
  484. // external.add( 'D' )
  485. // external -> [ 'A', 'B - skipped for internal', 'C - skipped for internal', 'D' ]
  486. //
  487. // We can't just add 'D' to internal at the same index as index in external because
  488. // this will produce empty indexes what is invalid:
  489. // internal -> [ 'A', empty, empty, 'D' ]
  490. //
  491. // So we need to include skipped items and decrease index
  492. // internal -> [ 'A', 'D' ]
  493. for ( const skipped of this._skippedIndexesFromExternal ) {
  494. if ( index > skipped ) {
  495. finalIndex--;
  496. }
  497. }
  498. // We need to take into consideration that external collection could skip some items from
  499. // internal collection.
  500. //
  501. // For the following example:
  502. // internal -> [ 'A', 'B - skipped for external', 'C - skipped for external' ]
  503. // external -> [ A ]
  504. //
  505. // Another item is been added at the end of external collection:
  506. // external.add( 'D' )
  507. // external -> [ 'A', 'D' ]
  508. //
  509. // We need to include skipped items and place new item after them:
  510. // internal -> [ 'A', 'B - skipped for external', 'C - skipped for external', 'D' ]
  511. for ( const skipped of externalCollection._skippedIndexesFromExternal ) {
  512. if ( finalIndex >= skipped ) {
  513. finalIndex++;
  514. }
  515. }
  516. this._bindToExternalToInternalMap.set( externalItem, item );
  517. this._bindToInternalToExternalMap.set( item, externalItem );
  518. this.add( item, finalIndex );
  519. // After adding new element to internal collection we need update indexes
  520. // of skipped items in external collection.
  521. for ( let i = 0; i < externalCollection._skippedIndexesFromExternal.length; i++ ) {
  522. if ( finalIndex <= externalCollection._skippedIndexesFromExternal[ i ] ) {
  523. externalCollection._skippedIndexesFromExternal[ i ]++;
  524. }
  525. }
  526. }
  527. };
  528. // Load the initial content of the collection.
  529. for ( const externalItem of externalCollection ) {
  530. addItem( null, externalItem, externalCollection.getIndex( externalItem ) );
  531. }
  532. // Synchronize the with collection as new items are added.
  533. this.listenTo( externalCollection, 'add', addItem );
  534. // Synchronize the with collection as new items are removed.
  535. this.listenTo( externalCollection, 'remove', ( evt, externalItem, index ) => {
  536. const item = this._bindToExternalToInternalMap.get( externalItem );
  537. if ( item ) {
  538. this.remove( item );
  539. }
  540. // After removing element from external collection we need update/remove indexes
  541. // of skipped items in internal collection.
  542. this._skippedIndexesFromExternal = this._skippedIndexesFromExternal.reduce( ( result, skipped ) => {
  543. if ( index < skipped ) {
  544. result.push( skipped - 1 );
  545. }
  546. if ( index > skipped ) {
  547. result.push( skipped );
  548. }
  549. return result;
  550. }, [] );
  551. } );
  552. }
  553. /**
  554. * Iterable interface.
  555. *
  556. * @returns {Iterable.<*>}
  557. */
  558. [ Symbol.iterator ]() {
  559. return this._items[ Symbol.iterator ]();
  560. }
  561. /**
  562. * Fired when an item is added to the collection.
  563. *
  564. * @event add
  565. * @param {Object} item The added item.
  566. */
  567. /**
  568. * Fired when an item is removed from the collection.
  569. *
  570. * @event remove
  571. * @param {Object} item The removed item.
  572. * @param {Number} index Index from which item was removed.
  573. */
  574. }
  575. mix( Collection, EmitterMixin );
  576. /**
  577. * An object returned by the {@link module:utils/collection~Collection#bindTo `bindTo()`} method
  578. * providing functions that specify the type of the binding.
  579. *
  580. * See the {@link module:utils/collection~Collection#bindTo `bindTo()`} documentation for examples.
  581. *
  582. * @interface module:utils/collection~CollectionBindToChain
  583. */
  584. /**
  585. * Creates a callback or a property binding.
  586. *
  587. * @method #using
  588. * @param {Function|String} callbackOrProperty When the function is passed, it should return
  589. * the collection items. When the string is provided, the property value is used to create the bound collection items.
  590. */
  591. /**
  592. * Creates the class factory binding in which items of the source collection are passed to
  593. * the constructor of the specified class.
  594. *
  595. * @method #as
  596. * @param {Function} Class The class constructor used to create instances in the factory.
  597. */