collection.js 21 KB

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