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