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