imageuploadediting.js 19 KB

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