8
0

mediaembedcommand.js 2.0 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 position = selection.getFirstPosition();
  31. const selectedMedia = getSelectedMediaModelWidget( selection );
  32. let parent = position.parent;
  33. if ( parent != parent.root ) {
  34. parent = parent.parent;
  35. }
  36. this.value = selectedMedia ? selectedMedia.getAttribute( 'url' ) : null;
  37. this.isEnabled = schema.checkChild( parent, 'media' );
  38. }
  39. /**
  40. * Executes the command, which either:
  41. *
  42. * * updates the URL of the selected media,
  43. * * inserts the new media into the editor and puts the selection around it.
  44. *
  45. * @fires execute
  46. * @param {String} url The URL of the media.
  47. */
  48. execute( url ) {
  49. const model = this.editor.model;
  50. const selection = model.document.selection;
  51. const selectedMedia = getSelectedMediaModelWidget( selection );
  52. if ( selectedMedia ) {
  53. model.change( writer => {
  54. writer.setAttribute( 'url', url, selectedMedia );
  55. } );
  56. } else {
  57. const insertPosition = findOptimalInsertionPosition( selection, model );
  58. insertMedia( model, url, insertPosition );
  59. }
  60. }
  61. }