imageresize.js 19 KB

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