f56c0dbbacac78c008635e612b3f700c5045610e
[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 no-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 } );
1088
1089 $result = $( '<div>' )
1090 .append( $progressText, progress.$element );
1091
1092 resultPage = page = new OO.ui.PageLayout( '|results|', { expanded: false } );
1093 page.setupOutlineItem = function () {
1094 this.outlineItem.setLabel( mw.message( 'apisandbox-results' ).text() );
1095 };
1096
1097 if ( !formatDropdown ) {
1098 formatDropdown = new OO.ui.DropdownWidget( {
1099 menu: { items: [] },
1100 $overlay: true
1101 } );
1102 formatDropdown.getMenu().on( 'select', Util.onFormatDropdownChange );
1103 }
1104
1105 menu = formatDropdown.getMenu();
1106 selectedLabel = menu.findSelectedItem() ? menu.findSelectedItem().getLabel() : '';
1107 if ( typeof selectedLabel !== 'string' ) {
1108 selectedLabel = selectedLabel.text();
1109 }
1110 menu.clearItems().addItems( formatItems );
1111 menu.chooseItem( menu.getItemFromLabel( selectedLabel ) || menu.findFirstSelectableItem() );
1112
1113 // Fire the event to update field visibilities
1114 Util.onFormatDropdownChange();
1115
1116 page.$element.empty()
1117 .append(
1118 new OO.ui.FieldLayout(
1119 formatDropdown, {
1120 label: Util.parseMsg( 'apisandbox-request-selectformat-label' )
1121 }
1122 ).$element,
1123 formatItems.map( function ( item ) {
1124 return item.getData().$element;
1125 } ),
1126 $result
1127 );
1128 ApiSandbox.updateUI();
1129 booklet.setPage( '|results|' );
1130
1131 location.href = oldhash = '#' + query;
1132
1133 api.post( params, {
1134 contentType: 'multipart/form-data',
1135 dataType: 'text',
1136 xhr: function () {
1137 var xhr = new window.XMLHttpRequest();
1138 xhr.upload.addEventListener( 'progress', function ( e ) {
1139 if ( !progressLoading ) {
1140 if ( e.lengthComputable ) {
1141 progress.setProgress( e.loaded * 100 / e.total );
1142 } else {
1143 progress.setProgress( false );
1144 }
1145 }
1146 } );
1147 xhr.addEventListener( 'progress', function ( e ) {
1148 if ( !progressLoading ) {
1149 progressLoading = true;
1150 $progressText.text( mw.message( 'apisandbox-loading-results' ).text() );
1151 }
1152 if ( e.lengthComputable ) {
1153 progress.setProgress( e.loaded * 100 / e.total );
1154 } else {
1155 progress.setProgress( false );
1156 }
1157 } );
1158 return xhr;
1159 }
1160 } )
1161 .catch( function ( code, data, result, jqXHR ) {
1162 var deferred = $.Deferred();
1163
1164 if ( code !== 'http' ) {
1165 // Not really an error, work around mw.Api thinking it is.
1166 deferred.resolve( result, jqXHR );
1167 } else {
1168 // Just forward it.
1169 deferred.reject.apply( deferred, arguments );
1170 }
1171 return deferred.promise();
1172 } )
1173 .then( function ( data, jqXHR ) {
1174 var m, loadTime, button, clear,
1175 ct = jqXHR.getResponseHeader( 'Content-Type' ),
1176 loginSuppressed = jqXHR.getResponseHeader( 'MediaWiki-Login-Suppressed' ) || 'false';
1177
1178 $result.empty();
1179 if ( loginSuppressed !== 'false' ) {
1180 $( '<div>' )
1181 .addClass( 'warning' )
1182 .append( Util.parseMsg( 'apisandbox-results-login-suppressed' ) )
1183 .appendTo( $result );
1184 }
1185 if ( /^text\/mediawiki-api-prettyprint-wrapped(?:;|$)/.test( ct ) ) {
1186 data = JSON.parse( data );
1187 if ( data.modules.length ) {
1188 mw.loader.load( data.modules );
1189 }
1190 if ( data.status && data.status !== 200 ) {
1191 $( '<div>' )
1192 .addClass( 'api-pretty-header api-pretty-status' )
1193 .append( Util.parseMsg( 'api-format-prettyprint-status', data.status, data.statustext ) )
1194 .appendTo( $result );
1195 }
1196 $result.append( Util.parseHTML( data.html ) );
1197 loadTime = data.time;
1198 } else if ( ( m = data.match( /<pre[ >][\s\S]*<\/pre>/ ) ) ) {
1199 $result.append( Util.parseHTML( m[ 0 ] ) );
1200 if ( ( m = data.match( /"wgBackendResponseTime":\s*(\d+)/ ) ) ) {
1201 loadTime = parseInt( m[ 1 ], 10 );
1202 }
1203 } else {
1204 $( '<pre>' )
1205 .addClass( 'api-pretty-content' )
1206 .text( data )
1207 .appendTo( $result );
1208 }
1209 if ( paramsAreForced || data.continue ) {
1210 $result.append(
1211 $( '<div>' ).append(
1212 new OO.ui.ButtonWidget( {
1213 label: mw.message( 'apisandbox-continue' ).text()
1214 } ).on( 'click', function () {
1215 ApiSandbox.sendRequest( $.extend( {}, baseRequestParams, data.continue ) );
1216 } ).setDisabled( !data.continue ).$element,
1217 ( clear = new OO.ui.ButtonWidget( {
1218 label: mw.message( 'apisandbox-continue-clear' ).text()
1219 } ).on( 'click', function () {
1220 ApiSandbox.updateUI( baseRequestParams );
1221 clear.setDisabled( true );
1222 booklet.setPage( '|results|' );
1223 } ).setDisabled( !paramsAreForced ) ).$element,
1224 new OO.ui.PopupButtonWidget( {
1225 $overlay: true,
1226 framed: false,
1227 icon: 'info',
1228 popup: {
1229 $content: $( '<div>' ).append( Util.parseMsg( 'apisandbox-continue-help' ) ),
1230 padded: true,
1231 width: 'auto'
1232 }
1233 } ).$element
1234 )
1235 );
1236 }
1237 if ( typeof loadTime === 'number' ) {
1238 $result.append(
1239 $( '<div>' ).append(
1240 new OO.ui.LabelWidget( {
1241 label: mw.message( 'apisandbox-request-time', loadTime ).text()
1242 } ).$element
1243 )
1244 );
1245 }
1246
1247 if ( jqXHR.getResponseHeader( 'MediaWiki-API-Error' ) === 'badtoken' ) {
1248 // Flush all saved tokens in case one of them is the bad one.
1249 Util.markTokensBad();
1250 button = new OO.ui.ButtonWidget( {
1251 label: mw.message( 'apisandbox-results-fixtoken' ).text()
1252 } );
1253 button.on( 'click', ApiSandbox.fixTokenAndResend )
1254 .on( 'click', button.setDisabled, [ true ], button )
1255 .$element.appendTo( $result );
1256 }
1257 }, function ( code, data ) {
1258 var details = 'HTTP error: ' + data.exception;
1259 $result.empty()
1260 .append(
1261 new OO.ui.LabelWidget( {
1262 label: mw.message( 'apisandbox-results-error', details ).text(),
1263 classes: [ 'error' ]
1264 } ).$element
1265 );
1266 } );
1267 } );
1268 },
1269
1270 /**
1271 * Handler for the "Correct token and resubmit" button
1272 *
1273 * Used on a 'badtoken' error, it re-fetches token parameters for all
1274 * pages and then re-submits the query.
1275 */
1276 fixTokenAndResend: function () {
1277 var page, subpages, i, k,
1278 ok = true,
1279 tokenWait = { dummy: true },
1280 checkPages = [ pages.main ],
1281 success = function ( k ) {
1282 delete tokenWait[ k ];
1283 if ( ok && $.isEmptyObject( tokenWait ) ) {
1284 ApiSandbox.sendRequest();
1285 }
1286 },
1287 failure = function ( k ) {
1288 delete tokenWait[ k ];
1289 ok = false;
1290 };
1291
1292 while ( checkPages.length ) {
1293 page = checkPages.shift();
1294
1295 if ( page.tokenWidget ) {
1296 k = page.apiModule + page.tokenWidget.paramInfo.name;
1297 tokenWait[ k ] = page.tokenWidget.fetchToken();
1298 tokenWait[ k ]
1299 .done( success.bind( page.tokenWidget, k ) )
1300 .fail( failure.bind( page.tokenWidget, k ) );
1301 }
1302
1303 subpages = page.getSubpages();
1304 for ( i = 0; i < subpages.length; i++ ) {
1305 if ( Object.prototype.hasOwnProperty.call( pages, subpages[ i ].key ) ) {
1306 checkPages.push( pages[ subpages[ i ].key ] );
1307 }
1308 }
1309 }
1310
1311 success( 'dummy', '' );
1312 },
1313
1314 /**
1315 * Reset validity indicators for all widgets
1316 */
1317 updateValidityIndicators: function () {
1318 var page, subpages, i,
1319 checkPages = [ pages.main ];
1320
1321 while ( checkPages.length ) {
1322 page = checkPages.shift();
1323 page.apiCheckValid();
1324 subpages = page.getSubpages();
1325 for ( i = 0; i < subpages.length; i++ ) {
1326 if ( Object.prototype.hasOwnProperty.call( pages, subpages[ i ].key ) ) {
1327 checkPages.push( pages[ subpages[ i ].key ] );
1328 }
1329 }
1330 }
1331 }
1332 };
1333
1334 /**
1335 * PageLayout for API modules
1336 *
1337 * @class
1338 * @private
1339 * @extends OO.ui.PageLayout
1340 * @constructor
1341 * @param {Object} [config] Configuration options
1342 */
1343 ApiSandbox.PageLayout = function ( config ) {
1344 config = $.extend( { prefix: '', expanded: false }, config );
1345 this.displayText = config.key;
1346 this.apiModule = config.path;
1347 this.prefix = config.prefix;
1348 this.paramInfo = null;
1349 this.apiIsValid = true;
1350 this.loadFromQueryParams = null;
1351 this.widgets = {};
1352 this.itemsFieldset = null;
1353 this.deprecatedItemsFieldset = null;
1354 this.templatedItemsCache = {};
1355 this.tokenWidget = null;
1356 this.indentLevel = config.indentLevel ? config.indentLevel : 0;
1357 ApiSandbox.PageLayout.super.call( this, config.key, config );
1358 this.loadParamInfo();
1359 };
1360 OO.inheritClass( ApiSandbox.PageLayout, OO.ui.PageLayout );
1361 ApiSandbox.PageLayout.prototype.setupOutlineItem = function () {
1362 this.outlineItem.setLevel( this.indentLevel );
1363 this.outlineItem.setLabel( this.displayText );
1364 this.outlineItem.setIcon( this.apiIsValid || suppressErrors ? null : 'alert' );
1365 this.outlineItem.setTitle(
1366 this.apiIsValid || suppressErrors ? '' : mw.message( 'apisandbox-alert-page' ).plain()
1367 );
1368 };
1369
1370 function widgetLabelOnClick() {
1371 var f = this.getField();
1372 if ( typeof f.setDisabled === 'function' ) {
1373 f.setDisabled( false );
1374 }
1375 if ( typeof f.focus === 'function' ) {
1376 f.focus();
1377 }
1378 }
1379
1380 /**
1381 * Create a widget and the FieldLayouts it needs
1382 * @private
1383 * @param {Object} ppi API paraminfo data for the parameter
1384 * @param {string} name API parameter name
1385 * @return {Object}
1386 * @return {OO.ui.Widget} return.widget
1387 * @return {OO.ui.FieldLayout} return.widgetField
1388 * @return {OO.ui.FieldLayout} return.helpField
1389 */
1390 ApiSandbox.PageLayout.prototype.makeWidgetFieldLayouts = function ( ppi, name ) {
1391 var j, l, widget, descriptionContainer, tmp, flag, count, button, widgetField, helpField, layoutConfig;
1392
1393 widget = Util.createWidgetForParameter( ppi );
1394 if ( ppi.tokentype ) {
1395 this.tokenWidget = widget;
1396 }
1397 if ( this.paramInfo.templatedparameters.length ) {
1398 widget.on( 'change', this.updateTemplatedParameters, [ null ], this );
1399 }
1400
1401 descriptionContainer = $( '<div>' );
1402
1403 tmp = Util.parseHTML( ppi.description );
1404 tmp.filter( 'dl' ).makeCollapsible( {
1405 collapsed: true
1406 } ).children( '.mw-collapsible-toggle' ).each( function () {
1407 var $this = $( this );
1408 $this.parent().prev( 'p' ).append( $this );
1409 } );
1410 descriptionContainer.append( $( '<div>' ).addClass( 'description' ).append( tmp ) );
1411
1412 if ( ppi.info && ppi.info.length ) {
1413 for ( j = 0; j < ppi.info.length; j++ ) {
1414 descriptionContainer.append( $( '<div>' )
1415 .addClass( 'info' )
1416 .append( Util.parseHTML( ppi.info[ j ] ) )
1417 );
1418 }
1419 }
1420 flag = true;
1421 count = Infinity;
1422 switch ( ppi.type ) {
1423 case 'namespace':
1424 flag = false;
1425 count = mw.config.get( 'wgFormattedNamespaces' ).length;
1426 break;
1427
1428 case 'limit':
1429 if ( ppi.highmax !== undefined ) {
1430 descriptionContainer.append( $( '<div>' )
1431 .addClass( 'info' )
1432 .append(
1433 Util.parseMsg(
1434 'api-help-param-limit2', ppi.max, ppi.highmax
1435 ),
1436 ' ',
1437 Util.parseMsg( 'apisandbox-param-limit' )
1438 )
1439 );
1440 } else {
1441 descriptionContainer.append( $( '<div>' )
1442 .addClass( 'info' )
1443 .append(
1444 Util.parseMsg( 'api-help-param-limit', ppi.max ),
1445 ' ',
1446 Util.parseMsg( 'apisandbox-param-limit' )
1447 )
1448 );
1449 }
1450 break;
1451
1452 case 'integer':
1453 tmp = '';
1454 if ( ppi.min !== undefined ) {
1455 tmp += 'min';
1456 }
1457 if ( ppi.max !== undefined ) {
1458 tmp += 'max';
1459 }
1460 if ( tmp !== '' ) {
1461 descriptionContainer.append( $( '<div>' )
1462 .addClass( 'info' )
1463 .append( Util.parseMsg(
1464 'api-help-param-integer-' + tmp,
1465 Util.apiBool( ppi.multi ) ? 2 : 1,
1466 ppi.min, ppi.max
1467 ) )
1468 );
1469 }
1470 break;
1471
1472 default:
1473 if ( Array.isArray( ppi.type ) ) {
1474 flag = false;
1475 count = ppi.type.length;
1476 }
1477 break;
1478 }
1479 if ( Util.apiBool( ppi.multi ) ) {
1480 tmp = [];
1481 if ( flag && !( widget instanceof OO.ui.TagMultiselectWidget ) &&
1482 !(
1483 widget instanceof OptionalWidget &&
1484 widget.widget instanceof OO.ui.TagMultiselectWidget
1485 )
1486 ) {
1487 tmp.push( mw.message( 'api-help-param-multi-separate' ).parse() );
1488 }
1489 if ( count > ppi.lowlimit ) {
1490 tmp.push(
1491 mw.message( 'api-help-param-multi-max', ppi.lowlimit, ppi.highlimit ).parse()
1492 );
1493 }
1494 if ( tmp.length ) {
1495 descriptionContainer.append( $( '<div>' )
1496 .addClass( 'info' )
1497 .append( Util.parseHTML( tmp.join( ' ' ) ) )
1498 );
1499 }
1500 }
1501 if ( 'maxbytes' in ppi ) {
1502 descriptionContainer.append( $( '<div>' )
1503 .addClass( 'info' )
1504 .append( Util.parseMsg( 'api-help-param-maxbytes', ppi.maxbytes ) )
1505 );
1506 }
1507 if ( 'maxchars' in ppi ) {
1508 descriptionContainer.append( $( '<div>' )
1509 .addClass( 'info' )
1510 .append( Util.parseMsg( 'api-help-param-maxchars', ppi.maxchars ) )
1511 );
1512 }
1513 if ( ppi.usedTemplateVars && ppi.usedTemplateVars.length ) {
1514 tmp = $();
1515 for ( j = 0, l = ppi.usedTemplateVars.length; j < l; j++ ) {
1516 tmp = tmp.add( $( '<var>' ).text( ppi.usedTemplateVars[ j ] ) );
1517 if ( j === l - 2 ) {
1518 tmp = tmp.add( mw.message( 'and' ).parseDom() );
1519 tmp = tmp.add( mw.message( 'word-separator' ).parseDom() );
1520 } else if ( j !== l - 1 ) {
1521 tmp = tmp.add( mw.message( 'comma-separator' ).parseDom() );
1522 }
1523 }
1524 descriptionContainer.append( $( '<div>' )
1525 .addClass( 'info' )
1526 .append( Util.parseMsg(
1527 'apisandbox-templated-parameter-reason',
1528 ppi.usedTemplateVars.length,
1529 tmp
1530 ) )
1531 );
1532 }
1533
1534 helpField = new OO.ui.FieldLayout(
1535 new OO.ui.Widget( {
1536 $content: '\xa0',
1537 classes: [ 'mw-apisandbox-spacer' ]
1538 } ), {
1539 align: 'inline',
1540 classes: [ 'mw-apisandbox-help-field' ],
1541 label: descriptionContainer
1542 }
1543 );
1544
1545 layoutConfig = {
1546 align: 'left',
1547 classes: [ 'mw-apisandbox-widget-field' ],
1548 label: name
1549 };
1550
1551 if ( ppi.tokentype ) {
1552 button = new OO.ui.ButtonWidget( {
1553 label: mw.message( 'apisandbox-fetch-token' ).text()
1554 } );
1555 button.on( 'click', widget.fetchToken, [], widget );
1556
1557 widgetField = new OO.ui.ActionFieldLayout( widget, button, layoutConfig );
1558 } else {
1559 widgetField = new OO.ui.FieldLayout( widget, layoutConfig );
1560 }
1561
1562 // We need our own click handler on the widget label to
1563 // turn off the disablement.
1564 widgetField.$label.on( 'click', widgetLabelOnClick.bind( widgetField ) );
1565
1566 // Don't grey out the label when the field is disabled,
1567 // it makes it too hard to read and our "disabled"
1568 // isn't really disabled.
1569 widgetField.onFieldDisable( false );
1570 widgetField.onFieldDisable = function () {};
1571
1572 widgetField.apiParamIndex = ppi.index;
1573
1574 return {
1575 widget: widget,
1576 widgetField: widgetField,
1577 helpField: helpField
1578 };
1579 };
1580
1581 /**
1582 * Update templated parameters in the page
1583 * @private
1584 * @param {Object} [params] Query parameters for initializing the widgets
1585 */
1586 ApiSandbox.PageLayout.prototype.updateTemplatedParameters = function ( params ) {
1587 var p, toProcess, doProcess, tmp, toRemove,
1588 that = this,
1589 pi = this.paramInfo,
1590 prefix = that.prefix + pi.prefix;
1591
1592 if ( !pi || !pi.templatedparameters.length ) {
1593 return;
1594 }
1595
1596 if ( !$.isPlainObject( params ) ) {
1597 params = null;
1598 }
1599
1600 toRemove = {};
1601 // eslint-disable-next-line no-jquery/no-each-util
1602 $.each( this.templatedItemsCache, function ( k, el ) {
1603 if ( el.widget.isElementAttached() ) {
1604 toRemove[ k ] = el;
1605 }
1606 } );
1607
1608 // This bit duplicates the PHP logic in ApiBase::extractRequestParams().
1609 // If you update this, see if that needs updating too.
1610 toProcess = pi.templatedparameters.map( function ( p ) {
1611 return {
1612 name: prefix + p.name,
1613 info: p,
1614 vars: $.extend( {}, p.templatevars ),
1615 usedVars: []
1616 };
1617 } );
1618 doProcess = function ( placeholder, target ) {
1619 var values, container, index, usedVars, done, items, i;
1620
1621 target = prefix + target;
1622
1623 if ( !that.widgets[ target ] ) {
1624 // The target wasn't processed yet, try the next one.
1625 // If all hit this case, the parameter has no expansions.
1626 return true;
1627 }
1628
1629 if ( !that.widgets[ target ].getApiValueForTemplates ) {
1630 // Not a multi-valued widget, so it can't have expansions.
1631 return false;
1632 }
1633
1634 values = that.widgets[ target ].getApiValueForTemplates();
1635 if ( !Array.isArray( values ) || !values.length ) {
1636 // The target was processed but has no (valid) values.
1637 // That means it has no expansions.
1638 return false;
1639 }
1640
1641 // Expand this target in the name and all other targets,
1642 // then requeue if there are more targets left or create the widget
1643 // and add it to the form if all are done.
1644 delete p.vars[ placeholder ];
1645 usedVars = p.usedVars.concat( [ target ] );
1646 placeholder = '{' + placeholder + '}';
1647 done = $.isEmptyObject( p.vars );
1648 if ( done ) {
1649 container = Util.apiBool( p.info.deprecated ) ? that.deprecatedItemsFieldset : that.itemsFieldset;
1650 items = container.getItems();
1651 index = undefined;
1652 for ( i = 0; i < items.length; i++ ) {
1653 if ( items[ i ].apiParamIndex !== undefined && items[ i ].apiParamIndex > p.info.index ) {
1654 index = i;
1655 break;
1656 }
1657 }
1658 }
1659 values.forEach( function ( value ) {
1660 var name, newVars;
1661
1662 if ( !/^[^{}]*$/.exec( value ) ) {
1663 // Skip values that make invalid parameter names
1664 return;
1665 }
1666
1667 name = p.name.replace( placeholder, value );
1668 if ( done ) {
1669 if ( that.templatedItemsCache[ name ] ) {
1670 tmp = that.templatedItemsCache[ name ];
1671 } else {
1672 tmp = that.makeWidgetFieldLayouts(
1673 $.extend( {}, p.info, { usedTemplateVars: usedVars } ), name
1674 );
1675 that.templatedItemsCache[ name ] = tmp;
1676 }
1677 delete toRemove[ name ];
1678 if ( !tmp.widget.isElementAttached() ) {
1679 that.widgets[ name ] = tmp.widget;
1680 container.addItems( [ tmp.widgetField, tmp.helpField ], index );
1681 if ( index !== undefined ) {
1682 index += 2;
1683 }
1684 }
1685 if ( params ) {
1686 tmp.widget.setApiValue( Object.prototype.hasOwnProperty.call( params, name ) ? params[ name ] : undefined );
1687 }
1688 } else {
1689 newVars = {};
1690 // eslint-disable-next-line no-jquery/no-each-util
1691 $.each( p.vars, function ( k, v ) {
1692 newVars[ k ] = v.replace( placeholder, value );
1693 } );
1694 toProcess.push( {
1695 name: name,
1696 info: p.info,
1697 vars: newVars,
1698 usedVars: usedVars
1699 } );
1700 }
1701 } );
1702 return false;
1703 };
1704 while ( toProcess.length ) {
1705 p = toProcess.shift();
1706 // eslint-disable-next-line no-jquery/no-each-util
1707 $.each( p.vars, doProcess );
1708 }
1709
1710 // eslint-disable-next-line no-jquery/no-map-util
1711 toRemove = $.map( toRemove, function ( el, name ) {
1712 delete that.widgets[ name ];
1713 return [ el.widgetField, el.helpField ];
1714 } );
1715 if ( toRemove.length ) {
1716 this.itemsFieldset.removeItems( toRemove );
1717 this.deprecatedItemsFieldset.removeItems( toRemove );
1718 }
1719 };
1720
1721 /**
1722 * Fetch module information for this page's module, then create UI
1723 */
1724 ApiSandbox.PageLayout.prototype.loadParamInfo = function () {
1725 var dynamicFieldset, dynamicParamNameWidget,
1726 that = this,
1727 removeDynamicParamWidget = function ( name, layout ) {
1728 dynamicFieldset.removeItems( [ layout ] );
1729 delete that.widgets[ name ];
1730 },
1731 addDynamicParamWidget = function () {
1732 var name, layout, widget, button;
1733
1734 // Check name is filled in
1735 name = dynamicParamNameWidget.getValue().trim();
1736 if ( name === '' ) {
1737 dynamicParamNameWidget.focus();
1738 return;
1739 }
1740
1741 if ( that.widgets[ name ] !== undefined ) {
1742 windowManager.openWindow( 'errorAlert', {
1743 title: Util.parseMsg( 'apisandbox-dynamic-error-exists', name ),
1744 actions: [
1745 {
1746 action: 'accept',
1747 label: OO.ui.msg( 'ooui-dialog-process-dismiss' ),
1748 flags: 'primary'
1749 }
1750 ]
1751 } );
1752 return;
1753 }
1754
1755 widget = Util.createWidgetForParameter( {
1756 name: name,
1757 type: 'string',
1758 default: ''
1759 }, {
1760 nooptional: true
1761 } );
1762 button = new OO.ui.ButtonWidget( {
1763 icon: 'trash',
1764 flags: 'destructive'
1765 } );
1766 layout = new OO.ui.ActionFieldLayout(
1767 widget,
1768 button,
1769 {
1770 label: name,
1771 align: 'left'
1772 }
1773 );
1774 button.on( 'click', removeDynamicParamWidget, [ name, layout ] );
1775 that.widgets[ name ] = widget;
1776 dynamicFieldset.addItems( [ layout ], dynamicFieldset.getItems().length - 1 );
1777 widget.focus();
1778
1779 dynamicParamNameWidget.setValue( '' );
1780 };
1781
1782 this.$element.empty()
1783 .append(
1784 document.createTextNode(
1785 mw.message( 'apisandbox-loading', this.displayText ).text()
1786 ),
1787 new OO.ui.ProgressBarWidget( { progress: false } ).$element
1788 );
1789
1790 Util.fetchModuleInfo( this.apiModule )
1791 .done( function ( pi ) {
1792 var prefix, i, j, tmp,
1793 items = [],
1794 deprecatedItems = [],
1795 buttons = [],
1796 filterFmModules = function ( v ) {
1797 return v.substr( -2 ) !== 'fm' ||
1798 !Object.prototype.hasOwnProperty.call( availableFormats, v.substr( 0, v.length - 2 ) );
1799 };
1800
1801 // This is something of a hack. We always want the 'format' and
1802 // 'action' parameters from the main module to be specified,
1803 // and for 'format' we also want to simplify the dropdown since
1804 // we always send the 'fm' variant.
1805 if ( that.apiModule === 'main' ) {
1806 for ( i = 0; i < pi.parameters.length; i++ ) {
1807 if ( pi.parameters[ i ].name === 'action' ) {
1808 pi.parameters[ i ].required = true;
1809 delete pi.parameters[ i ].default;
1810 }
1811 if ( pi.parameters[ i ].name === 'format' ) {
1812 tmp = pi.parameters[ i ].type;
1813 for ( j = 0; j < tmp.length; j++ ) {
1814 availableFormats[ tmp[ j ] ] = true;
1815 }
1816 pi.parameters[ i ].type = tmp.filter( filterFmModules );
1817 pi.parameters[ i ].default = 'json';
1818 pi.parameters[ i ].required = true;
1819 }
1820 }
1821 }
1822
1823 // Hide the 'wrappedhtml' parameter on format modules
1824 if ( pi.group === 'format' ) {
1825 pi.parameters = pi.parameters.filter( function ( p ) {
1826 return p.name !== 'wrappedhtml';
1827 } );
1828 }
1829
1830 that.paramInfo = pi;
1831
1832 items.push( new OO.ui.FieldLayout(
1833 new OO.ui.Widget( {} ).toggle( false ), {
1834 align: 'top',
1835 label: Util.parseHTML( pi.description )
1836 }
1837 ) );
1838
1839 if ( pi.helpurls.length ) {
1840 buttons.push( new OO.ui.PopupButtonWidget( {
1841 $overlay: true,
1842 label: mw.message( 'apisandbox-helpurls' ).text(),
1843 icon: 'help',
1844 popup: {
1845 width: 'auto',
1846 padded: true,
1847 $content: $( '<ul>' ).append( pi.helpurls.map( function ( link ) {
1848 return $( '<li>' ).append( $( '<a>' )
1849 .attr( { href: link, target: '_blank' } )
1850 .text( link )
1851 );
1852 } ) )
1853 }
1854 } ) );
1855 }
1856
1857 if ( pi.examples.length ) {
1858 buttons.push( new OO.ui.PopupButtonWidget( {
1859 $overlay: true,
1860 label: mw.message( 'apisandbox-examples' ).text(),
1861 icon: 'code',
1862 popup: {
1863 width: 'auto',
1864 padded: true,
1865 $content: $( '<ul>' ).append( pi.examples.map( function ( example ) {
1866 var a = $( '<a>' )
1867 .attr( 'href', '#' + example.query )
1868 .html( example.description );
1869 a.find( 'a' ).contents().unwrap(); // Can't nest links
1870 return $( '<li>' ).append( a );
1871 } ) )
1872 }
1873 } ) );
1874 }
1875
1876 if ( buttons.length ) {
1877 items.push( new OO.ui.FieldLayout(
1878 new OO.ui.ButtonGroupWidget( {
1879 items: buttons
1880 } ), { align: 'top' }
1881 ) );
1882 }
1883
1884 if ( pi.parameters.length ) {
1885 prefix = that.prefix + pi.prefix;
1886 for ( i = 0; i < pi.parameters.length; i++ ) {
1887 tmp = that.makeWidgetFieldLayouts( pi.parameters[ i ], prefix + pi.parameters[ i ].name );
1888 that.widgets[ prefix + pi.parameters[ i ].name ] = tmp.widget;
1889 if ( Util.apiBool( pi.parameters[ i ].deprecated ) ) {
1890 deprecatedItems.push( tmp.widgetField, tmp.helpField );
1891 } else {
1892 items.push( tmp.widgetField, tmp.helpField );
1893 }
1894 }
1895 }
1896
1897 if ( !pi.parameters.length && !Util.apiBool( pi.dynamicparameters ) ) {
1898 items.push( new OO.ui.FieldLayout(
1899 new OO.ui.Widget( {} ).toggle( false ), {
1900 align: 'top',
1901 label: Util.parseMsg( 'apisandbox-no-parameters' )
1902 }
1903 ) );
1904 }
1905
1906 that.$element.empty();
1907
1908 that.itemsFieldset = new OO.ui.FieldsetLayout( {
1909 label: that.displayText
1910 } );
1911 that.itemsFieldset.addItems( items );
1912 that.itemsFieldset.$element.appendTo( that.$element );
1913
1914 if ( Util.apiBool( pi.dynamicparameters ) ) {
1915 dynamicFieldset = new OO.ui.FieldsetLayout();
1916 dynamicParamNameWidget = new OO.ui.TextInputWidget( {
1917 placeholder: mw.message( 'apisandbox-dynamic-parameters-add-placeholder' ).text()
1918 } ).on( 'enter', addDynamicParamWidget );
1919 dynamicFieldset.addItems( [
1920 new OO.ui.FieldLayout(
1921 new OO.ui.Widget( {} ).toggle( false ), {
1922 align: 'top',
1923 label: Util.parseHTML( pi.dynamicparameters )
1924 }
1925 ),
1926 new OO.ui.ActionFieldLayout(
1927 dynamicParamNameWidget,
1928 new OO.ui.ButtonWidget( {
1929 icon: 'add',
1930 flags: 'progressive'
1931 } ).on( 'click', addDynamicParamWidget ),
1932 {
1933 label: mw.message( 'apisandbox-dynamic-parameters-add-label' ).text(),
1934 align: 'left'
1935 }
1936 )
1937 ] );
1938 $( '<fieldset>' )
1939 .append(
1940 $( '<legend>' ).text( mw.message( 'apisandbox-dynamic-parameters' ).text() ),
1941 dynamicFieldset.$element
1942 )
1943 .appendTo( that.$element );
1944 }
1945
1946 that.deprecatedItemsFieldset = new OO.ui.FieldsetLayout().addItems( deprecatedItems ).toggle( false );
1947 tmp = $( '<fieldset>' )
1948 .toggle( !that.deprecatedItemsFieldset.isEmpty() )
1949 .append(
1950 $( '<legend>' ).append(
1951 new OO.ui.ToggleButtonWidget( {
1952 label: mw.message( 'apisandbox-deprecated-parameters' ).text()
1953 } ).on( 'change', that.deprecatedItemsFieldset.toggle, [], that.deprecatedItemsFieldset ).$element
1954 ),
1955 that.deprecatedItemsFieldset.$element
1956 )
1957 .appendTo( that.$element );
1958 that.deprecatedItemsFieldset.on( 'add', function () {
1959 this.toggle( !that.deprecatedItemsFieldset.isEmpty() );
1960 }, [], tmp );
1961 that.deprecatedItemsFieldset.on( 'remove', function () {
1962 this.toggle( !that.deprecatedItemsFieldset.isEmpty() );
1963 }, [], tmp );
1964
1965 // Load stored params, if any, then update the booklet if we
1966 // have subpages (or else just update our valid-indicator).
1967 tmp = that.loadFromQueryParams;
1968 that.loadFromQueryParams = null;
1969 if ( $.isPlainObject( tmp ) ) {
1970 that.loadQueryParams( tmp );
1971 } else {
1972 that.updateTemplatedParameters();
1973 }
1974 if ( that.getSubpages().length > 0 ) {
1975 ApiSandbox.updateUI( tmp );
1976 } else {
1977 that.apiCheckValid();
1978 }
1979 } ).fail( function ( code, detail ) {
1980 that.$element.empty()
1981 .append(
1982 new OO.ui.LabelWidget( {
1983 label: mw.message( 'apisandbox-load-error', that.apiModule, detail ).text(),
1984 classes: [ 'error' ]
1985 } ).$element,
1986 new OO.ui.ButtonWidget( {
1987 label: mw.message( 'apisandbox-retry' ).text()
1988 } ).on( 'click', that.loadParamInfo, [], that ).$element
1989 );
1990 } );
1991 };
1992
1993 /**
1994 * Check that all widgets on the page are in a valid state.
1995 *
1996 * @return {jQuery.Promise[]} One promise for each widget, resolved with `false` if invalid
1997 */
1998 ApiSandbox.PageLayout.prototype.apiCheckValid = function () {
1999 var promises, that = this;
2000
2001 if ( this.paramInfo === null ) {
2002 return [];
2003 } else {
2004 // eslint-disable-next-line no-jquery/no-map-util
2005 promises = $.map( this.widgets, function ( widget ) {
2006 return widget.apiCheckValid();
2007 } );
2008 $.when.apply( $, promises ).then( function () {
2009 that.apiIsValid = Array.prototype.indexOf.call( arguments, false ) === -1;
2010 if ( that.getOutlineItem() ) {
2011 that.getOutlineItem().setIcon( that.apiIsValid || suppressErrors ? null : 'alert' );
2012 that.getOutlineItem().setTitle(
2013 that.apiIsValid || suppressErrors ? '' : mw.message( 'apisandbox-alert-page' ).plain()
2014 );
2015 }
2016 } );
2017 return promises;
2018 }
2019 };
2020
2021 /**
2022 * Load form fields from query parameters
2023 *
2024 * @param {Object} params
2025 */
2026 ApiSandbox.PageLayout.prototype.loadQueryParams = function ( params ) {
2027 if ( this.paramInfo === null ) {
2028 this.loadFromQueryParams = params;
2029 } else {
2030 // eslint-disable-next-line no-jquery/no-each-util
2031 $.each( this.widgets, function ( name, widget ) {
2032 var v = Object.prototype.hasOwnProperty.call( params, name ) ? params[ name ] : undefined;
2033 widget.setApiValue( v );
2034 } );
2035 this.updateTemplatedParameters( params );
2036 }
2037 };
2038
2039 /**
2040 * Load query params from form fields
2041 *
2042 * @param {Object} params Write query parameters into this object
2043 * @param {Object} displayParams Write query parameters for display into this object
2044 */
2045 ApiSandbox.PageLayout.prototype.getQueryParams = function ( params, displayParams ) {
2046 // eslint-disable-next-line no-jquery/no-each-util
2047 $.each( this.widgets, function ( name, widget ) {
2048 var value = widget.getApiValue();
2049 if ( value !== undefined ) {
2050 params[ name ] = value;
2051 if ( typeof widget.getApiValueForDisplay === 'function' ) {
2052 value = widget.getApiValueForDisplay();
2053 }
2054 displayParams[ name ] = value;
2055 }
2056 } );
2057 };
2058
2059 /**
2060 * Fetch a list of subpage names loaded by this page
2061 *
2062 * @return {Array}
2063 */
2064 ApiSandbox.PageLayout.prototype.getSubpages = function () {
2065 var ret = [];
2066 // eslint-disable-next-line no-jquery/no-each-util
2067 $.each( this.widgets, function ( name, widget ) {
2068 var submodules, i;
2069 if ( typeof widget.getSubmodules === 'function' ) {
2070 submodules = widget.getSubmodules();
2071 for ( i = 0; i < submodules.length; i++ ) {
2072 ret.push( {
2073 key: name + '=' + submodules[ i ].value,
2074 path: submodules[ i ].path,
2075 prefix: widget.paramInfo.submoduleparamprefix || ''
2076 } );
2077 }
2078 }
2079 } );
2080 return ret;
2081 };
2082
2083 $( ApiSandbox.init );
2084
2085 module.exports = ApiSandbox;
2086
2087 }() );