imageuploadcommand.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /**
  2. * @license Copyright (c) 2003-2017, 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 './filerepository';
  9. import Command from '@ckeditor/ckeditor5-core/src/command';
  10. /**
  11. * @module upload/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 executed command.
  24. * @param {File} options.file Image file to upload.
  25. * @param {module:engine/model/position~Position} [options.insertAt] 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 UX perspective.
  29. */
  30. execute( options ) {
  31. const editor = this.editor;
  32. const doc = editor.model.document;
  33. const file = options.file;
  34. const selection = doc.selection;
  35. const fileRepository = editor.plugins.get( FileRepository );
  36. editor.model.change( () => {
  37. const loader = fileRepository.createLoader( file );
  38. // Do not throw when upload adapter is not set. FileRepository will log an error anyway.
  39. if ( !loader ) {
  40. return;
  41. }
  42. const imageElement = new ModelElement( 'image', {
  43. uploadId: loader.id
  44. } );
  45. let insertAtSelection;
  46. if ( options.insertAt ) {
  47. insertAtSelection = new ModelSelection( [ new ModelRange( options.insertAt ) ] );
  48. } else {
  49. insertAtSelection = doc.selection;
  50. }
  51. editor.data.insertContent( imageElement, insertAtSelection );
  52. // Inserting an image might've failed due to schema regulations.
  53. if ( imageElement.parent ) {
  54. selection.setRanges( [ ModelRange.createOn( imageElement ) ] );
  55. }
  56. } );
  57. }
  58. }