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