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