Merge "WebdriverIO should be able to run Chrome headlessly"
[lhc/web/wiklou.git] / resources / src / mediawiki.special / mediawiki.special.apisandbox.js
1 ( function ( $, mw, OO ) {
2 'use strict';
3 var ApiSandbox, Util, WidgetMethods, Validators,
4 $content, panel, booklet, oldhash, windowManager, fullscreenButton,
5 formatDropdown,
6 api = new mw.Api(),
7 bookletPages = [],
8 availableFormats = {},
9 resultPage = null,
10 suppressErrors = true,
11 updatingBooklet = false,
12 pages = {},
13 moduleInfoCache = {},
14 baseRequestParams;
15
16 /**
17 * A wrapper for a widget that provides an enable/disable button
18 *
19 * @class
20 * @private
21 * @constructor
22 * @param {OO.ui.Widget} widget
23 * @param {Object} [config] Configuration options
24 */
25 function OptionalWidget( widget, config ) {
26 var k;
27
28 config = config || {};
29
30 this.widget = widget;
31 this.$cover = config.$cover ||
32 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-cover' );
33 this.checkbox = new OO.ui.CheckboxInputWidget( config.checkbox )
34 .on( 'change', this.onCheckboxChange, [], this );
35
36 OptionalWidget[ 'super' ].call( this, config );
37
38 // Forward most methods for convenience
39 for ( k in this.widget ) {
40 if ( $.isFunction( this.widget[ k ] ) && !this[ k ] ) {
41 this[ k ] = this.widget[ k ].bind( this.widget );
42 }
43 }
44
45 this.$cover.on( 'click', this.onOverlayClick.bind( this ) );
46
47 this.$element
48 .addClass( 'mw-apisandbox-optionalWidget' )
49 .append(
50 this.$cover,
51 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-fields' ).append(
52 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-widget' ).append(
53 widget.$element
54 ),
55 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-checkbox' ).append(
56 this.checkbox.$element
57 )
58 )
59 );
60
61 this.setDisabled( widget.isDisabled() );
62 }
63 OO.inheritClass( OptionalWidget, OO.ui.Widget );
64 OptionalWidget.prototype.onCheckboxChange = function ( checked ) {
65 this.setDisabled( !checked );
66 };
67 OptionalWidget.prototype.onOverlayClick = function () {
68 this.setDisabled( false );
69 if ( $.isFunction( this.widget.focus ) ) {
70 this.widget.focus();
71 }
72 };
73 OptionalWidget.prototype.setDisabled = function ( disabled ) {
74 OptionalWidget[ 'super' ].prototype.setDisabled.call( this, disabled );
75 this.widget.setDisabled( this.isDisabled() );
76 this.checkbox.setSelected( !this.isDisabled() );
77 this.$cover.toggle( this.isDisabled() );
78 return this;
79 };
80
81 WidgetMethods = {
82 textInputWidget: {
83 getApiValue: function () {
84 return this.getValue();
85 },
86 setApiValue: function ( v ) {
87 if ( v === undefined ) {
88 v = this.paramInfo[ 'default' ];
89 }
90 this.setValue( v );
91 },
92 apiCheckValid: function () {
93 var that = this;
94 return this.getValidity().then( function () {
95 return $.Deferred().resolve( true ).promise();
96 }, function () {
97 return $.Deferred().resolve( false ).promise();
98 } ).done( function ( ok ) {
99 ok = ok || suppressErrors;
100 that.setIcon( ok ? null : 'alert' );
101 that.setIconTitle( ok ? '' : mw.message( 'apisandbox-alert-field' ).plain() );
102 } );
103 }
104 },
105
106 dateTimeInputWidget: {
107 getValidity: function () {
108 if ( !Util.apiBool( this.paramInfo.required ) || this.getApiValue() !== '' ) {
109 return $.Deferred().resolve().promise();
110 } else {
111 return $.Deferred().reject().promise();
112 }
113 }
114 },
115
116 tokenWidget: {
117 alertTokenError: function ( code, error ) {
118 windowManager.openWindow( 'errorAlert', {
119 title: Util.parseMsg( 'apisandbox-results-fixtoken-fail', this.paramInfo.tokentype ),
120 message: error,
121 actions: [
122 {
123 action: 'accept',
124 label: OO.ui.msg( 'ooui-dialog-process-dismiss' ),
125 flags: 'primary'
126 }
127 ]
128 } );
129 },
130 fetchToken: function () {
131 this.pushPending();
132 return api.getToken( this.paramInfo.tokentype )
133 .done( this.setApiValue.bind( this ) )
134 .fail( this.alertTokenError.bind( this ) )
135 .always( this.popPending.bind( this ) );
136 },
137 setApiValue: function ( v ) {
138 WidgetMethods.textInputWidget.setApiValue.call( this, v );
139 if ( v === '123ABC' ) {
140 this.fetchToken();
141 }
142 }
143 },
144
145 passwordWidget: {
146 getApiValueForDisplay: function () {
147 return '';
148 }
149 },
150
151 toggleSwitchWidget: {
152 getApiValue: function () {
153 return this.getValue() ? 1 : undefined;
154 },
155 setApiValue: function ( v ) {
156 this.setValue( Util.apiBool( v ) );
157 },
158 apiCheckValid: function () {
159 return $.Deferred().resolve( true ).promise();
160 }
161 },
162
163 dropdownWidget: {
164 getApiValue: function () {
165 var item = this.getMenu().findSelectedItem();
166 return item === null ? undefined : item.getData();
167 },
168 setApiValue: function ( v ) {
169 var menu = this.getMenu();
170
171 if ( v === undefined ) {
172 v = this.paramInfo[ 'default' ];
173 }
174 if ( v === undefined ) {
175 menu.selectItem();
176 } else {
177 menu.selectItemByData( String( v ) );
178 }
179 },
180 apiCheckValid: function () {
181 var ok = this.getApiValue() !== undefined || suppressErrors;
182 this.setIcon( ok ? null : 'alert' );
183 this.setIconTitle( ok ? '' : mw.message( 'apisandbox-alert-field' ).plain() );
184 return $.Deferred().resolve( ok ).promise();
185 }
186 },
187
188 tagWidget: {
189 getApiValue: function () {
190 var items = this.getValue();
191 if ( items.join( '' ).indexOf( '|' ) === -1 ) {
192 return items.join( '|' );
193 } else {
194 return '\x1f' + items.join( '\x1f' );
195 }
196 },
197 setApiValue: function ( v ) {
198 if ( v === undefined || v === '' || v === '\x1f' ) {
199 this.setValue( [] );
200 } else {
201 v = String( v );
202 if ( v.indexOf( '\x1f' ) !== 0 ) {
203 this.setValue( v.split( '|' ) );
204 } else {
205 this.setValue( v.substr( 1 ).split( '\x1f' ) );
206 }
207 }
208 },
209 apiCheckValid: function () {
210 var ok = true,
211 pi = this.paramInfo;
212
213 if ( !suppressErrors ) {
214 ok = this.getApiValue() !== undefined && !(
215 pi.allspecifier !== undefined &&
216 this.getValue().length > 1 &&
217 this.getValue().indexOf( pi.allspecifier ) !== -1
218 );
219 }
220
221 this.setIcon( ok ? null : 'alert' );
222 this.setIconTitle( ok ? '' : mw.message( 'apisandbox-alert-field' ).plain() );
223 return $.Deferred().resolve( ok ).promise();
224 },
225 createTagItemWidget: function ( data, label ) {
226 var item = OO.ui.TagMultiselectWidget.prototype.createTagItemWidget.call( this, data, label );
227 if ( this.paramInfo.deprecatedvalues &&
228 this.paramInfo.deprecatedvalues.indexOf( data ) >= 0
229 ) {
230 item.$element.addClass( 'apihelp-deprecated-value' );
231 }
232 return item;
233 }
234 },
235
236 optionalWidget: {
237 getApiValue: function () {
238 return this.isDisabled() ? undefined : this.widget.getApiValue();
239 },
240 setApiValue: function ( v ) {
241 this.setDisabled( v === undefined );
242 this.widget.setApiValue( v );
243 },
244 apiCheckValid: function () {
245 if ( this.isDisabled() ) {
246 return $.Deferred().resolve( true ).promise();
247 } else {
248 return this.widget.apiCheckValid();
249 }
250 }
251 },
252
253 submoduleWidget: {
254 single: function () {
255 var v = this.isDisabled() ? this.paramInfo[ 'default' ] : this.getApiValue();
256 return v === undefined ? [] : [ { value: v, path: this.paramInfo.submodules[ v ] } ];
257 },
258 multi: function () {
259 var map = this.paramInfo.submodules,
260 v = this.isDisabled() ? this.paramInfo[ 'default' ] : this.getApiValue();
261 return v === undefined || v === '' ? [] : String( v ).split( '|' ).map( function ( v ) {
262 return { value: v, path: map[ v ] };
263 } );
264 }
265 },
266
267 uploadWidget: {
268 getApiValueForDisplay: function () {
269 return '...';
270 },
271 getApiValue: function () {
272 return this.getValue();
273 },
274 setApiValue: function () {
275 // Can't, sorry.
276 },
277 apiCheckValid: function () {
278 var ok = this.getValue() !== null || suppressErrors;
279 this.setIcon( ok ? null : 'alert' );
280 this.setIconTitle( ok ? '' : mw.message( 'apisandbox-alert-field' ).plain() );
281 return $.Deferred().resolve( ok ).promise();
282 }
283 }
284 };
285
286 Validators = {
287 generic: function () {
288 return !Util.apiBool( this.paramInfo.required ) || this.getApiValue() !== '';
289 }
290 };
291
292 /**
293 * @class mw.special.ApiSandbox.Util
294 * @private
295 */
296 Util = {
297 /**
298 * Fetch API module info
299 *
300 * @param {string} module Module to fetch data for
301 * @return {jQuery.Promise}
302 */
303 fetchModuleInfo: function ( module ) {
304 var apiPromise,
305 deferred = $.Deferred();
306
307 if ( moduleInfoCache.hasOwnProperty( module ) ) {
308 return deferred
309 .resolve( moduleInfoCache[ module ] )
310 .promise( { abort: function () {} } );
311 } else {
312 apiPromise = api.post( {
313 action: 'paraminfo',
314 modules: module,
315 helpformat: 'html',
316 uselang: mw.config.get( 'wgUserLanguage' )
317 } ).done( function ( data ) {
318 var info;
319
320 if ( data.warnings && data.warnings.paraminfo ) {
321 deferred.reject( '???', data.warnings.paraminfo[ '*' ] );
322 return;
323 }
324
325 info = data.paraminfo.modules;
326 if ( !info || info.length !== 1 || info[ 0 ].path !== module ) {
327 deferred.reject( '???', 'No module data returned' );
328 return;
329 }
330
331 moduleInfoCache[ module ] = info[ 0 ];
332 deferred.resolve( info[ 0 ] );
333 } ).fail( function ( code, details ) {
334 if ( code === 'http' ) {
335 details = 'HTTP error: ' + details.exception;
336 } else if ( details.error ) {
337 details = details.error.info;
338 }
339 deferred.reject( code, details );
340 } );
341 return deferred
342 .promise( { abort: apiPromise.abort } );
343 }
344 },
345
346 /**
347 * Mark all currently-in-use tokens as bad
348 */
349 markTokensBad: function () {
350 var page, subpages, i,
351 checkPages = [ pages.main ];
352
353 while ( checkPages.length ) {
354 page = checkPages.shift();
355
356 if ( page.tokenWidget ) {
357 api.badToken( page.tokenWidget.paramInfo.tokentype );
358 }
359
360 subpages = page.getSubpages();
361 for ( i = 0; i < subpages.length; i++ ) {
362 if ( pages.hasOwnProperty( subpages[ i ].key ) ) {
363 checkPages.push( pages[ subpages[ i ].key ] );
364 }
365 }
366 }
367 },
368
369 /**
370 * Test an API boolean
371 *
372 * @param {Mixed} value
373 * @return {boolean}
374 */
375 apiBool: function ( value ) {
376 return value !== undefined && value !== false;
377 },
378
379 /**
380 * Create a widget for a parameter.
381 *
382 * @param {Object} pi Parameter info from API
383 * @param {Object} opts Additional options
384 * @return {OO.ui.Widget}
385 */
386 createWidgetForParameter: function ( pi, opts ) {
387 var widget, innerWidget, finalWidget, items, $content, func,
388 multiModeButton = null,
389 multiModeInput = null,
390 multiModeAllowed = false;
391
392 opts = opts || {};
393
394 switch ( pi.type ) {
395 case 'boolean':
396 widget = new OO.ui.ToggleSwitchWidget();
397 widget.paramInfo = pi;
398 $.extend( widget, WidgetMethods.toggleSwitchWidget );
399 pi.required = true; // Avoid wrapping in the non-required widget
400 break;
401
402 case 'string':
403 case 'user':
404 if ( Util.apiBool( pi.multi ) ) {
405 widget = new OO.ui.TagMultiselectWidget( {
406 allowArbitrary: true,
407 allowDuplicates: Util.apiBool( pi.allowsduplicates ),
408 $overlay: true
409 } );
410 widget.paramInfo = pi;
411 $.extend( widget, WidgetMethods.tagWidget );
412 } else {
413 widget = new OO.ui.TextInputWidget( {
414 required: Util.apiBool( pi.required )
415 } );
416 }
417 if ( !Util.apiBool( pi.multi ) ) {
418 widget.paramInfo = pi;
419 $.extend( widget, WidgetMethods.textInputWidget );
420 widget.setValidation( Validators.generic );
421 }
422 if ( pi.tokentype ) {
423 widget.paramInfo = pi;
424 $.extend( widget, WidgetMethods.textInputWidget );
425 $.extend( widget, WidgetMethods.tokenWidget );
426 }
427 break;
428
429 case 'text':
430 widget = new OO.ui.MultilineTextInputWidget( {
431 required: Util.apiBool( pi.required )
432 } );
433 widget.paramInfo = pi;
434 $.extend( widget, WidgetMethods.textInputWidget );
435 widget.setValidation( Validators.generic );
436 break;
437
438 case 'password':
439 widget = new OO.ui.TextInputWidget( {
440 type: 'password',
441 required: Util.apiBool( pi.required )
442 } );
443 widget.paramInfo = pi;
444 $.extend( widget, WidgetMethods.textInputWidget );
445 $.extend( widget, WidgetMethods.passwordWidget );
446 widget.setValidation( Validators.generic );
447 multiModeAllowed = true;
448 multiModeInput = widget;
449 break;
450
451 case 'integer':
452 widget = new OO.ui.NumberInputWidget( {
453 required: Util.apiBool( pi.required ),
454 isInteger: true
455 } );
456 widget.setIcon = widget.input.setIcon.bind( widget.input );
457 widget.setIconTitle = widget.input.setIconTitle.bind( widget.input );
458 widget.getValidity = widget.input.getValidity.bind( widget.input );
459 widget.paramInfo = pi;
460 $.extend( widget, WidgetMethods.textInputWidget );
461 if ( Util.apiBool( pi.enforcerange ) ) {
462 widget.setRange( pi.min || -Infinity, pi.max || Infinity );
463 }
464 multiModeAllowed = true;
465 multiModeInput = widget;
466 break;
467
468 case 'limit':
469 widget = new OO.ui.TextInputWidget( {
470 required: Util.apiBool( pi.required )
471 } );
472 widget.setValidation( function ( value ) {
473 var n, pi = this.paramInfo;
474
475 if ( value === 'max' ) {
476 return true;
477 } else {
478 n = +value;
479 return !isNaN( n ) && isFinite( n ) &&
480 Math.floor( n ) === n &&
481 n >= pi.min && n <= pi.apiSandboxMax;
482 }
483 } );
484 pi.min = pi.min || 0;
485 pi.apiSandboxMax = mw.config.get( 'apihighlimits' ) ? pi.highmax : pi.max;
486 widget.paramInfo = pi;
487 $.extend( widget, WidgetMethods.textInputWidget );
488 multiModeAllowed = true;
489 multiModeInput = widget;
490 break;
491
492 case 'timestamp':
493 widget = new mw.widgets.datetime.DateTimeInputWidget( {
494 formatter: {
495 format: '${year|0}-${month|0}-${day|0}T${hour|0}:${minute|0}:${second|0}${zone|short}'
496 },
497 required: Util.apiBool( pi.required ),
498 clearable: false
499 } );
500 widget.paramInfo = pi;
501 $.extend( widget, WidgetMethods.textInputWidget );
502 $.extend( widget, WidgetMethods.dateTimeInputWidget );
503 multiModeAllowed = true;
504 break;
505
506 case 'upload':
507 widget = new OO.ui.SelectFileWidget();
508 widget.paramInfo = pi;
509 $.extend( widget, WidgetMethods.uploadWidget );
510 break;
511
512 case 'namespace':
513 items = $.map( mw.config.get( 'wgFormattedNamespaces' ), function ( name, ns ) {
514 if ( ns === '0' ) {
515 name = mw.message( 'blanknamespace' ).text();
516 }
517 return new OO.ui.MenuOptionWidget( { data: ns, label: name } );
518 } ).sort( function ( a, b ) {
519 return a.data - b.data;
520 } );
521 if ( Util.apiBool( pi.multi ) ) {
522 if ( pi.allspecifier !== undefined ) {
523 items.unshift( new OO.ui.MenuOptionWidget( {
524 data: pi.allspecifier,
525 label: mw.message( 'apisandbox-multivalue-all-namespaces', pi.allspecifier ).text()
526 } ) );
527 }
528
529 widget = new OO.ui.MenuTagMultiselectWidget( {
530 menu: { items: items },
531 $overlay: true
532 } );
533 widget.paramInfo = pi;
534 $.extend( widget, WidgetMethods.tagWidget );
535 } else {
536 widget = new OO.ui.DropdownWidget( {
537 menu: { items: items },
538 $overlay: true
539 } );
540 widget.paramInfo = pi;
541 $.extend( widget, WidgetMethods.dropdownWidget );
542 }
543 break;
544
545 default:
546 if ( !Array.isArray( pi.type ) ) {
547 throw new Error( 'Unknown parameter type ' + pi.type );
548 }
549
550 items = pi.type.map( function ( v ) {
551 var config = {
552 data: String( v ),
553 label: String( v ),
554 classes: []
555 };
556 if ( pi.deprecatedvalues && pi.deprecatedvalues.indexOf( v ) >= 0 ) {
557 config.classes.push( 'apihelp-deprecated-value' );
558 }
559 return new OO.ui.MenuOptionWidget( config );
560 } );
561 if ( Util.apiBool( pi.multi ) ) {
562 if ( pi.allspecifier !== undefined ) {
563 items.unshift( new OO.ui.MenuOptionWidget( {
564 data: pi.allspecifier,
565 label: mw.message( 'apisandbox-multivalue-all-values', pi.allspecifier ).text()
566 } ) );
567 }
568
569 widget = new OO.ui.MenuTagMultiselectWidget( {
570 menu: { items: items },
571 $overlay: true
572 } );
573 widget.paramInfo = pi;
574 $.extend( widget, WidgetMethods.tagWidget );
575 if ( Util.apiBool( pi.submodules ) ) {
576 widget.getSubmodules = WidgetMethods.submoduleWidget.multi;
577 widget.on( 'change', ApiSandbox.updateUI );
578 }
579 } else {
580 widget = new OO.ui.DropdownWidget( {
581 menu: { items: items },
582 $overlay: true
583 } );
584 widget.paramInfo = pi;
585 $.extend( widget, WidgetMethods.dropdownWidget );
586 if ( Util.apiBool( pi.submodules ) ) {
587 widget.getSubmodules = WidgetMethods.submoduleWidget.single;
588 widget.getMenu().on( 'select', ApiSandbox.updateUI );
589 }
590 if ( pi.deprecatedvalues ) {
591 widget.getMenu().on( 'select', function ( item ) {
592 this.$element.toggleClass(
593 'apihelp-deprecated-value',
594 pi.deprecatedvalues.indexOf( item.data ) >= 0
595 );
596 }, [], widget );
597 }
598 }
599
600 break;
601 }
602
603 if ( Util.apiBool( pi.multi ) && multiModeAllowed ) {
604 innerWidget = widget;
605
606 multiModeButton = new OO.ui.ButtonWidget( {
607 label: mw.message( 'apisandbox-add-multi' ).text()
608 } );
609 $content = innerWidget.$element.add( multiModeButton.$element );
610
611 widget = new OO.ui.PopupTagMultiselectWidget( {
612 allowArbitrary: true,
613 allowDuplicates: Util.apiBool( pi.allowsduplicates ),
614 $overlay: true,
615 popup: {
616 classes: [ 'mw-apisandbox-popup' ],
617 $content: $content
618 }
619 } );
620 widget.paramInfo = pi;
621 $.extend( widget, WidgetMethods.tagWidget );
622
623 func = function () {
624 if ( !innerWidget.isDisabled() ) {
625 innerWidget.apiCheckValid().done( function ( ok ) {
626 if ( ok ) {
627 widget.addTag( innerWidget.getApiValue() );
628 innerWidget.setApiValue( undefined );
629 }
630 } );
631 return false;
632 }
633 };
634
635 if ( multiModeInput ) {
636 multiModeInput.on( 'enter', func );
637 }
638 multiModeButton.on( 'click', func );
639 }
640
641 if ( Util.apiBool( pi.required ) || opts.nooptional ) {
642 finalWidget = widget;
643 } else {
644 finalWidget = new OptionalWidget( widget );
645 finalWidget.paramInfo = pi;
646 $.extend( finalWidget, WidgetMethods.optionalWidget );
647 if ( widget.getSubmodules ) {
648 finalWidget.getSubmodules = widget.getSubmodules.bind( widget );
649 finalWidget.on( 'disable', function () { setTimeout( ApiSandbox.updateUI ); } );
650 }
651 finalWidget.setDisabled( true );
652 }
653
654 widget.setApiValue( pi[ 'default' ] );
655
656 return finalWidget;
657 },
658
659 /**
660 * Parse an HTML string and call Util.fixupHTML()
661 *
662 * @param {string} html HTML to parse
663 * @return {jQuery}
664 */
665 parseHTML: function ( html ) {
666 var $ret = $( $.parseHTML( html ) );
667 return Util.fixupHTML( $ret );
668 },
669
670 /**
671 * Parse an i18n message and call Util.fixupHTML()
672 *
673 * @param {string} key Key of message to get
674 * @param {...Mixed} parameters Values for $N replacements
675 * @return {jQuery}
676 */
677 parseMsg: function () {
678 var $ret = mw.message.apply( mw.message, arguments ).parseDom();
679 return Util.fixupHTML( $ret );
680 },
681
682 /**
683 * Fix HTML for ApiSandbox display
684 *
685 * Fixes are:
686 * - Add target="_blank" to any links
687 *
688 * @param {jQuery} $html DOM to process
689 * @return {jQuery}
690 */
691 fixupHTML: function ( $html ) {
692 $html.filter( 'a' ).add( $html.find( 'a' ) )
693 .filter( '[href]:not([target])' )
694 .attr( 'target', '_blank' );
695 return $html;
696 },
697
698 /**
699 * Format a request and return a bunch of menu option widgets
700 *
701 * @param {Object} displayParams Query parameters, sanitized for display.
702 * @param {Object} rawParams Query parameters. You should probably use displayParams instead.
703 * @return {OO.ui.MenuOptionWidget[]} Each item's data should be an OO.ui.FieldLayout
704 */
705 formatRequest: function ( displayParams, rawParams ) {
706 var jsonInput,
707 items = [
708 new OO.ui.MenuOptionWidget( {
709 label: Util.parseMsg( 'apisandbox-request-format-url-label' ),
710 data: new OO.ui.FieldLayout(
711 new OO.ui.TextInputWidget( {
712 readOnly: true,
713 value: mw.util.wikiScript( 'api' ) + '?' + $.param( displayParams )
714 } ), {
715 label: Util.parseMsg( 'apisandbox-request-url-label' )
716 }
717 )
718 } ),
719 new OO.ui.MenuOptionWidget( {
720 label: Util.parseMsg( 'apisandbox-request-format-json-label' ),
721 data: new OO.ui.FieldLayout(
722 jsonInput = new OO.ui.MultilineTextInputWidget( {
723 classes: [ 'mw-apisandbox-textInputCode' ],
724 readOnly: true,
725 autosize: true,
726 maxRows: 6,
727 value: JSON.stringify( displayParams, null, '\t' )
728 } ), {
729 label: Util.parseMsg( 'apisandbox-request-json-label' )
730 }
731 ).on( 'toggle', function ( visible ) {
732 if ( visible ) {
733 // Call updatePosition instead of adjustSize
734 // because the latter has weird caching
735 // behavior and the former bypasses it.
736 jsonInput.updatePosition();
737 }
738 } )
739 } )
740 ];
741
742 mw.hook( 'apisandbox.formatRequest' ).fire( items, displayParams, rawParams );
743
744 return items;
745 },
746
747 /**
748 * Event handler for when formatDropdown's selection changes
749 */
750 onFormatDropdownChange: function () {
751 var i,
752 menu = formatDropdown.getMenu(),
753 items = menu.getItems(),
754 selectedField = menu.findSelectedItem() ? menu.findSelectedItem().getData() : null;
755
756 for ( i = 0; i < items.length; i++ ) {
757 items[ i ].getData().toggle( items[ i ].getData() === selectedField );
758 }
759 }
760 };
761
762 /**
763 * Interface to ApiSandbox UI
764 *
765 * @class mw.special.ApiSandbox
766 */
767 ApiSandbox = {
768 /**
769 * Initialize the UI
770 *
771 * Automatically called on $.ready()
772 */
773 init: function () {
774 var $toolbar;
775
776 ApiSandbox.isFullscreen = false;
777
778 $content = $( '#mw-apisandbox' );
779
780 windowManager = new OO.ui.WindowManager();
781 $( 'body' ).append( windowManager.$element );
782 windowManager.addWindows( {
783 errorAlert: new OO.ui.MessageDialog()
784 } );
785
786 fullscreenButton = new OO.ui.ButtonWidget( {
787 label: mw.message( 'apisandbox-fullscreen' ).text(),
788 title: mw.message( 'apisandbox-fullscreen-tooltip' ).text()
789 } ).on( 'click', ApiSandbox.toggleFullscreen );
790
791 $toolbar = $( '<div>' )
792 .addClass( 'mw-apisandbox-toolbar' )
793 .append(
794 fullscreenButton.$element,
795 new OO.ui.ButtonWidget( {
796 label: mw.message( 'apisandbox-submit' ).text(),
797 flags: [ 'primary', 'progressive' ]
798 } ).on( 'click', ApiSandbox.sendRequest ).$element,
799 new OO.ui.ButtonWidget( {
800 label: mw.message( 'apisandbox-reset' ).text(),
801 flags: 'destructive'
802 } ).on( 'click', ApiSandbox.resetUI ).$element
803 );
804
805 booklet = new OO.ui.BookletLayout( {
806 outlined: true,
807 autoFocus: false
808 } );
809
810 panel = new OO.ui.PanelLayout( {
811 classes: [ 'mw-apisandbox-container' ],
812 content: [ booklet ],
813 expanded: false,
814 framed: true
815 } );
816
817 pages.main = new ApiSandbox.PageLayout( { key: 'main', path: 'main' } );
818
819 // Parse the current hash string
820 if ( !ApiSandbox.loadFromHash() ) {
821 ApiSandbox.updateUI();
822 }
823
824 // If the hashchange event exists, use it. Otherwise, fake it.
825 // And, of course, IE has to be dumb.
826 if ( 'onhashchange' in window &&
827 ( document.documentMode === undefined || document.documentMode >= 8 )
828 ) {
829 $( window ).on( 'hashchange', ApiSandbox.loadFromHash );
830 } else {
831 setInterval( function () {
832 if ( oldhash !== location.hash ) {
833 ApiSandbox.loadFromHash();
834 }
835 }, 1000 );
836 }
837
838 $content
839 .empty()
840 .append( $( '<p>' ).append( Util.parseMsg( 'apisandbox-intro' ) ) )
841 .append(
842 $( '<div>' ).attr( 'id', 'mw-apisandbox-ui' )
843 .append( $toolbar )
844 .append( panel.$element )
845 );
846
847 $( window ).on( 'resize', ApiSandbox.resizePanel );
848
849 ApiSandbox.resizePanel();
850 },
851
852 /**
853 * Toggle "fullscreen" mode
854 */
855 toggleFullscreen: function () {
856 var $body = $( document.body ),
857 $ui = $( '#mw-apisandbox-ui' );
858
859 ApiSandbox.isFullscreen = !ApiSandbox.isFullscreen;
860
861 $body.toggleClass( 'mw-apisandbox-fullscreen', ApiSandbox.isFullscreen );
862 $ui.toggleClass( 'mw-body-content', ApiSandbox.isFullscreen );
863 if ( ApiSandbox.isFullscreen ) {
864 fullscreenButton.setLabel( mw.message( 'apisandbox-unfullscreen' ).text() );
865 fullscreenButton.setTitle( mw.message( 'apisandbox-unfullscreen-tooltip' ).text() );
866 OO.ui.getDefaultOverlay().prepend( $ui );
867 } else {
868 fullscreenButton.setLabel( mw.message( 'apisandbox-fullscreen' ).text() );
869 fullscreenButton.setTitle( mw.message( 'apisandbox-fullscreen-tooltip' ).text() );
870 $content.append( $ui );
871 }
872 ApiSandbox.resizePanel();
873 },
874
875 /**
876 * Set the height of the panel based on the current viewport.
877 */
878 resizePanel: function () {
879 var height = $( window ).height(),
880 contentTop = $content.offset().top;
881
882 if ( ApiSandbox.isFullscreen ) {
883 height -= panel.$element.offset().top - $( '#mw-apisandbox-ui' ).offset().top;
884 panel.$element.height( height - 1 );
885 } else {
886 // Subtract the height of the intro text
887 height -= panel.$element.offset().top - contentTop;
888
889 panel.$element.height( height - 10 );
890 $( window ).scrollTop( contentTop - 5 );
891 }
892 },
893
894 /**
895 * Update the current query when the page hash changes
896 *
897 * @return {boolean} Successful
898 */
899 loadFromHash: function () {
900 var params, m, re,
901 hash = location.hash;
902
903 if ( oldhash === hash ) {
904 return false;
905 }
906 oldhash = hash;
907 if ( hash === '' ) {
908 return false;
909 }
910
911 // I'm surprised this doesn't seem to exist in jQuery or mw.util.
912 params = {};
913 hash = hash.replace( /\+/g, '%20' );
914 re = /([^&=#]+)=?([^&#]*)/g;
915 while ( ( m = re.exec( hash ) ) ) {
916 params[ decodeURIComponent( m[ 1 ] ) ] = decodeURIComponent( m[ 2 ] );
917 }
918
919 ApiSandbox.updateUI( params );
920 return true;
921 },
922
923 /**
924 * Update the pages in the booklet
925 *
926 * @param {Object} [params] Optional query parameters to load
927 */
928 updateUI: function ( params ) {
929 var i, page, subpages, j, removePages,
930 addPages = [];
931
932 if ( !$.isPlainObject( params ) ) {
933 params = undefined;
934 }
935
936 if ( updatingBooklet ) {
937 return;
938 }
939 updatingBooklet = true;
940 try {
941 if ( params !== undefined ) {
942 pages.main.loadQueryParams( params );
943 }
944 addPages.push( pages.main );
945 if ( resultPage !== null ) {
946 addPages.push( resultPage );
947 }
948 pages.main.apiCheckValid();
949
950 i = 0;
951 while ( addPages.length ) {
952 page = addPages.shift();
953 if ( bookletPages[ i ] !== page ) {
954 for ( j = i; j < bookletPages.length; j++ ) {
955 if ( bookletPages[ j ].getName() === page.getName() ) {
956 bookletPages.splice( j, 1 );
957 }
958 }
959 bookletPages.splice( i, 0, page );
960 booklet.addPages( [ page ], i );
961 }
962 i++;
963
964 if ( page.getSubpages ) {
965 subpages = page.getSubpages();
966 for ( j = 0; j < subpages.length; j++ ) {
967 if ( !pages.hasOwnProperty( subpages[ j ].key ) ) {
968 subpages[ j ].indentLevel = page.indentLevel + 1;
969 pages[ subpages[ j ].key ] = new ApiSandbox.PageLayout( subpages[ j ] );
970 }
971 if ( params !== undefined ) {
972 pages[ subpages[ j ].key ].loadQueryParams( params );
973 }
974 addPages.splice( j, 0, pages[ subpages[ j ].key ] );
975 pages[ subpages[ j ].key ].apiCheckValid();
976 }
977 }
978 }
979
980 if ( bookletPages.length > i ) {
981 removePages = bookletPages.splice( i, bookletPages.length - i );
982 booklet.removePages( removePages );
983 }
984
985 if ( !booklet.getCurrentPageName() ) {
986 booklet.selectFirstSelectablePage();
987 }
988 } finally {
989 updatingBooklet = false;
990 }
991 },
992
993 /**
994 * Reset button handler
995 */
996 resetUI: function () {
997 suppressErrors = true;
998 pages = {
999 main: new ApiSandbox.PageLayout( { key: 'main', path: 'main' } )
1000 };
1001 resultPage = null;
1002 ApiSandbox.updateUI();
1003 },
1004
1005 /**
1006 * Submit button handler
1007 *
1008 * @param {Object} [params] Use this set of params instead of those in the form fields.
1009 * The form fields will be updated to match.
1010 */
1011 sendRequest: function ( params ) {
1012 var page, subpages, i, query, $result, $focus,
1013 progress, $progressText, progressLoading,
1014 deferreds = [],
1015 paramsAreForced = !!params,
1016 displayParams = {},
1017 checkPages = [ pages.main ];
1018
1019 // Blur any focused widget before submit, because
1020 // OO.ui.ButtonWidget doesn't take focus itself (T128054)
1021 $focus = $( '#mw-apisandbox-ui' ).find( document.activeElement );
1022 if ( $focus.length ) {
1023 $focus[ 0 ].blur();
1024 }
1025
1026 suppressErrors = false;
1027
1028 // save widget state in params (or load from it if we are forced)
1029 if ( paramsAreForced ) {
1030 ApiSandbox.updateUI( params );
1031 }
1032 params = {};
1033 while ( checkPages.length ) {
1034 page = checkPages.shift();
1035 deferreds.push( page.apiCheckValid() );
1036 page.getQueryParams( params, displayParams );
1037 subpages = page.getSubpages();
1038 for ( i = 0; i < subpages.length; i++ ) {
1039 if ( pages.hasOwnProperty( subpages[ i ].key ) ) {
1040 checkPages.push( pages[ subpages[ i ].key ] );
1041 }
1042 }
1043 }
1044
1045 if ( !paramsAreForced ) {
1046 // forced params means we are continuing a query; the base query should be preserved
1047 baseRequestParams = $.extend( {}, params );
1048 }
1049
1050 $.when.apply( $, deferreds ).done( function () {
1051 var formatItems, menu, selectedLabel;
1052
1053 if ( $.inArray( false, arguments ) !== -1 ) {
1054 windowManager.openWindow( 'errorAlert', {
1055 title: Util.parseMsg( 'apisandbox-submit-invalid-fields-title' ),
1056 message: Util.parseMsg( 'apisandbox-submit-invalid-fields-message' ),
1057 actions: [
1058 {
1059 action: 'accept',
1060 label: OO.ui.msg( 'ooui-dialog-process-dismiss' ),
1061 flags: 'primary'
1062 }
1063 ]
1064 } );
1065 return;
1066 }
1067
1068 query = $.param( displayParams );
1069
1070 formatItems = Util.formatRequest( displayParams, params );
1071
1072 // Force a 'fm' format with wrappedhtml=1, if available
1073 if ( params.format !== undefined ) {
1074 if ( availableFormats.hasOwnProperty( params.format + 'fm' ) ) {
1075 params.format = params.format + 'fm';
1076 }
1077 if ( params.format.substr( -2 ) === 'fm' ) {
1078 params.wrappedhtml = 1;
1079 }
1080 }
1081
1082 progressLoading = false;
1083 $progressText = $( '<span>' ).text( mw.message( 'apisandbox-sending-request' ).text() );
1084 progress = new OO.ui.ProgressBarWidget( {
1085 progress: false,
1086 $content: $progressText
1087 } );
1088
1089 $result = $( '<div>' )
1090 .append( progress.$element );
1091
1092 resultPage = page = new OO.ui.PageLayout( '|results|' );
1093 page.setupOutlineItem = function () {
1094 this.outlineItem.setLabel( mw.message( 'apisandbox-results' ).text() );
1095 };
1096
1097 if ( !formatDropdown ) {
1098 formatDropdown = new OO.ui.DropdownWidget( {
1099 menu: { items: [] },
1100 $overlay: true
1101 } );
1102 formatDropdown.getMenu().on( 'select', Util.onFormatDropdownChange );
1103 }
1104
1105 menu = formatDropdown.getMenu();
1106 selectedLabel = menu.findSelectedItem() ? menu.findSelectedItem().getLabel() : '';
1107 if ( typeof selectedLabel !== 'string' ) {
1108 selectedLabel = selectedLabel.text();
1109 }
1110 menu.clearItems().addItems( formatItems );
1111 menu.chooseItem( menu.getItemFromLabel( selectedLabel ) || menu.findFirstSelectableItem() );
1112
1113 // Fire the event to update field visibilities
1114 Util.onFormatDropdownChange();
1115
1116 page.$element.empty()
1117 .append(
1118 new OO.ui.FieldLayout(
1119 formatDropdown, {
1120 label: Util.parseMsg( 'apisandbox-request-selectformat-label' )
1121 }
1122 ).$element,
1123 formatItems.map( function ( item ) {
1124 return item.getData().$element;
1125 } ),
1126 $result
1127 );
1128 ApiSandbox.updateUI();
1129 booklet.setPage( '|results|' );
1130
1131 location.href = oldhash = '#' + query;
1132
1133 api.post( params, {
1134 contentType: 'multipart/form-data',
1135 dataType: 'text',
1136 xhr: function () {
1137 var xhr = new window.XMLHttpRequest();
1138 xhr.upload.addEventListener( 'progress', function ( e ) {
1139 if ( !progressLoading ) {
1140 if ( e.lengthComputable ) {
1141 progress.setProgress( e.loaded * 100 / e.total );
1142 } else {
1143 progress.setProgress( false );
1144 }
1145 }
1146 } );
1147 xhr.addEventListener( 'progress', function ( e ) {
1148 if ( !progressLoading ) {
1149 progressLoading = true;
1150 $progressText.text( mw.message( 'apisandbox-loading-results' ).text() );
1151 }
1152 if ( e.lengthComputable ) {
1153 progress.setProgress( e.loaded * 100 / e.total );
1154 } else {
1155 progress.setProgress( false );
1156 }
1157 } );
1158 return xhr;
1159 }
1160 } )
1161 .catch( function ( code, data, result, jqXHR ) {
1162 var deferred = $.Deferred();
1163
1164 if ( code !== 'http' ) {
1165 // Not really an error, work around mw.Api thinking it is.
1166 deferred.resolve( result, jqXHR );
1167 } else {
1168 // Just forward it.
1169 deferred.reject.apply( deferred, arguments );
1170 }
1171 return deferred.promise();
1172 } )
1173 .then( function ( data, jqXHR ) {
1174 var m, loadTime, button, clear,
1175 ct = jqXHR.getResponseHeader( 'Content-Type' ),
1176 loginSuppressed = jqXHR.getResponseHeader( 'MediaWiki-Login-Suppressed' ) || 'false';
1177
1178 $result.empty();
1179 if ( loginSuppressed !== 'false' ) {
1180 $( '<div>' )
1181 .addClass( 'warning' )
1182 .append( Util.parseMsg( 'apisandbox-results-login-suppressed' ) )
1183 .appendTo( $result );
1184 }
1185 if ( /^text\/mediawiki-api-prettyprint-wrapped(?:;|$)/.test( ct ) ) {
1186 data = JSON.parse( data );
1187 if ( data.modules.length ) {
1188 mw.loader.load( data.modules );
1189 }
1190 if ( data.status && data.status !== 200 ) {
1191 $( '<div>' )
1192 .addClass( 'api-pretty-header api-pretty-status' )
1193 .append( Util.parseMsg( 'api-format-prettyprint-status', data.status, data.statustext ) )
1194 .appendTo( $result );
1195 }
1196 $result.append( Util.parseHTML( data.html ) );
1197 loadTime = data.time;
1198 } else if ( ( m = data.match( /<pre[ >][\s\S]*<\/pre>/ ) ) ) {
1199 $result.append( Util.parseHTML( m[ 0 ] ) );
1200 if ( ( m = data.match( /"wgBackendResponseTime":\s*(\d+)/ ) ) ) {
1201 loadTime = parseInt( m[ 1 ], 10 );
1202 }
1203 } else {
1204 $( '<pre>' )
1205 .addClass( 'api-pretty-content' )
1206 .text( data )
1207 .appendTo( $result );
1208 }
1209 if ( paramsAreForced || data[ 'continue' ] ) {
1210 $result.append(
1211 $( '<div>' ).append(
1212 new OO.ui.ButtonWidget( {
1213 label: mw.message( 'apisandbox-continue' ).text()
1214 } ).on( 'click', function () {
1215 ApiSandbox.sendRequest( $.extend( {}, baseRequestParams, data[ 'continue' ] ) );
1216 } ).setDisabled( !data[ 'continue' ] ).$element,
1217 ( clear = new OO.ui.ButtonWidget( {
1218 label: mw.message( 'apisandbox-continue-clear' ).text()
1219 } ).on( 'click', function () {
1220 ApiSandbox.updateUI( baseRequestParams );
1221 clear.setDisabled( true );
1222 booklet.setPage( '|results|' );
1223 } ).setDisabled( !paramsAreForced ) ).$element,
1224 new OO.ui.PopupButtonWidget( {
1225 $overlay: true,
1226 framed: false,
1227 icon: 'info',
1228 popup: {
1229 $content: $( '<div>' ).append( Util.parseMsg( 'apisandbox-continue-help' ) ),
1230 padded: true,
1231 width: 'auto'
1232 }
1233 } ).$element
1234 )
1235 );
1236 }
1237 if ( typeof loadTime === 'number' ) {
1238 $result.append(
1239 $( '<div>' ).append(
1240 new OO.ui.LabelWidget( {
1241 label: mw.message( 'apisandbox-request-time', loadTime ).text()
1242 } ).$element
1243 )
1244 );
1245 }
1246
1247 if ( jqXHR.getResponseHeader( 'MediaWiki-API-Error' ) === 'badtoken' ) {
1248 // Flush all saved tokens in case one of them is the bad one.
1249 Util.markTokensBad();
1250 button = new OO.ui.ButtonWidget( {
1251 label: mw.message( 'apisandbox-results-fixtoken' ).text()
1252 } );
1253 button.on( 'click', ApiSandbox.fixTokenAndResend )
1254 .on( 'click', button.setDisabled, [ true ], button )
1255 .$element.appendTo( $result );
1256 }
1257 }, function ( code, data ) {
1258 var details = 'HTTP error: ' + data.exception;
1259 $result.empty()
1260 .append(
1261 new OO.ui.LabelWidget( {
1262 label: mw.message( 'apisandbox-results-error', details ).text(),
1263 classes: [ 'error' ]
1264 } ).$element
1265 );
1266 } );
1267 } );
1268 },
1269
1270 /**
1271 * Handler for the "Correct token and resubmit" button
1272 *
1273 * Used on a 'badtoken' error, it re-fetches token parameters for all
1274 * pages and then re-submits the query.
1275 */
1276 fixTokenAndResend: function () {
1277 var page, subpages, i, k,
1278 ok = true,
1279 tokenWait = { dummy: true },
1280 checkPages = [ pages.main ],
1281 success = function ( k ) {
1282 delete tokenWait[ k ];
1283 if ( ok && $.isEmptyObject( tokenWait ) ) {
1284 ApiSandbox.sendRequest();
1285 }
1286 },
1287 failure = function ( k ) {
1288 delete tokenWait[ k ];
1289 ok = false;
1290 };
1291
1292 while ( checkPages.length ) {
1293 page = checkPages.shift();
1294
1295 if ( page.tokenWidget ) {
1296 k = page.apiModule + page.tokenWidget.paramInfo.name;
1297 tokenWait[ k ] = page.tokenWidget.fetchToken();
1298 tokenWait[ k ]
1299 .done( success.bind( page.tokenWidget, k ) )
1300 .fail( failure.bind( page.tokenWidget, k ) );
1301 }
1302
1303 subpages = page.getSubpages();
1304 for ( i = 0; i < subpages.length; i++ ) {
1305 if ( pages.hasOwnProperty( subpages[ i ].key ) ) {
1306 checkPages.push( pages[ subpages[ i ].key ] );
1307 }
1308 }
1309 }
1310
1311 success( 'dummy', '' );
1312 },
1313
1314 /**
1315 * Reset validity indicators for all widgets
1316 */
1317 updateValidityIndicators: function () {
1318 var page, subpages, i,
1319 checkPages = [ pages.main ];
1320
1321 while ( checkPages.length ) {
1322 page = checkPages.shift();
1323 page.apiCheckValid();
1324 subpages = page.getSubpages();
1325 for ( i = 0; i < subpages.length; i++ ) {
1326 if ( pages.hasOwnProperty( subpages[ i ].key ) ) {
1327 checkPages.push( pages[ subpages[ i ].key ] );
1328 }
1329 }
1330 }
1331 }
1332 };
1333
1334 /**
1335 * PageLayout for API modules
1336 *
1337 * @class
1338 * @private
1339 * @extends OO.ui.PageLayout
1340 * @constructor
1341 * @param {Object} [config] Configuration options
1342 */
1343 ApiSandbox.PageLayout = function ( config ) {
1344 config = $.extend( { prefix: '' }, config );
1345 this.displayText = config.key;
1346 this.apiModule = config.path;
1347 this.prefix = config.prefix;
1348 this.paramInfo = null;
1349 this.apiIsValid = true;
1350 this.loadFromQueryParams = null;
1351 this.widgets = {};
1352 this.tokenWidget = null;
1353 this.indentLevel = config.indentLevel ? config.indentLevel : 0;
1354 ApiSandbox.PageLayout[ 'super' ].call( this, config.key, config );
1355 this.loadParamInfo();
1356 };
1357 OO.inheritClass( ApiSandbox.PageLayout, OO.ui.PageLayout );
1358 ApiSandbox.PageLayout.prototype.setupOutlineItem = function () {
1359 this.outlineItem.setLevel( this.indentLevel );
1360 this.outlineItem.setLabel( this.displayText );
1361 this.outlineItem.setIcon( this.apiIsValid || suppressErrors ? null : 'alert' );
1362 this.outlineItem.setIconTitle(
1363 this.apiIsValid || suppressErrors ? '' : mw.message( 'apisandbox-alert-page' ).plain()
1364 );
1365 };
1366
1367 /**
1368 * Fetch module information for this page's module, then create UI
1369 */
1370 ApiSandbox.PageLayout.prototype.loadParamInfo = function () {
1371 var dynamicFieldset, dynamicParamNameWidget,
1372 that = this,
1373 removeDynamicParamWidget = function ( name, layout ) {
1374 dynamicFieldset.removeItems( [ layout ] );
1375 delete that.widgets[ name ];
1376 },
1377 addDynamicParamWidget = function () {
1378 var name, layout, widget, button;
1379
1380 // Check name is filled in
1381 name = dynamicParamNameWidget.getValue().trim();
1382 if ( name === '' ) {
1383 dynamicParamNameWidget.focus();
1384 return;
1385 }
1386
1387 if ( that.widgets[ name ] !== undefined ) {
1388 windowManager.openWindow( 'errorAlert', {
1389 title: Util.parseMsg( 'apisandbox-dynamic-error-exists', name ),
1390 actions: [
1391 {
1392 action: 'accept',
1393 label: OO.ui.msg( 'ooui-dialog-process-dismiss' ),
1394 flags: 'primary'
1395 }
1396 ]
1397 } );
1398 return;
1399 }
1400
1401 widget = Util.createWidgetForParameter( {
1402 name: name,
1403 type: 'string',
1404 'default': ''
1405 }, {
1406 nooptional: true
1407 } );
1408 button = new OO.ui.ButtonWidget( {
1409 icon: 'trash',
1410 flags: 'destructive'
1411 } );
1412 layout = new OO.ui.ActionFieldLayout(
1413 widget,
1414 button,
1415 {
1416 label: name,
1417 align: 'left'
1418 }
1419 );
1420 button.on( 'click', removeDynamicParamWidget, [ name, layout ] );
1421 that.widgets[ name ] = widget;
1422 dynamicFieldset.addItems( [ layout ], dynamicFieldset.getItems().length - 1 );
1423 widget.focus();
1424
1425 dynamicParamNameWidget.setValue( '' );
1426 };
1427
1428 this.$element.empty()
1429 .append( new OO.ui.ProgressBarWidget( {
1430 progress: false,
1431 text: mw.message( 'apisandbox-loading', this.displayText ).text()
1432 } ).$element );
1433
1434 Util.fetchModuleInfo( this.apiModule )
1435 .done( function ( pi ) {
1436 var prefix, i, j, descriptionContainer, widget, layoutConfig, button, widgetField, helpField, tmp, flag, count,
1437 items = [],
1438 deprecatedItems = [],
1439 buttons = [],
1440 filterFmModules = function ( v ) {
1441 return v.substr( -2 ) !== 'fm' ||
1442 !availableFormats.hasOwnProperty( v.substr( 0, v.length - 2 ) );
1443 },
1444 widgetLabelOnClick = function () {
1445 var f = this.getField();
1446 if ( $.isFunction( f.setDisabled ) ) {
1447 f.setDisabled( false );
1448 }
1449 if ( $.isFunction( f.focus ) ) {
1450 f.focus();
1451 }
1452 };
1453
1454 // This is something of a hack. We always want the 'format' and
1455 // 'action' parameters from the main module to be specified,
1456 // and for 'format' we also want to simplify the dropdown since
1457 // we always send the 'fm' variant.
1458 if ( that.apiModule === 'main' ) {
1459 for ( i = 0; i < pi.parameters.length; i++ ) {
1460 if ( pi.parameters[ i ].name === 'action' ) {
1461 pi.parameters[ i ].required = true;
1462 delete pi.parameters[ i ][ 'default' ];
1463 }
1464 if ( pi.parameters[ i ].name === 'format' ) {
1465 tmp = pi.parameters[ i ].type;
1466 for ( j = 0; j < tmp.length; j++ ) {
1467 availableFormats[ tmp[ j ] ] = true;
1468 }
1469 pi.parameters[ i ].type = tmp.filter( filterFmModules );
1470 pi.parameters[ i ][ 'default' ] = 'json';
1471 pi.parameters[ i ].required = true;
1472 }
1473 }
1474 }
1475
1476 // Hide the 'wrappedhtml' parameter on format modules
1477 if ( pi.group === 'format' ) {
1478 pi.parameters = pi.parameters.filter( function ( p ) {
1479 return p.name !== 'wrappedhtml';
1480 } );
1481 }
1482
1483 that.paramInfo = pi;
1484
1485 items.push( new OO.ui.FieldLayout(
1486 new OO.ui.Widget( {} ).toggle( false ), {
1487 align: 'top',
1488 label: Util.parseHTML( pi.description )
1489 }
1490 ) );
1491
1492 if ( pi.helpurls.length ) {
1493 buttons.push( new OO.ui.PopupButtonWidget( {
1494 $overlay: true,
1495 label: mw.message( 'apisandbox-helpurls' ).text(),
1496 icon: 'help',
1497 popup: {
1498 width: 'auto',
1499 padded: true,
1500 $content: $( '<ul>' ).append( pi.helpurls.map( function ( link ) {
1501 return $( '<li>' ).append( $( '<a>' )
1502 .attr( { href: link, target: '_blank' } )
1503 .text( link )
1504 );
1505 } ) )
1506 }
1507 } ) );
1508 }
1509
1510 if ( pi.examples.length ) {
1511 buttons.push( new OO.ui.PopupButtonWidget( {
1512 $overlay: true,
1513 label: mw.message( 'apisandbox-examples' ).text(),
1514 icon: 'code',
1515 popup: {
1516 width: 'auto',
1517 padded: true,
1518 $content: $( '<ul>' ).append( pi.examples.map( function ( example ) {
1519 var a = $( '<a>' )
1520 .attr( 'href', '#' + example.query )
1521 .html( example.description );
1522 a.find( 'a' ).contents().unwrap(); // Can't nest links
1523 return $( '<li>' ).append( a );
1524 } ) )
1525 }
1526 } ) );
1527 }
1528
1529 if ( buttons.length ) {
1530 items.push( new OO.ui.FieldLayout(
1531 new OO.ui.ButtonGroupWidget( {
1532 items: buttons
1533 } ), { align: 'top' }
1534 ) );
1535 }
1536
1537 if ( pi.parameters.length ) {
1538 prefix = that.prefix + pi.prefix;
1539 for ( i = 0; i < pi.parameters.length; i++ ) {
1540 widget = Util.createWidgetForParameter( pi.parameters[ i ] );
1541 that.widgets[ prefix + pi.parameters[ i ].name ] = widget;
1542 if ( pi.parameters[ i ].tokentype ) {
1543 that.tokenWidget = widget;
1544 }
1545
1546 descriptionContainer = $( '<div>' );
1547
1548 tmp = Util.parseHTML( pi.parameters[ i ].description );
1549 tmp.filter( 'dl' ).makeCollapsible( {
1550 collapsed: true
1551 } ).children( '.mw-collapsible-toggle' ).each( function () {
1552 var $this = $( this );
1553 $this.parent().prev( 'p' ).append( $this );
1554 } );
1555 descriptionContainer.append( $( '<div>' ).addClass( 'description' ).append( tmp ) );
1556
1557 if ( pi.parameters[ i ].info && pi.parameters[ i ].info.length ) {
1558 for ( j = 0; j < pi.parameters[ i ].info.length; j++ ) {
1559 descriptionContainer.append( $( '<div>' )
1560 .addClass( 'info' )
1561 .append( Util.parseHTML( pi.parameters[ i ].info[ j ] ) )
1562 );
1563 }
1564 }
1565 flag = true;
1566 count = 1e100;
1567 switch ( pi.parameters[ i ].type ) {
1568 case 'namespace':
1569 flag = false;
1570 count = mw.config.get( 'wgFormattedNamespaces' ).length;
1571 break;
1572
1573 case 'limit':
1574 if ( pi.parameters[ i ].highmax !== undefined ) {
1575 descriptionContainer.append( $( '<div>' )
1576 .addClass( 'info' )
1577 .append(
1578 Util.parseMsg(
1579 'api-help-param-limit2', pi.parameters[ i ].max, pi.parameters[ i ].highmax
1580 ),
1581 ' ',
1582 Util.parseMsg( 'apisandbox-param-limit' )
1583 )
1584 );
1585 } else {
1586 descriptionContainer.append( $( '<div>' )
1587 .addClass( 'info' )
1588 .append(
1589 Util.parseMsg( 'api-help-param-limit', pi.parameters[ i ].max ),
1590 ' ',
1591 Util.parseMsg( 'apisandbox-param-limit' )
1592 )
1593 );
1594 }
1595 break;
1596
1597 case 'integer':
1598 tmp = '';
1599 if ( pi.parameters[ i ].min !== undefined ) {
1600 tmp += 'min';
1601 }
1602 if ( pi.parameters[ i ].max !== undefined ) {
1603 tmp += 'max';
1604 }
1605 if ( tmp !== '' ) {
1606 descriptionContainer.append( $( '<div>' )
1607 .addClass( 'info' )
1608 .append( Util.parseMsg(
1609 'api-help-param-integer-' + tmp,
1610 Util.apiBool( pi.parameters[ i ].multi ) ? 2 : 1,
1611 pi.parameters[ i ].min, pi.parameters[ i ].max
1612 ) )
1613 );
1614 }
1615 break;
1616
1617 default:
1618 if ( Array.isArray( pi.parameters[ i ].type ) ) {
1619 flag = false;
1620 count = pi.parameters[ i ].type.length;
1621 }
1622 break;
1623 }
1624 if ( Util.apiBool( pi.parameters[ i ].multi ) ) {
1625 tmp = [];
1626 if ( flag && !( widget instanceof OO.ui.TagMultiselectWidget ) &&
1627 !(
1628 widget instanceof OptionalWidget &&
1629 widget.widget instanceof OO.ui.TagMultiselectWidget
1630 )
1631 ) {
1632 tmp.push( mw.message( 'api-help-param-multi-separate' ).parse() );
1633 }
1634 if ( count > pi.parameters[ i ].lowlimit ) {
1635 tmp.push(
1636 mw.message( 'api-help-param-multi-max',
1637 pi.parameters[ i ].lowlimit, pi.parameters[ i ].highlimit
1638 ).parse()
1639 );
1640 }
1641 if ( tmp.length ) {
1642 descriptionContainer.append( $( '<div>' )
1643 .addClass( 'info' )
1644 .append( Util.parseHTML( tmp.join( ' ' ) ) )
1645 );
1646 }
1647 }
1648 if ( 'maxbytes' in pi.parameters[ i ] ) {
1649 descriptionContainer.append( $( '<div>' )
1650 .addClass( 'info' )
1651 .append( Util.parseMsg( 'api-help-param-maxbytes', pi.parameters[ i ].maxbytes ) )
1652 );
1653 }
1654 if ( 'maxchars' in pi.parameters[ i ] ) {
1655 descriptionContainer.append( $( '<div>' )
1656 .addClass( 'info' )
1657 .append( Util.parseMsg( 'api-help-param-maxchars', pi.parameters[ i ].maxchars ) )
1658 );
1659 }
1660 helpField = new OO.ui.FieldLayout(
1661 new OO.ui.Widget( {
1662 $content: '\xa0',
1663 classes: [ 'mw-apisandbox-spacer' ]
1664 } ), {
1665 align: 'inline',
1666 classes: [ 'mw-apisandbox-help-field' ],
1667 label: descriptionContainer
1668 }
1669 );
1670
1671 layoutConfig = {
1672 align: 'left',
1673 classes: [ 'mw-apisandbox-widget-field' ],
1674 label: prefix + pi.parameters[ i ].name
1675 };
1676
1677 if ( pi.parameters[ i ].tokentype ) {
1678 button = new OO.ui.ButtonWidget( {
1679 label: mw.message( 'apisandbox-fetch-token' ).text()
1680 } );
1681 button.on( 'click', widget.fetchToken, [], widget );
1682
1683 widgetField = new OO.ui.ActionFieldLayout( widget, button, layoutConfig );
1684 } else {
1685 widgetField = new OO.ui.FieldLayout( widget, layoutConfig );
1686 }
1687
1688 // We need our own click handler on the widget label to
1689 // turn off the disablement.
1690 widgetField.$label.on( 'click', widgetLabelOnClick.bind( widgetField ) );
1691
1692 // Don't grey out the label when the field is disabled,
1693 // it makes it too hard to read and our "disabled"
1694 // isn't really disabled.
1695 widgetField.onFieldDisable( false );
1696 widgetField.onFieldDisable = $.noop;
1697
1698 if ( Util.apiBool( pi.parameters[ i ].deprecated ) ) {
1699 deprecatedItems.push( widgetField, helpField );
1700 } else {
1701 items.push( widgetField, helpField );
1702 }
1703 }
1704 }
1705
1706 if ( !pi.parameters.length && !Util.apiBool( pi.dynamicparameters ) ) {
1707 items.push( new OO.ui.FieldLayout(
1708 new OO.ui.Widget( {} ).toggle( false ), {
1709 align: 'top',
1710 label: Util.parseMsg( 'apisandbox-no-parameters' )
1711 }
1712 ) );
1713 }
1714
1715 that.$element.empty();
1716
1717 new OO.ui.FieldsetLayout( {
1718 label: that.displayText
1719 } ).addItems( items )
1720 .$element.appendTo( that.$element );
1721
1722 if ( Util.apiBool( pi.dynamicparameters ) ) {
1723 dynamicFieldset = new OO.ui.FieldsetLayout();
1724 dynamicParamNameWidget = new OO.ui.TextInputWidget( {
1725 placeholder: mw.message( 'apisandbox-dynamic-parameters-add-placeholder' ).text()
1726 } ).on( 'enter', addDynamicParamWidget );
1727 dynamicFieldset.addItems( [
1728 new OO.ui.FieldLayout(
1729 new OO.ui.Widget( {} ).toggle( false ), {
1730 align: 'top',
1731 label: Util.parseHTML( pi.dynamicparameters )
1732 }
1733 ),
1734 new OO.ui.ActionFieldLayout(
1735 dynamicParamNameWidget,
1736 new OO.ui.ButtonWidget( {
1737 icon: 'add',
1738 flags: 'progressive'
1739 } ).on( 'click', addDynamicParamWidget ),
1740 {
1741 label: mw.message( 'apisandbox-dynamic-parameters-add-label' ).text(),
1742 align: 'left'
1743 }
1744 )
1745 ] );
1746 $( '<fieldset>' )
1747 .append(
1748 $( '<legend>' ).text( mw.message( 'apisandbox-dynamic-parameters' ).text() ),
1749 dynamicFieldset.$element
1750 )
1751 .appendTo( that.$element );
1752 }
1753
1754 if ( deprecatedItems.length ) {
1755 tmp = new OO.ui.FieldsetLayout().addItems( deprecatedItems ).toggle( false );
1756 $( '<fieldset>' )
1757 .append(
1758 $( '<legend>' ).append(
1759 new OO.ui.ToggleButtonWidget( {
1760 label: mw.message( 'apisandbox-deprecated-parameters' ).text()
1761 } ).on( 'change', tmp.toggle, [], tmp ).$element
1762 ),
1763 tmp.$element
1764 )
1765 .appendTo( that.$element );
1766 }
1767
1768 // Load stored params, if any, then update the booklet if we
1769 // have subpages (or else just update our valid-indicator).
1770 tmp = that.loadFromQueryParams;
1771 that.loadFromQueryParams = null;
1772 if ( $.isPlainObject( tmp ) ) {
1773 that.loadQueryParams( tmp );
1774 }
1775 if ( that.getSubpages().length > 0 ) {
1776 ApiSandbox.updateUI( tmp );
1777 } else {
1778 that.apiCheckValid();
1779 }
1780 } ).fail( function ( code, detail ) {
1781 that.$element.empty()
1782 .append(
1783 new OO.ui.LabelWidget( {
1784 label: mw.message( 'apisandbox-load-error', that.apiModule, detail ).text(),
1785 classes: [ 'error' ]
1786 } ).$element,
1787 new OO.ui.ButtonWidget( {
1788 label: mw.message( 'apisandbox-retry' ).text()
1789 } ).on( 'click', that.loadParamInfo, [], that ).$element
1790 );
1791 } );
1792 };
1793
1794 /**
1795 * Check that all widgets on the page are in a valid state.
1796 *
1797 * @return {boolean}
1798 */
1799 ApiSandbox.PageLayout.prototype.apiCheckValid = function () {
1800 var that = this;
1801
1802 if ( this.paramInfo === null ) {
1803 return $.Deferred().resolve( false ).promise();
1804 } else {
1805 return $.when.apply( $, $.map( this.widgets, function ( widget ) {
1806 return widget.apiCheckValid();
1807 } ) ).then( function () {
1808 that.apiIsValid = $.inArray( false, arguments ) === -1;
1809 if ( that.getOutlineItem() ) {
1810 that.getOutlineItem().setIcon( that.apiIsValid || suppressErrors ? null : 'alert' );
1811 that.getOutlineItem().setIconTitle(
1812 that.apiIsValid || suppressErrors ? '' : mw.message( 'apisandbox-alert-page' ).plain()
1813 );
1814 }
1815 return $.Deferred().resolve( that.apiIsValid ).promise();
1816 } );
1817 }
1818 };
1819
1820 /**
1821 * Load form fields from query parameters
1822 *
1823 * @param {Object} params
1824 */
1825 ApiSandbox.PageLayout.prototype.loadQueryParams = function ( params ) {
1826 if ( this.paramInfo === null ) {
1827 this.loadFromQueryParams = params;
1828 } else {
1829 $.each( this.widgets, function ( name, widget ) {
1830 var v = params.hasOwnProperty( name ) ? params[ name ] : undefined;
1831 widget.setApiValue( v );
1832 } );
1833 }
1834 };
1835
1836 /**
1837 * Load query params from form fields
1838 *
1839 * @param {Object} params Write query parameters into this object
1840 * @param {Object} displayParams Write query parameters for display into this object
1841 */
1842 ApiSandbox.PageLayout.prototype.getQueryParams = function ( params, displayParams ) {
1843 $.each( this.widgets, function ( name, widget ) {
1844 var value = widget.getApiValue();
1845 if ( value !== undefined ) {
1846 params[ name ] = value;
1847 if ( $.isFunction( widget.getApiValueForDisplay ) ) {
1848 value = widget.getApiValueForDisplay();
1849 }
1850 displayParams[ name ] = value;
1851 }
1852 } );
1853 };
1854
1855 /**
1856 * Fetch a list of subpage names loaded by this page
1857 *
1858 * @return {Array}
1859 */
1860 ApiSandbox.PageLayout.prototype.getSubpages = function () {
1861 var ret = [];
1862 $.each( this.widgets, function ( name, widget ) {
1863 var submodules, i;
1864 if ( $.isFunction( widget.getSubmodules ) ) {
1865 submodules = widget.getSubmodules();
1866 for ( i = 0; i < submodules.length; i++ ) {
1867 ret.push( {
1868 key: name + '=' + submodules[ i ].value,
1869 path: submodules[ i ].path,
1870 prefix: widget.paramInfo.submoduleparamprefix || ''
1871 } );
1872 }
1873 }
1874 } );
1875 return ret;
1876 };
1877
1878 $( ApiSandbox.init );
1879
1880 module.exports = ApiSandbox;
1881
1882 }( jQuery, mediaWiki, OO ) );