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