collection.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. /**
  2. * @license Copyright (c) 2003-2019, 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 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', this );
  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', this );
  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', this );
  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.', this );
  184. }
  185. return item || null;
  186. }
  187. /**
  188. * Returns a boolean indicating whether the collection contains an item.
  189. *
  190. * @param {Object|String} itemOrId The item or its id in the collection.
  191. * @returns {Boolean} `true` if the collection contains the item, `false` otherwise.
  192. */
  193. has( itemOrId ) {
  194. if ( typeof itemOrId == 'string' ) {
  195. return this._itemMap.has( itemOrId );
  196. } else { // Object
  197. const idProperty = this._idProperty;
  198. const id = itemOrId[ idProperty ];
  199. return this._itemMap.has( id );
  200. }
  201. }
  202. /**
  203. * Gets index of item in the collection.
  204. * When item is not defined in the collection then index will be equal -1.
  205. *
  206. * @param {Object|String} itemOrId The item or its id in the collection.
  207. * @returns {Number} Index of given item.
  208. */
  209. getIndex( itemOrId ) {
  210. let item;
  211. if ( typeof itemOrId == 'string' ) {
  212. item = this._itemMap.get( itemOrId );
  213. } else {
  214. item = itemOrId;
  215. }
  216. return this._items.indexOf( item );
  217. }
  218. /**
  219. * Removes an item from the collection.
  220. *
  221. * @param {Object|Number|String} subject The item to remove, its id or index in the collection.
  222. * @returns {Object} The removed item.
  223. * @fires remove
  224. */
  225. remove( subject ) {
  226. let index, id, item;
  227. let itemDoesNotExist = false;
  228. const idProperty = this._idProperty;
  229. if ( typeof subject == 'string' ) {
  230. id = subject;
  231. item = this._itemMap.get( id );
  232. itemDoesNotExist = !item;
  233. if ( item ) {
  234. index = this._items.indexOf( item );
  235. }
  236. } else if ( typeof subject == 'number' ) {
  237. index = subject;
  238. item = this._items[ index ];
  239. itemDoesNotExist = !item;
  240. if ( item ) {
  241. id = item[ idProperty ];
  242. }
  243. } else {
  244. item = subject;
  245. id = item[ idProperty ];
  246. index = this._items.indexOf( item );
  247. itemDoesNotExist = ( index == -1 || !this._itemMap.get( id ) );
  248. }
  249. if ( itemDoesNotExist ) {
  250. /**
  251. * Item not found.
  252. *
  253. * @error collection-remove-404
  254. */
  255. throw new CKEditorError( 'collection-remove-404: Item not found.', this );
  256. }
  257. this._items.splice( index, 1 );
  258. this._itemMap.delete( id );
  259. const externalItem = this._bindToInternalToExternalMap.get( item );
  260. this._bindToInternalToExternalMap.delete( item );
  261. this._bindToExternalToInternalMap.delete( externalItem );
  262. this.fire( 'remove', item, index );
  263. return item;
  264. }
  265. /**
  266. * Executes the callback for each item in the collection and composes an array or values returned by this callback.
  267. *
  268. * @param {Function} callback
  269. * @param {Object} callback.item
  270. * @param {Number} callback.index
  271. * @param {Object} ctx Context in which the `callback` will be called.
  272. * @returns {Array} The result of mapping.
  273. */
  274. map( callback, ctx ) {
  275. return this._items.map( callback, ctx );
  276. }
  277. /**
  278. * Finds the first item in the collection for which the `callback` returns a true value.
  279. *
  280. * @param {Function} callback
  281. * @param {Object} callback.item
  282. * @param {Number} callback.index
  283. * @param {Object} ctx Context in which the `callback` will be called.
  284. * @returns {Object} The item for which `callback` returned a true value.
  285. */
  286. find( callback, ctx ) {
  287. return this._items.find( callback, ctx );
  288. }
  289. /**
  290. * Returns an array with items for which the `callback` returned a true value.
  291. *
  292. * @param {Function} callback
  293. * @param {Object} callback.item
  294. * @param {Number} callback.index
  295. * @param {Object} ctx Context in which the `callback` will be called.
  296. * @returns {Object[]} The array with matching items.
  297. */
  298. filter( callback, ctx ) {
  299. return this._items.filter( callback, ctx );
  300. }
  301. /**
  302. * Removes all items from the collection and destroys the binding created using
  303. * {@link #bindTo}.
  304. */
  305. clear() {
  306. if ( this._bindToCollection ) {
  307. this.stopListening( this._bindToCollection );
  308. this._bindToCollection = null;
  309. }
  310. while ( this.length ) {
  311. this.remove( 0 );
  312. }
  313. }
  314. /**
  315. * Binds and synchronizes the collection with another one.
  316. *
  317. * The binding can be a simple factory:
  318. *
  319. * class FactoryClass {
  320. * constructor( data ) {
  321. * this.label = data.label;
  322. * }
  323. * }
  324. *
  325. * const source = new Collection( { idProperty: 'label' } );
  326. * const target = new Collection();
  327. *
  328. * target.bindTo( source ).as( FactoryClass );
  329. *
  330. * source.add( { label: 'foo' } );
  331. * source.add( { label: 'bar' } );
  332. *
  333. * console.log( target.length ); // 2
  334. * console.log( target.get( 1 ).label ); // 'bar'
  335. *
  336. * source.remove( 0 );
  337. * console.log( target.length ); // 1
  338. * console.log( target.get( 0 ).label ); // 'bar'
  339. *
  340. * or the factory driven by a custom callback:
  341. *
  342. * class FooClass {
  343. * constructor( data ) {
  344. * this.label = data.label;
  345. * }
  346. * }
  347. *
  348. * class BarClass {
  349. * constructor( data ) {
  350. * this.label = data.label;
  351. * }
  352. * }
  353. *
  354. * const source = new Collection( { idProperty: 'label' } );
  355. * const target = new Collection();
  356. *
  357. * target.bindTo( source ).using( ( item ) => {
  358. * if ( item.label == 'foo' ) {
  359. * return new FooClass( item );
  360. * } else {
  361. * return new BarClass( item );
  362. * }
  363. * } );
  364. *
  365. * source.add( { label: 'foo' } );
  366. * source.add( { label: 'bar' } );
  367. *
  368. * console.log( target.length ); // 2
  369. * console.log( target.get( 0 ) instanceof FooClass ); // true
  370. * console.log( target.get( 1 ) instanceof BarClass ); // true
  371. *
  372. * or the factory out of property name:
  373. *
  374. * const source = new Collection( { idProperty: 'label' } );
  375. * const target = new Collection();
  376. *
  377. * target.bindTo( source ).using( 'label' );
  378. *
  379. * source.add( { label: { value: 'foo' } } );
  380. * source.add( { label: { value: 'bar' } } );
  381. *
  382. * console.log( target.length ); // 2
  383. * console.log( target.get( 0 ).value ); // 'foo'
  384. * console.log( target.get( 1 ).value ); // 'bar'
  385. *
  386. * It's possible to skip specified items by returning falsy value:
  387. *
  388. * const source = new Collection();
  389. * const target = new Collection();
  390. *
  391. * target.bindTo( source ).using( item => {
  392. * if ( item.hidden ) {
  393. * return null;
  394. * }
  395. *
  396. * return item;
  397. * } );
  398. *
  399. * source.add( { hidden: true } );
  400. * source.add( { hidden: false } );
  401. *
  402. * console.log( source.length ); // 2
  403. * console.log( target.length ); // 1
  404. *
  405. * **Note**: {@link #clear} can be used to break the binding.
  406. *
  407. * @param {module:utils/collection~Collection} externalCollection A collection to be bound.
  408. * @returns {Object}
  409. * @returns {module:utils/collection~CollectionBindToChain} The binding chain object.
  410. */
  411. bindTo( externalCollection ) {
  412. if ( this._bindToCollection ) {
  413. /**
  414. * The collection cannot be bound more than once.
  415. *
  416. * @error collection-bind-to-rebind
  417. */
  418. throw new CKEditorError( 'collection-bind-to-rebind: The collection cannot be bound more than once.', this );
  419. }
  420. this._bindToCollection = externalCollection;
  421. return {
  422. as: Class => {
  423. this._setUpBindToBinding( item => new Class( item ) );
  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 );
  565. /**
  566. * An object returned by the {@link module:utils/collection~Collection#bindTo `bindTo()`} method
  567. * providing functions that specify the type of the binding.
  568. *
  569. * See the {@link module:utils/collection~Collection#bindTo `bindTo()`} documentation for examples.
  570. *
  571. * @interface module:utils/collection~CollectionBindToChain
  572. */
  573. /**
  574. * Creates a callback or a property binding.
  575. *
  576. * @method #using
  577. * @param {Function|String} callbackOrProperty When the function is passed, it should return
  578. * the collection items. When the string is provided, the property value is used to create the bound collection items.
  579. */
  580. /**
  581. * Creates the class factory binding in which items of the source collection are passed to
  582. * the constructor of the specified class.
  583. *
  584. * @method #as
  585. * @param {Function} Class The class constructor used to create instances in the factory.
  586. */