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