documentcolorcollection.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 font/documentcolorcollection
  7. */
  8. import Collection from '@ckeditor/ckeditor5-utils/src/collection';
  9. import ObservableMixin from '@ckeditor/ckeditor5-utils/src/observablemixin';
  10. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  11. /**
  12. * A collection to store document colors. It enforces colors to be unique.
  13. *
  14. * @mixes module:utils/observablemixin~ObservableMixin
  15. * @extends module:utils/collection~Collection
  16. */
  17. export default class DocumentColorCollection extends Collection {
  18. constructor( options ) {
  19. super( options );
  20. /**
  21. * Indicates whether the document color collection is empty.
  22. *
  23. * @observable
  24. * @readonly
  25. * @member {Boolean} #isEmpty
  26. */
  27. this.set( 'isEmpty', true );
  28. this.on( 'change', () => {
  29. this.set( 'isEmpty', this.length === 0 );
  30. } );
  31. }
  32. /**
  33. * Adds a color to the document color collection.
  34. *
  35. * This method ensures that no color duplicates are inserted (compared using
  36. * the color value of the {@link module:ui/colorgrid/colorgrid~ColorDefinition}).
  37. *
  38. * If the item does not have an ID, it will be automatically generated and set on the item.
  39. *
  40. * @chainable
  41. * @param {module:ui/colorgrid/colorgrid~ColorDefinition} item
  42. * @param {Number} [index] The position of the item in the collection. The item
  43. * is pushed to the collection when `index` is not specified.
  44. * @fires add
  45. * @fires change
  46. */
  47. add( item, index ) {
  48. if ( this.find( element => element.color === item.color ) ) {
  49. // No duplicates are allowed.
  50. return;
  51. }
  52. super.add( item, index );
  53. }
  54. /**
  55. * Checks if an object with given colors is present in the document color collection.
  56. *
  57. * @param {String} color
  58. * @returns {Boolean}
  59. */
  60. hasColor( color ) {
  61. return !!this.find( item => item.color === color );
  62. }
  63. }
  64. mix( DocumentColorCollection, ObservableMixin );