imageuploadediting.js 11 KB

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