imageuploadcommand.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. import ModelElement from '@ckeditor/ckeditor5-engine/src/model/element';
  6. import ModelRange from '@ckeditor/ckeditor5-engine/src/model/range';
  7. import ModelSelection from '@ckeditor/ckeditor5-engine/src/model/selection';
  8. import FileRepository from '@ckeditor/ckeditor5-upload/src/filerepository';
  9. import Command from '@ckeditor/ckeditor5-core/src/command';
  10. /**
  11. * @module image/imageupload/imageuploadcommand
  12. */
  13. /**
  14. * Image upload command.
  15. *
  16. * @extends module:core/command~Command
  17. */
  18. export default class ImageUploadCommand extends Command {
  19. /**
  20. * Executes the command.
  21. *
  22. * @fires execute
  23. * @param {Object} options Options for the executed command.
  24. * @param {File} options.file The image file to upload.
  25. * @param {module:engine/model/position~Position} [options.insertAt] The position at which the image should be inserted.
  26. * If the position is not specified, the image will be inserted into the current selection.
  27. * Note: You can use the {@link module:upload/utils~findOptimalInsertionPosition} function to calculate
  28. * (e.g. based on the current selection) a position which is more optimal from the UX perspective.
  29. */
  30. execute( options ) {
  31. const editor = this.editor;
  32. const doc = editor.model.document;
  33. const file = options.file;
  34. const fileRepository = editor.plugins.get( FileRepository );
  35. editor.model.change( writer => {
  36. const loader = fileRepository.createLoader( file );
  37. // Do not throw when upload adapter is not set. FileRepository will log an error anyway.
  38. if ( !loader ) {
  39. return;
  40. }
  41. const imageElement = new ModelElement( 'image', {
  42. uploadId: loader.id
  43. } );
  44. let insertAtSelection;
  45. if ( options.insertAt ) {
  46. insertAtSelection = new ModelSelection( [ new ModelRange( options.insertAt ) ] );
  47. } else {
  48. insertAtSelection = doc.selection;
  49. }
  50. editor.model.insertContent( imageElement, insertAtSelection );
  51. // Inserting an image might've failed due to schema regulations.
  52. if ( imageElement.parent ) {
  53. writer.setSelection( ModelRange.createOn( imageElement ) );
  54. }
  55. } );
  56. }
  57. }