Pull rendering of single result out of SpecialSearch
[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 if ( $.inArray( false, arguments ) !== -1 ) {
920 windowManager.openWindow( 'errorAlert', {
921 title: Util.parseMsg( 'apisandbox-submit-invalid-fields-title' ),
922 message: Util.parseMsg( 'apisandbox-submit-invalid-fields-message' ),
923 actions: [
924 {
925 action: 'accept',
926 label: OO.ui.msg( 'ooui-dialog-process-dismiss' ),
927 flags: 'primary'
928 }
929 ]
930 } );
931 return;
932 }
933
934 query = $.param( displayParams );
935
936 // Force a 'fm' format with wrappedhtml=1, if available
937 if ( params.format !== undefined ) {
938 if ( availableFormats.hasOwnProperty( params.format + 'fm' ) ) {
939 params.format = params.format + 'fm';
940 }
941 if ( params.format.substr( -2 ) === 'fm' ) {
942 params.wrappedhtml = 1;
943 }
944 }
945
946 progressLoading = false;
947 $progressText = $( '<span>' ).text( mw.message( 'apisandbox-sending-request' ).text() );
948 progress = new OO.ui.ProgressBarWidget( {
949 progress: false,
950 $content: $progressText
951 } );
952
953 $result = $( '<div>' )
954 .append( progress.$element );
955
956 resultPage = page = new OO.ui.PageLayout( '|results|' );
957 page.setupOutlineItem = function () {
958 this.outlineItem.setLabel( mw.message( 'apisandbox-results' ).text() );
959 };
960 page.$element.empty()
961 .append(
962 new OO.ui.FieldLayout(
963 new OO.ui.TextInputWidget( {
964 readOnly: true,
965 value: mw.util.wikiScript( 'api' ) + '?' + query
966 } ), {
967 label: Util.parseMsg( 'apisandbox-request-url-label' )
968 }
969 ).$element,
970 $result
971 );
972 ApiSandbox.updateUI();
973 booklet.setPage( '|results|' );
974
975 location.href = oldhash = '#' + query;
976
977 api.post( params, {
978 contentType: 'multipart/form-data',
979 dataType: 'text',
980 xhr: function () {
981 var xhr = new window.XMLHttpRequest();
982 xhr.upload.addEventListener( 'progress', function ( e ) {
983 if ( !progressLoading ) {
984 if ( e.lengthComputable ) {
985 progress.setProgress( e.loaded * 100 / e.total );
986 } else {
987 progress.setProgress( false );
988 }
989 }
990 } );
991 xhr.addEventListener( 'progress', function ( e ) {
992 if ( !progressLoading ) {
993 progressLoading = true;
994 $progressText.text( mw.message( 'apisandbox-loading-results' ).text() );
995 }
996 if ( e.lengthComputable ) {
997 progress.setProgress( e.loaded * 100 / e.total );
998 } else {
999 progress.setProgress( false );
1000 }
1001 } );
1002 return xhr;
1003 }
1004 } )
1005 .then( null, function ( code, data, result, jqXHR ) {
1006 if ( code !== 'http' ) {
1007 // Not really an error, work around mw.Api thinking it is.
1008 return $.Deferred()
1009 .resolve( result, jqXHR )
1010 .promise();
1011 }
1012 return this;
1013 } )
1014 .fail( function ( code, data ) {
1015 var details = 'HTTP error: ' + data.exception;
1016 $result.empty()
1017 .append(
1018 new OO.ui.LabelWidget( {
1019 label: mw.message( 'apisandbox-results-error', details ).text(),
1020 classes: [ 'error' ]
1021 } ).$element
1022 );
1023 } )
1024 .done( function ( data, jqXHR ) {
1025 var m, loadTime, button, clear,
1026 ct = jqXHR.getResponseHeader( 'Content-Type' );
1027
1028 $result.empty();
1029 if ( /^text\/mediawiki-api-prettyprint-wrapped(?:;|$)/.test( ct ) ) {
1030 data = JSON.parse( data );
1031 if ( data.modules.length ) {
1032 mw.loader.load( data.modules );
1033 }
1034 if ( data.status && data.status !== 200 ) {
1035 $( '<div>' )
1036 .addClass( 'api-pretty-header api-pretty-status' )
1037 .append( Util.parseMsg( 'api-format-prettyprint-status', data.status, data.statustext ) )
1038 .appendTo( $result );
1039 }
1040 $result.append( Util.parseHTML( data.html ) );
1041 loadTime = data.time;
1042 } else if ( ( m = data.match( /<pre[ >][\s\S]*<\/pre>/ ) ) ) {
1043 $result.append( Util.parseHTML( m[ 0 ] ) );
1044 if ( ( m = data.match( /"wgBackendResponseTime":\s*(\d+)/ ) ) ) {
1045 loadTime = parseInt( m[ 1 ], 10 );
1046 }
1047 } else {
1048 $( '<pre>' )
1049 .addClass( 'api-pretty-content' )
1050 .text( data )
1051 .appendTo( $result );
1052 }
1053 if ( paramsAreForced || data[ 'continue' ] ) {
1054 $result.append(
1055 $( '<div>' ).append(
1056 new OO.ui.ButtonWidget( {
1057 label: mw.message( 'apisandbox-continue' ).text()
1058 } ).on( 'click', function () {
1059 ApiSandbox.sendRequest( $.extend( {}, baseRequestParams, data[ 'continue' ] ) );
1060 } ).setDisabled( !data[ 'continue' ] ).$element,
1061 ( clear = new OO.ui.ButtonWidget( {
1062 label: mw.message( 'apisandbox-continue-clear' ).text()
1063 } ).on( 'click', function () {
1064 ApiSandbox.updateUI( baseRequestParams );
1065 clear.setDisabled( true );
1066 booklet.setPage( '|results|' );
1067 } ).setDisabled( !paramsAreForced ) ).$element,
1068 new OO.ui.PopupButtonWidget( {
1069 framed: false,
1070 icon: 'info',
1071 popup: {
1072 $content: $( '<div>' ).append( Util.parseMsg( 'apisandbox-continue-help' ) ),
1073 padded: true
1074 }
1075 } ).$element
1076 )
1077 );
1078 }
1079 if ( typeof loadTime === 'number' ) {
1080 $result.append(
1081 $( '<div>' ).append(
1082 new OO.ui.LabelWidget( {
1083 label: mw.message( 'apisandbox-request-time', loadTime ).text()
1084 } ).$element
1085 )
1086 );
1087 }
1088
1089 if ( jqXHR.getResponseHeader( 'MediaWiki-API-Error' ) === 'badtoken' ) {
1090 // Flush all saved tokens in case one of them is the bad one.
1091 Util.markTokensBad();
1092 button = new OO.ui.ButtonWidget( {
1093 label: mw.message( 'apisandbox-results-fixtoken' ).text()
1094 } );
1095 button.on( 'click', ApiSandbox.fixTokenAndResend )
1096 .on( 'click', button.setDisabled, [ true ], button )
1097 .$element.appendTo( $result );
1098 }
1099 } );
1100 } );
1101 },
1102
1103 /**
1104 * Handler for the "Correct token and resubmit" button
1105 *
1106 * Used on a 'badtoken' error, it re-fetches token parameters for all
1107 * pages and then re-submits the query.
1108 */
1109 fixTokenAndResend: function () {
1110 var page, subpages, i, k,
1111 ok = true,
1112 tokenWait = { dummy: true },
1113 checkPages = [ pages.main ],
1114 success = function ( k ) {
1115 delete tokenWait[ k ];
1116 if ( ok && $.isEmptyObject( tokenWait ) ) {
1117 ApiSandbox.sendRequest();
1118 }
1119 },
1120 failure = function ( k ) {
1121 delete tokenWait[ k ];
1122 ok = false;
1123 };
1124
1125 while ( checkPages.length ) {
1126 page = checkPages.shift();
1127
1128 if ( page.tokenWidget ) {
1129 k = page.apiModule + page.tokenWidget.paramInfo.name;
1130 tokenWait[ k ] = page.tokenWidget.fetchToken()
1131 .done( success.bind( page.tokenWidget, k ) )
1132 .fail( failure.bind( page.tokenWidget, k ) );
1133 }
1134
1135 subpages = page.getSubpages();
1136 for ( i = 0; i < subpages.length; i++ ) {
1137 if ( pages.hasOwnProperty( subpages[ i ].key ) ) {
1138 checkPages.push( pages[ subpages[ i ].key ] );
1139 }
1140 }
1141 }
1142
1143 success( 'dummy', '' );
1144 },
1145
1146 /**
1147 * Reset validity indicators for all widgets
1148 */
1149 updateValidityIndicators: function () {
1150 var page, subpages, i,
1151 checkPages = [ pages.main ];
1152
1153 while ( checkPages.length ) {
1154 page = checkPages.shift();
1155 page.apiCheckValid();
1156 subpages = page.getSubpages();
1157 for ( i = 0; i < subpages.length; i++ ) {
1158 if ( pages.hasOwnProperty( subpages[ i ].key ) ) {
1159 checkPages.push( pages[ subpages[ i ].key ] );
1160 }
1161 }
1162 }
1163 }
1164 };
1165
1166 /**
1167 * PageLayout for API modules
1168 *
1169 * @class
1170 * @private
1171 * @extends OO.ui.PageLayout
1172 * @constructor
1173 * @param {Object} [config] Configuration options
1174 */
1175 ApiSandbox.PageLayout = function ( config ) {
1176 config = $.extend( { prefix: '' }, config );
1177 this.displayText = config.key;
1178 this.apiModule = config.path;
1179 this.prefix = config.prefix;
1180 this.paramInfo = null;
1181 this.apiIsValid = true;
1182 this.loadFromQueryParams = null;
1183 this.widgets = {};
1184 this.tokenWidget = null;
1185 this.indentLevel = config.indentLevel ? config.indentLevel : 0;
1186 ApiSandbox.PageLayout[ 'super' ].call( this, config.key, config );
1187 this.loadParamInfo();
1188 };
1189 OO.inheritClass( ApiSandbox.PageLayout, OO.ui.PageLayout );
1190 ApiSandbox.PageLayout.prototype.setupOutlineItem = function () {
1191 this.outlineItem.setLevel( this.indentLevel );
1192 this.outlineItem.setLabel( this.displayText );
1193 this.outlineItem.setIcon( this.apiIsValid || suppressErrors ? null : 'alert' );
1194 this.outlineItem.setIconTitle(
1195 this.apiIsValid || suppressErrors ? '' : mw.message( 'apisandbox-alert-page' ).plain()
1196 );
1197 };
1198
1199 /**
1200 * Fetch module information for this page's module, then create UI
1201 */
1202 ApiSandbox.PageLayout.prototype.loadParamInfo = function () {
1203 var dynamicFieldset, dynamicParamNameWidget,
1204 that = this,
1205 removeDynamicParamWidget = function ( name, layout ) {
1206 dynamicFieldset.removeItems( [ layout ] );
1207 delete that.widgets[ name ];
1208 },
1209 addDynamicParamWidget = function () {
1210 var name, layout, widget, button;
1211
1212 // Check name is filled in
1213 name = dynamicParamNameWidget.getValue().trim();
1214 if ( name === '' ) {
1215 dynamicParamNameWidget.focus();
1216 return;
1217 }
1218
1219 if ( that.widgets[ name ] !== undefined ) {
1220 windowManager.openWindow( 'errorAlert', {
1221 title: Util.parseMsg( 'apisandbox-dynamic-error-exists', name ),
1222 actions: [
1223 {
1224 action: 'accept',
1225 label: OO.ui.msg( 'ooui-dialog-process-dismiss' ),
1226 flags: 'primary'
1227 }
1228 ]
1229 } );
1230 return;
1231 }
1232
1233 widget = Util.createWidgetForParameter( {
1234 name: name,
1235 type: 'string',
1236 'default': ''
1237 }, {
1238 nooptional: true
1239 } );
1240 button = new OO.ui.ButtonWidget( {
1241 icon: 'remove',
1242 flags: 'destructive'
1243 } );
1244 layout = new OO.ui.ActionFieldLayout(
1245 widget,
1246 button,
1247 {
1248 label: name,
1249 align: 'left'
1250 }
1251 );
1252 button.on( 'click', removeDynamicParamWidget, [ name, layout ] );
1253 that.widgets[ name ] = widget;
1254 dynamicFieldset.addItems( [ layout ], dynamicFieldset.getItems().length - 1 );
1255 widget.focus();
1256
1257 dynamicParamNameWidget.setValue( '' );
1258 };
1259
1260 this.$element.empty()
1261 .append( new OO.ui.ProgressBarWidget( {
1262 progress: false,
1263 text: mw.message( 'apisandbox-loading', this.displayText ).text()
1264 } ).$element );
1265
1266 Util.fetchModuleInfo( this.apiModule )
1267 .done( function ( pi ) {
1268 var prefix, i, j, dl, widget, $widgetLabel, widgetField, helpField, tmp, flag, count,
1269 items = [],
1270 deprecatedItems = [],
1271 buttons = [],
1272 filterFmModules = function ( v ) {
1273 return v.substr( -2 ) !== 'fm' ||
1274 !availableFormats.hasOwnProperty( v.substr( 0, v.length - 2 ) );
1275 },
1276 widgetLabelOnClick = function () {
1277 var f = this.getField();
1278 if ( $.isFunction( f.setDisabled ) ) {
1279 f.setDisabled( false );
1280 }
1281 if ( $.isFunction( f.focus ) ) {
1282 f.focus();
1283 }
1284 },
1285 doNothing = function () {};
1286
1287 // This is something of a hack. We always want the 'format' and
1288 // 'action' parameters from the main module to be specified,
1289 // and for 'format' we also want to simplify the dropdown since
1290 // we always send the 'fm' variant.
1291 if ( that.apiModule === 'main' ) {
1292 for ( i = 0; i < pi.parameters.length; i++ ) {
1293 if ( pi.parameters[ i ].name === 'action' ) {
1294 pi.parameters[ i ].required = true;
1295 delete pi.parameters[ i ][ 'default' ];
1296 }
1297 if ( pi.parameters[ i ].name === 'format' ) {
1298 tmp = pi.parameters[ i ].type;
1299 for ( j = 0; j < tmp.length; j++ ) {
1300 availableFormats[ tmp[ j ] ] = true;
1301 }
1302 pi.parameters[ i ].type = $.grep( tmp, filterFmModules );
1303 pi.parameters[ i ][ 'default' ] = 'json';
1304 pi.parameters[ i ].required = true;
1305 }
1306 }
1307 }
1308
1309 // Hide the 'wrappedhtml' parameter on format modules
1310 if ( pi.group === 'format' ) {
1311 pi.parameters = $.grep( pi.parameters, function ( p ) {
1312 return p.name !== 'wrappedhtml';
1313 } );
1314 }
1315
1316 that.paramInfo = pi;
1317
1318 items.push( new OO.ui.FieldLayout(
1319 new OO.ui.Widget( {} ).toggle( false ), {
1320 align: 'top',
1321 label: Util.parseHTML( pi.description )
1322 }
1323 ) );
1324
1325 if ( pi.helpurls.length ) {
1326 buttons.push( new OO.ui.PopupButtonWidget( {
1327 label: mw.message( 'apisandbox-helpurls' ).text(),
1328 icon: 'help',
1329 popup: {
1330 $content: $( '<ul>' ).append( $.map( pi.helpurls, function ( link ) {
1331 return $( '<li>' ).append( $( '<a>', {
1332 href: link,
1333 target: '_blank',
1334 text: link
1335 } ) );
1336 } ) )
1337 }
1338 } ) );
1339 }
1340
1341 if ( pi.examples.length ) {
1342 buttons.push( new OO.ui.PopupButtonWidget( {
1343 label: mw.message( 'apisandbox-examples' ).text(),
1344 icon: 'code',
1345 popup: {
1346 $content: $( '<ul>' ).append( $.map( pi.examples, function ( example ) {
1347 var a = $( '<a>', {
1348 href: '#' + example.query,
1349 html: example.description
1350 } );
1351 a.find( 'a' ).contents().unwrap(); // Can't nest links
1352 return $( '<li>' ).append( a );
1353 } ) )
1354 }
1355 } ) );
1356 }
1357
1358 if ( buttons.length ) {
1359 items.push( new OO.ui.FieldLayout(
1360 new OO.ui.ButtonGroupWidget( {
1361 items: buttons
1362 } ), { align: 'top' }
1363 ) );
1364 }
1365
1366 if ( pi.parameters.length ) {
1367 prefix = that.prefix + pi.prefix;
1368 for ( i = 0; i < pi.parameters.length; i++ ) {
1369 widget = Util.createWidgetForParameter( pi.parameters[ i ] );
1370 that.widgets[ prefix + pi.parameters[ i ].name ] = widget;
1371 if ( pi.parameters[ i ].tokentype ) {
1372 that.tokenWidget = widget;
1373 }
1374
1375 dl = $( '<dl>' );
1376 dl.append( $( '<dd>', {
1377 addClass: 'description',
1378 append: Util.parseHTML( pi.parameters[ i ].description )
1379 } ) );
1380 if ( pi.parameters[ i ].info && pi.parameters[ i ].info.length ) {
1381 for ( j = 0; j < pi.parameters[ i ].info.length; j++ ) {
1382 dl.append( $( '<dd>', {
1383 addClass: 'info',
1384 append: Util.parseHTML( pi.parameters[ i ].info[ j ] )
1385 } ) );
1386 }
1387 }
1388 flag = true;
1389 count = 1e100;
1390 switch ( pi.parameters[ i ].type ) {
1391 case 'namespace':
1392 flag = false;
1393 count = mw.config.get( 'wgFormattedNamespaces' ).length;
1394 break;
1395
1396 case 'limit':
1397 if ( pi.parameters[ i ].highmax !== undefined ) {
1398 dl.append( $( '<dd>', {
1399 addClass: 'info',
1400 append: [
1401 Util.parseMsg(
1402 'api-help-param-limit2', pi.parameters[ i ].max, pi.parameters[ i ].highmax
1403 ),
1404 ' ',
1405 Util.parseMsg( 'apisandbox-param-limit' )
1406 ]
1407 } ) );
1408 } else {
1409 dl.append( $( '<dd>', {
1410 addClass: 'info',
1411 append: [
1412 Util.parseMsg( 'api-help-param-limit', pi.parameters[ i ].max ),
1413 ' ',
1414 Util.parseMsg( 'apisandbox-param-limit' )
1415 ]
1416 } ) );
1417 }
1418 break;
1419
1420 case 'integer':
1421 tmp = '';
1422 if ( pi.parameters[ i ].min !== undefined ) {
1423 tmp += 'min';
1424 }
1425 if ( pi.parameters[ i ].max !== undefined ) {
1426 tmp += 'max';
1427 }
1428 if ( tmp !== '' ) {
1429 dl.append( $( '<dd>', {
1430 addClass: 'info',
1431 append: Util.parseMsg(
1432 'api-help-param-integer-' + tmp,
1433 Util.apiBool( pi.parameters[ i ].multi ) ? 2 : 1,
1434 pi.parameters[ i ].min, pi.parameters[ i ].max
1435 )
1436 } ) );
1437 }
1438 break;
1439
1440 default:
1441 if ( $.isArray( pi.parameters[ i ].type ) ) {
1442 flag = false;
1443 count = pi.parameters[ i ].type.length;
1444 }
1445 break;
1446 }
1447 if ( Util.apiBool( pi.parameters[ i ].multi ) ) {
1448 tmp = [];
1449 if ( flag && !( widget instanceof OO.ui.CapsuleMultiselectWidget ) &&
1450 !(
1451 widget instanceof OptionalWidget &&
1452 widget.widget instanceof OO.ui.CapsuleMultiselectWidget
1453 )
1454 ) {
1455 tmp.push( mw.message( 'api-help-param-multi-separate' ).parse() );
1456 }
1457 if ( count > pi.parameters[ i ].lowlimit ) {
1458 tmp.push(
1459 mw.message( 'api-help-param-multi-max',
1460 pi.parameters[ i ].lowlimit, pi.parameters[ i ].highlimit
1461 ).parse()
1462 );
1463 }
1464 if ( tmp.length ) {
1465 dl.append( $( '<dd>', {
1466 addClass: 'info',
1467 append: Util.parseHTML( tmp.join( ' ' ) )
1468 } ) );
1469 }
1470 }
1471 helpField = new OO.ui.FieldLayout(
1472 new OO.ui.Widget( {
1473 $content: '\xa0',
1474 classes: [ 'mw-apisandbox-spacer' ]
1475 } ), {
1476 align: 'inline',
1477 classes: [ 'mw-apisandbox-help-field' ],
1478 label: dl
1479 }
1480 );
1481
1482 $widgetLabel = $( '<span>' );
1483 widgetField = new OO.ui.FieldLayout(
1484 widget,
1485 {
1486 align: 'left',
1487 classes: [ 'mw-apisandbox-widget-field' ],
1488 label: prefix + pi.parameters[ i ].name,
1489 $label: $widgetLabel
1490 }
1491 );
1492
1493 // FieldLayout only does click for InputElement
1494 // widgets. So supply our own click handler.
1495 $widgetLabel.on( 'click', widgetLabelOnClick.bind( widgetField ) );
1496
1497 // Don't grey out the label when the field is disabled,
1498 // it makes it too hard to read and our "disabled"
1499 // isn't really disabled.
1500 widgetField.onFieldDisable( false );
1501 widgetField.onFieldDisable = doNothing;
1502
1503 if ( Util.apiBool( pi.parameters[ i ].deprecated ) ) {
1504 deprecatedItems.push( widgetField, helpField );
1505 } else {
1506 items.push( widgetField, helpField );
1507 }
1508 }
1509 }
1510
1511 if ( !pi.parameters.length && !Util.apiBool( pi.dynamicparameters ) ) {
1512 items.push( new OO.ui.FieldLayout(
1513 new OO.ui.Widget( {} ).toggle( false ), {
1514 align: 'top',
1515 label: Util.parseMsg( 'apisandbox-no-parameters' )
1516 }
1517 ) );
1518 }
1519
1520 that.$element.empty();
1521
1522 new OO.ui.FieldsetLayout( {
1523 label: that.displayText
1524 } ).addItems( items )
1525 .$element.appendTo( that.$element );
1526
1527 if ( Util.apiBool( pi.dynamicparameters ) ) {
1528 dynamicFieldset = new OO.ui.FieldsetLayout();
1529 dynamicParamNameWidget = new OO.ui.TextInputWidget( {
1530 placeholder: mw.message( 'apisandbox-dynamic-parameters-add-placeholder' ).text()
1531 } ).on( 'enter', addDynamicParamWidget );
1532 dynamicFieldset.addItems( [
1533 new OO.ui.FieldLayout(
1534 new OO.ui.Widget( {} ).toggle( false ), {
1535 align: 'top',
1536 label: Util.parseHTML( pi.dynamicparameters )
1537 }
1538 ),
1539 new OO.ui.ActionFieldLayout(
1540 dynamicParamNameWidget,
1541 new OO.ui.ButtonWidget( {
1542 icon: 'add',
1543 flags: 'progressive'
1544 } ).on( 'click', addDynamicParamWidget ),
1545 {
1546 label: mw.message( 'apisandbox-dynamic-parameters-add-label' ).text(),
1547 align: 'left'
1548 }
1549 )
1550 ] );
1551 $( '<fieldset>' )
1552 .append(
1553 $( '<legend>' ).text( mw.message( 'apisandbox-dynamic-parameters' ).text() ),
1554 dynamicFieldset.$element
1555 )
1556 .appendTo( that.$element );
1557 }
1558
1559 if ( deprecatedItems.length ) {
1560 tmp = new OO.ui.FieldsetLayout().addItems( deprecatedItems ).toggle( false );
1561 $( '<fieldset>' )
1562 .append(
1563 $( '<legend>' ).append(
1564 new OO.ui.ToggleButtonWidget( {
1565 label: mw.message( 'apisandbox-deprecated-parameters' ).text()
1566 } ).on( 'change', tmp.toggle, [], tmp ).$element
1567 ),
1568 tmp.$element
1569 )
1570 .appendTo( that.$element );
1571 }
1572
1573 // Load stored params, if any, then update the booklet if we
1574 // have subpages (or else just update our valid-indicator).
1575 tmp = that.loadFromQueryParams;
1576 that.loadFromQueryParams = null;
1577 if ( $.isPlainObject( tmp ) ) {
1578 that.loadQueryParams( tmp );
1579 }
1580 if ( that.getSubpages().length > 0 ) {
1581 ApiSandbox.updateUI( tmp );
1582 } else {
1583 that.apiCheckValid();
1584 }
1585 } ).fail( function ( code, detail ) {
1586 that.$element.empty()
1587 .append(
1588 new OO.ui.LabelWidget( {
1589 label: mw.message( 'apisandbox-load-error', that.apiModule, detail ).text(),
1590 classes: [ 'error' ]
1591 } ).$element,
1592 new OO.ui.ButtonWidget( {
1593 label: mw.message( 'apisandbox-retry' ).text()
1594 } ).on( 'click', that.loadParamInfo, [], that ).$element
1595 );
1596 } );
1597 };
1598
1599 /**
1600 * Check that all widgets on the page are in a valid state.
1601 *
1602 * @return {boolean}
1603 */
1604 ApiSandbox.PageLayout.prototype.apiCheckValid = function () {
1605 var that = this;
1606
1607 if ( this.paramInfo === null ) {
1608 return $.Deferred().resolve( false ).promise();
1609 } else {
1610 return $.when.apply( $, $.map( this.widgets, function ( widget ) {
1611 return widget.apiCheckValid();
1612 } ) ).then( function () {
1613 that.apiIsValid = $.inArray( false, arguments ) === -1;
1614 if ( that.getOutlineItem() ) {
1615 that.getOutlineItem().setIcon( that.apiIsValid || suppressErrors ? null : 'alert' );
1616 that.getOutlineItem().setIconTitle(
1617 that.apiIsValid || suppressErrors ? '' : mw.message( 'apisandbox-alert-page' ).plain()
1618 );
1619 }
1620 return $.Deferred().resolve( that.apiIsValid ).promise();
1621 } );
1622 }
1623 };
1624
1625 /**
1626 * Load form fields from query parameters
1627 *
1628 * @param {Object} params
1629 */
1630 ApiSandbox.PageLayout.prototype.loadQueryParams = function ( params ) {
1631 if ( this.paramInfo === null ) {
1632 this.loadFromQueryParams = params;
1633 } else {
1634 $.each( this.widgets, function ( name, widget ) {
1635 var v = params.hasOwnProperty( name ) ? params[ name ] : undefined;
1636 widget.setApiValue( v );
1637 } );
1638 }
1639 };
1640
1641 /**
1642 * Load query params from form fields
1643 *
1644 * @param {Object} params Write query parameters into this object
1645 * @param {Object} displayParams Write query parameters for display into this object
1646 */
1647 ApiSandbox.PageLayout.prototype.getQueryParams = function ( params, displayParams ) {
1648 $.each( this.widgets, function ( name, widget ) {
1649 var value = widget.getApiValue();
1650 if ( value !== undefined ) {
1651 params[ name ] = value;
1652 if ( $.isFunction( widget.getApiValueForDisplay ) ) {
1653 value = widget.getApiValueForDisplay();
1654 }
1655 displayParams[ name ] = value;
1656 }
1657 } );
1658 };
1659
1660 /**
1661 * Fetch a list of subpage names loaded by this page
1662 *
1663 * @return {Array}
1664 */
1665 ApiSandbox.PageLayout.prototype.getSubpages = function () {
1666 var ret = [];
1667 $.each( this.widgets, function ( name, widget ) {
1668 var submodules, i;
1669 if ( $.isFunction( widget.getSubmodules ) ) {
1670 submodules = widget.getSubmodules();
1671 for ( i = 0; i < submodules.length; i++ ) {
1672 ret.push( {
1673 key: name + '=' + submodules[ i ].value,
1674 path: submodules[ i ].path,
1675 prefix: widget.paramInfo.submoduleparamprefix || ''
1676 } );
1677 }
1678 }
1679 } );
1680 return ret;
1681 };
1682
1683 /**
1684 * A text input with a clickable indicator
1685 *
1686 * @class
1687 * @private
1688 * @constructor
1689 * @param {Object} [config] Configuration options
1690 */
1691 function TextInputWithIndicatorWidget( config ) {
1692 var k;
1693
1694 config = config || {};
1695 TextInputWithIndicatorWidget[ 'super' ].call( this, config );
1696
1697 this.$indicator = $( '<span>' ).addClass( 'mw-apisandbox-clickable-indicator' );
1698 OO.ui.mixin.TabIndexedElement.call(
1699 this, $.extend( {}, config, { $tabIndexed: this.$indicator } )
1700 );
1701
1702 this.input = new OO.ui.TextInputWidget( $.extend( {
1703 $indicator: this.$indicator,
1704 disabled: this.isDisabled()
1705 }, config.input ) );
1706
1707 // Forward most methods for convenience
1708 for ( k in this.input ) {
1709 if ( $.isFunction( this.input[ k ] ) && !this[ k ] ) {
1710 this[ k ] = this.input[ k ].bind( this.input );
1711 }
1712 }
1713
1714 this.$indicator.on( {
1715 click: this.onIndicatorClick.bind( this ),
1716 keypress: this.onIndicatorKeyPress.bind( this )
1717 } );
1718
1719 this.$element.append( this.input.$element );
1720 }
1721 OO.inheritClass( TextInputWithIndicatorWidget, OO.ui.Widget );
1722 OO.mixinClass( TextInputWithIndicatorWidget, OO.ui.mixin.TabIndexedElement );
1723 TextInputWithIndicatorWidget.prototype.onIndicatorClick = function ( e ) {
1724 if ( !this.isDisabled() && e.which === 1 ) {
1725 this.emit( 'indicator' );
1726 }
1727 return false;
1728 };
1729 TextInputWithIndicatorWidget.prototype.onIndicatorKeyPress = function ( e ) {
1730 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
1731 this.emit( 'indicator' );
1732 return false;
1733 }
1734 };
1735 TextInputWithIndicatorWidget.prototype.setDisabled = function ( disabled ) {
1736 TextInputWithIndicatorWidget[ 'super' ].prototype.setDisabled.call( this, disabled );
1737 if ( this.input ) {
1738 this.input.setDisabled( this.isDisabled() );
1739 }
1740 return this;
1741 };
1742
1743 /**
1744 * A wrapper for a widget that provides an enable/disable button
1745 *
1746 * @class
1747 * @private
1748 * @constructor
1749 * @param {OO.ui.Widget} widget
1750 * @param {Object} [config] Configuration options
1751 */
1752 function OptionalWidget( widget, config ) {
1753 var k;
1754
1755 config = config || {};
1756
1757 this.widget = widget;
1758 this.$overlay = config.$overlay ||
1759 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-overlay' );
1760 this.checkbox = new OO.ui.CheckboxInputWidget( config.checkbox )
1761 .on( 'change', this.onCheckboxChange, [], this );
1762
1763 OptionalWidget[ 'super' ].call( this, config );
1764
1765 // Forward most methods for convenience
1766 for ( k in this.widget ) {
1767 if ( $.isFunction( this.widget[ k ] ) && !this[ k ] ) {
1768 this[ k ] = this.widget[ k ].bind( this.widget );
1769 }
1770 }
1771
1772 this.$overlay.on( 'click', this.onOverlayClick.bind( this ) );
1773
1774 this.$element
1775 .addClass( 'mw-apisandbox-optionalWidget' )
1776 .append(
1777 this.$overlay,
1778 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-fields' ).append(
1779 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-widget' ).append(
1780 widget.$element
1781 ),
1782 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-checkbox' ).append(
1783 this.checkbox.$element
1784 )
1785 )
1786 );
1787
1788 this.setDisabled( widget.isDisabled() );
1789 }
1790 OO.inheritClass( OptionalWidget, OO.ui.Widget );
1791 OptionalWidget.prototype.onCheckboxChange = function ( checked ) {
1792 this.setDisabled( !checked );
1793 };
1794 OptionalWidget.prototype.onOverlayClick = function () {
1795 this.setDisabled( false );
1796 if ( $.isFunction( this.widget.focus ) ) {
1797 this.widget.focus();
1798 }
1799 };
1800 OptionalWidget.prototype.setDisabled = function ( disabled ) {
1801 OptionalWidget[ 'super' ].prototype.setDisabled.call( this, disabled );
1802 this.widget.setDisabled( this.isDisabled() );
1803 this.checkbox.setSelected( !this.isDisabled() );
1804 this.$overlay.toggle( this.isDisabled() );
1805 return this;
1806 };
1807
1808 $( ApiSandbox.init );
1809
1810 module.exports = ApiSandbox;
1811
1812 }( jQuery, mediaWiki, OO ) );