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