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