imageuploadediting.js 19 KB

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