1 ( function ( $, mw
, OO
) {
3 var ApiSandbox
, Util
, WidgetMethods
, Validators
,
4 $content
, panel
, booklet
, oldhash
, windowManager
, fullscreenButton
,
10 suppressErrors
= true,
11 updatingBooklet
= false,
17 * A wrapper for a widget that provides an enable/disable button
22 * @param {OO.ui.Widget} widget
23 * @param {Object} [config] Configuration options
25 function OptionalWidget( widget
, config
) {
28 config
= config
|| {};
31 this.$cover
= config
.$cover
||
32 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-cover' );
33 this.checkbox
= new OO
.ui
.CheckboxInputWidget( config
.checkbox
)
34 .on( 'change', this.onCheckboxChange
, [], this );
36 OptionalWidget
[ 'super' ].call( this, config
);
38 // Forward most methods for convenience
39 for ( k
in this.widget
) {
40 if ( $.isFunction( this.widget
[ k
] ) && !this[ k
] ) {
41 this[ k
] = this.widget
[ k
].bind( this.widget
);
45 this.$cover
.on( 'click', this.onOverlayClick
.bind( this ) );
48 .addClass( 'mw-apisandbox-optionalWidget' )
51 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-fields' ).append(
52 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-widget' ).append(
55 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-checkbox' ).append(
56 this.checkbox
.$element
61 this.setDisabled( widget
.isDisabled() );
63 OO
.inheritClass( OptionalWidget
, OO
.ui
.Widget
);
64 OptionalWidget
.prototype.onCheckboxChange = function ( checked
) {
65 this.setDisabled( !checked
);
67 OptionalWidget
.prototype.onOverlayClick = function () {
68 this.setDisabled( false );
69 if ( $.isFunction( this.widget
.focus
) ) {
73 OptionalWidget
.prototype.setDisabled = function ( disabled
) {
74 OptionalWidget
[ 'super' ].prototype.setDisabled
.call( this, disabled
);
75 this.widget
.setDisabled( this.isDisabled() );
76 this.checkbox
.setSelected( !this.isDisabled() );
77 this.$cover
.toggle( this.isDisabled() );
83 getApiValue: function () {
84 return this.getValue();
86 setApiValue: function ( v
) {
87 if ( v
=== undefined ) {
88 v
= this.paramInfo
[ 'default' ];
92 apiCheckValid: function () {
94 return this.getValidity().then( function () {
95 return $.Deferred().resolve( true ).promise();
97 return $.Deferred().resolve( false ).promise();
98 } ).done( function ( ok
) {
99 ok
= ok
|| suppressErrors
;
100 that
.setIcon( ok
? null : 'alert' );
101 that
.setIconTitle( ok
? '' : mw
.message( 'apisandbox-alert-field' ).plain() );
106 dateTimeInputWidget
: {
107 getValidity: function () {
108 if ( !Util
.apiBool( this.paramInfo
.required
) || this.getApiValue() !== '' ) {
109 return $.Deferred().resolve().promise();
111 return $.Deferred().reject().promise();
117 alertTokenError: function ( code
, error
) {
118 windowManager
.openWindow( 'errorAlert', {
119 title
: Util
.parseMsg( 'apisandbox-results-fixtoken-fail', this.paramInfo
.tokentype
),
124 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' ),
130 fetchToken: function () {
132 return api
.getToken( this.paramInfo
.tokentype
)
133 .done( this.setApiValue
.bind( this ) )
134 .fail( this.alertTokenError
.bind( this ) )
135 .always( this.popPending
.bind( this ) );
137 setApiValue: function ( v
) {
138 WidgetMethods
.textInputWidget
.setApiValue
.call( this, v
);
139 if ( v
=== '123ABC' ) {
146 getApiValueForDisplay: function () {
151 toggleSwitchWidget
: {
152 getApiValue: function () {
153 return this.getValue() ? 1 : undefined;
155 setApiValue: function ( v
) {
156 this.setValue( Util
.apiBool( v
) );
158 apiCheckValid: function () {
159 return $.Deferred().resolve( true ).promise();
164 getApiValue: function () {
165 var item
= this.getMenu().findSelectedItem();
166 return item
=== null ? undefined : item
.getData();
168 setApiValue: function ( v
) {
169 var menu
= this.getMenu();
171 if ( v
=== undefined ) {
172 v
= this.paramInfo
[ 'default' ];
174 if ( v
=== undefined ) {
177 menu
.selectItemByData( String( v
) );
180 apiCheckValid: function () {
181 var ok
= this.getApiValue() !== undefined || suppressErrors
;
182 this.setIcon( ok
? null : 'alert' );
183 this.setIconTitle( ok
? '' : mw
.message( 'apisandbox-alert-field' ).plain() );
184 return $.Deferred().resolve( ok
).promise();
189 getApiValue: function () {
190 var items
= this.getValue();
191 if ( items
.join( '' ).indexOf( '|' ) === -1 ) {
192 return items
.join( '|' );
194 return '\x1f' + items
.join( '\x1f' );
197 setApiValue: function ( v
) {
198 if ( v
=== undefined || v
=== '' || v
=== '\x1f' ) {
202 if ( v
.indexOf( '\x1f' ) !== 0 ) {
203 this.setValue( v
.split( '|' ) );
205 this.setValue( v
.substr( 1 ).split( '\x1f' ) );
209 apiCheckValid: function () {
213 if ( !suppressErrors
) {
214 ok
= this.getApiValue() !== undefined && !(
215 pi
.allspecifier
!== undefined &&
216 this.getValue().length
> 1 &&
217 this.getValue().indexOf( pi
.allspecifier
) !== -1
221 this.setIcon( ok
? null : 'alert' );
222 this.setIconTitle( ok
? '' : mw
.message( 'apisandbox-alert-field' ).plain() );
223 return $.Deferred().resolve( ok
).promise();
225 createTagItemWidget: function ( data
, label
) {
226 var item
= OO
.ui
.TagMultiselectWidget
.prototype.createTagItemWidget
.call( this, data
, label
);
227 if ( this.paramInfo
.deprecatedvalues
&&
228 this.paramInfo
.deprecatedvalues
.indexOf( data
) >= 0
230 item
.$element
.addClass( 'apihelp-deprecated-value' );
237 getApiValue: function () {
238 return this.isDisabled() ? undefined : this.widget
.getApiValue();
240 setApiValue: function ( v
) {
241 this.setDisabled( v
=== undefined );
242 this.widget
.setApiValue( v
);
244 apiCheckValid: function () {
245 if ( this.isDisabled() ) {
246 return $.Deferred().resolve( true ).promise();
248 return this.widget
.apiCheckValid();
254 single: function () {
255 var v
= this.isDisabled() ? this.paramInfo
[ 'default' ] : this.getApiValue();
256 return v
=== undefined ? [] : [ { value
: v
, path
: this.paramInfo
.submodules
[ v
] } ];
259 var map
= this.paramInfo
.submodules
,
260 v
= this.isDisabled() ? this.paramInfo
[ 'default' ] : this.getApiValue();
261 return v
=== undefined || v
=== '' ? [] : String( v
).split( '|' ).map( function ( v
) {
262 return { value
: v
, path
: map
[ v
] };
268 getApiValueForDisplay: function () {
271 getApiValue: function () {
272 return this.getValue();
274 setApiValue: function () {
277 apiCheckValid: function () {
278 var ok
= this.getValue() !== null || suppressErrors
;
279 this.setIcon( ok
? null : 'alert' );
280 this.setIconTitle( ok
? '' : mw
.message( 'apisandbox-alert-field' ).plain() );
281 return $.Deferred().resolve( ok
).promise();
287 generic: function () {
288 return !Util
.apiBool( this.paramInfo
.required
) || this.getApiValue() !== '';
293 * @class mw.special.ApiSandbox.Util
298 * Fetch API module info
300 * @param {string} module Module to fetch data for
301 * @return {jQuery.Promise}
303 fetchModuleInfo: function ( module
) {
305 deferred
= $.Deferred();
307 if ( moduleInfoCache
.hasOwnProperty( module
) ) {
309 .resolve( moduleInfoCache
[ module
] )
310 .promise( { abort: function () {} } );
312 apiPromise
= api
.post( {
316 uselang
: mw
.config
.get( 'wgUserLanguage' )
317 } ).done( function ( data
) {
320 if ( data
.warnings
&& data
.warnings
.paraminfo
) {
321 deferred
.reject( '???', data
.warnings
.paraminfo
[ '*' ] );
325 info
= data
.paraminfo
.modules
;
326 if ( !info
|| info
.length
!== 1 || info
[ 0 ].path
!== module
) {
327 deferred
.reject( '???', 'No module data returned' );
331 moduleInfoCache
[ module
] = info
[ 0 ];
332 deferred
.resolve( info
[ 0 ] );
333 } ).fail( function ( code
, details
) {
334 if ( code
=== 'http' ) {
335 details
= 'HTTP error: ' + details
.exception
;
336 } else if ( details
.error
) {
337 details
= details
.error
.info
;
339 deferred
.reject( code
, details
);
342 .promise( { abort
: apiPromise
.abort
} );
347 * Mark all currently-in-use tokens as bad
349 markTokensBad: function () {
350 var page
, subpages
, i
,
351 checkPages
= [ pages
.main
];
353 while ( checkPages
.length
) {
354 page
= checkPages
.shift();
356 if ( page
.tokenWidget
) {
357 api
.badToken( page
.tokenWidget
.paramInfo
.tokentype
);
360 subpages
= page
.getSubpages();
361 for ( i
= 0; i
< subpages
.length
; i
++ ) {
362 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
363 checkPages
.push( pages
[ subpages
[ i
].key
] );
370 * Test an API boolean
372 * @param {Mixed} value
375 apiBool: function ( value
) {
376 return value
!== undefined && value
!== false;
380 * Create a widget for a parameter.
382 * @param {Object} pi Parameter info from API
383 * @param {Object} opts Additional options
384 * @return {OO.ui.Widget}
386 createWidgetForParameter: function ( pi
, opts
) {
387 var widget
, innerWidget
, finalWidget
, items
, $button
, $content
, func
,
394 widget
= new OO
.ui
.ToggleSwitchWidget();
395 widget
.paramInfo
= pi
;
396 $.extend( widget
, WidgetMethods
.toggleSwitchWidget
);
397 pi
.required
= true; // Avoid wrapping in the non-required widget
402 if ( Util
.apiBool( pi
.multi
) ) {
403 widget
= new OO
.ui
.TagMultiselectWidget( {
404 allowArbitrary
: true,
405 allowDuplicates
: Util
.apiBool( pi
.allowsduplicates
),
408 widget
.paramInfo
= pi
;
409 $.extend( widget
, WidgetMethods
.tagWidget
);
411 widget
= new OO
.ui
.TextInputWidget( {
412 required
: Util
.apiBool( pi
.required
)
415 if ( !Util
.apiBool( pi
.multi
) ) {
416 widget
.paramInfo
= pi
;
417 $.extend( widget
, WidgetMethods
.textInputWidget
);
418 widget
.setValidation( Validators
.generic
);
420 if ( pi
.tokentype
) {
421 widget
.paramInfo
= pi
;
422 $.extend( widget
, WidgetMethods
.textInputWidget
);
423 $.extend( widget
, WidgetMethods
.tokenWidget
);
428 widget
= new OO
.ui
.MultilineTextInputWidget( {
429 required
: Util
.apiBool( pi
.required
)
431 widget
.paramInfo
= pi
;
432 $.extend( widget
, WidgetMethods
.textInputWidget
);
433 widget
.setValidation( Validators
.generic
);
437 widget
= new OO
.ui
.TextInputWidget( {
439 required
: Util
.apiBool( pi
.required
)
441 widget
.paramInfo
= pi
;
442 $.extend( widget
, WidgetMethods
.textInputWidget
);
443 $.extend( widget
, WidgetMethods
.passwordWidget
);
444 widget
.setValidation( Validators
.generic
);
449 widget
= new OO
.ui
.NumberInputWidget( {
450 required
: Util
.apiBool( pi
.required
),
453 widget
.setIcon
= widget
.input
.setIcon
.bind( widget
.input
);
454 widget
.setIconTitle
= widget
.input
.setIconTitle
.bind( widget
.input
);
455 widget
.getValidity
= widget
.input
.getValidity
.bind( widget
.input
);
456 widget
.paramInfo
= pi
;
457 $.extend( widget
, WidgetMethods
.textInputWidget
);
458 if ( Util
.apiBool( pi
.enforcerange
) ) {
459 widget
.setRange( pi
.min
|| -Infinity
, pi
.max
|| Infinity
);
465 widget
= new OO
.ui
.TextInputWidget( {
466 required
: Util
.apiBool( pi
.required
)
468 widget
.setValidation( function ( value
) {
469 var n
, pi
= this.paramInfo
;
471 if ( value
=== 'max' ) {
475 return !isNaN( n
) && isFinite( n
) &&
476 Math
.floor( n
) === n
&&
477 n
>= pi
.min
&& n
<= pi
.apiSandboxMax
;
480 pi
.min
= pi
.min
|| 0;
481 pi
.apiSandboxMax
= mw
.config
.get( 'apihighlimits' ) ? pi
.highmax
: pi
.max
;
482 widget
.paramInfo
= pi
;
483 $.extend( widget
, WidgetMethods
.textInputWidget
);
488 widget
= new mw
.widgets
.datetime
.DateTimeInputWidget( {
490 format
: '${year|0}-${month|0}-${day|0}T${hour|0}:${minute|0}:${second|0}${zone|short}'
492 required
: Util
.apiBool( pi
.required
),
495 widget
.paramInfo
= pi
;
496 $.extend( widget
, WidgetMethods
.textInputWidget
);
497 $.extend( widget
, WidgetMethods
.dateTimeInputWidget
);
498 multiMode
= 'indicator';
502 widget
= new OO
.ui
.SelectFileWidget();
503 widget
.paramInfo
= pi
;
504 $.extend( widget
, WidgetMethods
.uploadWidget
);
508 items
= $.map( mw
.config
.get( 'wgFormattedNamespaces' ), function ( name
, ns
) {
510 name
= mw
.message( 'blanknamespace' ).text();
512 return new OO
.ui
.MenuOptionWidget( { data
: ns
, label
: name
} );
513 } ).sort( function ( a
, b
) {
514 return a
.data
- b
.data
;
516 if ( Util
.apiBool( pi
.multi
) ) {
517 if ( pi
.allspecifier
!== undefined ) {
518 items
.unshift( new OO
.ui
.MenuOptionWidget( {
519 data
: pi
.allspecifier
,
520 label
: mw
.message( 'apisandbox-multivalue-all-namespaces', pi
.allspecifier
).text()
524 widget
= new OO
.ui
.MenuTagMultiselectWidget( {
525 menu
: { items
: items
},
528 widget
.paramInfo
= pi
;
529 $.extend( widget
, WidgetMethods
.tagWidget
);
531 widget
= new OO
.ui
.DropdownWidget( {
532 menu
: { items
: items
},
535 widget
.paramInfo
= pi
;
536 $.extend( widget
, WidgetMethods
.dropdownWidget
);
541 if ( !Array
.isArray( pi
.type
) ) {
542 throw new Error( 'Unknown parameter type ' + pi
.type
);
545 items
= pi
.type
.map( function ( v
) {
551 if ( pi
.deprecatedvalues
&& pi
.deprecatedvalues
.indexOf( v
) >= 0 ) {
552 config
.classes
.push( 'apihelp-deprecated-value' );
554 return new OO
.ui
.MenuOptionWidget( config
);
556 if ( Util
.apiBool( pi
.multi
) ) {
557 if ( pi
.allspecifier
!== undefined ) {
558 items
.unshift( new OO
.ui
.MenuOptionWidget( {
559 data
: pi
.allspecifier
,
560 label
: mw
.message( 'apisandbox-multivalue-all-values', pi
.allspecifier
).text()
564 widget
= new OO
.ui
.MenuTagMultiselectWidget( {
565 menu
: { items
: items
},
568 widget
.paramInfo
= pi
;
569 $.extend( widget
, WidgetMethods
.tagWidget
);
570 if ( Util
.apiBool( pi
.submodules
) ) {
571 widget
.getSubmodules
= WidgetMethods
.submoduleWidget
.multi
;
572 widget
.on( 'change', ApiSandbox
.updateUI
);
575 widget
= new OO
.ui
.DropdownWidget( {
576 menu
: { items
: items
},
579 widget
.paramInfo
= pi
;
580 $.extend( widget
, WidgetMethods
.dropdownWidget
);
581 if ( Util
.apiBool( pi
.submodules
) ) {
582 widget
.getSubmodules
= WidgetMethods
.submoduleWidget
.single
;
583 widget
.getMenu().on( 'select', ApiSandbox
.updateUI
);
585 if ( pi
.deprecatedvalues
) {
586 widget
.getMenu().on( 'select', function ( item
) {
587 this.$element
.toggleClass(
588 'apihelp-deprecated-value',
589 pi
.deprecatedvalues
.indexOf( item
.data
) >= 0
598 if ( Util
.apiBool( pi
.multi
) && multiMode
!== 'none' ) {
599 innerWidget
= widget
;
600 switch ( multiMode
) {
602 $content
= innerWidget
.$element
;
606 $button
= innerWidget
.$indicator
;
607 $button
.css( 'cursor', 'pointer' );
608 $button
.attr( 'tabindex', 0 );
609 $button
.parent().append( $button
);
610 innerWidget
.setIndicator( 'next' );
611 $content
= innerWidget
.$element
;
615 throw new Error( 'Unknown multiMode "' + multiMode
+ '"' );
618 widget
= new OO
.ui
.PopupTagMultiselectWidget( {
619 allowArbitrary
: true,
620 allowDuplicates
: Util
.apiBool( pi
.allowsduplicates
),
623 classes
: [ 'mw-apisandbox-popup' ],
627 widget
.paramInfo
= pi
;
628 $.extend( widget
, WidgetMethods
.tagWidget
);
631 if ( !innerWidget
.isDisabled() ) {
632 innerWidget
.apiCheckValid().done( function ( ok
) {
634 widget
.addTag( innerWidget
.getApiValue() );
635 innerWidget
.setApiValue( undefined );
641 switch ( multiMode
) {
643 innerWidget
.connect( null, { enter
: func
} );
649 keypress: function ( e
) {
650 if ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) {
659 if ( Util
.apiBool( pi
.required
) || opts
.nooptional
) {
660 finalWidget
= widget
;
662 finalWidget
= new OptionalWidget( widget
);
663 finalWidget
.paramInfo
= pi
;
664 $.extend( finalWidget
, WidgetMethods
.optionalWidget
);
665 if ( widget
.getSubmodules
) {
666 finalWidget
.getSubmodules
= widget
.getSubmodules
.bind( widget
);
667 finalWidget
.on( 'disable', function () { setTimeout( ApiSandbox
.updateUI
); } );
669 finalWidget
.setDisabled( true );
672 widget
.setApiValue( pi
[ 'default' ] );
678 * Parse an HTML string and call Util.fixupHTML()
680 * @param {string} html HTML to parse
683 parseHTML: function ( html
) {
684 var $ret
= $( $.parseHTML( html
) );
685 return Util
.fixupHTML( $ret
);
689 * Parse an i18n message and call Util.fixupHTML()
691 * @param {string} key Key of message to get
692 * @param {...Mixed} parameters Values for $N replacements
695 parseMsg: function () {
696 var $ret
= mw
.message
.apply( mw
.message
, arguments
).parseDom();
697 return Util
.fixupHTML( $ret
);
701 * Fix HTML for ApiSandbox display
704 * - Add target="_blank" to any links
706 * @param {jQuery} $html DOM to process
709 fixupHTML: function ( $html
) {
710 $html
.filter( 'a' ).add( $html
.find( 'a' ) )
711 .filter( '[href]:not([target])' )
712 .attr( 'target', '_blank' );
717 * Format a request and return a bunch of menu option widgets
719 * @param {Object} displayParams Query parameters, sanitized for display.
720 * @param {Object} rawParams Query parameters. You should probably use displayParams instead.
721 * @return {OO.ui.MenuOptionWidget[]} Each item's data should be an OO.ui.FieldLayout
723 formatRequest: function ( displayParams
, rawParams
) {
726 new OO
.ui
.MenuOptionWidget( {
727 label
: Util
.parseMsg( 'apisandbox-request-format-url-label' ),
728 data
: new OO
.ui
.FieldLayout(
729 new OO
.ui
.TextInputWidget( {
731 value
: mw
.util
.wikiScript( 'api' ) + '?' + $.param( displayParams
)
733 label
: Util
.parseMsg( 'apisandbox-request-url-label' )
737 new OO
.ui
.MenuOptionWidget( {
738 label
: Util
.parseMsg( 'apisandbox-request-format-json-label' ),
739 data
: new OO
.ui
.FieldLayout(
740 jsonInput
= new OO
.ui
.MultilineTextInputWidget( {
741 classes
: [ 'mw-apisandbox-textInputCode' ],
745 value
: JSON
.stringify( displayParams
, null, '\t' )
747 label
: Util
.parseMsg( 'apisandbox-request-json-label' )
749 ).on( 'toggle', function ( visible
) {
751 // Call updatePosition instead of adjustSize
752 // because the latter has weird caching
753 // behavior and the former bypasses it.
754 jsonInput
.updatePosition();
760 mw
.hook( 'apisandbox.formatRequest' ).fire( items
, displayParams
, rawParams
);
766 * Event handler for when formatDropdown's selection changes
768 onFormatDropdownChange: function () {
770 menu
= formatDropdown
.getMenu(),
771 items
= menu
.getItems(),
772 selectedField
= menu
.findSelectedItem() ? menu
.findSelectedItem().getData() : null;
774 for ( i
= 0; i
< items
.length
; i
++ ) {
775 items
[ i
].getData().toggle( items
[ i
].getData() === selectedField
);
781 * Interface to ApiSandbox UI
783 * @class mw.special.ApiSandbox
789 * Automatically called on $.ready()
794 ApiSandbox
.isFullscreen
= false;
796 $content
= $( '#mw-apisandbox' );
798 windowManager
= new OO
.ui
.WindowManager();
799 $( 'body' ).append( windowManager
.$element
);
800 windowManager
.addWindows( {
801 errorAlert
: new OO
.ui
.MessageDialog()
804 fullscreenButton
= new OO
.ui
.ButtonWidget( {
805 label
: mw
.message( 'apisandbox-fullscreen' ).text(),
806 title
: mw
.message( 'apisandbox-fullscreen-tooltip' ).text()
807 } ).on( 'click', ApiSandbox
.toggleFullscreen
);
809 $toolbar
= $( '<div>' )
810 .addClass( 'mw-apisandbox-toolbar' )
812 fullscreenButton
.$element
,
813 new OO
.ui
.ButtonWidget( {
814 label
: mw
.message( 'apisandbox-submit' ).text(),
815 flags
: [ 'primary', 'progressive' ]
816 } ).on( 'click', ApiSandbox
.sendRequest
).$element
,
817 new OO
.ui
.ButtonWidget( {
818 label
: mw
.message( 'apisandbox-reset' ).text(),
820 } ).on( 'click', ApiSandbox
.resetUI
).$element
823 booklet
= new OO
.ui
.BookletLayout( {
828 panel
= new OO
.ui
.PanelLayout( {
829 classes
: [ 'mw-apisandbox-container' ],
830 content
: [ booklet
],
835 pages
.main
= new ApiSandbox
.PageLayout( { key
: 'main', path
: 'main' } );
837 // Parse the current hash string
838 if ( !ApiSandbox
.loadFromHash() ) {
839 ApiSandbox
.updateUI();
842 // If the hashchange event exists, use it. Otherwise, fake it.
843 // And, of course, IE has to be dumb.
844 if ( 'onhashchange' in window
&&
845 ( document
.documentMode
=== undefined || document
.documentMode
>= 8 )
847 $( window
).on( 'hashchange', ApiSandbox
.loadFromHash
);
849 setInterval( function () {
850 if ( oldhash
!== location
.hash
) {
851 ApiSandbox
.loadFromHash();
858 .append( $( '<p>' ).append( Util
.parseMsg( 'apisandbox-intro' ) ) )
860 $( '<div>' ).attr( 'id', 'mw-apisandbox-ui' )
862 .append( panel
.$element
)
865 $( window
).on( 'resize', ApiSandbox
.resizePanel
);
867 ApiSandbox
.resizePanel();
871 * Toggle "fullscreen" mode
873 toggleFullscreen: function () {
874 var $body
= $( document
.body
),
875 $ui
= $( '#mw-apisandbox-ui' );
877 ApiSandbox
.isFullscreen
= !ApiSandbox
.isFullscreen
;
879 $body
.toggleClass( 'mw-apisandbox-fullscreen', ApiSandbox
.isFullscreen
);
880 $ui
.toggleClass( 'mw-body-content', ApiSandbox
.isFullscreen
);
881 if ( ApiSandbox
.isFullscreen
) {
882 fullscreenButton
.setLabel( mw
.message( 'apisandbox-unfullscreen' ).text() );
883 fullscreenButton
.setTitle( mw
.message( 'apisandbox-unfullscreen-tooltip' ).text() );
884 OO
.ui
.getDefaultOverlay().prepend( $ui
);
886 fullscreenButton
.setLabel( mw
.message( 'apisandbox-fullscreen' ).text() );
887 fullscreenButton
.setTitle( mw
.message( 'apisandbox-fullscreen-tooltip' ).text() );
888 $content
.append( $ui
);
890 ApiSandbox
.resizePanel();
894 * Set the height of the panel based on the current viewport.
896 resizePanel: function () {
897 var height
= $( window
).height(),
898 contentTop
= $content
.offset().top
;
900 if ( ApiSandbox
.isFullscreen
) {
901 height
-= panel
.$element
.offset().top
- $( '#mw-apisandbox-ui' ).offset().top
;
902 panel
.$element
.height( height
- 1 );
904 // Subtract the height of the intro text
905 height
-= panel
.$element
.offset().top
- contentTop
;
907 panel
.$element
.height( height
- 10 );
908 $( window
).scrollTop( contentTop
- 5 );
913 * Update the current query when the page hash changes
915 * @return {boolean} Successful
917 loadFromHash: function () {
919 hash
= location
.hash
;
921 if ( oldhash
=== hash
) {
929 // I'm surprised this doesn't seem to exist in jQuery or mw.util.
931 hash
= hash
.replace( /\+/g, '%20' );
932 re
= /([^&=#]+)=?([^&#]*)/g;
933 while ( ( m
= re
.exec( hash
) ) ) {
934 params
[ decodeURIComponent( m
[ 1 ] ) ] = decodeURIComponent( m
[ 2 ] );
937 ApiSandbox
.updateUI( params
);
942 * Update the pages in the booklet
944 * @param {Object} [params] Optional query parameters to load
946 updateUI: function ( params
) {
947 var i
, page
, subpages
, j
, removePages
,
950 if ( !$.isPlainObject( params
) ) {
954 if ( updatingBooklet
) {
957 updatingBooklet
= true;
959 if ( params
!== undefined ) {
960 pages
.main
.loadQueryParams( params
);
962 addPages
.push( pages
.main
);
963 if ( resultPage
!== null ) {
964 addPages
.push( resultPage
);
966 pages
.main
.apiCheckValid();
969 while ( addPages
.length
) {
970 page
= addPages
.shift();
971 if ( bookletPages
[ i
] !== page
) {
972 for ( j
= i
; j
< bookletPages
.length
; j
++ ) {
973 if ( bookletPages
[ j
].getName() === page
.getName() ) {
974 bookletPages
.splice( j
, 1 );
977 bookletPages
.splice( i
, 0, page
);
978 booklet
.addPages( [ page
], i
);
982 if ( page
.getSubpages
) {
983 subpages
= page
.getSubpages();
984 for ( j
= 0; j
< subpages
.length
; j
++ ) {
985 if ( !pages
.hasOwnProperty( subpages
[ j
].key
) ) {
986 subpages
[ j
].indentLevel
= page
.indentLevel
+ 1;
987 pages
[ subpages
[ j
].key
] = new ApiSandbox
.PageLayout( subpages
[ j
] );
989 if ( params
!== undefined ) {
990 pages
[ subpages
[ j
].key
].loadQueryParams( params
);
992 addPages
.splice( j
, 0, pages
[ subpages
[ j
].key
] );
993 pages
[ subpages
[ j
].key
].apiCheckValid();
998 if ( bookletPages
.length
> i
) {
999 removePages
= bookletPages
.splice( i
, bookletPages
.length
- i
);
1000 booklet
.removePages( removePages
);
1003 if ( !booklet
.getCurrentPageName() ) {
1004 booklet
.selectFirstSelectablePage();
1007 updatingBooklet
= false;
1012 * Reset button handler
1014 resetUI: function () {
1015 suppressErrors
= true;
1017 main
: new ApiSandbox
.PageLayout( { key
: 'main', path
: 'main' } )
1020 ApiSandbox
.updateUI();
1024 * Submit button handler
1026 * @param {Object} [params] Use this set of params instead of those in the form fields.
1027 * The form fields will be updated to match.
1029 sendRequest: function ( params
) {
1030 var page
, subpages
, i
, query
, $result
, $focus
,
1031 progress
, $progressText
, progressLoading
,
1033 paramsAreForced
= !!params
,
1035 checkPages
= [ pages
.main
];
1037 // Blur any focused widget before submit, because
1038 // OO.ui.ButtonWidget doesn't take focus itself (T128054)
1039 $focus
= $( '#mw-apisandbox-ui' ).find( document
.activeElement
);
1040 if ( $focus
.length
) {
1044 suppressErrors
= false;
1046 // save widget state in params (or load from it if we are forced)
1047 if ( paramsAreForced
) {
1048 ApiSandbox
.updateUI( params
);
1051 while ( checkPages
.length
) {
1052 page
= checkPages
.shift();
1053 deferreds
.push( page
.apiCheckValid() );
1054 page
.getQueryParams( params
, displayParams
);
1055 subpages
= page
.getSubpages();
1056 for ( i
= 0; i
< subpages
.length
; i
++ ) {
1057 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
1058 checkPages
.push( pages
[ subpages
[ i
].key
] );
1063 if ( !paramsAreForced
) {
1064 // forced params means we are continuing a query; the base query should be preserved
1065 baseRequestParams
= $.extend( {}, params
);
1068 $.when
.apply( $, deferreds
).done( function () {
1069 var formatItems
, menu
, selectedLabel
;
1071 if ( $.inArray( false, arguments
) !== -1 ) {
1072 windowManager
.openWindow( 'errorAlert', {
1073 title
: Util
.parseMsg( 'apisandbox-submit-invalid-fields-title' ),
1074 message
: Util
.parseMsg( 'apisandbox-submit-invalid-fields-message' ),
1078 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' ),
1086 query
= $.param( displayParams
);
1088 formatItems
= Util
.formatRequest( displayParams
, params
);
1090 // Force a 'fm' format with wrappedhtml=1, if available
1091 if ( params
.format
!== undefined ) {
1092 if ( availableFormats
.hasOwnProperty( params
.format
+ 'fm' ) ) {
1093 params
.format
= params
.format
+ 'fm';
1095 if ( params
.format
.substr( -2 ) === 'fm' ) {
1096 params
.wrappedhtml
= 1;
1100 progressLoading
= false;
1101 $progressText
= $( '<span>' ).text( mw
.message( 'apisandbox-sending-request' ).text() );
1102 progress
= new OO
.ui
.ProgressBarWidget( {
1104 $content
: $progressText
1107 $result
= $( '<div>' )
1108 .append( progress
.$element
);
1110 resultPage
= page
= new OO
.ui
.PageLayout( '|results|' );
1111 page
.setupOutlineItem = function () {
1112 this.outlineItem
.setLabel( mw
.message( 'apisandbox-results' ).text() );
1115 if ( !formatDropdown
) {
1116 formatDropdown
= new OO
.ui
.DropdownWidget( {
1117 menu
: { items
: [] },
1120 formatDropdown
.getMenu().on( 'select', Util
.onFormatDropdownChange
);
1123 menu
= formatDropdown
.getMenu();
1124 selectedLabel
= menu
.findSelectedItem() ? menu
.findSelectedItem().getLabel() : '';
1125 if ( typeof selectedLabel
!== 'string' ) {
1126 selectedLabel
= selectedLabel
.text();
1128 menu
.clearItems().addItems( formatItems
);
1129 menu
.chooseItem( menu
.getItemFromLabel( selectedLabel
) || menu
.findFirstSelectableItem() );
1131 // Fire the event to update field visibilities
1132 Util
.onFormatDropdownChange();
1134 page
.$element
.empty()
1136 new OO
.ui
.FieldLayout(
1138 label
: Util
.parseMsg( 'apisandbox-request-selectformat-label' )
1141 formatItems
.map( function ( item
) {
1142 return item
.getData().$element
;
1146 ApiSandbox
.updateUI();
1147 booklet
.setPage( '|results|' );
1149 location
.href
= oldhash
= '#' + query
;
1152 contentType
: 'multipart/form-data',
1155 var xhr
= new window
.XMLHttpRequest();
1156 xhr
.upload
.addEventListener( 'progress', function ( e
) {
1157 if ( !progressLoading
) {
1158 if ( e
.lengthComputable
) {
1159 progress
.setProgress( e
.loaded
* 100 / e
.total
);
1161 progress
.setProgress( false );
1165 xhr
.addEventListener( 'progress', function ( e
) {
1166 if ( !progressLoading
) {
1167 progressLoading
= true;
1168 $progressText
.text( mw
.message( 'apisandbox-loading-results' ).text() );
1170 if ( e
.lengthComputable
) {
1171 progress
.setProgress( e
.loaded
* 100 / e
.total
);
1173 progress
.setProgress( false );
1179 .catch( function ( code
, data
, result
, jqXHR
) {
1180 var deferred
= $.Deferred();
1182 if ( code
!== 'http' ) {
1183 // Not really an error, work around mw.Api thinking it is.
1184 deferred
.resolve( result
, jqXHR
);
1187 deferred
.reject
.apply( deferred
, arguments
);
1189 return deferred
.promise();
1191 .then( function ( data
, jqXHR
) {
1192 var m
, loadTime
, button
, clear
,
1193 ct
= jqXHR
.getResponseHeader( 'Content-Type' ),
1194 loginSuppressed
= jqXHR
.getResponseHeader( 'MediaWiki-Login-Suppressed' ) || 'false';
1197 if ( loginSuppressed
!== 'false' ) {
1199 .addClass( 'warning' )
1200 .append( Util
.parseMsg( 'apisandbox-results-login-suppressed' ) )
1201 .appendTo( $result
);
1203 if ( /^text\/mediawiki-api-prettyprint-wrapped(?:;|$)/.test( ct
) ) {
1204 data
= JSON
.parse( data
);
1205 if ( data
.modules
.length
) {
1206 mw
.loader
.load( data
.modules
);
1208 if ( data
.status
&& data
.status
!== 200 ) {
1210 .addClass( 'api-pretty-header api-pretty-status' )
1211 .append( Util
.parseMsg( 'api-format-prettyprint-status', data
.status
, data
.statustext
) )
1212 .appendTo( $result
);
1214 $result
.append( Util
.parseHTML( data
.html
) );
1215 loadTime
= data
.time
;
1216 } else if ( ( m
= data
.match( /<pre[ >][\s\S]*<\/pre>/ ) ) ) {
1217 $result
.append( Util
.parseHTML( m
[ 0 ] ) );
1218 if ( ( m
= data
.match( /"wgBackendResponseTime":\s*(\d+)/ ) ) ) {
1219 loadTime
= parseInt( m
[ 1 ], 10 );
1223 .addClass( 'api-pretty-content' )
1225 .appendTo( $result
);
1227 if ( paramsAreForced
|| data
[ 'continue' ] ) {
1229 $( '<div>' ).append(
1230 new OO
.ui
.ButtonWidget( {
1231 label
: mw
.message( 'apisandbox-continue' ).text()
1232 } ).on( 'click', function () {
1233 ApiSandbox
.sendRequest( $.extend( {}, baseRequestParams
, data
[ 'continue' ] ) );
1234 } ).setDisabled( !data
[ 'continue' ] ).$element
,
1235 ( clear
= new OO
.ui
.ButtonWidget( {
1236 label
: mw
.message( 'apisandbox-continue-clear' ).text()
1237 } ).on( 'click', function () {
1238 ApiSandbox
.updateUI( baseRequestParams
);
1239 clear
.setDisabled( true );
1240 booklet
.setPage( '|results|' );
1241 } ).setDisabled( !paramsAreForced
) ).$element
,
1242 new OO
.ui
.PopupButtonWidget( {
1247 $content
: $( '<div>' ).append( Util
.parseMsg( 'apisandbox-continue-help' ) ),
1255 if ( typeof loadTime
=== 'number' ) {
1257 $( '<div>' ).append(
1258 new OO
.ui
.LabelWidget( {
1259 label
: mw
.message( 'apisandbox-request-time', loadTime
).text()
1265 if ( jqXHR
.getResponseHeader( 'MediaWiki-API-Error' ) === 'badtoken' ) {
1266 // Flush all saved tokens in case one of them is the bad one.
1267 Util
.markTokensBad();
1268 button
= new OO
.ui
.ButtonWidget( {
1269 label
: mw
.message( 'apisandbox-results-fixtoken' ).text()
1271 button
.on( 'click', ApiSandbox
.fixTokenAndResend
)
1272 .on( 'click', button
.setDisabled
, [ true ], button
)
1273 .$element
.appendTo( $result
);
1275 }, function ( code
, data
) {
1276 var details
= 'HTTP error: ' + data
.exception
;
1279 new OO
.ui
.LabelWidget( {
1280 label
: mw
.message( 'apisandbox-results-error', details
).text(),
1281 classes
: [ 'error' ]
1289 * Handler for the "Correct token and resubmit" button
1291 * Used on a 'badtoken' error, it re-fetches token parameters for all
1292 * pages and then re-submits the query.
1294 fixTokenAndResend: function () {
1295 var page
, subpages
, i
, k
,
1297 tokenWait
= { dummy
: true },
1298 checkPages
= [ pages
.main
],
1299 success = function ( k
) {
1300 delete tokenWait
[ k
];
1301 if ( ok
&& $.isEmptyObject( tokenWait
) ) {
1302 ApiSandbox
.sendRequest();
1305 failure = function ( k
) {
1306 delete tokenWait
[ k
];
1310 while ( checkPages
.length
) {
1311 page
= checkPages
.shift();
1313 if ( page
.tokenWidget
) {
1314 k
= page
.apiModule
+ page
.tokenWidget
.paramInfo
.name
;
1315 tokenWait
[ k
] = page
.tokenWidget
.fetchToken();
1317 .done( success
.bind( page
.tokenWidget
, k
) )
1318 .fail( failure
.bind( page
.tokenWidget
, k
) );
1321 subpages
= page
.getSubpages();
1322 for ( i
= 0; i
< subpages
.length
; i
++ ) {
1323 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
1324 checkPages
.push( pages
[ subpages
[ i
].key
] );
1329 success( 'dummy', '' );
1333 * Reset validity indicators for all widgets
1335 updateValidityIndicators: function () {
1336 var page
, subpages
, i
,
1337 checkPages
= [ pages
.main
];
1339 while ( checkPages
.length
) {
1340 page
= checkPages
.shift();
1341 page
.apiCheckValid();
1342 subpages
= page
.getSubpages();
1343 for ( i
= 0; i
< subpages
.length
; i
++ ) {
1344 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
1345 checkPages
.push( pages
[ subpages
[ i
].key
] );
1353 * PageLayout for API modules
1357 * @extends OO.ui.PageLayout
1359 * @param {Object} [config] Configuration options
1361 ApiSandbox
.PageLayout = function ( config
) {
1362 config
= $.extend( { prefix
: '' }, config
);
1363 this.displayText
= config
.key
;
1364 this.apiModule
= config
.path
;
1365 this.prefix
= config
.prefix
;
1366 this.paramInfo
= null;
1367 this.apiIsValid
= true;
1368 this.loadFromQueryParams
= null;
1370 this.tokenWidget
= null;
1371 this.indentLevel
= config
.indentLevel
? config
.indentLevel
: 0;
1372 ApiSandbox
.PageLayout
[ 'super' ].call( this, config
.key
, config
);
1373 this.loadParamInfo();
1375 OO
.inheritClass( ApiSandbox
.PageLayout
, OO
.ui
.PageLayout
);
1376 ApiSandbox
.PageLayout
.prototype.setupOutlineItem = function () {
1377 this.outlineItem
.setLevel( this.indentLevel
);
1378 this.outlineItem
.setLabel( this.displayText
);
1379 this.outlineItem
.setIcon( this.apiIsValid
|| suppressErrors
? null : 'alert' );
1380 this.outlineItem
.setIconTitle(
1381 this.apiIsValid
|| suppressErrors
? '' : mw
.message( 'apisandbox-alert-page' ).plain()
1386 * Fetch module information for this page's module, then create UI
1388 ApiSandbox
.PageLayout
.prototype.loadParamInfo = function () {
1389 var dynamicFieldset
, dynamicParamNameWidget
,
1391 removeDynamicParamWidget = function ( name
, layout
) {
1392 dynamicFieldset
.removeItems( [ layout
] );
1393 delete that
.widgets
[ name
];
1395 addDynamicParamWidget = function () {
1396 var name
, layout
, widget
, button
;
1398 // Check name is filled in
1399 name
= dynamicParamNameWidget
.getValue().trim();
1400 if ( name
=== '' ) {
1401 dynamicParamNameWidget
.focus();
1405 if ( that
.widgets
[ name
] !== undefined ) {
1406 windowManager
.openWindow( 'errorAlert', {
1407 title
: Util
.parseMsg( 'apisandbox-dynamic-error-exists', name
),
1411 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' ),
1419 widget
= Util
.createWidgetForParameter( {
1426 button
= new OO
.ui
.ButtonWidget( {
1428 flags
: 'destructive'
1430 layout
= new OO
.ui
.ActionFieldLayout(
1438 button
.on( 'click', removeDynamicParamWidget
, [ name
, layout
] );
1439 that
.widgets
[ name
] = widget
;
1440 dynamicFieldset
.addItems( [ layout
], dynamicFieldset
.getItems().length
- 1 );
1443 dynamicParamNameWidget
.setValue( '' );
1446 this.$element
.empty()
1447 .append( new OO
.ui
.ProgressBarWidget( {
1449 text
: mw
.message( 'apisandbox-loading', this.displayText
).text()
1452 Util
.fetchModuleInfo( this.apiModule
)
1453 .done( function ( pi
) {
1454 var prefix
, i
, j
, descriptionContainer
, widget
, layoutConfig
, button
, widgetField
, helpField
, tmp
, flag
, count
,
1456 deprecatedItems
= [],
1458 filterFmModules = function ( v
) {
1459 return v
.substr( -2 ) !== 'fm' ||
1460 !availableFormats
.hasOwnProperty( v
.substr( 0, v
.length
- 2 ) );
1462 widgetLabelOnClick = function () {
1463 var f
= this.getField();
1464 if ( $.isFunction( f
.setDisabled
) ) {
1465 f
.setDisabled( false );
1467 if ( $.isFunction( f
.focus
) ) {
1472 // This is something of a hack. We always want the 'format' and
1473 // 'action' parameters from the main module to be specified,
1474 // and for 'format' we also want to simplify the dropdown since
1475 // we always send the 'fm' variant.
1476 if ( that
.apiModule
=== 'main' ) {
1477 for ( i
= 0; i
< pi
.parameters
.length
; i
++ ) {
1478 if ( pi
.parameters
[ i
].name
=== 'action' ) {
1479 pi
.parameters
[ i
].required
= true;
1480 delete pi
.parameters
[ i
][ 'default' ];
1482 if ( pi
.parameters
[ i
].name
=== 'format' ) {
1483 tmp
= pi
.parameters
[ i
].type
;
1484 for ( j
= 0; j
< tmp
.length
; j
++ ) {
1485 availableFormats
[ tmp
[ j
] ] = true;
1487 pi
.parameters
[ i
].type
= tmp
.filter( filterFmModules
);
1488 pi
.parameters
[ i
][ 'default' ] = 'json';
1489 pi
.parameters
[ i
].required
= true;
1494 // Hide the 'wrappedhtml' parameter on format modules
1495 if ( pi
.group
=== 'format' ) {
1496 pi
.parameters
= pi
.parameters
.filter( function ( p
) {
1497 return p
.name
!== 'wrappedhtml';
1501 that
.paramInfo
= pi
;
1503 items
.push( new OO
.ui
.FieldLayout(
1504 new OO
.ui
.Widget( {} ).toggle( false ), {
1506 label
: Util
.parseHTML( pi
.description
)
1510 if ( pi
.helpurls
.length
) {
1511 buttons
.push( new OO
.ui
.PopupButtonWidget( {
1513 label
: mw
.message( 'apisandbox-helpurls' ).text(),
1518 $content
: $( '<ul>' ).append( pi
.helpurls
.map( function ( link
) {
1519 return $( '<li>' ).append( $( '<a>' )
1520 .attr( { href
: link
, target
: '_blank' } )
1528 if ( pi
.examples
.length
) {
1529 buttons
.push( new OO
.ui
.PopupButtonWidget( {
1531 label
: mw
.message( 'apisandbox-examples' ).text(),
1536 $content
: $( '<ul>' ).append( pi
.examples
.map( function ( example
) {
1538 .attr( 'href', '#' + example
.query
)
1539 .html( example
.description
);
1540 a
.find( 'a' ).contents().unwrap(); // Can't nest links
1541 return $( '<li>' ).append( a
);
1547 if ( buttons
.length
) {
1548 items
.push( new OO
.ui
.FieldLayout(
1549 new OO
.ui
.ButtonGroupWidget( {
1551 } ), { align
: 'top' }
1555 if ( pi
.parameters
.length
) {
1556 prefix
= that
.prefix
+ pi
.prefix
;
1557 for ( i
= 0; i
< pi
.parameters
.length
; i
++ ) {
1558 widget
= Util
.createWidgetForParameter( pi
.parameters
[ i
] );
1559 that
.widgets
[ prefix
+ pi
.parameters
[ i
].name
] = widget
;
1560 if ( pi
.parameters
[ i
].tokentype
) {
1561 that
.tokenWidget
= widget
;
1564 descriptionContainer
= $( '<div>' );
1566 tmp
= Util
.parseHTML( pi
.parameters
[ i
].description
);
1567 tmp
.filter( 'dl' ).makeCollapsible( {
1569 } ).children( '.mw-collapsible-toggle' ).each( function () {
1570 var $this = $( this );
1571 $this.parent().prev( 'p' ).append( $this );
1573 descriptionContainer
.append( $( '<div>' ).addClass( 'description' ).append( tmp
) );
1575 if ( pi
.parameters
[ i
].info
&& pi
.parameters
[ i
].info
.length
) {
1576 for ( j
= 0; j
< pi
.parameters
[ i
].info
.length
; j
++ ) {
1577 descriptionContainer
.append( $( '<div>' )
1579 .append( Util
.parseHTML( pi
.parameters
[ i
].info
[ j
] ) )
1585 switch ( pi
.parameters
[ i
].type
) {
1588 count
= mw
.config
.get( 'wgFormattedNamespaces' ).length
;
1592 if ( pi
.parameters
[ i
].highmax
!== undefined ) {
1593 descriptionContainer
.append( $( '<div>' )
1597 'api-help-param-limit2', pi
.parameters
[ i
].max
, pi
.parameters
[ i
].highmax
1600 Util
.parseMsg( 'apisandbox-param-limit' )
1604 descriptionContainer
.append( $( '<div>' )
1607 Util
.parseMsg( 'api-help-param-limit', pi
.parameters
[ i
].max
),
1609 Util
.parseMsg( 'apisandbox-param-limit' )
1617 if ( pi
.parameters
[ i
].min
!== undefined ) {
1620 if ( pi
.parameters
[ i
].max
!== undefined ) {
1624 descriptionContainer
.append( $( '<div>' )
1626 .append( Util
.parseMsg(
1627 'api-help-param-integer-' + tmp
,
1628 Util
.apiBool( pi
.parameters
[ i
].multi
) ? 2 : 1,
1629 pi
.parameters
[ i
].min
, pi
.parameters
[ i
].max
1636 if ( Array
.isArray( pi
.parameters
[ i
].type
) ) {
1638 count
= pi
.parameters
[ i
].type
.length
;
1642 if ( Util
.apiBool( pi
.parameters
[ i
].multi
) ) {
1644 if ( flag
&& !( widget
instanceof OO
.ui
.TagMultiselectWidget
) &&
1646 widget
instanceof OptionalWidget
&&
1647 widget
.widget
instanceof OO
.ui
.TagMultiselectWidget
1650 tmp
.push( mw
.message( 'api-help-param-multi-separate' ).parse() );
1652 if ( count
> pi
.parameters
[ i
].lowlimit
) {
1654 mw
.message( 'api-help-param-multi-max',
1655 pi
.parameters
[ i
].lowlimit
, pi
.parameters
[ i
].highlimit
1660 descriptionContainer
.append( $( '<div>' )
1662 .append( Util
.parseHTML( tmp
.join( ' ' ) ) )
1666 if ( 'maxbytes' in pi
.parameters
[ i
] ) {
1667 descriptionContainer
.append( $( '<div>' )
1669 .append( Util
.parseMsg( 'api-help-param-maxbytes', pi
.parameters
[ i
].maxbytes
) )
1672 if ( 'maxchars' in pi
.parameters
[ i
] ) {
1673 descriptionContainer
.append( $( '<div>' )
1675 .append( Util
.parseMsg( 'api-help-param-maxchars', pi
.parameters
[ i
].maxchars
) )
1678 helpField
= new OO
.ui
.FieldLayout(
1681 classes
: [ 'mw-apisandbox-spacer' ]
1684 classes
: [ 'mw-apisandbox-help-field' ],
1685 label
: descriptionContainer
1691 classes
: [ 'mw-apisandbox-widget-field' ],
1692 label
: prefix
+ pi
.parameters
[ i
].name
1695 if ( pi
.parameters
[ i
].tokentype
) {
1696 button
= new OO
.ui
.ButtonWidget( {
1697 label
: mw
.message( 'apisandbox-fetch-token' ).text()
1699 button
.on( 'click', widget
.fetchToken
, [], widget
);
1701 widgetField
= new OO
.ui
.ActionFieldLayout( widget
, button
, layoutConfig
);
1703 widgetField
= new OO
.ui
.FieldLayout( widget
, layoutConfig
);
1706 // We need our own click handler on the widget label to
1707 // turn off the disablement.
1708 widgetField
.$label
.on( 'click', widgetLabelOnClick
.bind( widgetField
) );
1710 // Don't grey out the label when the field is disabled,
1711 // it makes it too hard to read and our "disabled"
1712 // isn't really disabled.
1713 widgetField
.onFieldDisable( false );
1714 widgetField
.onFieldDisable
= $.noop
;
1716 if ( Util
.apiBool( pi
.parameters
[ i
].deprecated
) ) {
1717 deprecatedItems
.push( widgetField
, helpField
);
1719 items
.push( widgetField
, helpField
);
1724 if ( !pi
.parameters
.length
&& !Util
.apiBool( pi
.dynamicparameters
) ) {
1725 items
.push( new OO
.ui
.FieldLayout(
1726 new OO
.ui
.Widget( {} ).toggle( false ), {
1728 label
: Util
.parseMsg( 'apisandbox-no-parameters' )
1733 that
.$element
.empty();
1735 new OO
.ui
.FieldsetLayout( {
1736 label
: that
.displayText
1737 } ).addItems( items
)
1738 .$element
.appendTo( that
.$element
);
1740 if ( Util
.apiBool( pi
.dynamicparameters
) ) {
1741 dynamicFieldset
= new OO
.ui
.FieldsetLayout();
1742 dynamicParamNameWidget
= new OO
.ui
.TextInputWidget( {
1743 placeholder
: mw
.message( 'apisandbox-dynamic-parameters-add-placeholder' ).text()
1744 } ).on( 'enter', addDynamicParamWidget
);
1745 dynamicFieldset
.addItems( [
1746 new OO
.ui
.FieldLayout(
1747 new OO
.ui
.Widget( {} ).toggle( false ), {
1749 label
: Util
.parseHTML( pi
.dynamicparameters
)
1752 new OO
.ui
.ActionFieldLayout(
1753 dynamicParamNameWidget
,
1754 new OO
.ui
.ButtonWidget( {
1756 flags
: 'progressive'
1757 } ).on( 'click', addDynamicParamWidget
),
1759 label
: mw
.message( 'apisandbox-dynamic-parameters-add-label' ).text(),
1766 $( '<legend>' ).text( mw
.message( 'apisandbox-dynamic-parameters' ).text() ),
1767 dynamicFieldset
.$element
1769 .appendTo( that
.$element
);
1772 if ( deprecatedItems
.length
) {
1773 tmp
= new OO
.ui
.FieldsetLayout().addItems( deprecatedItems
).toggle( false );
1776 $( '<legend>' ).append(
1777 new OO
.ui
.ToggleButtonWidget( {
1778 label
: mw
.message( 'apisandbox-deprecated-parameters' ).text()
1779 } ).on( 'change', tmp
.toggle
, [], tmp
).$element
1783 .appendTo( that
.$element
);
1786 // Load stored params, if any, then update the booklet if we
1787 // have subpages (or else just update our valid-indicator).
1788 tmp
= that
.loadFromQueryParams
;
1789 that
.loadFromQueryParams
= null;
1790 if ( $.isPlainObject( tmp
) ) {
1791 that
.loadQueryParams( tmp
);
1793 if ( that
.getSubpages().length
> 0 ) {
1794 ApiSandbox
.updateUI( tmp
);
1796 that
.apiCheckValid();
1798 } ).fail( function ( code
, detail
) {
1799 that
.$element
.empty()
1801 new OO
.ui
.LabelWidget( {
1802 label
: mw
.message( 'apisandbox-load-error', that
.apiModule
, detail
).text(),
1803 classes
: [ 'error' ]
1805 new OO
.ui
.ButtonWidget( {
1806 label
: mw
.message( 'apisandbox-retry' ).text()
1807 } ).on( 'click', that
.loadParamInfo
, [], that
).$element
1813 * Check that all widgets on the page are in a valid state.
1817 ApiSandbox
.PageLayout
.prototype.apiCheckValid = function () {
1820 if ( this.paramInfo
=== null ) {
1821 return $.Deferred().resolve( false ).promise();
1823 return $.when
.apply( $, $.map( this.widgets
, function ( widget
) {
1824 return widget
.apiCheckValid();
1825 } ) ).then( function () {
1826 that
.apiIsValid
= $.inArray( false, arguments
) === -1;
1827 if ( that
.getOutlineItem() ) {
1828 that
.getOutlineItem().setIcon( that
.apiIsValid
|| suppressErrors
? null : 'alert' );
1829 that
.getOutlineItem().setIconTitle(
1830 that
.apiIsValid
|| suppressErrors
? '' : mw
.message( 'apisandbox-alert-page' ).plain()
1833 return $.Deferred().resolve( that
.apiIsValid
).promise();
1839 * Load form fields from query parameters
1841 * @param {Object} params
1843 ApiSandbox
.PageLayout
.prototype.loadQueryParams = function ( params
) {
1844 if ( this.paramInfo
=== null ) {
1845 this.loadFromQueryParams
= params
;
1847 $.each( this.widgets
, function ( name
, widget
) {
1848 var v
= params
.hasOwnProperty( name
) ? params
[ name
] : undefined;
1849 widget
.setApiValue( v
);
1855 * Load query params from form fields
1857 * @param {Object} params Write query parameters into this object
1858 * @param {Object} displayParams Write query parameters for display into this object
1860 ApiSandbox
.PageLayout
.prototype.getQueryParams = function ( params
, displayParams
) {
1861 $.each( this.widgets
, function ( name
, widget
) {
1862 var value
= widget
.getApiValue();
1863 if ( value
!== undefined ) {
1864 params
[ name
] = value
;
1865 if ( $.isFunction( widget
.getApiValueForDisplay
) ) {
1866 value
= widget
.getApiValueForDisplay();
1868 displayParams
[ name
] = value
;
1874 * Fetch a list of subpage names loaded by this page
1878 ApiSandbox
.PageLayout
.prototype.getSubpages = function () {
1880 $.each( this.widgets
, function ( name
, widget
) {
1882 if ( $.isFunction( widget
.getSubmodules
) ) {
1883 submodules
= widget
.getSubmodules();
1884 for ( i
= 0; i
< submodules
.length
; i
++ ) {
1886 key
: name
+ '=' + submodules
[ i
].value
,
1887 path
: submodules
[ i
].path
,
1888 prefix
: widget
.paramInfo
.submoduleparamprefix
|| ''
1896 $( ApiSandbox
.init
);
1898 module
.exports
= ApiSandbox
;
1900 }( jQuery
, mediaWiki
, OO
) );