collection.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. /**
  2. * @license Copyright (c) 2003-2017, 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 EventEmitter
  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 && options.idProperty || 'id';
  53. /**
  54. * A helper mapping external items of a bound collection ({@link #bindTo})
  55. * and actual items of this collection.
  56. *
  57. * @protected
  58. * @member {Map}
  59. */
  60. this._bindToExternalToInternalMap = new Map();
  61. /**
  62. * A helper mapping items of this collection to external items of a bound collection
  63. * ({@link #bindTo}).
  64. *
  65. * @protected
  66. * @member {Map}
  67. */
  68. this._bindToInternalToExternalMap = new Map();
  69. /**
  70. * A collection instance this collection is bound to as a result
  71. * of calling {@link #bindTo} method.
  72. *
  73. * @protected
  74. * @member {module:utils/collection~Collection} #_bindToCollection
  75. */
  76. }
  77. /**
  78. * The number of items available in the collection.
  79. *
  80. * @member {Number} #length
  81. */
  82. get length() {
  83. return this._items.length;
  84. }
  85. /**
  86. * Adds an item into the collection.
  87. *
  88. * If the item does not have an id, then it will be automatically generated and set on the item.
  89. *
  90. * @chainable
  91. * @param {Object} item
  92. * @param {Number} [index] The position of the item in the collection. The item
  93. * is pushed to the collection when `index` not specified.
  94. * @fires add
  95. */
  96. add( item, index ) {
  97. let itemId;
  98. const idProperty = this._idProperty;
  99. if ( ( idProperty in item ) ) {
  100. itemId = item[ idProperty ];
  101. if ( typeof itemId != 'string' ) {
  102. /**
  103. * This item's id should be a string.
  104. *
  105. * @error collection-add-invalid-id
  106. */
  107. throw new CKEditorError( 'collection-add-invalid-id' );
  108. }
  109. if ( this.get( itemId ) ) {
  110. /**
  111. * This item already exists in the collection.
  112. *
  113. * @error collection-add-item-already-exists
  114. */
  115. throw new CKEditorError( 'collection-add-item-already-exists' );
  116. }
  117. } else {
  118. item[ idProperty ] = itemId = uid();
  119. }
  120. // TODO: Use ES6 default function argument.
  121. if ( index === undefined ) {
  122. index = this._items.length;
  123. } else if ( index > this._items.length || index < 0 ) {
  124. /**
  125. * The index number has invalid value.
  126. *
  127. * @error collection-add-item-bad-index
  128. */
  129. throw new CKEditorError( 'collection-add-item-invalid-index' );
  130. }
  131. this._items.splice( index, 0, item );
  132. this._itemMap.set( itemId, item );
  133. this.fire( 'add', item, index );
  134. return this;
  135. }
  136. /**
  137. * Gets item by its id or index.
  138. *
  139. * @param {String|Number} idOrIndex The item id or index in the collection.
  140. * @returns {Object} The requested item or `null` if such item does not exist.
  141. */
  142. get( idOrIndex ) {
  143. let item;
  144. if ( typeof idOrIndex == 'string' ) {
  145. item = this._itemMap.get( idOrIndex );
  146. } else if ( typeof idOrIndex == 'number' ) {
  147. item = this._items[ idOrIndex ];
  148. } else {
  149. /**
  150. * Index or id must be given.
  151. *
  152. * @error collection-get-invalid-arg
  153. */
  154. throw new CKEditorError( 'collection-get-invalid-arg: Index or id must be given.' );
  155. }
  156. return item || null;
  157. }
  158. /**
  159. * Gets index of item in the collection.
  160. * When item is not defined in the collection then index will be equal -1.
  161. *
  162. * @param {String|Object} idOrItem The item or its id in the collection.
  163. * @returns {Number} Index of given item.
  164. */
  165. getIndex( idOrItem ) {
  166. let item;
  167. if ( typeof idOrItem == 'string' ) {
  168. item = this._itemMap.get( idOrItem );
  169. } else {
  170. item = idOrItem;
  171. }
  172. return this._items.indexOf( item );
  173. }
  174. /**
  175. * Removes an item from the collection.
  176. *
  177. * @param {Object|Number|String} subject The item to remove, its id or index in the collection.
  178. * @returns {Object} The removed item.
  179. * @fires remove
  180. */
  181. remove( subject ) {
  182. let index, id, item;
  183. let itemDoesNotExist = false;
  184. const idProperty = this._idProperty;
  185. if ( typeof subject == 'string' ) {
  186. id = subject;
  187. item = this._itemMap.get( id );
  188. itemDoesNotExist = !item;
  189. if ( item ) {
  190. index = this._items.indexOf( item );
  191. }
  192. } else if ( typeof subject == 'number' ) {
  193. index = subject;
  194. item = this._items[ index ];
  195. itemDoesNotExist = !item;
  196. if ( item ) {
  197. id = item[ idProperty ];
  198. }
  199. } else {
  200. item = subject;
  201. id = item[ idProperty ];
  202. index = this._items.indexOf( item );
  203. itemDoesNotExist = ( index == -1 || !this._itemMap.get( id ) );
  204. }
  205. if ( itemDoesNotExist ) {
  206. /**
  207. * Item not found.
  208. *
  209. * @error collection-remove-404
  210. */
  211. throw new CKEditorError( 'collection-remove-404: Item not found.' );
  212. }
  213. this._items.splice( index, 1 );
  214. this._itemMap.delete( id );
  215. const externalItem = this._bindToInternalToExternalMap.get( item );
  216. this._bindToInternalToExternalMap.delete( item );
  217. this._bindToExternalToInternalMap.delete( externalItem );
  218. this.fire( 'remove', item );
  219. return item;
  220. }
  221. /**
  222. * Executes the callback for each item in the collection and composes an array or values returned by this callback.
  223. *
  224. * @param {Function} callback
  225. * @param {Object} callback.item
  226. * @param {Number} callback.index
  227. * @params {Object} ctx Context in which the `callback` will be called.
  228. * @returns {Array} The result of mapping.
  229. */
  230. map( callback, ctx ) {
  231. return this._items.map( callback, ctx );
  232. }
  233. /**
  234. * Finds the first item in the collection for which the `callback` returns a true value.
  235. *
  236. * @param {Function} callback
  237. * @param {Object} callback.item
  238. * @param {Number} callback.index
  239. * @returns {Object} The item for which `callback` returned a true value.
  240. * @params {Object} ctx Context in which the `callback` will be called.
  241. */
  242. find( callback, ctx ) {
  243. return this._items.find( callback, ctx );
  244. }
  245. /**
  246. * Returns an array with items for which the `callback` returned a true value.
  247. *
  248. * @param {Function} callback
  249. * @param {Object} callback.item
  250. * @param {Number} callback.index
  251. * @params {Object} ctx Context in which the `callback` will be called.
  252. * @returns {Object[]} The array with matching items.
  253. */
  254. filter( callback, ctx ) {
  255. return this._items.filter( callback, ctx );
  256. }
  257. /**
  258. * Removes all items from the collection and destroys the binding created using
  259. * {@link #bindTo}.
  260. */
  261. clear() {
  262. if ( this._bindToCollection ) {
  263. this.stopListening( this._bindToCollection );
  264. this._bindToCollection = null;
  265. }
  266. while ( this.length ) {
  267. this.remove( 0 );
  268. }
  269. }
  270. /**
  271. * Binds and synchronizes the collection with another one.
  272. *
  273. * The binding can be a simple factory:
  274. *
  275. * class FactoryClass {
  276. * constructor( data ) {
  277. * this.label = data.label;
  278. * }
  279. * }
  280. *
  281. * const source = new Collection( { idProperty: 'label' } );
  282. * const target = new Collection();
  283. *
  284. * target.bindTo( source ).as( FactoryClass );
  285. *
  286. * source.add( { label: 'foo' } );
  287. * source.add( { label: 'bar' } );
  288. *
  289. * console.log( target.length ); // 2
  290. * console.log( target.get( 1 ).label ); // 'bar'
  291. *
  292. * source.remove( 0 );
  293. * console.log( target.length ); // 1
  294. * console.log( target.get( 0 ).label ); // 'bar'
  295. *
  296. * or the factory driven by a custom callback:
  297. *
  298. * class FooClass {
  299. * constructor( data ) {
  300. * this.label = data.label;
  301. * }
  302. * }
  303. *
  304. * class BarClass {
  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 ).using( ( item ) => {
  314. * if ( item.label == 'foo' ) {
  315. * return new FooClass( item );
  316. * } else {
  317. * return new BarClass( item );
  318. * }
  319. * } );
  320. *
  321. * source.add( { label: 'foo' } );
  322. * source.add( { label: 'bar' } );
  323. *
  324. * console.log( target.length ); // 2
  325. * console.log( target.get( 0 ) instanceof FooClass ); // true
  326. * console.log( target.get( 1 ) instanceof BarClass ); // true
  327. *
  328. * or the factory out of property name:
  329. *
  330. * const source = new Collection( { idProperty: 'label' } );
  331. * const target = new Collection();
  332. *
  333. * target.bindTo( source ).using( 'label' );
  334. *
  335. * source.add( { label: { value: 'foo' } } );
  336. * source.add( { label: { value: 'bar' } } );
  337. *
  338. * console.log( target.length ); // 2
  339. * console.log( target.get( 0 ).value ); // 'foo'
  340. * console.log( target.get( 1 ).value ); // 'bar'
  341. *
  342. * **Note**: {@link #clear} can be used to break the binding.
  343. *
  344. * @param {module:utils/collection~Collection} collection A collection to be bound.
  345. * @returns {Object}
  346. * @returns {module:utils/collection~Collection#bindTo#as} return.as
  347. * @returns {module:utils/collection~Collection#bindTo#using} return.using
  348. */
  349. bindTo( externalCollection ) {
  350. if ( this._bindToCollection ) {
  351. /**
  352. * The collection cannot be bound more than once.
  353. *
  354. * @error collection-bind-to-rebind
  355. */
  356. throw new CKEditorError( 'collection-bind-to-rebind: The collection cannot be bound more than once.' );
  357. }
  358. this._bindToCollection = externalCollection;
  359. return {
  360. /**
  361. * Creates the class factory binding.
  362. *
  363. * @static
  364. * @param {Function} Class Specifies which class factory is to be initialized.
  365. */
  366. as: ( Class ) => {
  367. this._setUpBindToBinding( item => new Class( item ) );
  368. },
  369. /**
  370. * Creates callback or property binding.
  371. *
  372. * @static
  373. * @param {Function|String} callbackOrProperty When the function is passed, it is used to
  374. * produce the items. When the string is provided, the property value is used to create
  375. * the bound collection items.
  376. */
  377. using: ( callbackOrProperty ) => {
  378. if ( typeof callbackOrProperty == 'function' ) {
  379. this._setUpBindToBinding( item => callbackOrProperty( item ) );
  380. } else {
  381. this._setUpBindToBinding( item => item[ callbackOrProperty ] );
  382. }
  383. }
  384. };
  385. }
  386. /**
  387. * Finalizes and activates a binding initiated by {#bindTo}.
  388. *
  389. * @protected
  390. * @param {Function} factory A function which produces collection items.
  391. */
  392. _setUpBindToBinding( factory ) {
  393. const externalCollection = this._bindToCollection;
  394. // Adds the item to the collection once a change has been done to the external collection.
  395. //
  396. // @private
  397. const addItem = ( evt, externalItem, index ) => {
  398. const isExternalBoundToThis = externalCollection._bindToCollection == this;
  399. const externalItemBound = externalCollection._bindToInternalToExternalMap.get( externalItem );
  400. // If an external collection is bound to this collection, which makes it a 2–way binding,
  401. // and the particular external collection item is already bound, don't add it here.
  402. // The external item has been created **out of this collection's item** and (re)adding it will
  403. // cause a loop.
  404. if ( isExternalBoundToThis && externalItemBound ) {
  405. this._bindToExternalToInternalMap.set( externalItem, externalItemBound );
  406. this._bindToInternalToExternalMap.set( externalItemBound, externalItem );
  407. } else {
  408. const item = factory( externalItem );
  409. this._bindToExternalToInternalMap.set( externalItem, item );
  410. this._bindToInternalToExternalMap.set( item, externalItem );
  411. this.add( item, index );
  412. }
  413. };
  414. // Load the initial content of the collection.
  415. for ( let externalItem of externalCollection ) {
  416. addItem( null, externalItem );
  417. }
  418. // Synchronize the with collection as new items are added.
  419. this.listenTo( externalCollection, 'add', addItem );
  420. // Synchronize the with collection as new items are removed.
  421. this.listenTo( externalCollection, 'remove', ( evt, externalItem ) => {
  422. const item = this._bindToExternalToInternalMap.get( externalItem );
  423. if ( item ) {
  424. this.remove( item );
  425. }
  426. } );
  427. }
  428. /**
  429. * Collection iterator.
  430. */
  431. [ Symbol.iterator ]() {
  432. return this._items[ Symbol.iterator ]();
  433. }
  434. /**
  435. * Fired when an item is added to the collection.
  436. *
  437. * @event add
  438. * @param {Object} item The added item.
  439. */
  440. /**
  441. * Fired when an item is removed from the collection.
  442. *
  443. * @event remove
  444. * @param {Object} item The removed item.
  445. */
  446. }
  447. mix( Collection, EmitterMixin );