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