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