imageresize.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /* global document, window */
  6. // ClassicTestEditor can't be used, as it doesn't handle the focus, which is needed to test resizer visual cues.
  7. import ClassicEditor from '@ckeditor/ckeditor5-editor-classic/src/classiceditor';
  8. import Paragraph from '@ckeditor/ckeditor5-paragraph/src/paragraph';
  9. import Image from '../src/image';
  10. import ImageResize from '../src/imageresize';
  11. import ImageResizeCommand from '../src/imageresize/imageresizecommand';
  12. import ImageStyle from '../src/imagestyle';
  13. import ImageToolbar from '../src/imagetoolbar';
  14. import ImageTextAlternative from '../src/imagetextalternative';
  15. import Undo from '@ckeditor/ckeditor5-undo/src/undo';
  16. import Table from '@ckeditor/ckeditor5-table/src/table';
  17. import Rect from '@ckeditor/ckeditor5-utils/src/dom/rect';
  18. import { getData, setData } from '@ckeditor/ckeditor5-engine/src/dev-utils/model';
  19. import { mouseMock, getWidgetDomParts, getHandleCenterPoint } from '@ckeditor/ckeditor5-widget/tests/widgetresize/_utils/utils';
  20. describe( 'ImageResize', () => {
  21. // 100x50 black png image
  22. const IMAGE_SRC_FIXTURE = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAAAyCAQAAAAAPLY1AAAAQklEQVR42u3PQREAAAgDoK1/' +
  23. 'aM3g14MGNJMXKiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiJysRFNMgH0RpujAAAAAElFTkSuQmCC';
  24. let absoluteContainer, widget, editor, view, viewDocument, editorElement;
  25. before( () => {
  26. // This container is required to position editor element in a reliable element.
  27. // @todo ensure whether it's required after migrating the tests.
  28. absoluteContainer = document.createElement( 'div' );
  29. absoluteContainer.style.top = '50px';
  30. absoluteContainer.style.left = '50px';
  31. absoluteContainer.style.height = '1000px';
  32. absoluteContainer.style.width = '500px';
  33. absoluteContainer.style.position = 'absolute';
  34. document.body.appendChild( absoluteContainer );
  35. } );
  36. after( () => {
  37. absoluteContainer.remove();
  38. } );
  39. afterEach( () => {
  40. if ( editorElement ) {
  41. editorElement.remove();
  42. }
  43. if ( editor ) {
  44. return editor.destroy();
  45. }
  46. } );
  47. describe( 'conversion', () => {
  48. beforeEach( () => createEditor() );
  49. it( 'upcasts 100px width correctly', () => {
  50. editor.setData( `<figure class="image" style="width:100px;"><img src="${ IMAGE_SRC_FIXTURE }"></figure>` );
  51. expect( editor.model.document.getRoot().getChild( 0 ).getAttribute( 'width' ) ).to.equal( '100px' );
  52. } );
  53. it( 'upcasts 50% width correctly', () => {
  54. editor.setData( `<figure class="image" style="width:50%;"><img src="${ IMAGE_SRC_FIXTURE }"></figure>` );
  55. expect( editor.model.document.getRoot().getChild( 0 ).getAttribute( 'width' ) ).to.equal( '50%' );
  56. } );
  57. it( 'downcasts 100px width correctly', () => {
  58. setData( editor.model, `<image src="${ IMAGE_SRC_FIXTURE }" width="100px"></image>` );
  59. expect( editor.getData() )
  60. .to.equal( `<figure class="image image_resized" style="width:100px;"><img src="${ IMAGE_SRC_FIXTURE }"></figure>` );
  61. } );
  62. it( 'downcasts 50% width correctly', () => {
  63. setData( editor.model, `<image src="${ IMAGE_SRC_FIXTURE }" width="50%"></image>` );
  64. expect( editor.getData() )
  65. .to.equal( `<figure class="image image_resized" style="width:50%;"><img src="${ IMAGE_SRC_FIXTURE }"></figure>` );
  66. } );
  67. it( 'doesn\'t downcast consumed tokens', () => {
  68. editor.conversion.for( 'downcast' ).add( dispatcher =>
  69. dispatcher.on( 'attribute:width:image', ( evt, data, conversionApi ) => {
  70. conversionApi.consumable.consume( data.item, 'attribute:width:image' );
  71. }, { priority: 'high' } )
  72. );
  73. setData( editor.model, `<image src="${ IMAGE_SRC_FIXTURE }" width="50%"></image>` );
  74. expect( editor.getData() )
  75. .to.equal( `<figure class="image"><img src="${ IMAGE_SRC_FIXTURE }"></figure>` );
  76. } );
  77. } );
  78. describe( 'schema', () => {
  79. beforeEach( () => createEditor() );
  80. it( 'allows the width attribute', () => {
  81. expect( editor.model.schema.checkAttribute( 'image', 'width' ) ).to.be.true;
  82. } );
  83. it( 'defines width as a formatting attribute', () => {
  84. expect( editor.model.schema.getAttributeProperties( 'width' ) ).to.have.property( 'isFormatting', true );
  85. } );
  86. } );
  87. describe( 'command', () => {
  88. beforeEach( () => createEditor() );
  89. it( 'defines the imageResize command', () => {
  90. expect( editor.commands.get( 'imageResize' ) ).to.be.instanceOf( ImageResizeCommand );
  91. } );
  92. it( 'uses the command on commit', async () => {
  93. setData( editor.model, `<paragraph>foo</paragraph>[<image src="${ IMAGE_SRC_FIXTURE }"></image>]` );
  94. widget = viewDocument.getRoot().getChild( 1 );
  95. const spy = sinon.spy( editor.commands.get( 'imageResize' ), 'execute' );
  96. await generateResizeTest( {
  97. expectedWidth: 80,
  98. pointerOffset: {
  99. x: 10,
  100. y: -10
  101. },
  102. resizerPosition: 'bottom-left'
  103. } )();
  104. // It's either 80px or 81px depending on the device, so we need to make the test a bit more loose.
  105. const realWidth = editor.model.document.getRoot().getChild( 1 ).getAttribute( 'width' );
  106. expect( realWidth ).to.match( /^\d\dpx$/ );
  107. expect( spy.calledOnce ).to.be.true;
  108. expect( spy.args[ 0 ][ 0 ] ).to.deep.equal( { width: realWidth } );
  109. } );
  110. it( 'disables the resizer if the command is disabled', () => {
  111. setData( editor.model, `<paragraph>foo</paragraph>[<image src="${ IMAGE_SRC_FIXTURE }"></image>]` );
  112. const resizer = getSelectedImageResizer( editor );
  113. let isEnabled = false;
  114. editor.commands.get( 'imageResize' ).on( 'set:isEnabled', evt => {
  115. evt.return = isEnabled;
  116. evt.stop();
  117. }, { priority: 'highest' } );
  118. editor.commands.get( 'imageResize' ).refresh();
  119. expect( resizer.isEnabled ).to.be.false;
  120. isEnabled = true;
  121. editor.commands.get( 'imageResize' ).refresh();
  122. expect( resizer.isEnabled ).to.be.true;
  123. } );
  124. it( 'the resizer is disabled from the beginning when the command is disabled when the image is inserted', () => {
  125. setData( editor.model, '<paragraph>foo[]</paragraph>' );
  126. editor.commands.get( 'imageResize' ).on( 'set:isEnabled', evt => {
  127. evt.return = false;
  128. evt.stop();
  129. }, { priority: 'highest' } );
  130. editor.commands.get( 'imageResize' ).refresh();
  131. editor.model.change( writer => {
  132. editor.model.insertContent( writer.createElement( 'image', { src: IMAGE_SRC_FIXTURE } ) );
  133. } );
  134. const resizer = getSelectedImageResizer( editor );
  135. const resizerWrapper = editor.ui.getEditableElement().querySelector( '.ck-widget__resizer' );
  136. expect( resizer.isEnabled ).to.be.false;
  137. expect( resizerWrapper.style.display ).to.equal( 'none' );
  138. } );
  139. } );
  140. describe( 'side image resizing', () => {
  141. beforeEach( () => createEditor() );
  142. beforeEach( () => {
  143. setData( editor.model, `<paragraph>foo</paragraph>[<image imageStyle="side" src="${ IMAGE_SRC_FIXTURE }"></image>]` );
  144. widget = viewDocument.getRoot().getChild( 1 );
  145. } );
  146. it( 'doesn\'t flicker at the beginning of the resize', async () => {
  147. // (#5189)
  148. const resizerPosition = 'bottom-left';
  149. const domParts = getWidgetDomParts( editor, widget, resizerPosition );
  150. const initialPointerPosition = getHandleCenterPoint( domParts.widget, resizerPosition );
  151. const resizeWrapperView = widget.getChild( 1 );
  152. focusEditor( editor );
  153. mouseMock.down( editor, domParts.resizeHandle );
  154. await wait( 40 );
  155. mouseMock.move( editor, domParts.resizeHandle, null, initialPointerPosition );
  156. expect( resizeWrapperView.getStyle( 'width' ) ).to.be.equal( '100px' );
  157. mouseMock.up( editor );
  158. } );
  159. it( 'makes no change when clicking the handle without drag', () => {
  160. const resizerPosition = 'bottom-left';
  161. const expectedWidth = 100;
  162. const domParts = getWidgetDomParts( editor, widget, resizerPosition );
  163. focusEditor( editor );
  164. mouseMock.down( editor, domParts.resizeHandle );
  165. expect( getDomWidth( domParts.widget ), 'DOM width check' ).to.be.closeTo( expectedWidth, 2 );
  166. mouseMock.up( editor );
  167. const modelItem = editor.model.document.getRoot().getChild( 1 );
  168. expect( modelItem.getAttribute( 'width' ), 'model width attribute' ).to.be.undefined;
  169. } );
  170. } );
  171. describe( 'undo integration', () => {
  172. beforeEach( () => createEditor() );
  173. beforeEach( () => {
  174. setData( editor.model, `<paragraph>foo</paragraph>[<image src="${ IMAGE_SRC_FIXTURE }"></image>]` );
  175. widget = viewDocument.getRoot().getChild( 1 );
  176. } );
  177. it( 'has correct border size after undo', async () => {
  178. await generateResizeTest( {
  179. expectedWidth: 120,
  180. pointerOffset: {
  181. x: 0,
  182. y: 10
  183. },
  184. resizerPosition: 'bottom-left'
  185. } )();
  186. editor.commands.get( 'undo' ).execute();
  187. await wait( 160 ); // ui#update event is throttled.
  188. const resizerWrapper = document.querySelector( '.ck-widget__resizer' );
  189. const shadowBoundingRect = resizerWrapper.getBoundingClientRect();
  190. expect( shadowBoundingRect.width ).to.be.equal( 100 );
  191. expect( shadowBoundingRect.height ).to.be.equal( 50 );
  192. } );
  193. } );
  194. describe( 'table integration', () => {
  195. beforeEach( () => createEditor() );
  196. beforeEach( () => {
  197. setData( editor.model,
  198. '<table>' +
  199. `<tableRow><tableCell>[<image src="${ IMAGE_SRC_FIXTURE }"></image>]</tableCell></tableRow>` +
  200. '</table>'
  201. );
  202. widget = viewDocument.getRoot().getChild( 0 ).getChild( 1 ).getChild( 0 ).getChild( 0 ).getChild( 0 ).getChild( 0 );
  203. } );
  204. it( 'works when resizing in a table', generateResizeTest( {
  205. getModel: () => editor.model.document.getRoot().getChild( 0 ).getChild( 0 ).getChild( 0 ).getChild( 0 ),
  206. expectedWidth: 60,
  207. modelRegExp: /.+/,
  208. pointerOffset: {
  209. x: -40,
  210. y: -20
  211. },
  212. resizerPosition: 'bottom-right'
  213. } ) );
  214. } );
  215. describe( 'srcset integration', () => {
  216. beforeEach( () => createEditor() );
  217. // The image is 96x96 pixels.
  218. const imageBaseUrl = '/assets/sample.png';
  219. const getModel = () => editor.model.document.getRoot().getChild( 0 );
  220. let images = [];
  221. before( () => {
  222. return Promise.all( [
  223. preloadImage( imageBaseUrl ),
  224. preloadImage( imageBaseUrl + '?a' ),
  225. preloadImage( imageBaseUrl + '?b' ),
  226. preloadImage( imageBaseUrl + '?c' )
  227. ] ).then( loadedImages => {
  228. images = loadedImages;
  229. } );
  230. } );
  231. after( () => {
  232. for ( const image of images ) {
  233. image.remove();
  234. }
  235. } );
  236. beforeEach( () => {
  237. editor.setData(
  238. `<figure class="image">
  239. <img src="${ imageBaseUrl }"
  240. srcset="${ imageBaseUrl }?a 110w,
  241. ${ imageBaseUrl }?b 440w,
  242. ${ imageBaseUrl }?c 1025w"
  243. sizes="100vw" width="96">
  244. </figure>`
  245. );
  246. widget = viewDocument.getRoot().getChild( 0 );
  247. } );
  248. it( 'works with images containing srcset', generateResizeTest( {
  249. getModel,
  250. expectedWidth: 76,
  251. modelRegExp: /.+/,
  252. pointerOffset: {
  253. x: -20,
  254. y: -20
  255. },
  256. resizerPosition: 'bottom-right'
  257. } ) );
  258. it( 'retains width after removing srcset', async () => {
  259. await generateResizeTest( {
  260. getModel,
  261. expectedWidth: 80,
  262. modelRegExp: /.+/,
  263. pointerOffset: {
  264. x: -16,
  265. y: -16
  266. },
  267. resizerPosition: 'bottom-right'
  268. } )();
  269. editor.model.change( writer => {
  270. writer.removeAttribute( 'srcset', getModel() );
  271. } );
  272. expect( editor.getData() )
  273. .to.match( /<figure class="image image_resized" style="width:[\d.]{2,}px;"><img src="\/assets\/sample.png"><\/figure>/ );
  274. } );
  275. async function preloadImage( imageUrl ) {
  276. const image = document.createElement( 'img' );
  277. image.src = imageUrl;
  278. return new Promise( ( resolve, reject ) => {
  279. image.addEventListener( 'load', () => resolve( image ) );
  280. image.addEventListener( 'error', () => reject( image ) );
  281. document.body.appendChild( image );
  282. } );
  283. }
  284. } );
  285. describe( 'widget toolbar integration', () => {
  286. let widgetToolbarRepository;
  287. beforeEach( () => createEditor( {
  288. plugins: [ Image, ImageStyle, Paragraph, Undo, Table, ImageResize, ImageToolbar, ImageTextAlternative ],
  289. image: {
  290. toolbar: [ 'imageTextAlternative' ],
  291. resizeUnit: 'px'
  292. }
  293. } ) );
  294. beforeEach( async () => {
  295. setData( editor.model, `<paragraph>foo</paragraph>[<image src="${ IMAGE_SRC_FIXTURE }"></image>]` );
  296. widget = viewDocument.getRoot().getChild( 1 );
  297. widgetToolbarRepository = editor.plugins.get( 'WidgetToolbarRepository' );
  298. } );
  299. it( 'default toolbar visibility', async () => {
  300. expect( widgetToolbarRepository.isEnabled ).to.be.true;
  301. } );
  302. it( 'visibility during the resize', async () => {
  303. await generateResizeTest( {
  304. expectedWidth: 100,
  305. modelRegExp: /.+/,
  306. pointerOffset: {
  307. x: 0,
  308. y: 0
  309. },
  310. resizerPosition: 'bottom-right',
  311. checkBeforeMouseUp: () => {
  312. expect( widgetToolbarRepository.isEnabled ).to.be.false;
  313. }
  314. } )();
  315. } );
  316. it( 'visibility after the resize', async () => {
  317. await generateResizeTest( {
  318. expectedWidth: 100,
  319. modelRegExp: /.+/,
  320. pointerOffset: {
  321. x: 0,
  322. y: 0
  323. },
  324. resizerPosition: 'bottom-right'
  325. } )();
  326. expect( widgetToolbarRepository.isEnabled ).to.be.true;
  327. } );
  328. it( 'visibility after the resize was canceled', async () => {
  329. const resizer = getSelectedImageResizer( editor );
  330. await generateResizeTest( {
  331. expectedWidth: 100,
  332. modelRegExp: /.+/,
  333. pointerOffset: {
  334. x: 0,
  335. y: 0
  336. },
  337. resizerPosition: 'bottom-right',
  338. checkBeforeMouseUp: () => {
  339. resizer.cancel();
  340. expect( widgetToolbarRepository.isEnabled ).to.be.true;
  341. }
  342. } )();
  343. } );
  344. it( 'restores toolbar when clicking the handle without drag', () => {
  345. // (https://github.com/ckeditor/ckeditor5-widget/pull/112#pullrequestreview-337725256).
  346. const domResizeHandle = getWidgetDomParts( editor, widget, 'bottom-left' ).resizeHandle;
  347. focusEditor( editor );
  348. mouseMock.down( editor, domResizeHandle );
  349. mouseMock.up( editor, domResizeHandle );
  350. expect( widgetToolbarRepository.isEnabled ).to.be.true;
  351. } );
  352. } );
  353. function wait( delay ) {
  354. return new Promise( resolve => window.setTimeout( () => resolve(), delay ) );
  355. }
  356. function generateResizeTest( options ) {
  357. // options.resizerPosition - top-left / top-right / bottom-right / bottom-left
  358. // options.pointerOffset - object - pointer offset relative to the dragged corner. Negative values are perfectly fine.
  359. // e.g. { x: 10, y: -5 }
  360. // options.expectedWidth
  361. // Returns a test case that puts
  362. return async function() {
  363. const domParts = getWidgetDomParts( editor, widget, options.resizerPosition );
  364. const domResizeWrapper = view.domConverter.mapViewToDom( widget.getChild( 1 ) );
  365. const modelRegExp = options.modelRegExp ? options.modelRegExp :
  366. /<paragraph>foo<\/paragraph><image src=".+?" width="([\d]+)px"><\/image>/;
  367. focusEditor( editor );
  368. const initialPointerPosition = getHandleCenterPoint( domParts.widget, options.resizerPosition );
  369. mouseMock.down( editor, domParts.resizeHandle );
  370. mouseMock.move( editor, domParts.resizeHandle, null, initialPointerPosition );
  371. // We need to wait as mousemove events are throttled.
  372. await wait( 40 );
  373. const finishPointerPosition = initialPointerPosition.moveBy( options.pointerOffset.x || 0, options.pointerOffset.y || 0 );
  374. mouseMock.move( editor, domParts.resizeHandle, null, finishPointerPosition );
  375. expect( parseInt( domParts.widget.style.width ) ).to.be.closeTo( options.expectedWidth, 2, 'DOM width check' );
  376. if ( options.checkBeforeMouseUp ) {
  377. options.checkBeforeMouseUp( domParts.widget, domResizeWrapper );
  378. }
  379. mouseMock.up( editor );
  380. expect( getData( editor.model, {
  381. withoutSelection: true
  382. } ) ).to.match( modelRegExp );
  383. const modelItem = options.getModel ? options.getModel() : editor.model.document.getRoot().getChild( 1 );
  384. const modelWidth = modelItem.getAttribute( 'width' );
  385. expect( parseFloat( modelWidth, 0 ) )
  386. .to.be.closeTo( options.expectedWidth, 2, 'Model width check' );
  387. };
  388. }
  389. function focusEditor( editor ) {
  390. editor.editing.view.focus();
  391. editor.ui.focusTracker.isFocused = true;
  392. }
  393. function getDomWidth( domElement ) {
  394. return new Rect( domElement ).width;
  395. }
  396. function getSelectedImageResizer( editor ) {
  397. return editor.plugins.get( 'WidgetResize' )._getResizerByViewElement(
  398. editor.editing.view.document.selection.getSelectedElement()
  399. );
  400. }
  401. function createEditor( config ) {
  402. editorElement = document.createElement( 'div' );
  403. absoluteContainer.appendChild( editorElement );
  404. return ClassicEditor
  405. .create( editorElement, config || {
  406. plugins: [ Image, ImageStyle, Paragraph, Undo, Table, ImageResize ],
  407. image: {
  408. resizeUnit: 'px'
  409. }
  410. } )
  411. .then( newEditor => {
  412. editor = newEditor;
  413. view = editor.editing.view;
  414. viewDocument = view.document;
  415. widget = viewDocument.getRoot().getChild( 1 );
  416. } );
  417. }
  418. } );