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