documentcolorcollection.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. }
  29. /**
  30. * Adds a color to the document color collection.
  31. *
  32. * This method ensures that no color duplicates are inserted (compared using
  33. * the color value of the {@link module:ui/colorgrid/colorgrid~ColorDefinition}).
  34. *
  35. * If the item does not have an ID, it will be automatically generated and set on the item.
  36. *
  37. * @chainable
  38. * @param {module:ui/colorgrid/colorgrid~ColorDefinition} item
  39. * @param {Number} [index] The position of the item in the collection. The item
  40. * is pushed to the collection when `index` is not specified.
  41. * @fires add
  42. */
  43. add( item, index ) {
  44. if ( this.find( element => element.color === item.color ) ) {
  45. // No duplicates are allowed.
  46. return;
  47. }
  48. super.add( item, index );
  49. this.set( 'isEmpty', false );
  50. }
  51. /**
  52. * @inheritdoc
  53. */
  54. remove( subject ) {
  55. const ret = super.remove( subject );
  56. if ( this.length === 0 ) {
  57. this.set( 'isEmpty', true );
  58. }
  59. return ret;
  60. }
  61. /**
  62. * Checks if an object with given colors is present in the document color collection.
  63. *
  64. * @param {String} color
  65. * @returns {Boolean}
  66. */
  67. hasColor( color ) {
  68. return !!this.find( item => item.color === color );
  69. }
  70. }
  71. mix( DocumentColorCollection, ObservableMixin );