8
0

htmlembedcommand.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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/htmlembedcommand
  7. */
  8. import Command from '@ckeditor/ckeditor5-core/src/command';
  9. import { findOptimalInsertionPosition } from '@ckeditor/ckeditor5-widget/src/utils';
  10. import { getSelectedRawHtmlModelWidget, insertRawHtml } from './utils';
  11. /**
  12. * The HTML embed command.
  13. *
  14. * The command is registered by {@link module:html-embed/htmlembedediting~HTMLEmbedEditing} as `'htmlEmbed'`.
  15. *
  16. * To insert a HTML code at the current selection, execute the command:
  17. *
  18. * editor.execute( 'htmlEmbed', { html: 'HTML to insert.' } );
  19. *
  20. * @extends module:core/command~Command
  21. */
  22. export default class HTMLEmbedCommand extends Command {
  23. /**
  24. * @inheritDoc
  25. */
  26. refresh() {
  27. const model = this.editor.model;
  28. const selection = model.document.selection;
  29. const schema = model.schema;
  30. const insertPosition = findOptimalInsertionPosition( selection, model );
  31. const selectedRawHtml = getSelectedRawHtmlModelWidget( selection );
  32. let parent = insertPosition.parent;
  33. // The model.insertContent() will remove empty parent (unless it is a $root or a limit).
  34. if ( parent.isEmpty && !model.schema.isLimit( parent ) ) {
  35. parent = parent.parent;
  36. }
  37. this.value = selectedRawHtml ? selectedRawHtml.getAttribute( 'value' ) : null;
  38. this.isEnabled = schema.checkChild( parent, 'rawHtml' );
  39. }
  40. /**
  41. * Executes the command, which either:
  42. *
  43. * * updates the URL of the selected media,
  44. * * inserts the new media into the editor and puts the selection around it.
  45. *
  46. * @fires execute
  47. * @param {Object} [options={}] The command options.
  48. * @param {String} [options.rawHtml] A HTML string that will be inserted into the editor.
  49. * @param {module:engine/model/element~Element|null} [options.element] If present, the `value` attribute will be updated
  50. * with the specified `options.rawHtml` value. Otherwise, a new element will be inserted into the editor.
  51. */
  52. execute( options = {} ) {
  53. const model = this.editor.model;
  54. const rawHtml = options.rawHtml;
  55. const element = options.element;
  56. if ( element ) {
  57. model.change( writer => {
  58. writer.setAttribute( 'value', rawHtml, element );
  59. } );
  60. } else {
  61. insertRawHtml( model, rawHtml );
  62. }
  63. }
  64. }