mw.special.apisandbox: Offer to fill in token when not given
[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 // If the hashchange event exists, use it. Otherwise, fake it.
826 // And, of course, IE has to be dumb.
827 if ( 'onhashchange' in window &&
828 ( document.documentMode === undefined || document.documentMode >= 8 )
829 ) {
830 $( window ).on( 'hashchange', ApiSandbox.loadFromHash );
831 } else {
832 setInterval( function () {
833 if ( oldhash !== location.hash ) {
834 ApiSandbox.loadFromHash();
835 }
836 }, 1000 );
837 }
838
839 $content
840 .empty()
841 .append( $( '<p>' ).append( Util.parseMsg( 'apisandbox-intro' ) ) )
842 .append(
843 $( '<div>' ).attr( 'id', 'mw-apisandbox-ui' )
844 .append( $toolbar )
845 .append( panel.$element )
846 );
847
848 $( window ).on( 'resize', ApiSandbox.resizePanel );
849
850 ApiSandbox.resizePanel();
851 },
852
853 /**
854 * Toggle "fullscreen" mode
855 */
856 toggleFullscreen: function () {
857 var $body = $( document.body ),
858 $ui = $( '#mw-apisandbox-ui' );
859
860 ApiSandbox.isFullscreen = !ApiSandbox.isFullscreen;
861
862 $body.toggleClass( 'mw-apisandbox-fullscreen', ApiSandbox.isFullscreen );
863 $ui.toggleClass( 'mw-body-content', ApiSandbox.isFullscreen );
864 if ( ApiSandbox.isFullscreen ) {
865 fullscreenButton.setLabel( mw.message( 'apisandbox-unfullscreen' ).text() );
866 fullscreenButton.setTitle( mw.message( 'apisandbox-unfullscreen-tooltip' ).text() );
867 OO.ui.getDefaultOverlay().prepend( $ui );
868 } else {
869 fullscreenButton.setLabel( mw.message( 'apisandbox-fullscreen' ).text() );
870 fullscreenButton.setTitle( mw.message( 'apisandbox-fullscreen-tooltip' ).text() );
871 $content.append( $ui );
872 }
873 ApiSandbox.resizePanel();
874 },
875
876 /**
877 * Set the height of the panel based on the current viewport.
878 */
879 resizePanel: function () {
880 var height = $( window ).height(),
881 contentTop = $content.offset().top;
882
883 if ( ApiSandbox.isFullscreen ) {
884 height -= panel.$element.offset().top - $( '#mw-apisandbox-ui' ).offset().top;
885 panel.$element.height( height - 1 );
886 } else {
887 // Subtract the height of the intro text
888 height -= panel.$element.offset().top - contentTop;
889
890 panel.$element.height( height - 10 );
891 $( window ).scrollTop( contentTop - 5 );
892 }
893 },
894
895 /**
896 * Update the current query when the page hash changes
897 *
898 * @return {boolean} Successful
899 */
900 loadFromHash: function () {
901 var params, m, re,
902 hash = location.hash;
903
904 if ( oldhash === hash ) {
905 return false;
906 }
907 oldhash = hash;
908 if ( hash === '' ) {
909 return false;
910 }
911
912 // I'm surprised this doesn't seem to exist in jQuery or mw.util.
913 params = {};
914 hash = hash.replace( /\+/g, '%20' );
915 re = /([^&=#]+)=?([^&#]*)/g;
916 while ( ( m = re.exec( hash ) ) ) {
917 params[ decodeURIComponent( m[ 1 ] ) ] = decodeURIComponent( m[ 2 ] );
918 }
919
920 ApiSandbox.updateUI( params );
921 return true;
922 },
923
924 /**
925 * Update the pages in the booklet
926 *
927 * @param {Object} [params] Optional query parameters to load
928 */
929 updateUI: function ( params ) {
930 var i, page, subpages, j, removePages,
931 addPages = [];
932
933 if ( !$.isPlainObject( params ) ) {
934 params = undefined;
935 }
936
937 if ( updatingBooklet ) {
938 return;
939 }
940 updatingBooklet = true;
941 try {
942 if ( params !== undefined ) {
943 pages.main.loadQueryParams( params );
944 }
945 addPages.push( pages.main );
946 if ( resultPage !== null ) {
947 addPages.push( resultPage );
948 }
949 pages.main.apiCheckValid();
950
951 i = 0;
952 while ( addPages.length ) {
953 page = addPages.shift();
954 if ( bookletPages[ i ] !== page ) {
955 for ( j = i; j < bookletPages.length; j++ ) {
956 if ( bookletPages[ j ].getName() === page.getName() ) {
957 bookletPages.splice( j, 1 );
958 }
959 }
960 bookletPages.splice( i, 0, page );
961 booklet.addPages( [ page ], i );
962 }
963 i++;
964
965 if ( page.getSubpages ) {
966 subpages = page.getSubpages();
967 for ( j = 0; j < subpages.length; j++ ) {
968 if ( !pages.hasOwnProperty( subpages[ j ].key ) ) {
969 subpages[ j ].indentLevel = page.indentLevel + 1;
970 pages[ subpages[ j ].key ] = new ApiSandbox.PageLayout( subpages[ j ] );
971 }
972 if ( params !== undefined ) {
973 pages[ subpages[ j ].key ].loadQueryParams( params );
974 }
975 addPages.splice( j, 0, pages[ subpages[ j ].key ] );
976 pages[ subpages[ j ].key ].apiCheckValid();
977 }
978 }
979 }
980
981 if ( bookletPages.length > i ) {
982 removePages = bookletPages.splice( i, bookletPages.length - i );
983 booklet.removePages( removePages );
984 }
985
986 if ( !booklet.getCurrentPageName() ) {
987 booklet.selectFirstSelectablePage();
988 }
989 } finally {
990 updatingBooklet = false;
991 }
992 },
993
994 /**
995 * Reset button handler
996 */
997 resetUI: function () {
998 suppressErrors = true;
999 pages = {
1000 main: new ApiSandbox.PageLayout( { key: 'main', path: 'main' } )
1001 };
1002 resultPage = null;
1003 ApiSandbox.updateUI();
1004 },
1005
1006 /**
1007 * Submit button handler
1008 *
1009 * @param {Object} [params] Use this set of params instead of those in the form fields.
1010 * The form fields will be updated to match.
1011 */
1012 sendRequest: function ( params ) {
1013 var page, subpages, i, query, $result, $focus,
1014 progress, $progressText, progressLoading,
1015 deferreds = [],
1016 paramsAreForced = !!params,
1017 displayParams = {},
1018 tokenWidgets = [],
1019 checkPages = [ pages.main ];
1020
1021 // Blur any focused widget before submit, because
1022 // OO.ui.ButtonWidget doesn't take focus itself (T128054)
1023 $focus = $( '#mw-apisandbox-ui' ).find( document.activeElement );
1024 if ( $focus.length ) {
1025 $focus[ 0 ].blur();
1026 }
1027
1028 suppressErrors = false;
1029
1030 // save widget state in params (or load from it if we are forced)
1031 if ( paramsAreForced ) {
1032 ApiSandbox.updateUI( params );
1033 }
1034 params = {};
1035 while ( checkPages.length ) {
1036 page = checkPages.shift();
1037 if ( page.tokenWidget ) {
1038 tokenWidgets.push( page.tokenWidget );
1039 }
1040 deferreds = deferreds.concat( page.apiCheckValid() );
1041 page.getQueryParams( params, displayParams );
1042 subpages = page.getSubpages();
1043 for ( i = 0; i < subpages.length; i++ ) {
1044 if ( pages.hasOwnProperty( subpages[ i ].key ) ) {
1045 checkPages.push( pages[ subpages[ i ].key ] );
1046 }
1047 }
1048 }
1049
1050 if ( !paramsAreForced ) {
1051 // forced params means we are continuing a query; the base query should be preserved
1052 baseRequestParams = $.extend( {}, params );
1053 }
1054
1055 $.when.apply( $, deferreds ).done( function () {
1056 var formatItems, menu, selectedLabel, deferred, actions, errorCount;
1057
1058 // Count how many times `value` occurs in `array`.
1059 function countValues( value, array ) {
1060 var count, i;
1061 count = 0;
1062 for ( i = 0; i < array.length; i++ ) {
1063 if ( array[ i ] === value ) {
1064 count++;
1065 }
1066 }
1067 return count;
1068 }
1069
1070 errorCount = countValues( false, arguments );
1071 if ( errorCount > 0 ) {
1072 actions = [
1073 {
1074 action: 'accept',
1075 label: OO.ui.msg( 'ooui-dialog-process-dismiss' ),
1076 flags: 'primary'
1077 }
1078 ];
1079 if ( tokenWidgets.length ) {
1080 // Check all token widgets' validity separately
1081 deferred = $.when.apply( $, tokenWidgets.map( function ( w ) {
1082 return w.apiCheckValid();
1083 } ) );
1084
1085 deferred.done( function () {
1086 // If only the tokens are invalid, offer to fix them
1087 var tokenErrorCount = countValues( false, arguments );
1088 if ( tokenErrorCount === errorCount ) {
1089 delete actions[ 0 ].flags;
1090 actions.push( {
1091 action: 'fix',
1092 label: mw.message( 'apisandbox-results-fixtoken' ).text(),
1093 flags: 'primary'
1094 } );
1095 }
1096 } );
1097 } else {
1098 deferred = $.Deferred().resolve();
1099 }
1100 deferred.always( function () {
1101 windowManager.openWindow( 'errorAlert', {
1102 title: Util.parseMsg( 'apisandbox-submit-invalid-fields-title' ),
1103 message: Util.parseMsg( 'apisandbox-submit-invalid-fields-message' ),
1104 actions: actions
1105 } ).closed.then( function ( data ) {
1106 if ( data && data.action === 'fix' ) {
1107 ApiSandbox.fixTokenAndResend();
1108 }
1109 } );
1110 } );
1111 return;
1112 }
1113
1114 query = $.param( displayParams );
1115
1116 formatItems = Util.formatRequest( displayParams, params );
1117
1118 // Force a 'fm' format with wrappedhtml=1, if available
1119 if ( params.format !== undefined ) {
1120 if ( availableFormats.hasOwnProperty( params.format + 'fm' ) ) {
1121 params.format = params.format + 'fm';
1122 }
1123 if ( params.format.substr( -2 ) === 'fm' ) {
1124 params.wrappedhtml = 1;
1125 }
1126 }
1127
1128 progressLoading = false;
1129 $progressText = $( '<span>' ).text( mw.message( 'apisandbox-sending-request' ).text() );
1130 progress = new OO.ui.ProgressBarWidget( {
1131 progress: false,
1132 $content: $progressText
1133 } );
1134
1135 $result = $( '<div>' )
1136 .append( progress.$element );
1137
1138 resultPage = page = new OO.ui.PageLayout( '|results|' );
1139 page.setupOutlineItem = function () {
1140 this.outlineItem.setLabel( mw.message( 'apisandbox-results' ).text() );
1141 };
1142
1143 if ( !formatDropdown ) {
1144 formatDropdown = new OO.ui.DropdownWidget( {
1145 menu: { items: [] },
1146 $overlay: true
1147 } );
1148 formatDropdown.getMenu().on( 'select', Util.onFormatDropdownChange );
1149 }
1150
1151 menu = formatDropdown.getMenu();
1152 selectedLabel = menu.findSelectedItem() ? menu.findSelectedItem().getLabel() : '';
1153 if ( typeof selectedLabel !== 'string' ) {
1154 selectedLabel = selectedLabel.text();
1155 }
1156 menu.clearItems().addItems( formatItems );
1157 menu.chooseItem( menu.getItemFromLabel( selectedLabel ) || menu.findFirstSelectableItem() );
1158
1159 // Fire the event to update field visibilities
1160 Util.onFormatDropdownChange();
1161
1162 page.$element.empty()
1163 .append(
1164 new OO.ui.FieldLayout(
1165 formatDropdown, {
1166 label: Util.parseMsg( 'apisandbox-request-selectformat-label' )
1167 }
1168 ).$element,
1169 formatItems.map( function ( item ) {
1170 return item.getData().$element;
1171 } ),
1172 $result
1173 );
1174 ApiSandbox.updateUI();
1175 booklet.setPage( '|results|' );
1176
1177 location.href = oldhash = '#' + query;
1178
1179 api.post( params, {
1180 contentType: 'multipart/form-data',
1181 dataType: 'text',
1182 xhr: function () {
1183 var xhr = new window.XMLHttpRequest();
1184 xhr.upload.addEventListener( 'progress', function ( e ) {
1185 if ( !progressLoading ) {
1186 if ( e.lengthComputable ) {
1187 progress.setProgress( e.loaded * 100 / e.total );
1188 } else {
1189 progress.setProgress( false );
1190 }
1191 }
1192 } );
1193 xhr.addEventListener( 'progress', function ( e ) {
1194 if ( !progressLoading ) {
1195 progressLoading = true;
1196 $progressText.text( mw.message( 'apisandbox-loading-results' ).text() );
1197 }
1198 if ( e.lengthComputable ) {
1199 progress.setProgress( e.loaded * 100 / e.total );
1200 } else {
1201 progress.setProgress( false );
1202 }
1203 } );
1204 return xhr;
1205 }
1206 } )
1207 .catch( function ( code, data, result, jqXHR ) {
1208 var deferred = $.Deferred();
1209
1210 if ( code !== 'http' ) {
1211 // Not really an error, work around mw.Api thinking it is.
1212 deferred.resolve( result, jqXHR );
1213 } else {
1214 // Just forward it.
1215 deferred.reject.apply( deferred, arguments );
1216 }
1217 return deferred.promise();
1218 } )
1219 .then( function ( data, jqXHR ) {
1220 var m, loadTime, button, clear,
1221 ct = jqXHR.getResponseHeader( 'Content-Type' ),
1222 loginSuppressed = jqXHR.getResponseHeader( 'MediaWiki-Login-Suppressed' ) || 'false';
1223
1224 $result.empty();
1225 if ( loginSuppressed !== 'false' ) {
1226 $( '<div>' )
1227 .addClass( 'warning' )
1228 .append( Util.parseMsg( 'apisandbox-results-login-suppressed' ) )
1229 .appendTo( $result );
1230 }
1231 if ( /^text\/mediawiki-api-prettyprint-wrapped(?:;|$)/.test( ct ) ) {
1232 data = JSON.parse( data );
1233 if ( data.modules.length ) {
1234 mw.loader.load( data.modules );
1235 }
1236 if ( data.status && data.status !== 200 ) {
1237 $( '<div>' )
1238 .addClass( 'api-pretty-header api-pretty-status' )
1239 .append( Util.parseMsg( 'api-format-prettyprint-status', data.status, data.statustext ) )
1240 .appendTo( $result );
1241 }
1242 $result.append( Util.parseHTML( data.html ) );
1243 loadTime = data.time;
1244 } else if ( ( m = data.match( /<pre[ >][\s\S]*<\/pre>/ ) ) ) {
1245 $result.append( Util.parseHTML( m[ 0 ] ) );
1246 if ( ( m = data.match( /"wgBackendResponseTime":\s*(\d+)/ ) ) ) {
1247 loadTime = parseInt( m[ 1 ], 10 );
1248 }
1249 } else {
1250 $( '<pre>' )
1251 .addClass( 'api-pretty-content' )
1252 .text( data )
1253 .appendTo( $result );
1254 }
1255 if ( paramsAreForced || data[ 'continue' ] ) {
1256 $result.append(
1257 $( '<div>' ).append(
1258 new OO.ui.ButtonWidget( {
1259 label: mw.message( 'apisandbox-continue' ).text()
1260 } ).on( 'click', function () {
1261 ApiSandbox.sendRequest( $.extend( {}, baseRequestParams, data[ 'continue' ] ) );
1262 } ).setDisabled( !data[ 'continue' ] ).$element,
1263 ( clear = new OO.ui.ButtonWidget( {
1264 label: mw.message( 'apisandbox-continue-clear' ).text()
1265 } ).on( 'click', function () {
1266 ApiSandbox.updateUI( baseRequestParams );
1267 clear.setDisabled( true );
1268 booklet.setPage( '|results|' );
1269 } ).setDisabled( !paramsAreForced ) ).$element,
1270 new OO.ui.PopupButtonWidget( {
1271 $overlay: true,
1272 framed: false,
1273 icon: 'info',
1274 popup: {
1275 $content: $( '<div>' ).append( Util.parseMsg( 'apisandbox-continue-help' ) ),
1276 padded: true,
1277 width: 'auto'
1278 }
1279 } ).$element
1280 )
1281 );
1282 }
1283 if ( typeof loadTime === 'number' ) {
1284 $result.append(
1285 $( '<div>' ).append(
1286 new OO.ui.LabelWidget( {
1287 label: mw.message( 'apisandbox-request-time', loadTime ).text()
1288 } ).$element
1289 )
1290 );
1291 }
1292
1293 if ( jqXHR.getResponseHeader( 'MediaWiki-API-Error' ) === 'badtoken' ) {
1294 // Flush all saved tokens in case one of them is the bad one.
1295 Util.markTokensBad();
1296 button = new OO.ui.ButtonWidget( {
1297 label: mw.message( 'apisandbox-results-fixtoken' ).text()
1298 } );
1299 button.on( 'click', ApiSandbox.fixTokenAndResend )
1300 .on( 'click', button.setDisabled, [ true ], button )
1301 .$element.appendTo( $result );
1302 }
1303 }, function ( code, data ) {
1304 var details = 'HTTP error: ' + data.exception;
1305 $result.empty()
1306 .append(
1307 new OO.ui.LabelWidget( {
1308 label: mw.message( 'apisandbox-results-error', details ).text(),
1309 classes: [ 'error' ]
1310 } ).$element
1311 );
1312 } );
1313 } );
1314 },
1315
1316 /**
1317 * Handler for the "Correct token and resubmit" button
1318 *
1319 * Used on a 'badtoken' error, it re-fetches token parameters for all
1320 * pages and then re-submits the query.
1321 */
1322 fixTokenAndResend: function () {
1323 var page, subpages, i, k,
1324 ok = true,
1325 tokenWait = { dummy: true },
1326 checkPages = [ pages.main ],
1327 success = function ( k ) {
1328 delete tokenWait[ k ];
1329 if ( ok && $.isEmptyObject( tokenWait ) ) {
1330 ApiSandbox.sendRequest();
1331 }
1332 },
1333 failure = function ( k ) {
1334 delete tokenWait[ k ];
1335 ok = false;
1336 };
1337
1338 while ( checkPages.length ) {
1339 page = checkPages.shift();
1340
1341 if ( page.tokenWidget ) {
1342 k = page.apiModule + page.tokenWidget.paramInfo.name;
1343 tokenWait[ k ] = page.tokenWidget.fetchToken();
1344 tokenWait[ k ]
1345 .done( success.bind( page.tokenWidget, k ) )
1346 .fail( failure.bind( page.tokenWidget, k ) );
1347 }
1348
1349 subpages = page.getSubpages();
1350 for ( i = 0; i < subpages.length; i++ ) {
1351 if ( pages.hasOwnProperty( subpages[ i ].key ) ) {
1352 checkPages.push( pages[ subpages[ i ].key ] );
1353 }
1354 }
1355 }
1356
1357 success( 'dummy', '' );
1358 },
1359
1360 /**
1361 * Reset validity indicators for all widgets
1362 */
1363 updateValidityIndicators: function () {
1364 var page, subpages, i,
1365 checkPages = [ pages.main ];
1366
1367 while ( checkPages.length ) {
1368 page = checkPages.shift();
1369 page.apiCheckValid();
1370 subpages = page.getSubpages();
1371 for ( i = 0; i < subpages.length; i++ ) {
1372 if ( pages.hasOwnProperty( subpages[ i ].key ) ) {
1373 checkPages.push( pages[ subpages[ i ].key ] );
1374 }
1375 }
1376 }
1377 }
1378 };
1379
1380 /**
1381 * PageLayout for API modules
1382 *
1383 * @class
1384 * @private
1385 * @extends OO.ui.PageLayout
1386 * @constructor
1387 * @param {Object} [config] Configuration options
1388 */
1389 ApiSandbox.PageLayout = function ( config ) {
1390 config = $.extend( { prefix: '' }, config );
1391 this.displayText = config.key;
1392 this.apiModule = config.path;
1393 this.prefix = config.prefix;
1394 this.paramInfo = null;
1395 this.apiIsValid = true;
1396 this.loadFromQueryParams = null;
1397 this.widgets = {};
1398 this.tokenWidget = null;
1399 this.indentLevel = config.indentLevel ? config.indentLevel : 0;
1400 ApiSandbox.PageLayout[ 'super' ].call( this, config.key, config );
1401 this.loadParamInfo();
1402 };
1403 OO.inheritClass( ApiSandbox.PageLayout, OO.ui.PageLayout );
1404 ApiSandbox.PageLayout.prototype.setupOutlineItem = function () {
1405 this.outlineItem.setLevel( this.indentLevel );
1406 this.outlineItem.setLabel( this.displayText );
1407 this.outlineItem.setIcon( this.apiIsValid || suppressErrors ? null : 'alert' );
1408 this.outlineItem.setIconTitle(
1409 this.apiIsValid || suppressErrors ? '' : mw.message( 'apisandbox-alert-page' ).plain()
1410 );
1411 };
1412
1413 /**
1414 * Fetch module information for this page's module, then create UI
1415 */
1416 ApiSandbox.PageLayout.prototype.loadParamInfo = function () {
1417 var dynamicFieldset, dynamicParamNameWidget,
1418 that = this,
1419 removeDynamicParamWidget = function ( name, layout ) {
1420 dynamicFieldset.removeItems( [ layout ] );
1421 delete that.widgets[ name ];
1422 },
1423 addDynamicParamWidget = function () {
1424 var name, layout, widget, button;
1425
1426 // Check name is filled in
1427 name = dynamicParamNameWidget.getValue().trim();
1428 if ( name === '' ) {
1429 dynamicParamNameWidget.focus();
1430 return;
1431 }
1432
1433 if ( that.widgets[ name ] !== undefined ) {
1434 windowManager.openWindow( 'errorAlert', {
1435 title: Util.parseMsg( 'apisandbox-dynamic-error-exists', name ),
1436 actions: [
1437 {
1438 action: 'accept',
1439 label: OO.ui.msg( 'ooui-dialog-process-dismiss' ),
1440 flags: 'primary'
1441 }
1442 ]
1443 } );
1444 return;
1445 }
1446
1447 widget = Util.createWidgetForParameter( {
1448 name: name,
1449 type: 'string',
1450 'default': ''
1451 }, {
1452 nooptional: true
1453 } );
1454 button = new OO.ui.ButtonWidget( {
1455 icon: 'trash',
1456 flags: 'destructive'
1457 } );
1458 layout = new OO.ui.ActionFieldLayout(
1459 widget,
1460 button,
1461 {
1462 label: name,
1463 align: 'left'
1464 }
1465 );
1466 button.on( 'click', removeDynamicParamWidget, [ name, layout ] );
1467 that.widgets[ name ] = widget;
1468 dynamicFieldset.addItems( [ layout ], dynamicFieldset.getItems().length - 1 );
1469 widget.focus();
1470
1471 dynamicParamNameWidget.setValue( '' );
1472 };
1473
1474 this.$element.empty()
1475 .append( new OO.ui.ProgressBarWidget( {
1476 progress: false,
1477 text: mw.message( 'apisandbox-loading', this.displayText ).text()
1478 } ).$element );
1479
1480 Util.fetchModuleInfo( this.apiModule )
1481 .done( function ( pi ) {
1482 var prefix, i, j, descriptionContainer, widget, layoutConfig, button, widgetField, helpField, tmp, flag, count,
1483 items = [],
1484 deprecatedItems = [],
1485 buttons = [],
1486 filterFmModules = function ( v ) {
1487 return v.substr( -2 ) !== 'fm' ||
1488 !availableFormats.hasOwnProperty( v.substr( 0, v.length - 2 ) );
1489 },
1490 widgetLabelOnClick = function () {
1491 var f = this.getField();
1492 if ( $.isFunction( f.setDisabled ) ) {
1493 f.setDisabled( false );
1494 }
1495 if ( $.isFunction( f.focus ) ) {
1496 f.focus();
1497 }
1498 };
1499
1500 // This is something of a hack. We always want the 'format' and
1501 // 'action' parameters from the main module to be specified,
1502 // and for 'format' we also want to simplify the dropdown since
1503 // we always send the 'fm' variant.
1504 if ( that.apiModule === 'main' ) {
1505 for ( i = 0; i < pi.parameters.length; i++ ) {
1506 if ( pi.parameters[ i ].name === 'action' ) {
1507 pi.parameters[ i ].required = true;
1508 delete pi.parameters[ i ][ 'default' ];
1509 }
1510 if ( pi.parameters[ i ].name === 'format' ) {
1511 tmp = pi.parameters[ i ].type;
1512 for ( j = 0; j < tmp.length; j++ ) {
1513 availableFormats[ tmp[ j ] ] = true;
1514 }
1515 pi.parameters[ i ].type = tmp.filter( filterFmModules );
1516 pi.parameters[ i ][ 'default' ] = 'json';
1517 pi.parameters[ i ].required = true;
1518 }
1519 }
1520 }
1521
1522 // Hide the 'wrappedhtml' parameter on format modules
1523 if ( pi.group === 'format' ) {
1524 pi.parameters = pi.parameters.filter( function ( p ) {
1525 return p.name !== 'wrappedhtml';
1526 } );
1527 }
1528
1529 that.paramInfo = pi;
1530
1531 items.push( new OO.ui.FieldLayout(
1532 new OO.ui.Widget( {} ).toggle( false ), {
1533 align: 'top',
1534 label: Util.parseHTML( pi.description )
1535 }
1536 ) );
1537
1538 if ( pi.helpurls.length ) {
1539 buttons.push( new OO.ui.PopupButtonWidget( {
1540 $overlay: true,
1541 label: mw.message( 'apisandbox-helpurls' ).text(),
1542 icon: 'help',
1543 popup: {
1544 width: 'auto',
1545 padded: true,
1546 $content: $( '<ul>' ).append( pi.helpurls.map( function ( link ) {
1547 return $( '<li>' ).append( $( '<a>' )
1548 .attr( { href: link, target: '_blank' } )
1549 .text( link )
1550 );
1551 } ) )
1552 }
1553 } ) );
1554 }
1555
1556 if ( pi.examples.length ) {
1557 buttons.push( new OO.ui.PopupButtonWidget( {
1558 $overlay: true,
1559 label: mw.message( 'apisandbox-examples' ).text(),
1560 icon: 'code',
1561 popup: {
1562 width: 'auto',
1563 padded: true,
1564 $content: $( '<ul>' ).append( pi.examples.map( function ( example ) {
1565 var a = $( '<a>' )
1566 .attr( 'href', '#' + example.query )
1567 .html( example.description );
1568 a.find( 'a' ).contents().unwrap(); // Can't nest links
1569 return $( '<li>' ).append( a );
1570 } ) )
1571 }
1572 } ) );
1573 }
1574
1575 if ( buttons.length ) {
1576 items.push( new OO.ui.FieldLayout(
1577 new OO.ui.ButtonGroupWidget( {
1578 items: buttons
1579 } ), { align: 'top' }
1580 ) );
1581 }
1582
1583 if ( pi.parameters.length ) {
1584 prefix = that.prefix + pi.prefix;
1585 for ( i = 0; i < pi.parameters.length; i++ ) {
1586 widget = Util.createWidgetForParameter( pi.parameters[ i ] );
1587 that.widgets[ prefix + pi.parameters[ i ].name ] = widget;
1588 if ( pi.parameters[ i ].tokentype ) {
1589 that.tokenWidget = widget;
1590 }
1591
1592 descriptionContainer = $( '<div>' );
1593
1594 tmp = Util.parseHTML( pi.parameters[ i ].description );
1595 tmp.filter( 'dl' ).makeCollapsible( {
1596 collapsed: true
1597 } ).children( '.mw-collapsible-toggle' ).each( function () {
1598 var $this = $( this );
1599 $this.parent().prev( 'p' ).append( $this );
1600 } );
1601 descriptionContainer.append( $( '<div>' ).addClass( 'description' ).append( tmp ) );
1602
1603 if ( pi.parameters[ i ].info && pi.parameters[ i ].info.length ) {
1604 for ( j = 0; j < pi.parameters[ i ].info.length; j++ ) {
1605 descriptionContainer.append( $( '<div>' )
1606 .addClass( 'info' )
1607 .append( Util.parseHTML( pi.parameters[ i ].info[ j ] ) )
1608 );
1609 }
1610 }
1611 flag = true;
1612 count = 1e100;
1613 switch ( pi.parameters[ i ].type ) {
1614 case 'namespace':
1615 flag = false;
1616 count = mw.config.get( 'wgFormattedNamespaces' ).length;
1617 break;
1618
1619 case 'limit':
1620 if ( pi.parameters[ i ].highmax !== undefined ) {
1621 descriptionContainer.append( $( '<div>' )
1622 .addClass( 'info' )
1623 .append(
1624 Util.parseMsg(
1625 'api-help-param-limit2', pi.parameters[ i ].max, pi.parameters[ i ].highmax
1626 ),
1627 ' ',
1628 Util.parseMsg( 'apisandbox-param-limit' )
1629 )
1630 );
1631 } else {
1632 descriptionContainer.append( $( '<div>' )
1633 .addClass( 'info' )
1634 .append(
1635 Util.parseMsg( 'api-help-param-limit', pi.parameters[ i ].max ),
1636 ' ',
1637 Util.parseMsg( 'apisandbox-param-limit' )
1638 )
1639 );
1640 }
1641 break;
1642
1643 case 'integer':
1644 tmp = '';
1645 if ( pi.parameters[ i ].min !== undefined ) {
1646 tmp += 'min';
1647 }
1648 if ( pi.parameters[ i ].max !== undefined ) {
1649 tmp += 'max';
1650 }
1651 if ( tmp !== '' ) {
1652 descriptionContainer.append( $( '<div>' )
1653 .addClass( 'info' )
1654 .append( Util.parseMsg(
1655 'api-help-param-integer-' + tmp,
1656 Util.apiBool( pi.parameters[ i ].multi ) ? 2 : 1,
1657 pi.parameters[ i ].min, pi.parameters[ i ].max
1658 ) )
1659 );
1660 }
1661 break;
1662
1663 default:
1664 if ( Array.isArray( pi.parameters[ i ].type ) ) {
1665 flag = false;
1666 count = pi.parameters[ i ].type.length;
1667 }
1668 break;
1669 }
1670 if ( Util.apiBool( pi.parameters[ i ].multi ) ) {
1671 tmp = [];
1672 if ( flag && !( widget instanceof OO.ui.TagMultiselectWidget ) &&
1673 !(
1674 widget instanceof OptionalWidget &&
1675 widget.widget instanceof OO.ui.TagMultiselectWidget
1676 )
1677 ) {
1678 tmp.push( mw.message( 'api-help-param-multi-separate' ).parse() );
1679 }
1680 if ( count > pi.parameters[ i ].lowlimit ) {
1681 tmp.push(
1682 mw.message( 'api-help-param-multi-max',
1683 pi.parameters[ i ].lowlimit, pi.parameters[ i ].highlimit
1684 ).parse()
1685 );
1686 }
1687 if ( tmp.length ) {
1688 descriptionContainer.append( $( '<div>' )
1689 .addClass( 'info' )
1690 .append( Util.parseHTML( tmp.join( ' ' ) ) )
1691 );
1692 }
1693 }
1694 if ( 'maxbytes' in pi.parameters[ i ] ) {
1695 descriptionContainer.append( $( '<div>' )
1696 .addClass( 'info' )
1697 .append( Util.parseMsg( 'api-help-param-maxbytes', pi.parameters[ i ].maxbytes ) )
1698 );
1699 }
1700 if ( 'maxchars' in pi.parameters[ i ] ) {
1701 descriptionContainer.append( $( '<div>' )
1702 .addClass( 'info' )
1703 .append( Util.parseMsg( 'api-help-param-maxchars', pi.parameters[ i ].maxchars ) )
1704 );
1705 }
1706 helpField = new OO.ui.FieldLayout(
1707 new OO.ui.Widget( {
1708 $content: '\xa0',
1709 classes: [ 'mw-apisandbox-spacer' ]
1710 } ), {
1711 align: 'inline',
1712 classes: [ 'mw-apisandbox-help-field' ],
1713 label: descriptionContainer
1714 }
1715 );
1716
1717 layoutConfig = {
1718 align: 'left',
1719 classes: [ 'mw-apisandbox-widget-field' ],
1720 label: prefix + pi.parameters[ i ].name
1721 };
1722
1723 if ( pi.parameters[ i ].tokentype ) {
1724 button = new OO.ui.ButtonWidget( {
1725 label: mw.message( 'apisandbox-fetch-token' ).text()
1726 } );
1727 button.on( 'click', widget.fetchToken, [], widget );
1728
1729 widgetField = new OO.ui.ActionFieldLayout( widget, button, layoutConfig );
1730 } else {
1731 widgetField = new OO.ui.FieldLayout( widget, layoutConfig );
1732 }
1733
1734 // We need our own click handler on the widget label to
1735 // turn off the disablement.
1736 widgetField.$label.on( 'click', widgetLabelOnClick.bind( widgetField ) );
1737
1738 // Don't grey out the label when the field is disabled,
1739 // it makes it too hard to read and our "disabled"
1740 // isn't really disabled.
1741 widgetField.onFieldDisable( false );
1742 widgetField.onFieldDisable = $.noop;
1743
1744 if ( Util.apiBool( pi.parameters[ i ].deprecated ) ) {
1745 deprecatedItems.push( widgetField, helpField );
1746 } else {
1747 items.push( widgetField, helpField );
1748 }
1749 }
1750 }
1751
1752 if ( !pi.parameters.length && !Util.apiBool( pi.dynamicparameters ) ) {
1753 items.push( new OO.ui.FieldLayout(
1754 new OO.ui.Widget( {} ).toggle( false ), {
1755 align: 'top',
1756 label: Util.parseMsg( 'apisandbox-no-parameters' )
1757 }
1758 ) );
1759 }
1760
1761 that.$element.empty();
1762
1763 new OO.ui.FieldsetLayout( {
1764 label: that.displayText
1765 } ).addItems( items )
1766 .$element.appendTo( that.$element );
1767
1768 if ( Util.apiBool( pi.dynamicparameters ) ) {
1769 dynamicFieldset = new OO.ui.FieldsetLayout();
1770 dynamicParamNameWidget = new OO.ui.TextInputWidget( {
1771 placeholder: mw.message( 'apisandbox-dynamic-parameters-add-placeholder' ).text()
1772 } ).on( 'enter', addDynamicParamWidget );
1773 dynamicFieldset.addItems( [
1774 new OO.ui.FieldLayout(
1775 new OO.ui.Widget( {} ).toggle( false ), {
1776 align: 'top',
1777 label: Util.parseHTML( pi.dynamicparameters )
1778 }
1779 ),
1780 new OO.ui.ActionFieldLayout(
1781 dynamicParamNameWidget,
1782 new OO.ui.ButtonWidget( {
1783 icon: 'add',
1784 flags: 'progressive'
1785 } ).on( 'click', addDynamicParamWidget ),
1786 {
1787 label: mw.message( 'apisandbox-dynamic-parameters-add-label' ).text(),
1788 align: 'left'
1789 }
1790 )
1791 ] );
1792 $( '<fieldset>' )
1793 .append(
1794 $( '<legend>' ).text( mw.message( 'apisandbox-dynamic-parameters' ).text() ),
1795 dynamicFieldset.$element
1796 )
1797 .appendTo( that.$element );
1798 }
1799
1800 if ( deprecatedItems.length ) {
1801 tmp = new OO.ui.FieldsetLayout().addItems( deprecatedItems ).toggle( false );
1802 $( '<fieldset>' )
1803 .append(
1804 $( '<legend>' ).append(
1805 new OO.ui.ToggleButtonWidget( {
1806 label: mw.message( 'apisandbox-deprecated-parameters' ).text()
1807 } ).on( 'change', tmp.toggle, [], tmp ).$element
1808 ),
1809 tmp.$element
1810 )
1811 .appendTo( that.$element );
1812 }
1813
1814 // Load stored params, if any, then update the booklet if we
1815 // have subpages (or else just update our valid-indicator).
1816 tmp = that.loadFromQueryParams;
1817 that.loadFromQueryParams = null;
1818 if ( $.isPlainObject( tmp ) ) {
1819 that.loadQueryParams( tmp );
1820 }
1821 if ( that.getSubpages().length > 0 ) {
1822 ApiSandbox.updateUI( tmp );
1823 } else {
1824 that.apiCheckValid();
1825 }
1826 } ).fail( function ( code, detail ) {
1827 that.$element.empty()
1828 .append(
1829 new OO.ui.LabelWidget( {
1830 label: mw.message( 'apisandbox-load-error', that.apiModule, detail ).text(),
1831 classes: [ 'error' ]
1832 } ).$element,
1833 new OO.ui.ButtonWidget( {
1834 label: mw.message( 'apisandbox-retry' ).text()
1835 } ).on( 'click', that.loadParamInfo, [], that ).$element
1836 );
1837 } );
1838 };
1839
1840 /**
1841 * Check that all widgets on the page are in a valid state.
1842 *
1843 * @return {jQuery.Promise[]} One promise for each widget, resolved with `false` if invalid
1844 */
1845 ApiSandbox.PageLayout.prototype.apiCheckValid = function () {
1846 var promises, that = this;
1847
1848 if ( this.paramInfo === null ) {
1849 return [];
1850 } else {
1851 promises = $.map( this.widgets, function ( widget ) {
1852 return widget.apiCheckValid();
1853 } );
1854 $.when.apply( $, promises ).then( function () {
1855 that.apiIsValid = $.inArray( false, arguments ) === -1;
1856 if ( that.getOutlineItem() ) {
1857 that.getOutlineItem().setIcon( that.apiIsValid || suppressErrors ? null : 'alert' );
1858 that.getOutlineItem().setIconTitle(
1859 that.apiIsValid || suppressErrors ? '' : mw.message( 'apisandbox-alert-page' ).plain()
1860 );
1861 }
1862 } );
1863 return promises;
1864 }
1865 };
1866
1867 /**
1868 * Load form fields from query parameters
1869 *
1870 * @param {Object} params
1871 */
1872 ApiSandbox.PageLayout.prototype.loadQueryParams = function ( params ) {
1873 if ( this.paramInfo === null ) {
1874 this.loadFromQueryParams = params;
1875 } else {
1876 $.each( this.widgets, function ( name, widget ) {
1877 var v = params.hasOwnProperty( name ) ? params[ name ] : undefined;
1878 widget.setApiValue( v );
1879 } );
1880 }
1881 };
1882
1883 /**
1884 * Load query params from form fields
1885 *
1886 * @param {Object} params Write query parameters into this object
1887 * @param {Object} displayParams Write query parameters for display into this object
1888 */
1889 ApiSandbox.PageLayout.prototype.getQueryParams = function ( params, displayParams ) {
1890 $.each( this.widgets, function ( name, widget ) {
1891 var value = widget.getApiValue();
1892 if ( value !== undefined ) {
1893 params[ name ] = value;
1894 if ( $.isFunction( widget.getApiValueForDisplay ) ) {
1895 value = widget.getApiValueForDisplay();
1896 }
1897 displayParams[ name ] = value;
1898 }
1899 } );
1900 };
1901
1902 /**
1903 * Fetch a list of subpage names loaded by this page
1904 *
1905 * @return {Array}
1906 */
1907 ApiSandbox.PageLayout.prototype.getSubpages = function () {
1908 var ret = [];
1909 $.each( this.widgets, function ( name, widget ) {
1910 var submodules, i;
1911 if ( $.isFunction( widget.getSubmodules ) ) {
1912 submodules = widget.getSubmodules();
1913 for ( i = 0; i < submodules.length; i++ ) {
1914 ret.push( {
1915 key: name + '=' + submodules[ i ].value,
1916 path: submodules[ i ].path,
1917 prefix: widget.paramInfo.submoduleparamprefix || ''
1918 } );
1919 }
1920 }
1921 } );
1922 return ret;
1923 };
1924
1925 $( ApiSandbox.init );
1926
1927 module.exports = ApiSandbox;
1928
1929 }( jQuery, mediaWiki, OO ) );