collection.js 17 KB

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