Debian Codegraph @

extensions/VisualEditor/lib/ve/tests/ve.test.utils.js

raw symbols SCIP
1 /*!
2 * VisualEditor test utilities.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 ( function () {
8 /**
9 * @class
10 * @singleton
11 * @ignore
12 */
13 ve.test = { utils: {} };
14
15 // Create a dummy platform and target so ve.init.platform/target are available
16 function DummyPlatform() {
17 DummyPlatform.super.apply( this, arguments );
18 // Set this to true to test storage methods failing and returning false
19 this.storageDisabled = false;
20 }
21 OO.inheritClass( DummyPlatform, ve.init.Platform );
22 DummyPlatform.prototype.formatNumber = function ( number ) {
23 return number.toLocaleString();
24 };
25 DummyPlatform.prototype.getUserLanguages = function () {
26 return [ 'en' ];
27 };
28 DummyPlatform.prototype.getMessage = function () {
29 return Array.prototype.join.call( arguments, ',' );
30 };
31 DummyPlatform.prototype.getHtmlMessage = function ( ...args ) {
32 const $wrapper = $( '<div>' );
33 args.forEach( ( arg, i ) => {
34 $wrapper.append( arg );
35 if ( i < args.length - 1 ) {
36 $wrapper.append( ',' );
37 }
38 } );
39 // Merge text nodes
40 $wrapper[ 0 ].normalize();
41 return $wrapper.contents().toArray();
42 };
43 DummyPlatform.prototype.getLanguageCodes = function () {
44 return [ 'ar', 'en', 'es', 'fr', 'ru', 'zh' ];
45 };
46 DummyPlatform.prototype.getLanguageName = function ( lang ) {
47 return 'langname-' + lang;
48 };
49 DummyPlatform.prototype.getLanguageDirection = function () {
50 return 'ltr';
51 };
52 DummyPlatform.prototype.getExternalLinkUrlProtocolsRegExp = function () {
53 return /^https?:\/\//i;
54 };
55 DummyPlatform.prototype.getUnanchoredExternalLinkUrlProtocolsRegExp = function () {
56 return /https?:\/\//i;
57 };
58 DummyPlatform.prototype.getUserConfig = function () {
59 return undefined;
60 };
61 DummyPlatform.prototype.setUserConfig = function () {};
62 DummyPlatform.prototype.createSafeStorage = function ( store ) {
63 const platform = this;
64 const EXPIRY_PREFIX = '_EXPIRY_';
65
66 const MockSafeStorage = function ( s ) {
67 this.store = s;
68 };
69 OO.initClass( MockSafeStorage );
70 MockSafeStorage.prototype.get = function ( key ) {
71 if ( platform.storageDisabled ) {
72 return false;
73 }
74 return this.store.getItem( key );
75 };
76 MockSafeStorage.prototype.set = function ( key, value, expiry ) {
77 if ( platform.storageDisabled || value === '__FAIL__' ) {
78 return false;
79 }
80 this.store.setItem( key, value );
81 this.setExpires( key, expiry );
82 return true;
83 };
84 MockSafeStorage.prototype.remove = function ( key ) {
85 if ( platform.storageDisabled ) {
86 return false;
87 }
88 this.store.removeItem( key );
89 this.setExpires( key );
90 return true;
91 };
92 MockSafeStorage.prototype.getObject = function ( key ) {
93 const json = this.get( key );
94
95 if ( json === false ) {
96 return false;
97 }
98
99 try {
100 return JSON.parse( json );
101 } catch ( e ) {}
102
103 return null;
104 };
105 MockSafeStorage.prototype.setObject = function ( key, value ) {
106 try {
107 const json = JSON.stringify( value );
108 return this.set( key, json );
109 } catch ( e ) {}
110 return false;
111 };
112 MockSafeStorage.prototype.setExpires = function ( key, expiry ) {
113 if ( platform.storageDisabled ) {
114 return false;
115 }
116 if ( expiry ) {
117 this.store.setItem(
118 EXPIRY_PREFIX + key,
119 Math.floor( Date.now() / 1000 ) + expiry
120 );
121 } else {
122 this.store.removeItem( EXPIRY_PREFIX + key );
123 }
124 };
125
126 return new MockSafeStorage( store );
127 };
128 DummyPlatform.prototype.createLocalStorage = DummyPlatform.prototype.createSessionStorage = function ( store ) {
129 store = store || {};
130
131 const MockSystemStorage = function () {};
132 OO.initClass( MockSystemStorage );
133 MockSystemStorage.prototype.getItem = function ( key ) {
134 return Object.prototype.hasOwnProperty.call( store, key ) ?
135 store[ key ] :
136 null;
137 };
138 MockSystemStorage.prototype.setItem = function ( key, value ) {
139 store[ key ] = String( value );
140 };
141 MockSystemStorage.prototype.removeItem = function ( key ) {
142 delete store[ key ];
143 };
144 MockSystemStorage.prototype.clear = function () {
145 for ( const key in store ) {
146 delete store[ key ];
147 }
148 };
149 MockSystemStorage.prototype.key = function ( index ) {
150 const keys = Object.keys( store );
151 return index < keys.length ? keys[ index ] : null;
152 };
153 if ( !Object.prototype.hasOwnProperty.call( store, 'length' ) ) {
154 Object.defineProperty( store, 'length', {
155 get: function () {
156 return Object.keys( store ).length;
157 }
158 } );
159 }
160
161 const storage = this.createSafeStorage( new MockSystemStorage( store ) );
162
163 return ve.init.createConflictableStorage( storage );
164 };
165
166 ve.test.utils.DummyPlatform = DummyPlatform;
167
168 function DummyTarget() {
169 DummyTarget.super.apply( this, arguments );
170 }
171 OO.inheritClass( DummyTarget, ve.init.Target );
172 DummyTarget.prototype.addSurface = function () {
173 // Parent method
174 const surface = DummyTarget.super.prototype.addSurface.apply( this, arguments );
175 this.$element.append( surface.$element );
176 if ( !this.getSurface() ) {
177 this.setSurface( surface );
178 }
179 surface.initialize();
180 return surface;
181 };
182 DummyTarget.prototype.setupToolbar = function () {};
183
184 ve.test.utils.DummyTarget = DummyTarget;
185
186 /* eslint-disable no-new */
187 new ve.test.utils.DummyPlatform();
188 new ve.test.utils.DummyTarget(); // Target gets appended to qunit-fixture in ve.qunit.local.js
189 /* eslint-enable no-new */
190
191 // Disable scroll animatinos
192 ve.scrollIntoView = function () {
193 return ve.createDeferred().resolve().promise();
194 };
195
196 const voidGroup = '(' + ve.elementTypes.void.join( '|' ) + ')';
197
198 const voidRegexp = new RegExp( '(<' + voidGroup + '[^>]*?(/?))>', 'g' );
199 const originalCreateDocumentFromHtml = ve.createDocumentFromHtml;
200 /**
201 * Override ve.createDocumentFromHtml to validate HTML structure using an XML parser
202 *
203 * Some automatic fixes are applied to HTML to make it parseable,
204 * but some errors will still be thrown, for example:
205 * - Unescaped < or > in attributes
206 *
207 * If your test HTML is triggering a false positive warning, you can
208 * disable this check with the ignoreXmlWarnings param.
209 *
210 * @param {string} html
211 * @param {boolean} ignoreXmlWarnings Skip validation
212 * @return {HTMLDocument}
213 */
214 ve.createDocumentFromHtml = function ( html, ignoreXmlWarnings ) {
215 if ( html && !ignoreXmlWarnings ) {
216 const xml = '<xml>' +
217 html
218 // Close open void tags
219 .replace(
220 voidRegexp,
221 ( ...args ) => args[ 3 ] ?
222 // self-closing - do nothing
223 args[ 0 ] :
224 // add close tag
225 args[ 0 ] + '</' + args[ 2 ] + '>'
226 )
227 // Remove entities, named ones not recognised
228 .replace( /&[^;]+;/g, '' )
229 // Remove doctype
230 .replace( /<!doctype html>/i, '' ) +
231 '</xml>';
232 let xmlDoc;
233 // Firefox additionally throws an error
234 try {
235 xmlDoc = ( new DOMParser() ).parseFromString( xml, 'application/xml' );
236 } catch ( e ) {
237 }
238 if ( xmlDoc ) {
239 const parserError = xmlDoc.querySelector( 'parsererror' );
240 if ( parserError ) {
241 // eslint-disable-next-line no-console
242 console.warn( parserError.innerText, '\n', html, '\n', xml );
243 }
244 }
245 }
246
247 return originalCreateDocumentFromHtml( html );
248 };
249
250 function getSerializableData( model ) {
251 return model.getFullData( undefined, 'roundTrip' );
252 }
253
254 /**
255 * Make a HTML `<base>` tag
256 *
257 * @param {string} base Base URL
258 * @return {string}
259 */
260 ve.test.utils.makeBaseTag = function ( base ) {
261 if ( /[<>&'"]/.test( base ) ) {
262 throw new Error( 'Weird base' );
263 }
264 return '<base href="' + base + '">';
265 };
266
267 /**
268 * Add a `<base>` tag to `<head>` using HTML string splicing
269 *
270 * @param {string} docHtml Document HTML
271 * @param {string} base Base URL
272 * @return {string} Document HTML
273 */
274 ve.test.utils.addBaseTag = function ( docHtml, base ) {
275 if ( !ve.matchTag( docHtml, 'body' ) ) {
276 docHtml = '<body>' + docHtml + '</body>';
277 }
278 return ve.addHeadTag( docHtml, ve.test.utils.makeBaseTag( base ) );
279 };
280
281 /**
282 * @param {QUnit.Assert} assert
283 * @param {Object} caseItem
284 * @param {string} caseItem.type
285 * @param {ve.Range} caseItem.range
286 * @param {Function} caseItem.expected
287 * @param {string} caseItem.base
288 * @param {string} caseItem.msg
289 */
290 ve.test.utils.runIsolateTest = function ( assert, caseItem ) {
291 if ( arguments.length > 2 ) {
292 caseItem = {
293 type: arguments[ 1 ],
294 range: arguments[ 2 ],
295 expected: arguments[ 3 ],
296 base: arguments[ 4 ],
297 msg: arguments[ 5 ]
298 };
299 }
300 const doc = ve.dm.example.createExampleDocument( 'isolationData', null, caseItem.base ),
301 surface = new ve.dm.Surface( doc ),
302 fragment = surface.getLinearFragment( caseItem.range );
303
304 const data = ve.copy( getSerializableData( doc ) );
305 fragment.isolateAndUnwrap( caseItem.type );
306 caseItem.expected( data );
307
308 assert.deepEqual( getSerializableData( doc ), data, caseItem.msg );
309 };
310
311 /**
312 * @param {QUnit.Assert} assert
313 * @param {Object} caseItem
314 * @param {string} caseItem.msg
315 * @param {string} caseItem.actionName
316 * @param {string} caseItem.method
317 * @param {string} caseItem.html
318 * @param {Array} [caseItem.args] Arguments to pass to the action
319 * @param {ve.Range|Object|string} caseItem.rangeOrSelection
320 * @param {boolean} [caseItem.createView] Create a view surface, instead of just a model surface (slower)
321 * @param {ve.Range|Object|string} [caseItem.expectedRangeOrSelection]
322 * @param {ve.Range|Object|string} [caseItem.expectedOriginalRangeOrSelection]
323 * @param {boolean} [caseItem.undo] Test that the action undoes cleanly
324 * @param {Function} [caseItem.expectedData] Function to mutate linear data into expected data
325 * @param {Function} [caseItem.expectedOriginalData] Function to mutate linear data into expected data after undo
326 */
327 ve.test.utils.runActionTest = function ( assert, caseItem ) {
328 if ( arguments.length > 2 ) {
329 const args = Array.prototype.slice.call( arguments );
330 const options = args[ 8 ] || {};
331 assert = args[ 1 ];
332 caseItem = {
333 actionName: args[ 0 ],
334 html: args[ 2 ],
335 createView: args[ 3 ],
336 method: args[ 4 ],
337 args: args[ 5 ],
338 rangeOrSelection: args[ 6 ],
339 msg: args[ 7 ],
340 ...options
341 };
342 }
343 const surface = caseItem.createView ?
344 ve.test.utils.createViewOnlySurfaceFromHtml( caseItem.html || ve.dm.example.html ) :
345 ve.test.utils.createModelOnlySurfaceFromHtml( caseItem.html || ve.dm.example.html ),
346 action = ve.ui.actionFactory.create( caseItem.actionName, surface ),
347 data = ve.copy( getSerializableData( surface.getModel().getDocument() ) ),
348 documentModel = surface.getModel().getDocument(),
349 selection = ve.test.utils.selectionFromRangeOrSelection( documentModel, caseItem.rangeOrSelection ),
350 expectedSelection = caseItem.expectedRangeOrSelection && ve.test.utils.selectionFromRangeOrSelection( documentModel, caseItem.expectedRangeOrSelection );
351
352 let originalData;
353 if ( caseItem.undo ) {
354 originalData = ve.copy( data );
355 }
356
357 ve.dm.example.postprocessAnnotations( data, surface.getModel().getDocument().getStore() );
358
359 if ( caseItem.expectedData ) {
360 caseItem.expectedData( data, action );
361 }
362
363 surface.getModel().setSelection( selection );
364 action[ caseItem.method ].apply( action, caseItem.args || [] );
365
366 const afterApply = () => {
367 const actualData = getSerializableData( surface.getModel().getDocument() );
368 ve.dm.example.postprocessAnnotations( actualData, surface.getModel().getDocument().getStore() );
369 assert.equalLinearData( actualData, data, caseItem.msg + ': data models match' );
370 if ( expectedSelection ) {
371 assert.equalHash( surface.getModel().getSelection(), expectedSelection, caseItem.msg + ': selections match' );
372 }
373
374 if ( caseItem.undo ) {
375 if ( caseItem.expectedOriginalData ) {
376 caseItem.expectedOriginalData( originalData, action );
377 }
378
379 surface.getModel().undo();
380
381 assert.equalLinearData( getSerializableData( surface.getModel().getDocument() ), originalData, caseItem.msg + ' (undo): data models match' );
382 if ( expectedSelection ) {
383 const expectedOriginalRangeOrSelection = caseItem.expectedOriginalRangeOrSelection &&
384 ve.test.utils.selectionFromRangeOrSelection( documentModel, caseItem.expectedOriginalRangeOrSelection );
385 assert.equalHash( surface.getModel().getSelection(), expectedOriginalRangeOrSelection || selection, caseItem.msg + ' (undo): selections match' );
386 }
387 }
388 };
389
390 if ( caseItem.createView ) {
391 // When rendering a view, wait for MutationObserver events to fire
392 // before checking document state.
393 const done = assert.async();
394 setTimeout( () => {
395 afterApply();
396 done();
397 } );
398 } else {
399 // In model-only mode test synchronously
400 afterApply();
401 }
402 };
403
404 ve.test.utils.runGetModelFromDomTest = function ( assert, caseItem, msg ) {
405 if ( caseItem.head !== undefined || caseItem.body !== undefined ) {
406 const html = '<head>' + ( caseItem.head || '' ) + '</head><body>' + caseItem.body + '</body>';
407 const htmlDoc = ve.createDocumentFromHtml( ve.test.utils.addBaseTag( html, caseItem.base ), caseItem.ignoreXmlWarnings );
408 const model = ve.dm.converter.getModelFromDom( htmlDoc, { fromClipboard: !!caseItem.fromClipboard } );
409 let actualDataReal = model.getFullData();
410 let actualDataMeta = getSerializableData( model );
411
412 // Round-trip here, check round-trip later
413 if ( caseItem.modify ) {
414 actualDataReal = ve.copy( actualDataReal );
415 actualDataMeta = ve.copy( actualDataMeta );
416 caseItem.modify( model );
417 }
418 const actualRtDoc = ve.dm.converter.getDomFromModel( model );
419
420 // Normalize and verify data
421 ve.dm.example.postprocessAnnotations( actualDataReal, model.getStore(), caseItem.preserveAnnotationDomElements );
422 ve.dm.example.postprocessAnnotations( actualDataMeta, model.getStore(), caseItem.preserveAnnotationDomElements );
423
424 assert.equalLinearData( actualDataReal, ( caseItem.realData || caseItem.data ), msg + ': real data' );
425 assert.equalLinearData( actualDataMeta, caseItem.data, msg + ': data with metaItems restored' );
426
427 assert.deepEqual( model.getInnerWhitespace(), caseItem.innerWhitespace || new Array( 2 ), msg + ': inner whitespace' );
428 // Check storeItems have been added to store
429 if ( caseItem.storeItems ) {
430 for ( const hash in caseItem.storeItems ) {
431 assert.deepEqualWithDomElements(
432 model.getStore().value( hash ) || {},
433 caseItem.storeItems[ hash ],
434 msg + ': store item ' + hash + ' found'
435 );
436 }
437 }
438 // Check round-trip
439 const expectedRtDoc = caseItem.normalizedBody ?
440 ve.createDocumentFromHtml( ve.test.utils.addBaseTag( caseItem.normalizedBody, caseItem.base ), caseItem.ignoreXmlWarnings ) :
441 htmlDoc;
442 assert.equalDomElement( actualRtDoc.body, expectedRtDoc.body, msg + ': round-trip' );
443 }
444 };
445
446 ve.test.utils.getModelFromTestCase = function ( caseItem ) {
447 const store = new ve.dm.HashValueStore();
448
449 // Load storeItems into store
450 if ( caseItem.storeItems ) {
451 for ( const hash in caseItem.storeItems ) {
452 store.hashStore[ hash ] = ve.copy( caseItem.storeItems[ hash ] );
453 }
454 }
455 const model = new ve.dm.Document( ve.dm.example.preprocessAnnotations( caseItem.data, store ) );
456 ve.fixBase( model.getHtmlDocument(), model.getHtmlDocument(), caseItem.base );
457 model.innerWhitespace = caseItem.innerWhitespace ? ve.copy( caseItem.innerWhitespace ) : new Array( 2 );
458 if ( caseItem.modify ) {
459 caseItem.modify( model );
460 }
461 return model;
462 };
463
464 ve.test.utils.runGetDomFromModelTest = function ( assert, caseItem, msg ) {
465 const model = ve.test.utils.getModelFromTestCase( caseItem );
466 const originalData = ve.copy( getSerializableData( model ) );
467 const fromDataBody = caseItem.fromDataBody || caseItem.normalizedBody || caseItem.body;
468 const html = '<body>' + fromDataBody + '</body>';
469 const clipboardHtml = '<body>' + ( caseItem.clipboardBody || fromDataBody ) + '</body>';
470 const previewHtml = '<body>' + ( caseItem.previewBody || fromDataBody ) + '</body>';
471 assert.equalDomElement(
472 ve.dm.converter.getDomFromModel( model ),
473 ve.createDocumentFromHtml( html, caseItem.ignoreXmlWarnings ),
474 msg
475 );
476 assert.equalDomElement(
477 ve.dm.converter.getDomFromModel( model, ve.dm.Converter.static.CLIPBOARD_MODE ),
478 ve.createDocumentFromHtml( clipboardHtml, caseItem.ignoreXmlWarnings ),
479 msg + ' (clipboard mode)'
480 );
481 // Make this conditional on previewBody being present until downstream test-suites have been fixed.
482 // This should be changed to:
483 // if ( caseItem.previewBody !== false ) {
484 if ( caseItem.previewBody ) {
485 assert.equalDomElement(
486 ve.dm.converter.getDomFromModel( model, ve.dm.Converter.static.PREVIEW_MODE ),
487 ve.createDocumentFromHtml( previewHtml, caseItem.ignoreXmlWarnings ),
488 msg + ' (preview mode)'
489 );
490 }
491 assert.deepEqualWithDomElements( getSerializableData( model ), originalData, msg + ' (data hasn\'t changed)' );
492 };
493
494 ve.test.utils.runDiffElementTest = function ( assert, caseItem ) {
495 const oldDoc = ve.dm.converter.getModelFromDom( ve.createDocumentFromHtml( caseItem.oldDoc ) ),
496 newDoc = ve.dm.converter.getModelFromDom( ve.createDocumentFromHtml( caseItem.newDoc ) );
497 // TODO: Differ expects newDoc to be derived from oldDoc and contain all its store data.
498 // We may want to remove that assumption from the differ?
499 newDoc.getStore().merge( oldDoc.getStore() );
500 const visualDiff = new ve.dm.VisualDiff( oldDoc, newDoc, caseItem.forceTimeout ? -1 : undefined );
501 const diffElement = new ve.ui.DiffElement( visualDiff );
502 assert.equalDomElement( diffElement.$document[ 0 ], $( '<div>' ).addClass( 've-ui-diffElement-document' ).html( caseItem.expected )[ 0 ], caseItem.msg );
503 assert.deepEqualWithDomElements(
504 diffElement.descriptions.items.map( ( item ) => item.$label.contents().toArray() ),
505 ( caseItem.expectedDescriptions || [] ).map( ( expected ) => $.parseHTML( expected ) ),
506 caseItem.msg + ': sidebar'
507 );
508 assert.strictEqual(
509 diffElement.$messages.children().length, caseItem.forceTimeout ? 1 : 0,
510 'Timeout message ' + ( caseItem.forceTimeout ? 'shown' : 'not shown' )
511 );
512 };
513
514 /**
515 * Create a UI surface from some HTML
516 *
517 * This is incredibly slow (>100ms) so consider creating just a ce.Surface
518 * or dm.Surface, or a mock surface using create(View|Model)OnlySurface*.
519 *
520 * @param {string} html
521 * @param {Object} config Surface config
522 * @return {ve.ui.Surface}
523 */
524 ve.test.utils.createSurfaceFromHtml = function ( html, config ) {
525 return this.createSurfaceFromDocument(
526 ve.dm.converter.getModelFromDom( ve.createDocumentFromHtml( html ) ),
527 config
528 );
529 };
530
531 /**
532 * Create a UI surface from a document
533 *
534 * See warning in ve.test.utils.createSurfaceFromHtml.
535 *
536 * @param {ve.dm.Document} doc
537 * @param {Object} [config] Surface config
538 * @return {ve.ui.Surface}
539 */
540 ve.test.utils.createSurfaceFromDocument = function ( doc, config ) {
541 return ve.init.target.addSurface( doc, config );
542 };
543
544 /**
545 * Create a CE surface from some HTML
546 *
547 * @param {string} html
548 * @param {Object} config Surface config
549 * @return {ve.ce.Surface}
550 */
551 ve.test.utils.createSurfaceViewFromHtml = function ( html, config ) {
552 return this.createSurfaceViewFromDocument(
553 ve.dm.converter.getModelFromDom( ve.createDocumentFromHtml( html ) ),
554 config
555 );
556 };
557
558 /**
559 * Create a CE surface from a document or surface model
560 *
561 * TODO: Rename to createSurfaceViewFromModel
562 *
563 * @param {ve.dm.Document|ve.dm.Surface} docOrSurface Document or surface model
564 * @param {Object} config Surface config
565 * @return {ve.ce.Surface}
566 */
567 ve.test.utils.createSurfaceViewFromDocument = function ( docOrSurface, config ) {
568 config = ve.init.target.getSurfaceConfig( config );
569
570 let model = null, view = null;
571
572 const mockSurface = {
573 $blockers: $( '<div>' ),
574 $selections: $( '<div>' ),
575 $element: $( '<div>' ),
576 $scrollContainer: $( document.documentElement ),
577 $scrollListener: $( window ),
578 isMobile: function () {
579 return false;
580 },
581 isMultiline: function () {
582 return true;
583 },
584 isReadOnly: function () {
585 return false;
586 },
587 getBoundingClientRect: function () {
588 return this.$element[ 0 ].getClientRects()[ 0 ] || null;
589 },
590 getViewportDimensions: function () {
591 return null;
592 },
593 getImportRules: function () {
594 return this.importRules;
595 },
596 getMode: function () {
597 return config.mode || 'visual';
598 },
599 getModel: function () {
600 return model;
601 },
602 getView: function () {
603 return view;
604 },
605 getCommands: function () {
606 return ve.ui.commandRegistry.getNames();
607 },
608 getContext: function () {
609 return {
610 toggle: function () {},
611 updateDimensions: function () {}
612 };
613 },
614 isDisabled: function () {
615 return false;
616 },
617 emit: function () {},
618 connect: function () {},
619 disconnect: function () {},
620 execute: ve.ui.Surface.prototype.execute,
621 executeWithSource: ve.ui.Surface.prototype.executeWithSource,
622 createView: ve.ui.Surface.prototype.createView,
623 createModel: ve.ui.Surface.prototype.createModel,
624 context: {
625 // Used by ContentAction
626 isVisible: function () {
627 return false;
628 }
629 }
630 };
631 // Copied from ui.Surface constructor
632 mockSurface.commandRegistry = config.commandRegistry || ve.ui.commandRegistry;
633 mockSurface.sequenceRegistry = config.sequenceRegistry || ve.ui.sequenceRegistry;
634 mockSurface.dataTransferHandlerFactory = config.dataTransferHandlerFactory || ve.ui.dataTransferHandlerFactory;
635 mockSurface.commands = OO.simpleArrayDifference(
636 config.includeCommands || mockSurface.commandRegistry.getNames(), config.excludeCommands || []
637 );
638 mockSurface.triggerListener = new ve.TriggerListener( mockSurface.commands, mockSurface.commandRegistry );
639 mockSurface.importRules = config.importRules || {};
640
641 model = docOrSurface instanceof ve.dm.Surface ? docOrSurface : mockSurface.createModel( docOrSurface );
642 view = mockSurface.createView( model );
643
644 view.surface = mockSurface;
645 mockSurface.$element.append( view.$element );
646 // eslint-disable-next-line no-jquery/no-global-selector
647 $( '#qunit-fixture' ).append( mockSurface.$element );
648
649 view.initialize();
650 model.initialize();
651
652 return view;
653 };
654
655 /**
656 * Create a view-only UI surface from some HTML
657 *
658 * @param {string} html Document HTML
659 * @param {Object} config Surface config
660 * @return {Object} Mock UI surface which only returns a real view (and its model)
661 */
662 ve.test.utils.createViewOnlySurfaceFromHtml = function ( html, config ) {
663 const surfaceView = ve.test.utils.createSurfaceViewFromDocument(
664 ve.dm.converter.getModelFromDom( ve.createDocumentFromHtml( html ) ),
665 config
666 );
667
668 return surfaceView.surface;
669 };
670
671 /**
672 * Create a model-only UI surface from some HTML
673 *
674 * @param {string} html Document HTML
675 * @param {Object} config Surface config
676 * @return {Object} Mock UI surface which only returns a real model
677 */
678 ve.test.utils.createModelOnlySurfaceFromHtml = function ( html, config ) {
679 const model = new ve.dm.Surface(
680 ve.dm.converter.getModelFromDom( ve.createDocumentFromHtml( html ) ),
681 null,
682 config
683 );
684 return {
685 getModel: function () {
686 return model;
687 },
688 getView: function () {
689 // Mock view
690 return {
691 focus: function () {}
692 };
693 }
694 };
695 };
696
697 /**
698 * Create a DM selection from a range or a JSON selection
699 *
700 * @param {ve.dm.Document} doc
701 * @param {ve.Range|Object|string} rangeOrSelection Range or JSON selection
702 * @return {ve.dm.Selection}
703 */
704 ve.test.utils.selectionFromRangeOrSelection = function ( doc, rangeOrSelection ) {
705 return rangeOrSelection instanceof ve.Range ?
706 new ve.dm.LinearSelection( rangeOrSelection ) :
707 ve.dm.Selection.static.newFromJSON( rangeOrSelection );
708 };
709
710 /**
711 * Build a DOM from a JSON structure.
712 *
713 * @param {Object} data JSON structure
714 * @param {string} data.type Tag name or '#text' or '#comment'
715 * @param {string} [data.text] Node text, only used if type is '#text' or '#comment'
716 * @param {Object[]} [data.children] Node's children; array of objects like data
717 * @return {Node} DOM node corresponding to data
718 */
719 ve.test.utils.buildDom = function buildDom( data ) {
720 if ( data.type === '#text' ) {
721 return document.createTextNode( data.text );
722 }
723 if ( data.type === '#comment' ) {
724 return document.createComment( data.text );
725 }
726 const node = document.createElement( data.type );
727 if ( data.children ) {
728 for ( let i = 0; i < data.children.length; i++ ) {
729 node.appendChild( buildDom( data.children[ i ] ) );
730 }
731 }
732 return node;
733 };
734
735 /**
736 * Like a reduced outerHTML serialization, but with a position marker '|'.
737 *
738 * For clarity, also wraps each text node in a fake tag, and omits non-class attributes.
739 *
740 * @param {Node} rootNode The node to serialize
741 * @param {Object} position
742 * @param {Node} position.node The node at which the position marker lies
743 * @param {number} position.offset The offset at which the position marker lies
744 * @param {Object} [options]
745 * @param {Function|string} options.ignore Selector for nodes to omit from output
746 * @return {string} Serialization of the node and position
747 */
748 ve.test.utils.serializePosition = function ( rootNode, position, options ) {
749 const html = [];
750 function add( node ) {
751 if ( options && options.ignore && $( node ).is( options.ignore ) ) {
752 return;
753 } else if ( node.nodeType === Node.TEXT_NODE ) {
754 html.push( '<#text>' );
755 if ( node === position.node ) {
756 html.push( ve.escapeHtml(
757 node.textContent.slice( 0, position.offset ) +
758 '|' +
759 node.textContent.slice( position.offset )
760 ) );
761 } else {
762 html.push( ve.escapeHtml( node.textContent ) );
763 }
764 html.push( '</#text>' );
765 return;
766 } else if ( node.nodeType !== Node.ELEMENT_NODE ) {
767 html.push( '<#unknown type=\'' + node.nodeType + '\'/>' );
768 return;
769 }
770 // else node.nodeType === Node.ELEMENT_NODE
771
772 html.push( '<', ve.escapeHtml( node.nodeName.toLowerCase() ) );
773 if ( node.hasAttribute( 'class' ) ) {
774 // Single quotes are less annoying for JSON escaping
775 html.push(
776 ' class=\'',
777 ve.escapeHtml( node.getAttribute( 'class' ) ),
778 '\''
779 );
780 }
781 html.push( '>' );
782 for ( let i = 0, len = node.childNodes.length; i < len; i++ ) {
783 if ( node === position.node && i === position.offset ) {
784 html.push( '|' );
785 }
786 add( node.childNodes[ i ] );
787 }
788 if ( node === position.node && node.childNodes.length === position.offset ) {
789 html.push( '|' );
790 }
791 html.push( '</', ve.escapeHtml( node.nodeName.toLowerCase() ), '>' );
792 }
793 add( rootNode );
794 return html.join( '' );
795 };
796
797 /**
798 * Take control of EventSequencer timeouts
799 *
800 * Modifies an EventSequencer object in-place to allow setTimeout behaviour to be
801 * simulated by test code. Replaces `postpone` and `cancelPostponed` with methods that
802 * queue/unqueue to an array, and adds an `endLoop` method to unqueue and run every
803 * queued call.
804 *
805 * @param {ve.EventSequencer} eventSequencer The EventSequencer to hijack
806 */
807 ve.test.utils.hijackEventSequencerTimeouts = function ( eventSequencer ) {
808 eventSequencer.postponedCalls = [];
809
810 eventSequencer.postpone = function ( f ) {
811 this.postponedCalls.push( f );
812 return this.postponedCalls.length - 1;
813 };
814
815 eventSequencer.cancelPostponed = function ( callId ) {
816 this.postponedCalls[ callId ] = null;
817 };
818
819 eventSequencer.endLoop = function () {
820 // Run every postponed call in order of postponement. Do not cache
821 // list length, because postponed calls may add more postponed calls
822 for ( let i = 0; i < this.postponedCalls.length; i++ ) {
823 const f = this.postponedCalls[ i ];
824 if ( f ) {
825 // Exceptions thrown here will leave the postponed calls
826 // list in an inconsistent state
827 f();
828 }
829 }
830 this.postponedCalls.length = 0;
831 };
832 };
833 }() );