8
0

updatehtmlembedcommand.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 html-embed/updatehtmlembedcommand
  7. */
  8. import Command from '@ckeditor/ckeditor5-core/src/command';
  9. /**
  10. * The update HTML embed value command.
  11. *
  12. * The command is registered by {@link module:html-embed/htmlembedediting~HtmlEmbedEditing} as `'updateHtmlEmbed'`.
  13. *
  14. * To update the value of the HTML embed element at the current selection, execute the command:
  15. *
  16. * editor.execute( 'updateHtmlEmbed', '<b>HTML.</b>' );
  17. *
  18. * @extends module:core/command~Command
  19. */
  20. export default class UpdateHtmlEmbedCommand extends Command {
  21. /**
  22. * @inheritDoc
  23. */
  24. refresh() {
  25. const model = this.editor.model;
  26. const selection = model.document.selection;
  27. const rawHtmlElement = getSelectedRawHtmlModelWidget( selection );
  28. this.isEnabled = !!rawHtmlElement;
  29. }
  30. /**
  31. * Executes the command, which updates the `value` attribute of the embedded HTML element:
  32. *
  33. * @fires execute
  34. * @param {String} value HTML as a string.
  35. */
  36. execute( value ) {
  37. const model = this.editor.model;
  38. const selection = model.document.selection;
  39. const selectedRawHtmlElement = getSelectedRawHtmlModelWidget( selection );
  40. model.change( writer => {
  41. writer.setAttribute( 'value', value, selectedRawHtmlElement );
  42. } );
  43. }
  44. }
  45. // Returns the selected HTML embed element in the model, if any.
  46. //
  47. // @param {module:engine/model/selection~Selection} selection
  48. // @returns {module:engine/model/element~Element|null}
  49. function getSelectedRawHtmlModelWidget( selection ) {
  50. const selectedElement = selection.getSelectedElement();
  51. if ( selectedElement && selectedElement.is( 'element', 'rawHtml' ) ) {
  52. return selectedElement;
  53. }
  54. return null;
  55. }