imageuploadediting.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. this.listenTo( editor.plugins.get( 'Clipboard' ), 'inputTransformation', ( evt, data ) => {
  86. const fetchableImages = Array.from( editor.editing.view.createRangeIn( data.content ) )
  87. .filter( value => isLocalImage( value.item ) && !value.item.getAttribute( 'uploadProcessed' ) )
  88. .map( value => fetchLocalImage( value.item ) );
  89. if ( !fetchableImages.length ) {
  90. return;
  91. }
  92. evt.stop();
  93. Promise.all( fetchableImages ).then( items => {
  94. const writer = new UpcastWriter();
  95. for ( const item of items ) {
  96. if ( !item.file ) {
  97. // Failed to fetch image or create a file instance, remove image element.
  98. writer.remove( item.image );
  99. } else {
  100. // Set attribute marking the image as processed.
  101. writer.setAttribute( 'uploadProcessed', true, item.image );
  102. const loader = fileRepository.createLoader( item.file );
  103. if ( loader ) {
  104. writer.setAttribute( 'src', '', item.image );
  105. writer.setAttribute( 'uploadId', loader.id, item.image );
  106. }
  107. }
  108. }
  109. editor.plugins.get( 'Clipboard' ).fire( 'inputTransformation', data );
  110. } );
  111. } );
  112. // Prevents from the browser redirecting to the dropped image.
  113. editor.editing.view.document.on( 'dragover', ( evt, data ) => {
  114. data.preventDefault();
  115. } );
  116. // Upload placeholder images that appeared in the model.
  117. doc.on( 'change', () => {
  118. const changes = doc.differ.getChanges( { includeChangesInGraveyard: true } );
  119. for ( const entry of changes ) {
  120. if ( entry.type == 'insert' && entry.name == 'image' ) {
  121. const item = entry.position.nodeAfter;
  122. const isInGraveyard = entry.position.root.rootName == '$graveyard';
  123. // Check if the image element still has upload id.
  124. const uploadId = item.getAttribute( 'uploadId' );
  125. if ( !uploadId ) {
  126. continue;
  127. }
  128. // Check if the image is loaded on this client.
  129. const loader = fileRepository.loaders.get( uploadId );
  130. if ( !loader ) {
  131. continue;
  132. }
  133. if ( isInGraveyard ) {
  134. // If the image was inserted to the graveyard - abort the loading process.
  135. loader.abort();
  136. } else if ( loader.status == 'idle' ) {
  137. // If the image was inserted into content and has not been loaded yet, start loading it.
  138. this._readAndUpload( loader, item );
  139. }
  140. }
  141. }
  142. } );
  143. }
  144. /**
  145. * Read and upload an image.
  146. *
  147. * The image is read from the disk and as a base64 encoded string it is set temporarily to
  148. * `image[src]`. When the image is successfully uploaded the temporary data is replaced with the target
  149. * image's URL (the URL to the uploaded image on the server).
  150. *
  151. * @protected
  152. * @param {module:upload/filerepository~FileLoader} loader
  153. * @param {module:engine/model/element~Element} imageElement
  154. * @returns {Promise}
  155. */
  156. _readAndUpload( loader, imageElement ) {
  157. const editor = this.editor;
  158. const model = editor.model;
  159. const t = editor.locale.t;
  160. const fileRepository = editor.plugins.get( FileRepository );
  161. const notification = editor.plugins.get( Notification );
  162. model.enqueueChange( 'transparent', writer => {
  163. writer.setAttribute( 'uploadStatus', 'reading', imageElement );
  164. } );
  165. return loader.read()
  166. .then( data => {
  167. const viewFigure = editor.editing.mapper.toViewElement( imageElement );
  168. const viewImg = viewFigure.getChild( 0 );
  169. const promise = loader.upload();
  170. editor.editing.view.change( writer => {
  171. writer.setAttribute( 'src', data, viewImg );
  172. } );
  173. model.enqueueChange( 'transparent', writer => {
  174. writer.setAttribute( 'uploadStatus', 'uploading', imageElement );
  175. } );
  176. return promise;
  177. } )
  178. .then( data => {
  179. model.enqueueChange( 'transparent', writer => {
  180. writer.setAttributes( { uploadStatus: 'complete', src: data.default }, imageElement );
  181. this._parseAndSetSrcsetAttributeOnImage( data, imageElement, writer );
  182. } );
  183. clean();
  184. } )
  185. .catch( error => {
  186. // If status is not 'error' nor 'aborted' - throw error because it means that something else went wrong,
  187. // it might be generic error and it would be real pain to find what is going on.
  188. if ( loader.status !== 'error' && loader.status !== 'aborted' ) {
  189. throw error;
  190. }
  191. // Might be 'aborted'.
  192. if ( loader.status == 'error' ) {
  193. notification.showWarning( error, {
  194. title: t( 'Upload failed' ),
  195. namespace: 'upload'
  196. } );
  197. }
  198. clean();
  199. // Permanently remove image from insertion batch.
  200. model.enqueueChange( 'transparent', writer => {
  201. writer.remove( imageElement );
  202. } );
  203. } );
  204. function clean() {
  205. model.enqueueChange( 'transparent', writer => {
  206. writer.removeAttribute( 'uploadId', imageElement );
  207. writer.removeAttribute( 'uploadStatus', imageElement );
  208. } );
  209. fileRepository.destroyLoader( loader );
  210. }
  211. }
  212. /**
  213. * Creates `srcset` attribute based on a given file upload response and sets it as an attribute to a specific image element.
  214. *
  215. * @protected
  216. * @param {Object} data Data object from which `srcset` will be created.
  217. * @param {module:engine/model/element~Element} image The image element on which `srcset` attribute will be set.
  218. * @param {module:engine/model/writer~Writer} writer
  219. */
  220. _parseAndSetSrcsetAttributeOnImage( data, image, writer ) {
  221. // Srcset attribute for responsive images support.
  222. let maxWidth = 0;
  223. const srcsetAttribute = Object.keys( data )
  224. // Filter out keys that are not integers.
  225. .filter( key => {
  226. const width = parseInt( key, 10 );
  227. if ( !isNaN( width ) ) {
  228. maxWidth = Math.max( maxWidth, width );
  229. return true;
  230. }
  231. } )
  232. // Convert each key to srcset entry.
  233. .map( key => `${ data[ key ] } ${ key }w` )
  234. // Join all entries.
  235. .join( ', ' );
  236. if ( srcsetAttribute != '' ) {
  237. writer.setAttribute( 'srcset', {
  238. data: srcsetAttribute,
  239. width: maxWidth
  240. }, image );
  241. }
  242. }
  243. }
  244. // Returns `true` if non-empty `text/html` is included in the data transfer.
  245. //
  246. // @param {module:clipboard/datatransfer~DataTransfer} dataTransfer
  247. // @returns {Boolean}
  248. export function isHtmlIncluded( dataTransfer ) {
  249. return Array.from( dataTransfer.types ).includes( 'text/html' ) && dataTransfer.getData( 'text/html' ) !== '';
  250. }