imageuploadediting.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module image/imageupload/imageuploadediting
  7. */
  8. import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
  9. import FileRepository from '@ckeditor/ckeditor5-upload/src/filerepository';
  10. import Notification from '@ckeditor/ckeditor5-ui/src/notification/notification';
  11. import UpcastWriter from '@ckeditor/ckeditor5-engine/src/view/upcastwriter';
  12. import { upcastAttributeToAttribute } from '@ckeditor/ckeditor5-engine/src/conversion/upcast-converters';
  13. import ImageUploadCommand from '../../src/imageupload/imageuploadcommand';
  14. import { isImageType, isLocalImage, fetchLocalImage } from '../../src/imageupload/utils';
  15. /**
  16. * The editing part of the image upload feature. It registers the `'imageUpload'` command.
  17. *
  18. * @extends module:core/plugin~Plugin
  19. */
  20. export default class ImageUploadEditing extends Plugin {
  21. /**
  22. * @inheritDoc
  23. */
  24. static get requires() {
  25. return [ FileRepository, Notification ];
  26. }
  27. /**
  28. * @inheritDoc
  29. */
  30. init() {
  31. const editor = this.editor;
  32. const doc = editor.model.document;
  33. const schema = editor.model.schema;
  34. const conversion = editor.conversion;
  35. const fileRepository = editor.plugins.get( FileRepository );
  36. // Setup schema to allow uploadId and uploadStatus for images.
  37. schema.extend( 'image', {
  38. allowAttributes: [ 'uploadId', 'uploadStatus' ]
  39. } );
  40. // Register imageUpload command.
  41. editor.commands.add( 'imageUpload', new ImageUploadCommand( editor ) );
  42. // Register upcast converter for uploadId.
  43. conversion.for( 'upcast' )
  44. .add( upcastAttributeToAttribute( {
  45. view: {
  46. name: 'img',
  47. key: 'uploadId'
  48. },
  49. model: 'uploadId'
  50. } ) );
  51. // Handle pasted images.
  52. // For every image file, a new file loader is created and a placeholder image is
  53. // inserted into the content. Then, those images are uploaded once they appear in the model
  54. // (see Document#change listener below).
  55. this.listenTo( editor.editing.view.document, 'clipboardInput', ( evt, data ) => {
  56. // Skip if non empty HTML data is included.
  57. // https://github.com/ckeditor/ckeditor5-upload/issues/68
  58. if ( isHtmlIncluded( data.dataTransfer ) ) {
  59. return;
  60. }
  61. const images = Array.from( data.dataTransfer.files ).filter( file => {
  62. // See https://github.com/ckeditor/ckeditor5-image/pull/254.
  63. if ( !file ) {
  64. return false;
  65. }
  66. return isImageType( file );
  67. } );
  68. const ranges = data.targetRanges.map( viewRange => editor.editing.mapper.toModelRange( viewRange ) );
  69. editor.model.change( writer => {
  70. // Set selection to paste target.
  71. writer.setSelection( ranges );
  72. if ( images.length ) {
  73. evt.stop();
  74. // Upload images after the selection has changed in order to ensure the command's state is refreshed.
  75. editor.model.enqueueChange( 'default', () => {
  76. editor.execute( 'imageUpload', { file: images } );
  77. } );
  78. }
  79. } );
  80. } );
  81. // Handle HTML pasted with images with base64 or blob sources.
  82. // For every image file, a new file loader is created and a placeholder image is
  83. // inserted into the content. Then, those images are uploaded once they appear in the model
  84. // (see Document#change listener below).
  85. if ( editor.plugins.has( 'Clipboard' ) ) {
  86. this.listenTo( editor.plugins.get( 'Clipboard' ), 'inputTransformation', ( evt, data ) => {
  87. const fetchableImages = Array.from( editor.editing.view.createRangeIn( data.content ) )
  88. .filter( value => isLocalImage( value.item ) && !value.item.getAttribute( 'uploadProcessed' ) )
  89. .map( value => fetchLocalImage( value.item ) );
  90. if ( !fetchableImages.length ) {
  91. return;
  92. }
  93. evt.stop();
  94. Promise.all( fetchableImages ).then( items => {
  95. const writer = new UpcastWriter();
  96. for ( const item of items ) {
  97. if ( !item.file ) {
  98. // Failed to fetch image or create a file instance, remove image element.
  99. writer.remove( item.image );
  100. } else {
  101. // Set attribute marking the image as processed.
  102. writer.setAttribute( 'uploadProcessed', true, item.image );
  103. const loader = fileRepository.createLoader( item.file );
  104. if ( loader ) {
  105. writer.setAttribute( 'src', '', item.image );
  106. writer.setAttribute( 'uploadId', loader.id, item.image );
  107. }
  108. }
  109. }
  110. editor.plugins.get( 'Clipboard' ).fire( 'inputTransformation', data );
  111. } );
  112. } );
  113. }
  114. // Prevents from the browser redirecting to the dropped image.
  115. editor.editing.view.document.on( 'dragover', ( evt, data ) => {
  116. data.preventDefault();
  117. } );
  118. // Upload placeholder images that appeared in the model.
  119. doc.on( 'change', () => {
  120. const changes = doc.differ.getChanges( { includeChangesInGraveyard: true } );
  121. for ( const entry of changes ) {
  122. if ( entry.type == 'insert' && entry.name == 'image' ) {
  123. const item = entry.position.nodeAfter;
  124. const isInGraveyard = entry.position.root.rootName == '$graveyard';
  125. // Check if the image element still has upload id.
  126. const uploadId = item.getAttribute( 'uploadId' );
  127. if ( !uploadId ) {
  128. continue;
  129. }
  130. // Check if the image is loaded on this client.
  131. const loader = fileRepository.loaders.get( uploadId );
  132. if ( !loader ) {
  133. continue;
  134. }
  135. if ( isInGraveyard ) {
  136. // If the image was inserted to the graveyard - abort the loading process.
  137. loader.abort();
  138. } else if ( loader.status == 'idle' ) {
  139. // If the image was inserted into content and has not been loaded yet, start loading it.
  140. this._readAndUpload( loader, item );
  141. }
  142. }
  143. }
  144. } );
  145. }
  146. /**
  147. * Read and upload an image.
  148. *
  149. * The image is read from the disk and as a base64 encoded string it is set temporarily to
  150. * `image[src]`. When the image is successfully uploaded the temporary data is replaced with the target
  151. * image's URL (the URL to the uploaded image on the server).
  152. *
  153. * @protected
  154. * @param {module:upload/filerepository~FileLoader} loader
  155. * @param {module:engine/model/element~Element} imageElement
  156. * @returns {Promise}
  157. */
  158. _readAndUpload( loader, imageElement ) {
  159. const editor = this.editor;
  160. const model = editor.model;
  161. const t = editor.locale.t;
  162. const fileRepository = editor.plugins.get( FileRepository );
  163. const notification = editor.plugins.get( Notification );
  164. model.enqueueChange( 'transparent', writer => {
  165. writer.setAttribute( 'uploadStatus', 'reading', imageElement );
  166. } );
  167. return loader.read()
  168. .then( data => {
  169. const viewFigure = editor.editing.mapper.toViewElement( imageElement );
  170. const viewImg = viewFigure.getChild( 0 );
  171. const promise = loader.upload();
  172. editor.editing.view.change( writer => {
  173. writer.setAttribute( 'src', data, viewImg );
  174. } );
  175. model.enqueueChange( 'transparent', writer => {
  176. writer.setAttribute( 'uploadStatus', 'uploading', imageElement );
  177. } );
  178. return promise;
  179. } )
  180. .then( data => {
  181. model.enqueueChange( 'transparent', writer => {
  182. writer.setAttributes( { uploadStatus: 'complete', src: data.default }, imageElement );
  183. this._parseAndSetSrcsetAttributeOnImage( data, imageElement, writer );
  184. } );
  185. clean();
  186. } )
  187. .catch( error => {
  188. // If status is not 'error' nor 'aborted' - throw error because it means that something else went wrong,
  189. // it might be generic error and it would be real pain to find what is going on.
  190. if ( loader.status !== 'error' && loader.status !== 'aborted' ) {
  191. throw error;
  192. }
  193. // Might be 'aborted'.
  194. if ( loader.status == 'error' ) {
  195. notification.showWarning( error, {
  196. title: t( 'Upload failed' ),
  197. namespace: 'upload'
  198. } );
  199. }
  200. clean();
  201. // Permanently remove image from insertion batch.
  202. model.enqueueChange( 'transparent', writer => {
  203. writer.remove( imageElement );
  204. } );
  205. } );
  206. function clean() {
  207. model.enqueueChange( 'transparent', writer => {
  208. writer.removeAttribute( 'uploadId', imageElement );
  209. writer.removeAttribute( 'uploadStatus', imageElement );
  210. } );
  211. fileRepository.destroyLoader( loader );
  212. }
  213. }
  214. /**
  215. * Creates `srcset` attribute based on a given file upload response and sets it as an attribute to a specific image element.
  216. *
  217. * @protected
  218. * @param {Object} data Data object from which `srcset` will be created.
  219. * @param {module:engine/model/element~Element} image The image element on which `srcset` attribute will be set.
  220. * @param {module:engine/model/writer~Writer} writer
  221. */
  222. _parseAndSetSrcsetAttributeOnImage( data, image, writer ) {
  223. // Srcset attribute for responsive images support.
  224. let maxWidth = 0;
  225. const srcsetAttribute = Object.keys( data )
  226. // Filter out keys that are not integers.
  227. .filter( key => {
  228. const width = parseInt( key, 10 );
  229. if ( !isNaN( width ) ) {
  230. maxWidth = Math.max( maxWidth, width );
  231. return true;
  232. }
  233. } )
  234. // Convert each key to srcset entry.
  235. .map( key => `${ data[ key ] } ${ key }w` )
  236. // Join all entries.
  237. .join( ', ' );
  238. if ( srcsetAttribute != '' ) {
  239. writer.setAttribute( 'srcset', {
  240. data: srcsetAttribute,
  241. width: maxWidth
  242. }, image );
  243. }
  244. }
  245. }
  246. // Returns `true` if non-empty `text/html` is included in the data transfer.
  247. //
  248. // @param {module:clipboard/datatransfer~DataTransfer} dataTransfer
  249. // @returns {Boolean}
  250. export function isHtmlIncluded( dataTransfer ) {
  251. return Array.from( dataTransfer.types ).includes( 'text/html' ) && dataTransfer.getData( 'text/html' ) !== '';
  252. }