imageuploadediting.js 19 KB

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