mediaembedcommand.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 media-embed/mediaembedcommand
  7. */
  8. import Command from '@ckeditor/ckeditor5-core/src/command';
  9. import { findOptimalInsertionPosition } from '@ckeditor/ckeditor5-widget/src/utils';
  10. import { getSelectedMediaModelWidget, insertMedia } from './utils';
  11. /**
  12. * The insert media command.
  13. *
  14. * The command is registered by the {@link module:media-embed/mediaembedediting~MediaEmbedEditing} as `'mediaEmbed'`.
  15. *
  16. * To insert media at the current selection, execute the command and specify the URL:
  17. *
  18. * editor.execute( 'mediaEmbed', 'http://url.to.the/media' );
  19. *
  20. * @extends module:core/command~Command
  21. */
  22. export default class MediaEmbedCommand 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 selectedMedia = getSelectedMediaModelWidget( 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 = selectedMedia ? selectedMedia.getAttribute( 'url' ) : null;
  38. this.isEnabled = schema.checkChild( parent, 'media' );
  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 {String} url The URL of the media.
  48. */
  49. execute( url ) {
  50. const model = this.editor.model;
  51. const selection = model.document.selection;
  52. const selectedMedia = getSelectedMediaModelWidget( selection );
  53. if ( selectedMedia ) {
  54. model.change( writer => {
  55. writer.setAttribute( 'url', url, selectedMedia );
  56. } );
  57. } else {
  58. const insertPosition = findOptimalInsertionPosition( selection, model );
  59. insertMedia( model, url, insertPosition );
  60. }
  61. }
  62. }