collection.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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 with the specified id or index.
  189. *
  190. * @param {String|Number} idOrIndex The item id or index in the collection.
  191. * @returns {Boolean} `true` if the collection contains the item, `false` otherwise.
  192. */
  193. has( idOrIndex ) {
  194. let item;
  195. if ( typeof idOrIndex == 'string' ) {
  196. return this._itemMap.has( idOrIndex );
  197. } else if ( typeof idOrIndex == 'number' ) {
  198. return !!this._items[ idOrIndex ];
  199. }
  200. /**
  201. * Index or id must be given.
  202. *
  203. * @error collection-has-invalid-arg
  204. */
  205. throw new CKEditorError( 'collection-has-invalid-arg: Index or id must be given.' );
  206. }
  207. /**
  208. * Gets index of item in the collection.
  209. * When item is not defined in the collection then index will be equal -1.
  210. *
  211. * @param {String|Object} idOrItem The item or its id in the collection.
  212. * @returns {Number} Index of given item.
  213. */
  214. getIndex( idOrItem ) {
  215. let item;
  216. if ( typeof idOrItem == 'string' ) {
  217. item = this._itemMap.get( idOrItem );
  218. } else {
  219. item = idOrItem;
  220. }
  221. return this._items.indexOf( item );
  222. }
  223. /**
  224. * Removes an item from the collection.
  225. *
  226. * @param {Object|Number|String} subject The item to remove, its id or index in the collection.
  227. * @returns {Object} The removed item.
  228. * @fires remove
  229. */
  230. remove( subject ) {
  231. let index, id, item;
  232. let itemDoesNotExist = false;
  233. const idProperty = this._idProperty;
  234. if ( typeof subject == 'string' ) {
  235. id = subject;
  236. item = this._itemMap.get( id );
  237. itemDoesNotExist = !item;
  238. if ( item ) {
  239. index = this._items.indexOf( item );
  240. }
  241. } else if ( typeof subject == 'number' ) {
  242. index = subject;
  243. item = this._items[ index ];
  244. itemDoesNotExist = !item;
  245. if ( item ) {
  246. id = item[ idProperty ];
  247. }
  248. } else {
  249. item = subject;
  250. id = item[ idProperty ];
  251. index = this._items.indexOf( item );
  252. itemDoesNotExist = ( index == -1 || !this._itemMap.get( id ) );
  253. }
  254. if ( itemDoesNotExist ) {
  255. /**
  256. * Item not found.
  257. *
  258. * @error collection-remove-404
  259. */
  260. throw new CKEditorError( 'collection-remove-404: Item not found.' );
  261. }
  262. this._items.splice( index, 1 );
  263. this._itemMap.delete( id );
  264. const externalItem = this._bindToInternalToExternalMap.get( item );
  265. this._bindToInternalToExternalMap.delete( item );
  266. this._bindToExternalToInternalMap.delete( externalItem );
  267. this.fire( 'remove', item, index );
  268. return item;
  269. }
  270. /**
  271. * Executes the callback for each item in the collection and composes an array or values returned by this callback.
  272. *
  273. * @param {Function} callback
  274. * @param {Object} callback.item
  275. * @param {Number} callback.index
  276. * @param {Object} ctx Context in which the `callback` will be called.
  277. * @returns {Array} The result of mapping.
  278. */
  279. map( callback, ctx ) {
  280. return this._items.map( callback, ctx );
  281. }
  282. /**
  283. * Finds the first item in the collection for which the `callback` returns a true value.
  284. *
  285. * @param {Function} callback
  286. * @param {Object} callback.item
  287. * @param {Number} callback.index
  288. * @param {Object} ctx Context in which the `callback` will be called.
  289. * @returns {Object} The item for which `callback` returned a true value.
  290. */
  291. find( callback, ctx ) {
  292. return this._items.find( callback, ctx );
  293. }
  294. /**
  295. * Returns an array with items for which the `callback` returned a true value.
  296. *
  297. * @param {Function} callback
  298. * @param {Object} callback.item
  299. * @param {Number} callback.index
  300. * @param {Object} ctx Context in which the `callback` will be called.
  301. * @returns {Object[]} The array with matching items.
  302. */
  303. filter( callback, ctx ) {
  304. return this._items.filter( callback, ctx );
  305. }
  306. /**
  307. * Removes all items from the collection and destroys the binding created using
  308. * {@link #bindTo}.
  309. */
  310. clear() {
  311. if ( this._bindToCollection ) {
  312. this.stopListening( this._bindToCollection );
  313. this._bindToCollection = null;
  314. }
  315. while ( this.length ) {
  316. this.remove( 0 );
  317. }
  318. }
  319. /**
  320. * Binds and synchronizes the collection with another one.
  321. *
  322. * The binding can be a simple factory:
  323. *
  324. * class FactoryClass {
  325. * constructor( data ) {
  326. * this.label = data.label;
  327. * }
  328. * }
  329. *
  330. * const source = new Collection( { idProperty: 'label' } );
  331. * const target = new Collection();
  332. *
  333. * target.bindTo( source ).as( FactoryClass );
  334. *
  335. * source.add( { label: 'foo' } );
  336. * source.add( { label: 'bar' } );
  337. *
  338. * console.log( target.length ); // 2
  339. * console.log( target.get( 1 ).label ); // 'bar'
  340. *
  341. * source.remove( 0 );
  342. * console.log( target.length ); // 1
  343. * console.log( target.get( 0 ).label ); // 'bar'
  344. *
  345. * or the factory driven by a custom callback:
  346. *
  347. * class FooClass {
  348. * constructor( data ) {
  349. * this.label = data.label;
  350. * }
  351. * }
  352. *
  353. * class BarClass {
  354. * constructor( data ) {
  355. * this.label = data.label;
  356. * }
  357. * }
  358. *
  359. * const source = new Collection( { idProperty: 'label' } );
  360. * const target = new Collection();
  361. *
  362. * target.bindTo( source ).using( ( item ) => {
  363. * if ( item.label == 'foo' ) {
  364. * return new FooClass( item );
  365. * } else {
  366. * return new BarClass( item );
  367. * }
  368. * } );
  369. *
  370. * source.add( { label: 'foo' } );
  371. * source.add( { label: 'bar' } );
  372. *
  373. * console.log( target.length ); // 2
  374. * console.log( target.get( 0 ) instanceof FooClass ); // true
  375. * console.log( target.get( 1 ) instanceof BarClass ); // true
  376. *
  377. * or the factory out of property name:
  378. *
  379. * const source = new Collection( { idProperty: 'label' } );
  380. * const target = new Collection();
  381. *
  382. * target.bindTo( source ).using( 'label' );
  383. *
  384. * source.add( { label: { value: 'foo' } } );
  385. * source.add( { label: { value: 'bar' } } );
  386. *
  387. * console.log( target.length ); // 2
  388. * console.log( target.get( 0 ).value ); // 'foo'
  389. * console.log( target.get( 1 ).value ); // 'bar'
  390. *
  391. * It's possible to skip specified items by returning falsy value:
  392. *
  393. * const source = new Collection();
  394. * const target = new Collection();
  395. *
  396. * target.bindTo( source ).using( item => {
  397. * if ( item.hidden ) {
  398. * return null;
  399. * }
  400. *
  401. * return item;
  402. * } );
  403. *
  404. * source.add( { hidden: true } );
  405. * source.add( { hidden: false } );
  406. *
  407. * console.log( source.length ); // 2
  408. * console.log( target.length ); // 1
  409. *
  410. * **Note**: {@link #clear} can be used to break the binding.
  411. *
  412. * @param {module:utils/collection~Collection} externalCollection A collection to be bound.
  413. * @returns {Object}
  414. * @returns {module:utils/collection~CollectionBindToChain} The binding chain object.
  415. */
  416. bindTo( externalCollection ) {
  417. if ( this._bindToCollection ) {
  418. /**
  419. * The collection cannot be bound more than once.
  420. *
  421. * @error collection-bind-to-rebind
  422. */
  423. throw new CKEditorError( 'collection-bind-to-rebind: The collection cannot be bound more than once.' );
  424. }
  425. this._bindToCollection = externalCollection;
  426. return {
  427. as: Class => {
  428. this._setUpBindToBinding( item => new Class( item ) );
  429. },
  430. using: callbackOrProperty => {
  431. if ( typeof callbackOrProperty == 'function' ) {
  432. this._setUpBindToBinding( item => callbackOrProperty( item ) );
  433. } else {
  434. this._setUpBindToBinding( item => item[ callbackOrProperty ] );
  435. }
  436. }
  437. };
  438. }
  439. /**
  440. * Finalizes and activates a binding initiated by {#bindTo}.
  441. *
  442. * @protected
  443. * @param {Function} factory A function which produces collection items.
  444. */
  445. _setUpBindToBinding( factory ) {
  446. const externalCollection = this._bindToCollection;
  447. // Adds the item to the collection once a change has been done to the external collection.
  448. //
  449. // @private
  450. const addItem = ( evt, externalItem, index ) => {
  451. const isExternalBoundToThis = externalCollection._bindToCollection == this;
  452. const externalItemBound = externalCollection._bindToInternalToExternalMap.get( externalItem );
  453. // If an external collection is bound to this collection, which makes it a 2–way binding,
  454. // and the particular external collection item is already bound, don't add it here.
  455. // The external item has been created **out of this collection's item** and (re)adding it will
  456. // cause a loop.
  457. if ( isExternalBoundToThis && externalItemBound ) {
  458. this._bindToExternalToInternalMap.set( externalItem, externalItemBound );
  459. this._bindToInternalToExternalMap.set( externalItemBound, externalItem );
  460. } else {
  461. const item = factory( externalItem );
  462. // When there is no item we need to remember skipped index first and then we can skip this item.
  463. if ( !item ) {
  464. this._skippedIndexesFromExternal.push( index );
  465. return;
  466. }
  467. // Lets try to put item at the same index as index in external collection
  468. // but when there are a skipped items in one or both collections we need to recalculate this index.
  469. let finalIndex = index;
  470. // When we try to insert item after some skipped items from external collection we need
  471. // to include this skipped items and decrease index.
  472. //
  473. // For the following example:
  474. // external -> [ 'A', 'B - skipped for internal', 'C - skipped for internal' ]
  475. // internal -> [ A ]
  476. //
  477. // Another item is been added at the end of external collection:
  478. // external.add( 'D' )
  479. // external -> [ 'A', 'B - skipped for internal', 'C - skipped for internal', 'D' ]
  480. //
  481. // We can't just add 'D' to internal at the same index as index in external because
  482. // this will produce empty indexes what is invalid:
  483. // internal -> [ 'A', empty, empty, 'D' ]
  484. //
  485. // So we need to include skipped items and decrease index
  486. // internal -> [ 'A', 'D' ]
  487. for ( const skipped of this._skippedIndexesFromExternal ) {
  488. if ( index > skipped ) {
  489. finalIndex--;
  490. }
  491. }
  492. // We need to take into consideration that external collection could skip some items from
  493. // internal collection.
  494. //
  495. // For the following example:
  496. // internal -> [ 'A', 'B - skipped for external', 'C - skipped for external' ]
  497. // external -> [ A ]
  498. //
  499. // Another item is been added at the end of external collection:
  500. // external.add( 'D' )
  501. // external -> [ 'A', 'D' ]
  502. //
  503. // We need to include skipped items and place new item after them:
  504. // internal -> [ 'A', 'B - skipped for external', 'C - skipped for external', 'D' ]
  505. for ( const skipped of externalCollection._skippedIndexesFromExternal ) {
  506. if ( finalIndex >= skipped ) {
  507. finalIndex++;
  508. }
  509. }
  510. this._bindToExternalToInternalMap.set( externalItem, item );
  511. this._bindToInternalToExternalMap.set( item, externalItem );
  512. this.add( item, finalIndex );
  513. // After adding new element to internal collection we need update indexes
  514. // of skipped items in external collection.
  515. for ( let i = 0; i < externalCollection._skippedIndexesFromExternal.length; i++ ) {
  516. if ( finalIndex <= externalCollection._skippedIndexesFromExternal[ i ] ) {
  517. externalCollection._skippedIndexesFromExternal[ i ]++;
  518. }
  519. }
  520. }
  521. };
  522. // Load the initial content of the collection.
  523. for ( const externalItem of externalCollection ) {
  524. addItem( null, externalItem, externalCollection.getIndex( externalItem ) );
  525. }
  526. // Synchronize the with collection as new items are added.
  527. this.listenTo( externalCollection, 'add', addItem );
  528. // Synchronize the with collection as new items are removed.
  529. this.listenTo( externalCollection, 'remove', ( evt, externalItem, index ) => {
  530. const item = this._bindToExternalToInternalMap.get( externalItem );
  531. if ( item ) {
  532. this.remove( item );
  533. }
  534. // After removing element from external collection we need update/remove indexes
  535. // of skipped items in internal collection.
  536. this._skippedIndexesFromExternal = this._skippedIndexesFromExternal.reduce( ( result, skipped ) => {
  537. if ( index < skipped ) {
  538. result.push( skipped - 1 );
  539. }
  540. if ( index > skipped ) {
  541. result.push( skipped );
  542. }
  543. return result;
  544. }, [] );
  545. } );
  546. }
  547. /**
  548. * Iterable interface.
  549. *
  550. * @returns {Iterable.<*>}
  551. */
  552. [ Symbol.iterator ]() {
  553. return this._items[ Symbol.iterator ]();
  554. }
  555. /**
  556. * Fired when an item is added to the collection.
  557. *
  558. * @event add
  559. * @param {Object} item The added item.
  560. */
  561. /**
  562. * Fired when an item is removed from the collection.
  563. *
  564. * @event remove
  565. * @param {Object} item The removed item.
  566. * @param {Number} index Index from which item was removed.
  567. */
  568. }
  569. mix( Collection, EmitterMixin );
  570. /**
  571. * An object returned by the {@link module:utils/collection~Collection#bindTo `bindTo()`} method
  572. * providing functions that specify the type of the binding.
  573. *
  574. * See the {@link module:utils/collection~Collection#bindTo `bindTo()`} documentation for examples.
  575. *
  576. * @interface module:utils/collection~CollectionBindToChain
  577. */
  578. /**
  579. * Creates a callback or a property binding.
  580. *
  581. * @method #using
  582. * @param {Function|String} callbackOrProperty When the function is passed, it should return
  583. * the collection items. When the string is provided, the property value is used to create the bound collection items.
  584. */
  585. /**
  586. * Creates the class factory binding in which items of the source collection are passed to
  587. * the constructor of the specified class.
  588. *
  589. * @method #as
  590. * @param {Function} Class The class constructor used to create instances in the factory.
  591. */