8
0

imageuploadcommand.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. import ModelDocumentFragment from '@ckeditor/ckeditor5-engine/src/model/documentfragment';
  6. import ModelElement from '@ckeditor/ckeditor5-engine/src/model/element';
  7. import ModelRange from '@ckeditor/ckeditor5-engine/src/model/range';
  8. import ModelSelection from '@ckeditor/ckeditor5-engine/src/model/selection';
  9. import FileRepository from './filerepository';
  10. import { isImageType } from './utils';
  11. import Command from '@ckeditor/ckeditor5-core/src/command/command';
  12. /**
  13. * Image upload command.
  14. *
  15. * @extends module:core/command/command~Command
  16. */
  17. export default class ImageUploadCommand extends Command {
  18. /**
  19. * Executes command.
  20. *
  21. * @protected
  22. * @param {Object} options Options for executed command.
  23. * @param {File} options.file Image file to upload.
  24. * @param {module:engine/model/batch~Batch} [options.batch] Batch to collect all the change steps.
  25. * New batch will be created if this option is not set.
  26. */
  27. _doExecute( options = {} ) {
  28. const editor = this.editor;
  29. const doc = editor.document;
  30. const batch = options.batch || doc.batch();
  31. const file = options.file;
  32. const fileRepository = editor.plugins.get( FileRepository );
  33. if ( !isImageType( file ) ) {
  34. return;
  35. }
  36. doc.enqueueChanges( () => {
  37. const imageElement = new ModelElement( 'image', {
  38. uploadId: fileRepository.createLoader( file ).id
  39. } );
  40. const documentFragment = new ModelDocumentFragment( [ imageElement ] );
  41. const firstBlock = doc.selection.getSelectedBlocks().next().value;
  42. const range = ModelRange.createFromParentsAndOffsets( firstBlock, 0, firstBlock, 0 );
  43. const insertSelection = new ModelSelection();
  44. insertSelection.setRanges( [ range ] );
  45. editor.data.insertContent( documentFragment, insertSelection, batch );
  46. } );
  47. }
  48. }