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