imageuploadediting.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /* globals window, setTimeout */
  6. import VirtualTestEditor from '@ckeditor/ckeditor5-core/tests/_utils/virtualtesteditor';
  7. import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
  8. import ImageEditing from '../../src/image/imageediting';
  9. import ImageUploadEditing from '../../src/imageupload/imageuploadediting';
  10. import ImageUploadCommand from '../../src/imageupload/imageuploadcommand';
  11. import Paragraph from '@ckeditor/ckeditor5-paragraph/src/paragraph';
  12. import UndoEditing from '@ckeditor/ckeditor5-undo/src/undoediting';
  13. import DataTransfer from '@ckeditor/ckeditor5-clipboard/src/datatransfer';
  14. import FileRepository from '@ckeditor/ckeditor5-upload/src/filerepository';
  15. import { UploadAdapterMock, createNativeFileMock, NativeFileReaderMock } from '@ckeditor/ckeditor5-upload/tests/_utils/mocks';
  16. import { setData as setModelData, getData as getModelData } from '@ckeditor/ckeditor5-engine/src/dev-utils/model';
  17. import { getData as getViewData } from '@ckeditor/ckeditor5-engine/src/dev-utils/view';
  18. import Range from '@ckeditor/ckeditor5-engine/src/model/range';
  19. import Position from '@ckeditor/ckeditor5-engine/src/model/position';
  20. import testUtils from '@ckeditor/ckeditor5-core/tests/_utils/utils';
  21. import Notification from '@ckeditor/ckeditor5-ui/src/notification/notification';
  22. describe( 'ImageUploadEditing', () => {
  23. // eslint-disable-next-line max-len
  24. const base64Sample = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=';
  25. let editor, model, view, doc, fileRepository, viewDocument, nativeReaderMock, loader, adapterMock;
  26. testUtils.createSinonSandbox();
  27. class UploadAdapterPluginMock extends Plugin {
  28. init() {
  29. fileRepository = this.editor.plugins.get( FileRepository );
  30. fileRepository.createUploadAdapter = newLoader => {
  31. loader = newLoader;
  32. adapterMock = new UploadAdapterMock( loader );
  33. return adapterMock;
  34. };
  35. }
  36. }
  37. beforeEach( () => {
  38. testUtils.sinon.stub( window, 'FileReader' ).callsFake( () => {
  39. nativeReaderMock = new NativeFileReaderMock();
  40. return nativeReaderMock;
  41. } );
  42. return VirtualTestEditor
  43. .create( {
  44. plugins: [ ImageEditing, ImageUploadEditing, Paragraph, UndoEditing, UploadAdapterPluginMock ]
  45. } )
  46. .then( newEditor => {
  47. editor = newEditor;
  48. model = editor.model;
  49. doc = model.document;
  50. view = editor.editing.view;
  51. viewDocument = view.document;
  52. } );
  53. } );
  54. it( 'should register proper schema rules', () => {
  55. expect( model.schema.checkAttribute( [ '$root', 'image' ], 'uploadId' ) ).to.be.true;
  56. } );
  57. it( 'should register imageUpload command', () => {
  58. expect( editor.commands.get( 'imageUpload' ) ).to.be.instanceOf( ImageUploadCommand );
  59. } );
  60. it( 'should execute imageUpload command when image is pasted', () => {
  61. const spy = sinon.spy( editor, 'execute' );
  62. const fileMock = createNativeFileMock();
  63. const dataTransfer = new DataTransfer( { files: [ fileMock ], types: [ 'Files' ] } );
  64. setModelData( model, '<paragraph>[]foo</paragraph>' );
  65. const targetRange = Range.createFromParentsAndOffsets( doc.getRoot(), 1, doc.getRoot(), 1 );
  66. const targetViewRange = editor.editing.mapper.toViewRange( targetRange );
  67. viewDocument.fire( 'clipboardInput', { dataTransfer, targetRanges: [ targetViewRange ] } );
  68. sinon.assert.calledOnce( spy );
  69. sinon.assert.calledWith( spy, 'imageUpload' );
  70. const id = fileRepository.getLoader( fileMock ).id;
  71. expect( getModelData( model ) ).to.equal(
  72. `<paragraph>foo</paragraph>[<image uploadId="${ id }" uploadStatus="reading"></image>]`
  73. );
  74. } );
  75. it( 'should execute imageUpload command with an optimized position when image is pasted', () => {
  76. const spy = sinon.spy( editor, 'execute' );
  77. const fileMock = createNativeFileMock();
  78. const dataTransfer = new DataTransfer( { files: [ fileMock ], types: [ 'Files' ] } );
  79. setModelData( model, '<paragraph>[]foo</paragraph>' );
  80. const paragraph = doc.getRoot().getChild( 0 );
  81. const targetRange = Range.createFromParentsAndOffsets( paragraph, 1, paragraph, 1 ); // f[]oo
  82. const targetViewRange = editor.editing.mapper.toViewRange( targetRange );
  83. viewDocument.fire( 'clipboardInput', { dataTransfer, targetRanges: [ targetViewRange ] } );
  84. sinon.assert.calledOnce( spy );
  85. sinon.assert.calledWith( spy, 'imageUpload' );
  86. const id = fileRepository.getLoader( fileMock ).id;
  87. expect( getModelData( model ) ).to.equal(
  88. `[<image uploadId="${ id }" uploadStatus="reading"></image>]<paragraph>foo</paragraph>`
  89. );
  90. } );
  91. it( 'should execute imageUpload command when multiple files image are pasted', () => {
  92. const spy = sinon.spy( editor, 'execute' );
  93. const files = [ createNativeFileMock(), createNativeFileMock() ];
  94. const dataTransfer = new DataTransfer( { files, types: [ 'Files' ] } );
  95. setModelData( model, '<paragraph>[]foo</paragraph>' );
  96. const targetRange = Range.createFromParentsAndOffsets( doc.getRoot(), 1, doc.getRoot(), 1 );
  97. const targetViewRange = editor.editing.mapper.toViewRange( targetRange );
  98. viewDocument.fire( 'clipboardInput', { dataTransfer, targetRanges: [ targetViewRange ] } );
  99. sinon.assert.calledTwice( spy );
  100. sinon.assert.calledWith( spy, 'imageUpload' );
  101. const id1 = fileRepository.getLoader( files[ 0 ] ).id;
  102. const id2 = fileRepository.getLoader( files[ 1 ] ).id;
  103. expect( getModelData( model ) ).to.equal(
  104. '<paragraph>foo</paragraph>' +
  105. `<image uploadId="${ id1 }" uploadStatus="reading"></image>` +
  106. `[<image uploadId="${ id2 }" uploadStatus="reading"></image>]`
  107. );
  108. } );
  109. it( 'should not execute imageUpload command when file is not an image', () => {
  110. const spy = sinon.spy( editor, 'execute' );
  111. const viewDocument = editor.editing.view.document;
  112. const fileMock = {
  113. type: 'media/mp3',
  114. size: 1024
  115. };
  116. const dataTransfer = new DataTransfer( { files: [ fileMock ], types: [ 'Files' ] } );
  117. setModelData( model, '<paragraph>foo[]</paragraph>' );
  118. const targetRange = Range.createFromParentsAndOffsets( doc.getRoot(), 1, doc.getRoot(), 1 );
  119. const targetViewRange = editor.editing.mapper.toViewRange( targetRange );
  120. viewDocument.fire( 'clipboardInput', { dataTransfer, targetRanges: [ targetViewRange ] } );
  121. sinon.assert.notCalled( spy );
  122. } );
  123. it( 'should not execute imageUpload command when there is non-empty HTML content pasted', () => {
  124. const spy = sinon.spy( editor, 'execute' );
  125. const fileMock = createNativeFileMock();
  126. const dataTransfer = new DataTransfer( {
  127. files: [ fileMock ],
  128. types: [ 'Files', 'text/html' ],
  129. getData: type => type === 'text/html' ? '<p>SomeData</p>' : ''
  130. } );
  131. setModelData( model, '<paragraph>[]foo</paragraph>' );
  132. const targetRange = Range.createFromParentsAndOffsets( doc.getRoot(), 1, doc.getRoot(), 1 );
  133. const targetViewRange = editor.editing.mapper.toViewRange( targetRange );
  134. viewDocument.fire( 'clipboardInput', { dataTransfer, targetRanges: [ targetViewRange ] } );
  135. sinon.assert.notCalled( spy );
  136. } );
  137. // https://github.com/ckeditor/ckeditor5-upload/issues/70
  138. it( 'should not crash on browsers which do not implement DOMStringList as a child class of an Array', () => {
  139. const typesDomStringListMock = {
  140. length: 2,
  141. '0': 'text/html',
  142. '1': 'text/plain'
  143. };
  144. const dataTransfer = new DataTransfer( {
  145. types: typesDomStringListMock,
  146. getData: type => type === 'text/html' ? '<p>SomeData</p>' : 'SomeData'
  147. } );
  148. setModelData( model, '<paragraph>[]foo</paragraph>' );
  149. const targetRange = doc.selection.getFirstRange();
  150. const targetViewRange = editor.editing.mapper.toViewRange( targetRange );
  151. viewDocument.fire( 'clipboardInput', { dataTransfer, targetRanges: [ targetViewRange ] } );
  152. // Well, there's no clipboard plugin, so nothing happens.
  153. expect( getModelData( model ) ).to.equal( '<paragraph>[]foo</paragraph>' );
  154. } );
  155. it( 'should not convert image\'s uploadId attribute if is consumed already', () => {
  156. editor.editing.downcastDispatcher.on( 'attribute:uploadId:image', ( evt, data, conversionApi ) => {
  157. conversionApi.consumable.consume( data.item, evt.name );
  158. }, { priority: 'high' } );
  159. setModelData( model, '<image uploadId="1234"></image>' );
  160. expect( getViewData( view ) ).to.equal(
  161. '[<figure class="ck-widget image" contenteditable="false">' +
  162. '<img></img>' +
  163. '</figure>]' );
  164. } );
  165. it( 'should use read data once it is present', done => {
  166. const file = createNativeFileMock();
  167. setModelData( model, '<paragraph>{}foo bar</paragraph>' );
  168. editor.execute( 'imageUpload', { file } );
  169. model.once( '_change', () => {
  170. expect( getViewData( view ) ).to.equal(
  171. '[<figure class="ck-widget image" contenteditable="false">' +
  172. `<img src="${ base64Sample }"></img>` +
  173. '</figure>]' +
  174. '<p>foo bar</p>' );
  175. expect( loader.status ).to.equal( 'uploading' );
  176. done();
  177. } );
  178. expect( loader.status ).to.equal( 'reading' );
  179. nativeReaderMock.mockSuccess( base64Sample );
  180. } );
  181. it( 'should replace read data with server response once it is present', done => {
  182. const file = createNativeFileMock();
  183. setModelData( model, '<paragraph>{}foo bar</paragraph>' );
  184. editor.execute( 'imageUpload', { file } );
  185. model.document.once( 'change', () => {
  186. model.document.once( 'change', () => {
  187. expect( getViewData( view ) ).to.equal(
  188. '[<figure class="ck-widget image" contenteditable="false"><img src="image.png"></img></figure>]<p>foo bar</p>'
  189. );
  190. expect( loader.status ).to.equal( 'idle' );
  191. done();
  192. }, { priority: 'lowest' } );
  193. adapterMock.mockSuccess( { default: 'image.png' } );
  194. } );
  195. nativeReaderMock.mockSuccess( base64Sample );
  196. } );
  197. it( 'should fire notification event in case of error', done => {
  198. const notification = editor.plugins.get( Notification );
  199. const file = createNativeFileMock();
  200. notification.on( 'show:warning', ( evt, data ) => {
  201. expect( data.message ).to.equal( 'Reading error.' );
  202. expect( data.title ).to.equal( 'Upload failed' );
  203. evt.stop();
  204. done();
  205. }, { priority: 'high' } );
  206. setModelData( model, '<paragraph>{}foo bar</paragraph>' );
  207. editor.execute( 'imageUpload', { file } );
  208. nativeReaderMock.mockError( 'Reading error.' );
  209. } );
  210. it( 'should not fire notification on abort', done => {
  211. const notification = editor.plugins.get( Notification );
  212. const file = createNativeFileMock();
  213. const spy = testUtils.sinon.spy();
  214. notification.on( 'show:warning', evt => {
  215. spy();
  216. evt.stop();
  217. }, { priority: 'high' } );
  218. setModelData( model, '<paragraph>{}foo bar</paragraph>' );
  219. editor.execute( 'imageUpload', { file } );
  220. nativeReaderMock.abort();
  221. setTimeout( () => {
  222. sinon.assert.notCalled( spy );
  223. done();
  224. }, 0 );
  225. } );
  226. it( 'should throw when other error happens during upload', done => {
  227. const file = createNativeFileMock();
  228. const error = new Error( 'Foo bar baz' );
  229. const uploadEditing = editor.plugins.get( ImageUploadEditing );
  230. const loadSpy = sinon.spy( uploadEditing, '_load' );
  231. const catchSpy = sinon.spy();
  232. // Throw an error when async attribute change occur.
  233. editor.editing.downcastDispatcher.on( 'attribute:uploadStatus:image', ( evt, data ) => {
  234. if ( data.attributeNewValue == 'uploading' ) {
  235. throw error;
  236. }
  237. } );
  238. setModelData( model, '<paragraph>{}foo bar</paragraph>' );
  239. editor.execute( 'imageUpload', { file } );
  240. sinon.assert.calledOnce( loadSpy );
  241. const promise = loadSpy.returnValues[ 0 ];
  242. // Check if error can be caught.
  243. promise.catch( catchSpy );
  244. nativeReaderMock.mockSuccess();
  245. setTimeout( () => {
  246. sinon.assert.calledOnce( catchSpy );
  247. sinon.assert.calledWithExactly( catchSpy, error );
  248. done();
  249. }, 0 );
  250. } );
  251. it( 'should do nothing if image does not have uploadId', () => {
  252. setModelData( model, '<image src="image.png"></image>' );
  253. expect( getViewData( view ) ).to.equal(
  254. '[<figure class="ck-widget image" contenteditable="false"><img src="image.png"></img></figure>]'
  255. );
  256. } );
  257. it( 'should remove image in case of upload error', done => {
  258. const file = createNativeFileMock();
  259. const spy = testUtils.sinon.spy();
  260. const notification = editor.plugins.get( Notification );
  261. setModelData( model, '<paragraph>{}foo bar</paragraph>' );
  262. notification.on( 'show:warning', evt => {
  263. spy();
  264. evt.stop();
  265. }, { priority: 'high' } );
  266. editor.execute( 'imageUpload', { file } );
  267. model.document.once( 'change', () => {
  268. model.document.once( 'change', () => {
  269. expect( getModelData( model ) ).to.equal( '<paragraph>[]foo bar</paragraph>' );
  270. sinon.assert.calledOnce( spy );
  271. done();
  272. } );
  273. } );
  274. nativeReaderMock.mockError( 'Upload error.' );
  275. } );
  276. it( 'should abort upload if image is removed', () => {
  277. const file = createNativeFileMock();
  278. setModelData( model, '<paragraph>{}foo bar</paragraph>' );
  279. editor.execute( 'imageUpload', { file } );
  280. const abortSpy = testUtils.sinon.spy( loader, 'abort' );
  281. expect( loader.status ).to.equal( 'reading' );
  282. nativeReaderMock.mockSuccess( base64Sample );
  283. const image = doc.getRoot().getChild( 0 );
  284. model.change( writer => {
  285. writer.remove( image );
  286. } );
  287. expect( loader.status ).to.equal( 'aborted' );
  288. sinon.assert.calledOnce( abortSpy );
  289. } );
  290. it( 'should not abort and not restart upload when image is moved', () => {
  291. const file = createNativeFileMock();
  292. setModelData( model, '<paragraph>{}foo bar</paragraph>' );
  293. editor.execute( 'imageUpload', { file } );
  294. const abortSpy = testUtils.sinon.spy( loader, 'abort' );
  295. const loadSpy = testUtils.sinon.spy( loader, 'read' );
  296. const image = doc.getRoot().getChild( 0 );
  297. model.change( writer => {
  298. writer.move( Range.createOn( image ), Position.createAt( doc.getRoot(), 2 ) );
  299. } );
  300. expect( abortSpy.called ).to.be.false;
  301. expect( loadSpy.called ).to.be.false;
  302. } );
  303. it( 'image should be permanently removed if it is removed by user during upload', done => {
  304. const file = createNativeFileMock();
  305. const notification = editor.plugins.get( Notification );
  306. setModelData( model, '<paragraph>{}foo bar</paragraph>' );
  307. // Prevent popping up alert window.
  308. notification.on( 'show:warning', evt => {
  309. evt.stop();
  310. }, { priority: 'high' } );
  311. editor.execute( 'imageUpload', { file } );
  312. model.document.once( 'change', () => {
  313. // This is called after "manual" remove.
  314. model.document.once( 'change', () => {
  315. // This is called after attributes are removed.
  316. let undone = false;
  317. model.document.once( 'change', () => {
  318. if ( !undone ) {
  319. undone = true;
  320. // This is called after abort remove.
  321. expect( getModelData( model ) ).to.equal( '<paragraph>[]foo bar</paragraph>' );
  322. editor.execute( 'undo' );
  323. // Expect that the image has not been brought back.
  324. expect( getModelData( model ) ).to.equal( '<paragraph>[]foo bar</paragraph>' );
  325. done();
  326. }
  327. } );
  328. } );
  329. } );
  330. const image = doc.getRoot().getChild( 0 );
  331. model.change( writer => {
  332. writer.remove( image );
  333. } );
  334. } );
  335. it( 'should create responsive image if server return multiple images', done => {
  336. const file = createNativeFileMock();
  337. setModelData( model, '<paragraph>{}foo bar</paragraph>' );
  338. editor.execute( 'imageUpload', { file } );
  339. model.document.once( 'change', () => {
  340. model.document.once( 'change', () => {
  341. expect( getViewData( view ) ).to.equal(
  342. '[<figure class="ck-widget image" contenteditable="false">' +
  343. '<img sizes="100vw" src="image.png" srcset="image-500.png 500w, image-800.png 800w" width="800"></img>' +
  344. '</figure>]<p>foo bar</p>'
  345. );
  346. expect( loader.status ).to.equal( 'idle' );
  347. done();
  348. }, { priority: 'lowest' } );
  349. adapterMock.mockSuccess( { default: 'image.png', 500: 'image-500.png', 800: 'image-800.png' } );
  350. } );
  351. nativeReaderMock.mockSuccess( base64Sample );
  352. } );
  353. it( 'should prevent from browser redirecting when an image is dropped on another image', () => {
  354. const spy = testUtils.sinon.spy();
  355. editor.editing.view.document.fire( 'dragover', {
  356. preventDefault: spy
  357. } );
  358. expect( spy.calledOnce ).to.equal( true );
  359. } );
  360. } );