utils.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /* globals document */
  6. import VirtualTestEditor from '@ckeditor/ckeditor5-core/tests/_utils/virtualtesteditor';
  7. import ClassicTestEditor from '@ckeditor/ckeditor5-core/tests/_utils/classictesteditor';
  8. import PasteFromOffice from '../../src/pastefromoffice';
  9. import HtmlDataProcessor from '@ckeditor/ckeditor5-engine/src/dataprocessor/htmldataprocessor';
  10. import normalizeClipboardData from '@ckeditor/ckeditor5-clipboard/src/utils/normalizeclipboarddata';
  11. import normalizeHtml from '@ckeditor/ckeditor5-utils/tests/_utils/normalizehtml';
  12. import { setData, stringify as stringifyModel } from '@ckeditor/ckeditor5-engine/src/dev-utils/model';
  13. import { stringify as stringifyView } from '@ckeditor/ckeditor5-engine/src/dev-utils/view';
  14. import { fixtures, browserFixtures } from './fixtures';
  15. const htmlDataProcessor = new HtmlDataProcessor();
  16. /**
  17. * Mocks dataTransfer object which can be used for simulating paste.
  18. *
  19. * @param {Object} data Object containing 'mime type - data' pairs.
  20. * @returns {Object} DataTransfer mock object.
  21. */
  22. export function createDataTransfer( data ) {
  23. return {
  24. getData( type ) {
  25. return data[ type ];
  26. }
  27. };
  28. }
  29. /**
  30. * Generates test groups based on provided parameters. Generated tests are specifically designed
  31. * to test pasted content transformations.
  32. *
  33. * This function generates test groups based on available fixtures:
  34. *
  35. * 1. If only generic fixtures are available they will be used for all listed browsers and combined into one test group.
  36. * 2. If there are browser-specific fixtures available they will be used for matching browser resulting in a separate
  37. * test group. All unmatched browsers will use generic fixtures combined into one separate test group.
  38. * 3. If some fixtures are marked to be skipped for a specific browser, the separate test group will be created for this browser.
  39. *
  40. * @param {Object} config
  41. * @param {String} config.type Type of tests to generate, could be 'normalization' or 'integration'.
  42. * @param {String} config.input Name of the fixtures group. Usually stored in `/tests/_data/groupname/`.
  43. * @param {Array.<String>} config.browsers List of all browsers for which to generate tests.
  44. * @param {Object} [config.editorConfig] Editor config which is passed to editor `create()` method.
  45. * @param {Object} [config.skip] List of fixtures for any browser to skip. The supported format is:
  46. *
  47. * {
  48. * browserName: [ fixtureName1, fixtureName2 ]
  49. * }
  50. */
  51. export function generateTests( config ) {
  52. if ( [ 'normalization', 'integration' ].indexOf( config.type ) === -1 ) {
  53. throw new Error( `Invalid tests type - \`config.type\`: '${ config.type }'.` );
  54. }
  55. if ( !config.input ) {
  56. throw new Error( 'No `config.input` option provided.' );
  57. }
  58. if ( !config.browsers || !config.browsers.length ) {
  59. throw new Error( 'No or empty `config.browsers` option provided.' );
  60. }
  61. const groups = groupFixturesByBrowsers( config.browsers, config.input, config.skip );
  62. const generateSuiteFn = config.type === 'normalization' ? generateNormalizationTests : generateIntegrationTests;
  63. describe( config.type, () => {
  64. describe( config.input, () => {
  65. const editorConfig = config.editorConfig || {};
  66. for ( const group of Object.keys( groups ) ) {
  67. const skip = config.skip && config.skip[ group ] ? config.skip[ group ] : [];
  68. if ( groups[ group ] ) {
  69. generateSuiteFn( group, groups[ group ], editorConfig, skip );
  70. }
  71. }
  72. } );
  73. } );
  74. }
  75. // Creates browser groups combining all browsers using same fixtures. Each browser which have
  76. // some fixtures marked to be skipped automatically create separate groups.
  77. //
  78. // @param {Array.<String>} browsers List of all browsers for which fixture groups will be created.
  79. // @param {String} fixturesGroup Fixtures group name.
  80. // @returns {Object} Object containing browsers groups where key is the name of the group and value is fixtures object:
  81. //
  82. // {
  83. // 'safari': { ... }
  84. // 'edge': { ... }
  85. // 'chrome, firefox': { ... }
  86. // }
  87. function groupFixturesByBrowsers( browsers, fixturesGroup, skipBrowsers ) {
  88. const browsersGroups = {};
  89. const browsersGeneric = browsers.slice( 0 );
  90. // Create separate groups for browsers with browser-specific fixtures available.
  91. for ( const browser of browsers ) {
  92. if ( browserFixtures[ fixturesGroup ] && browserFixtures[ fixturesGroup ][ browser ] ) {
  93. browsersGroups[ browser ] = browserFixtures[ fixturesGroup ][ browser ];
  94. browsersGeneric.splice( browsersGeneric.indexOf( browser ), 1 );
  95. }
  96. }
  97. // Create separate groups for browsers with skipped tests.
  98. if ( skipBrowsers ) {
  99. for ( const browser of Object.keys( skipBrowsers ) ) {
  100. if ( browsersGeneric.indexOf( browser ) !== -1 ) {
  101. browsersGroups[ browser ] = fixtures[ fixturesGroup ] ? fixtures[ fixturesGroup ] : null;
  102. browsersGeneric.splice( browsersGeneric.indexOf( browser ), 1 );
  103. }
  104. }
  105. }
  106. // Use generic fixtures (if available) for browsers left.
  107. if ( browsersGeneric.length ) {
  108. browsersGroups[ browsersGeneric.join( ', ' ) ] = fixtures[ fixturesGroup ] ? fixtures[ fixturesGroup ] : null;
  109. }
  110. return browsersGroups;
  111. }
  112. // Generates normalization tests based on a provided fixtures. For each input fixture one test is generated.
  113. // Please notice that normalization compares generated Views, not DOM. That's why there might appear some not familiar structures,
  114. // like closing tags for void tags, for example `<br></br>`.
  115. //
  116. // @param {String} title Tests group title.
  117. // @param {Object} fixtures Object containing fixtures.
  118. // @param {Object} editorConfig Editor config with which test editor will be created.
  119. // @param {Array.<String>} skip Array of fixtures names which tests should be skipped.
  120. function generateNormalizationTests( title, fixtures, editorConfig, skip ) {
  121. describe( title, () => {
  122. let editor;
  123. beforeEach( () => {
  124. return VirtualTestEditor
  125. .create( editorConfig )
  126. .then( newEditor => {
  127. editor = newEditor;
  128. } );
  129. } );
  130. afterEach( () => {
  131. editor.destroy();
  132. } );
  133. for ( const name of Object.keys( fixtures.input ) ) {
  134. ( skip.indexOf( name ) !== -1 ? it.skip : it )( name, () => {
  135. // Simulate data from Clipboard event
  136. const data = {
  137. content: htmlDataProcessor.toView( normalizeClipboardData( fixtures.input[ name ] ) ),
  138. dataTransfer: createDataTransfer( {
  139. 'text/html': fixtures.input[ name ],
  140. 'text/rtf': fixtures.inputRtf && fixtures.inputRtf[ name ]
  141. } )
  142. };
  143. PasteFromOffice._inputTransformationListener( null, data );
  144. expectNormalized(
  145. data.content,
  146. fixtures.normalized[ name ]
  147. );
  148. } );
  149. }
  150. } );
  151. }
  152. // Generates integration tests based on a provided fixtures. For each input fixture one test is generated.
  153. //
  154. // @param {String} title Tests group title.
  155. // @param {Object} fixtures Object containing fixtures.
  156. // @param {Object} editorConfig Editor config with which test editor will be created.
  157. // @param {Array.<String>} skip Array of fixtures names which tests should be skipped.
  158. function generateIntegrationTests( title, fixtures, editorConfig, skip ) {
  159. describe( title, () => {
  160. let element, editor;
  161. let data = {};
  162. before( () => {
  163. element = document.createElement( 'div' );
  164. document.body.appendChild( element );
  165. return ClassicTestEditor
  166. .create( element, editorConfig )
  167. .then( editorInstance => {
  168. editor = editorInstance;
  169. } );
  170. } );
  171. beforeEach( () => {
  172. setData( editor.model, '<paragraph>[]</paragraph>' );
  173. const editorModel = editor.model;
  174. const insertContent = editorModel.insertContent;
  175. data = {};
  176. sinon.stub( editorModel, 'insertContent' ).callsFake( ( content, selection ) => {
  177. // Save model string representation now as it may change after `insertContent()` function call
  178. // so accessing it later may not work as it may have emptied/changed structure.
  179. data.actual = stringifyModel( content );
  180. insertContent.call( editorModel, content, selection );
  181. } );
  182. } );
  183. afterEach( () => {
  184. sinon.restore();
  185. } );
  186. after( () => {
  187. editor.destroy();
  188. element.remove();
  189. } );
  190. for ( const name of Object.keys( fixtures.input ) ) {
  191. ( skip.indexOf( name ) !== -1 ? it.skip : it )( name, () => {
  192. data.input = fixtures.input[ name ];
  193. data.model = fixtures.model[ name ];
  194. expectModel( data, editor, fixtures.inputRtf && fixtures.inputRtf[ name ] );
  195. } );
  196. }
  197. } );
  198. }
  199. // Checks if provided view element instance equals expected HTML. The element is stringified
  200. // before comparing so its entire structure can be compared.
  201. // If the given `actual` or `expected` structure contains base64 encoded images,
  202. // these images are extracted (so HTML diff is readable) and compared
  203. // one by one separately (so it is visible if base64 representation is malformed).
  204. //
  205. // This function is designed for comparing normalized data so expected input is preprocessed before comparing:
  206. //
  207. // * Tabs on the lines beginnings are removed.
  208. // * Line breaks and empty lines are removed.
  209. //
  210. // The expected input should be prepared in the above in mind which means every element containing text nodes must start
  211. // and end in the same line. So expected input may be formatted like:
  212. //
  213. // <span lang=PL style='mso-ansi-language:PL'> 03<span style='mso-spacerun:yes'> </span><o:p></o:p></span>
  214. //
  215. // but not like:
  216. //
  217. // <span lang=PL style='mso-ansi-language:PL'>
  218. // 03<span style='mso-spacerun:yes'> </span>
  219. // <o:p></o:p>
  220. // </span>
  221. //
  222. // because tab preceding `03` text will be treated as formatting character and will be removed.
  223. //
  224. // @param {module:engine/view/text~Text|module:engine/view/element~Element|module:engine/view/documentfragment~DocumentFragment}
  225. // actualView Actual HTML.
  226. // @param {String} expectedHtml Expected HTML.
  227. function expectNormalized( actualView, expectedHtml ) {
  228. // We are ok with both spaces and non-breaking spaces in the actual content.
  229. // Replace `&nbsp;` with regular spaces to align with expected content.
  230. const actualNormalized = stringifyView( actualView ).replace( /\u00A0/g, ' ' );
  231. const expectedNormalized = normalizeHtml( inlineData( expectedHtml ) );
  232. compareContentWithBase64Images( actualNormalized, expectedNormalized );
  233. }
  234. // Compares two models string representations. The input HTML is processed through paste
  235. // pipeline where it is transformed into model. This function hooks into {@link module:engine/model/model~Model#insertContent}
  236. // to get the model representation before it is inserted.
  237. //
  238. // @param {Object} data
  239. // @param {String} data.input Input HTML which will be pasted into the editor.
  240. // @param {String} data.actual Actual model data.
  241. // @param {String} data.model Expected model data.
  242. // @param {module:core/editor/editor~Editor} editor Editor instance.
  243. // @param {String} [inputRtf] Additional RTF input data which will be pasted into the editor as `text/rtf` together with regular input data.
  244. function expectModel( data, editor, inputRtf = null ) {
  245. firePasteEvent( editor, {
  246. 'text/html': data.input,
  247. 'text/rtf': inputRtf
  248. } );
  249. compareContentWithBase64Images( data.actual, inlineData( data.model ) );
  250. }
  251. // Compares actual and expected content. Before comparison the base64 images data is extracted so data diff is more readable.
  252. // If there were any images extracted their base64 data is also compared.
  253. //
  254. // @param {String} actual Actual content.
  255. // @param {String} expected Expected content.
  256. function compareContentWithBase64Images( actual, expected ) {
  257. // Extract base64 images so they do not pollute model diff and can be compared separately.
  258. const { data: actualModel, images: actualImages } = extractBase64Srcs( actual );
  259. const { data: expectedModel, images: expectedImages } = extractBase64Srcs( expected );
  260. // In some rare cases there might be `&nbsp;` in a model data
  261. // (see https://github.com/ckeditor/ckeditor5-paste-from-office/issues/27).
  262. expect( actualModel.replace( /\u00A0/g, ' ' ) ).to.equal( expectedModel );
  263. if ( actualImages.length > 0 && expectedImages.length > 0 ) {
  264. expect( actualImages.length ).to.equal( expectedImages.length );
  265. expect( actualImages ).to.deep.equal( expectedImages );
  266. }
  267. }
  268. // Inlines given HTML / model representation string by removing preceding tabs and line breaks.
  269. //
  270. // @param {String} data Data to be inlined.
  271. function inlineData( data ) {
  272. return data
  273. // Replace tabs on the lines beginning as normalized input files are formatted.
  274. .replace( /^\t*</gm, '<' )
  275. // Replace line breaks (after closing tags) too.
  276. .replace( /[\r\n]/gm, '' );
  277. }
  278. // Extracts base64 part representing an image from the given HTML / model representation.
  279. //
  280. // @param {String} data Data from which bas64 strings will be extracted.
  281. // @returns {Object} result
  282. // @returns {String} result.data Data without bas64 strings.
  283. // @returns {Array.<String>} result.images Array of extracted base64 strings.
  284. function extractBase64Srcs( data ) {
  285. const regexp = /src="data:image\/(png|jpe?g);base64,([^"]*)"/gm;
  286. const images = [];
  287. const replacements = [];
  288. let match;
  289. while ( ( match = regexp.exec( data ) ) !== null ) {
  290. images.push( match[ 2 ].toLowerCase() );
  291. replacements.push( match[ 2 ] );
  292. }
  293. for ( const replacement of replacements ) {
  294. data = data.replace( replacement, '' );
  295. }
  296. return { data, images };
  297. }
  298. // Fires paste event on a given editor instance with a specific HTML data.
  299. //
  300. // @param {module:core/editor/editor~Editor} editor Editor instance on which paste event will be fired.
  301. // @param {Object} data Object with `type: content` pairs used as data transfer data in the fired paste event.
  302. function firePasteEvent( editor, data ) {
  303. editor.editing.view.document.fire( 'paste', {
  304. dataTransfer: createDataTransfer( data ),
  305. preventDefault() {}
  306. } );
  307. }