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