imagealternatetextcommand.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module image/imagelaternatetext/imagealternatetextcommand
  7. */
  8. import Command from 'ckeditor5-core/src/command/command';
  9. import { isImage } from '../utils';
  10. /**
  11. * The image alternate text command. It is used to change `alt` attribute on `image` elements.
  12. *
  13. * @extends module:core/command/command~Command
  14. */
  15. export default class ImageAlternateTextCommand extends Command {
  16. /**
  17. * @inheritDoc
  18. */
  19. constructor( editor ) {
  20. super( editor );
  21. /**
  22. * The current command value - `false` if there is no `alt` attribute, otherwise contains string with `alt`
  23. * attribute value.
  24. *
  25. * @readonly
  26. * @observable
  27. * @member {String|Boolean} #value
  28. */
  29. this.set( 'value', false );
  30. // Update current value and refresh state each time something change in model document.
  31. this.listenTo( editor.document, 'changesDone', () => {
  32. this._updateValue();
  33. this.refreshState();
  34. } );
  35. }
  36. /**
  37. * Updates command's value.
  38. *
  39. * @private
  40. */
  41. _updateValue() {
  42. const doc = this.editor.document;
  43. const element = doc.selection.getSelectedElement();
  44. if ( isImage( element ) && element.hasAttribute( 'alt' ) ) {
  45. this.value = element.getAttribute( 'alt' );
  46. } else {
  47. this.value = false;
  48. }
  49. }
  50. /**
  51. * @inheritDoc
  52. */
  53. _checkEnabled() {
  54. const element = this.editor.document.selection.getSelectedElement();
  55. return isImage( element );
  56. }
  57. /**
  58. * Executes command.
  59. *
  60. * @protected
  61. * @param {Object} options
  62. * @param {String} options.newValue New value of `alt` attribute to set.
  63. * @param {module:engine/model/batch~Batch} [options.batch] Batch to collect all the change steps. New batch will be
  64. * created if this option is not set.
  65. */
  66. _doExecute( options ) {
  67. const editor = this.editor;
  68. const doc = editor.document;
  69. const imageElement = doc.selection.getSelectedElement();
  70. doc.enqueueChanges( () => {
  71. const batch = options.batch || doc.batch();
  72. batch.setAttribute( imageElement, 'alt', options.newValue );
  73. } );
  74. }
  75. }