imagestylecommand.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module image/imagestyle/imagestylecommand
  7. */
  8. import Command from '@ckeditor/ckeditor5-core/src/command';
  9. import { isImage } from '../image/utils';
  10. /**
  11. * The image style command. It is used to apply different image styles.
  12. *
  13. * @extends module:core/command~Command
  14. */
  15. export default class ImageStyleCommand extends Command {
  16. /**
  17. * Creates instance of the image style command. Each command instance is handling one style.
  18. *
  19. * @param {module:core/editor/editor~Editor} editor Editor instance.
  20. * @param {module:image/imagestyle/imagestyleengine~ImageStyleFormat} styles Style to apply by this command.
  21. */
  22. constructor( editor, style ) {
  23. super( editor );
  24. /**
  25. * The value of the command - `true` if style handled by the command is applied on currently selected image,
  26. * `false` otherwise.
  27. *
  28. * @readonly
  29. * @observable
  30. * @member {Boolean} #value
  31. */
  32. /**
  33. * Style handled by this command.
  34. *
  35. * @readonly
  36. * @member {module:image/imagestyle/imagestyleengine~ImageStyleFormat} #style
  37. */
  38. this.style = style;
  39. }
  40. /**
  41. * @inheritDoc
  42. */
  43. refresh() {
  44. const element = this.editor.document.selection.getSelectedElement();
  45. this.isEnabled = isImage( element );
  46. if ( !element ) {
  47. this.value = false;
  48. } else if ( this.style.value === null ) {
  49. this.value = !element.hasAttribute( 'imageStyle' );
  50. } else {
  51. this.value = ( element.getAttribute( 'imageStyle' ) == this.style.value );
  52. }
  53. }
  54. /**
  55. * Executes command.
  56. *
  57. * @fires execute
  58. * @param {Object} options
  59. * @param {module:engine/model/batch~Batch} [options.batch] Batch to collect all the change steps. New batch will be
  60. * created if this option is not set.
  61. */
  62. execute( options = {} ) {
  63. if ( this.value ) {
  64. return;
  65. }
  66. const doc = this.editor.document;
  67. const imageElement = doc.selection.getSelectedElement();
  68. doc.enqueueChanges( () => {
  69. const batch = options.batch || doc.batch();
  70. batch.setAttribute( imageElement, 'imageStyle', this.style.value );
  71. } );
  72. }
  73. }