documentcolorcollection.js 1.9 KB

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