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
, $content
, func
,
388 multiModeButton
= null,
389 multiModeInput
= null,
390 multiModeAllowed
= false;
396 widget
= new OO
.ui
.ToggleSwitchWidget();
397 widget
.paramInfo
= pi
;
398 $.extend( widget
, WidgetMethods
.toggleSwitchWidget
);
399 pi
.required
= true; // Avoid wrapping in the non-required widget
404 if ( Util
.apiBool( pi
.multi
) ) {
405 widget
= new OO
.ui
.TagMultiselectWidget( {
406 allowArbitrary
: true,
407 allowDuplicates
: Util
.apiBool( pi
.allowsduplicates
),
410 widget
.paramInfo
= pi
;
411 $.extend( widget
, WidgetMethods
.tagWidget
);
413 widget
= new OO
.ui
.TextInputWidget( {
414 required
: Util
.apiBool( pi
.required
)
417 if ( !Util
.apiBool( pi
.multi
) ) {
418 widget
.paramInfo
= pi
;
419 $.extend( widget
, WidgetMethods
.textInputWidget
);
420 widget
.setValidation( Validators
.generic
);
422 if ( pi
.tokentype
) {
423 widget
.paramInfo
= pi
;
424 $.extend( widget
, WidgetMethods
.textInputWidget
);
425 $.extend( widget
, WidgetMethods
.tokenWidget
);
430 widget
= new OO
.ui
.MultilineTextInputWidget( {
431 required
: Util
.apiBool( pi
.required
)
433 widget
.paramInfo
= pi
;
434 $.extend( widget
, WidgetMethods
.textInputWidget
);
435 widget
.setValidation( Validators
.generic
);
439 widget
= new OO
.ui
.TextInputWidget( {
441 required
: Util
.apiBool( pi
.required
)
443 widget
.paramInfo
= pi
;
444 $.extend( widget
, WidgetMethods
.textInputWidget
);
445 $.extend( widget
, WidgetMethods
.passwordWidget
);
446 widget
.setValidation( Validators
.generic
);
447 multiModeAllowed
= true;
448 multiModeInput
= widget
;
452 widget
= new OO
.ui
.NumberInputWidget( {
453 required
: Util
.apiBool( pi
.required
),
456 widget
.setIcon
= widget
.input
.setIcon
.bind( widget
.input
);
457 widget
.setIconTitle
= widget
.input
.setIconTitle
.bind( widget
.input
);
458 widget
.getValidity
= widget
.input
.getValidity
.bind( widget
.input
);
459 widget
.paramInfo
= pi
;
460 $.extend( widget
, WidgetMethods
.textInputWidget
);
461 if ( Util
.apiBool( pi
.enforcerange
) ) {
462 widget
.setRange( pi
.min
|| -Infinity
, pi
.max
|| Infinity
);
464 multiModeAllowed
= true;
465 multiModeInput
= widget
;
469 widget
= new OO
.ui
.TextInputWidget( {
470 required
: Util
.apiBool( pi
.required
)
472 widget
.setValidation( function ( value
) {
473 var n
, pi
= this.paramInfo
;
475 if ( value
=== 'max' ) {
479 return !isNaN( n
) && isFinite( n
) &&
480 Math
.floor( n
) === n
&&
481 n
>= pi
.min
&& n
<= pi
.apiSandboxMax
;
484 pi
.min
= pi
.min
|| 0;
485 pi
.apiSandboxMax
= mw
.config
.get( 'apihighlimits' ) ? pi
.highmax
: pi
.max
;
486 widget
.paramInfo
= pi
;
487 $.extend( widget
, WidgetMethods
.textInputWidget
);
488 multiModeAllowed
= true;
489 multiModeInput
= widget
;
493 widget
= new mw
.widgets
.datetime
.DateTimeInputWidget( {
495 format
: '${year|0}-${month|0}-${day|0}T${hour|0}:${minute|0}:${second|0}${zone|short}'
497 required
: Util
.apiBool( pi
.required
),
500 widget
.paramInfo
= pi
;
501 $.extend( widget
, WidgetMethods
.textInputWidget
);
502 $.extend( widget
, WidgetMethods
.dateTimeInputWidget
);
503 multiModeAllowed
= true;
507 widget
= new OO
.ui
.SelectFileWidget();
508 widget
.paramInfo
= pi
;
509 $.extend( widget
, WidgetMethods
.uploadWidget
);
513 items
= $.map( mw
.config
.get( 'wgFormattedNamespaces' ), function ( name
, ns
) {
515 name
= mw
.message( 'blanknamespace' ).text();
517 return new OO
.ui
.MenuOptionWidget( { data
: ns
, label
: name
} );
518 } ).sort( function ( a
, b
) {
519 return a
.data
- b
.data
;
521 if ( Util
.apiBool( pi
.multi
) ) {
522 if ( pi
.allspecifier
!== undefined ) {
523 items
.unshift( new OO
.ui
.MenuOptionWidget( {
524 data
: pi
.allspecifier
,
525 label
: mw
.message( 'apisandbox-multivalue-all-namespaces', pi
.allspecifier
).text()
529 widget
= new OO
.ui
.MenuTagMultiselectWidget( {
530 menu
: { items
: items
},
533 widget
.paramInfo
= pi
;
534 $.extend( widget
, WidgetMethods
.tagWidget
);
536 widget
= new OO
.ui
.DropdownWidget( {
537 menu
: { items
: items
},
540 widget
.paramInfo
= pi
;
541 $.extend( widget
, WidgetMethods
.dropdownWidget
);
546 if ( !Array
.isArray( pi
.type
) ) {
547 throw new Error( 'Unknown parameter type ' + pi
.type
);
550 items
= pi
.type
.map( function ( v
) {
556 if ( pi
.deprecatedvalues
&& pi
.deprecatedvalues
.indexOf( v
) >= 0 ) {
557 config
.classes
.push( 'apihelp-deprecated-value' );
559 return new OO
.ui
.MenuOptionWidget( config
);
561 if ( Util
.apiBool( pi
.multi
) ) {
562 if ( pi
.allspecifier
!== undefined ) {
563 items
.unshift( new OO
.ui
.MenuOptionWidget( {
564 data
: pi
.allspecifier
,
565 label
: mw
.message( 'apisandbox-multivalue-all-values', pi
.allspecifier
).text()
569 widget
= new OO
.ui
.MenuTagMultiselectWidget( {
570 menu
: { items
: items
},
573 widget
.paramInfo
= pi
;
574 $.extend( widget
, WidgetMethods
.tagWidget
);
575 if ( Util
.apiBool( pi
.submodules
) ) {
576 widget
.getSubmodules
= WidgetMethods
.submoduleWidget
.multi
;
577 widget
.on( 'change', ApiSandbox
.updateUI
);
580 widget
= new OO
.ui
.DropdownWidget( {
581 menu
: { items
: items
},
584 widget
.paramInfo
= pi
;
585 $.extend( widget
, WidgetMethods
.dropdownWidget
);
586 if ( Util
.apiBool( pi
.submodules
) ) {
587 widget
.getSubmodules
= WidgetMethods
.submoduleWidget
.single
;
588 widget
.getMenu().on( 'select', ApiSandbox
.updateUI
);
590 if ( pi
.deprecatedvalues
) {
591 widget
.getMenu().on( 'select', function ( item
) {
592 this.$element
.toggleClass(
593 'apihelp-deprecated-value',
594 pi
.deprecatedvalues
.indexOf( item
.data
) >= 0
603 if ( Util
.apiBool( pi
.multi
) && multiModeAllowed
) {
604 innerWidget
= widget
;
606 multiModeButton
= new OO
.ui
.ButtonWidget( {
607 label
: mw
.message( 'apisandbox-add-multi' ).text()
609 $content
= innerWidget
.$element
.add( multiModeButton
.$element
);
611 widget
= new OO
.ui
.PopupTagMultiselectWidget( {
612 allowArbitrary
: true,
613 allowDuplicates
: Util
.apiBool( pi
.allowsduplicates
),
616 classes
: [ 'mw-apisandbox-popup' ],
621 widget
.paramInfo
= pi
;
622 $.extend( widget
, WidgetMethods
.tagWidget
);
625 if ( !innerWidget
.isDisabled() ) {
626 innerWidget
.apiCheckValid().done( function ( ok
) {
628 widget
.addTag( innerWidget
.getApiValue() );
629 innerWidget
.setApiValue( undefined );
636 if ( multiModeInput
) {
637 multiModeInput
.on( 'enter', func
);
639 multiModeButton
.on( 'click', func
);
642 if ( Util
.apiBool( pi
.required
) || opts
.nooptional
) {
643 finalWidget
= widget
;
645 finalWidget
= new OptionalWidget( widget
);
646 finalWidget
.paramInfo
= pi
;
647 $.extend( finalWidget
, WidgetMethods
.optionalWidget
);
648 if ( widget
.getSubmodules
) {
649 finalWidget
.getSubmodules
= widget
.getSubmodules
.bind( widget
);
650 finalWidget
.on( 'disable', function () { setTimeout( ApiSandbox
.updateUI
); } );
652 finalWidget
.setDisabled( true );
655 widget
.setApiValue( pi
[ 'default' ] );
661 * Parse an HTML string and call Util.fixupHTML()
663 * @param {string} html HTML to parse
666 parseHTML: function ( html
) {
667 var $ret
= $( $.parseHTML( html
) );
668 return Util
.fixupHTML( $ret
);
672 * Parse an i18n message and call Util.fixupHTML()
674 * @param {string} key Key of message to get
675 * @param {...Mixed} parameters Values for $N replacements
678 parseMsg: function () {
679 var $ret
= mw
.message
.apply( mw
.message
, arguments
).parseDom();
680 return Util
.fixupHTML( $ret
);
684 * Fix HTML for ApiSandbox display
687 * - Add target="_blank" to any links
689 * @param {jQuery} $html DOM to process
692 fixupHTML: function ( $html
) {
693 $html
.filter( 'a' ).add( $html
.find( 'a' ) )
694 .filter( '[href]:not([target])' )
695 .attr( 'target', '_blank' );
700 * Format a request and return a bunch of menu option widgets
702 * @param {Object} displayParams Query parameters, sanitized for display.
703 * @param {Object} rawParams Query parameters. You should probably use displayParams instead.
704 * @return {OO.ui.MenuOptionWidget[]} Each item's data should be an OO.ui.FieldLayout
706 formatRequest: function ( displayParams
, rawParams
) {
709 new OO
.ui
.MenuOptionWidget( {
710 label
: Util
.parseMsg( 'apisandbox-request-format-url-label' ),
711 data
: new OO
.ui
.FieldLayout(
712 new OO
.ui
.TextInputWidget( {
714 value
: mw
.util
.wikiScript( 'api' ) + '?' + $.param( displayParams
)
716 label
: Util
.parseMsg( 'apisandbox-request-url-label' )
720 new OO
.ui
.MenuOptionWidget( {
721 label
: Util
.parseMsg( 'apisandbox-request-format-json-label' ),
722 data
: new OO
.ui
.FieldLayout(
723 jsonInput
= new OO
.ui
.MultilineTextInputWidget( {
724 classes
: [ 'mw-apisandbox-textInputCode' ],
728 value
: JSON
.stringify( displayParams
, null, '\t' )
730 label
: Util
.parseMsg( 'apisandbox-request-json-label' )
732 ).on( 'toggle', function ( visible
) {
734 // Call updatePosition instead of adjustSize
735 // because the latter has weird caching
736 // behavior and the former bypasses it.
737 jsonInput
.updatePosition();
743 mw
.hook( 'apisandbox.formatRequest' ).fire( items
, displayParams
, rawParams
);
749 * Event handler for when formatDropdown's selection changes
751 onFormatDropdownChange: function () {
753 menu
= formatDropdown
.getMenu(),
754 items
= menu
.getItems(),
755 selectedField
= menu
.findSelectedItem() ? menu
.findSelectedItem().getData() : null;
757 for ( i
= 0; i
< items
.length
; i
++ ) {
758 items
[ i
].getData().toggle( items
[ i
].getData() === selectedField
);
764 * Interface to ApiSandbox UI
766 * @class mw.special.ApiSandbox
772 * Automatically called on $.ready()
777 ApiSandbox
.isFullscreen
= false;
779 $content
= $( '#mw-apisandbox' );
781 windowManager
= new OO
.ui
.WindowManager();
782 $( 'body' ).append( windowManager
.$element
);
783 windowManager
.addWindows( {
784 errorAlert
: new OO
.ui
.MessageDialog()
787 fullscreenButton
= new OO
.ui
.ButtonWidget( {
788 label
: mw
.message( 'apisandbox-fullscreen' ).text(),
789 title
: mw
.message( 'apisandbox-fullscreen-tooltip' ).text()
790 } ).on( 'click', ApiSandbox
.toggleFullscreen
);
792 $toolbar
= $( '<div>' )
793 .addClass( 'mw-apisandbox-toolbar' )
795 fullscreenButton
.$element
,
796 new OO
.ui
.ButtonWidget( {
797 label
: mw
.message( 'apisandbox-submit' ).text(),
798 flags
: [ 'primary', 'progressive' ]
799 } ).on( 'click', ApiSandbox
.sendRequest
).$element
,
800 new OO
.ui
.ButtonWidget( {
801 label
: mw
.message( 'apisandbox-reset' ).text(),
803 } ).on( 'click', ApiSandbox
.resetUI
).$element
806 booklet
= new OO
.ui
.BookletLayout( {
811 panel
= new OO
.ui
.PanelLayout( {
812 classes
: [ 'mw-apisandbox-container' ],
813 content
: [ booklet
],
818 pages
.main
= new ApiSandbox
.PageLayout( { key
: 'main', path
: 'main' } );
820 // Parse the current hash string
821 if ( !ApiSandbox
.loadFromHash() ) {
822 ApiSandbox
.updateUI();
825 // If the hashchange event exists, use it. Otherwise, fake it.
826 // And, of course, IE has to be dumb.
827 if ( 'onhashchange' in window
&&
828 ( document
.documentMode
=== undefined || document
.documentMode
>= 8 )
830 $( window
).on( 'hashchange', ApiSandbox
.loadFromHash
);
832 setInterval( function () {
833 if ( oldhash
!== location
.hash
) {
834 ApiSandbox
.loadFromHash();
841 .append( $( '<p>' ).append( Util
.parseMsg( 'apisandbox-intro' ) ) )
843 $( '<div>' ).attr( 'id', 'mw-apisandbox-ui' )
845 .append( panel
.$element
)
848 $( window
).on( 'resize', ApiSandbox
.resizePanel
);
850 ApiSandbox
.resizePanel();
854 * Toggle "fullscreen" mode
856 toggleFullscreen: function () {
857 var $body
= $( document
.body
),
858 $ui
= $( '#mw-apisandbox-ui' );
860 ApiSandbox
.isFullscreen
= !ApiSandbox
.isFullscreen
;
862 $body
.toggleClass( 'mw-apisandbox-fullscreen', ApiSandbox
.isFullscreen
);
863 $ui
.toggleClass( 'mw-body-content', ApiSandbox
.isFullscreen
);
864 if ( ApiSandbox
.isFullscreen
) {
865 fullscreenButton
.setLabel( mw
.message( 'apisandbox-unfullscreen' ).text() );
866 fullscreenButton
.setTitle( mw
.message( 'apisandbox-unfullscreen-tooltip' ).text() );
867 OO
.ui
.getDefaultOverlay().prepend( $ui
);
869 fullscreenButton
.setLabel( mw
.message( 'apisandbox-fullscreen' ).text() );
870 fullscreenButton
.setTitle( mw
.message( 'apisandbox-fullscreen-tooltip' ).text() );
871 $content
.append( $ui
);
873 ApiSandbox
.resizePanel();
877 * Set the height of the panel based on the current viewport.
879 resizePanel: function () {
880 var height
= $( window
).height(),
881 contentTop
= $content
.offset().top
;
883 if ( ApiSandbox
.isFullscreen
) {
884 height
-= panel
.$element
.offset().top
- $( '#mw-apisandbox-ui' ).offset().top
;
885 panel
.$element
.height( height
- 1 );
887 // Subtract the height of the intro text
888 height
-= panel
.$element
.offset().top
- contentTop
;
890 panel
.$element
.height( height
- 10 );
891 $( window
).scrollTop( contentTop
- 5 );
896 * Update the current query when the page hash changes
898 * @return {boolean} Successful
900 loadFromHash: function () {
902 hash
= location
.hash
;
904 if ( oldhash
=== hash
) {
912 // I'm surprised this doesn't seem to exist in jQuery or mw.util.
914 hash
= hash
.replace( /\+/g, '%20' );
915 re
= /([^&=#]+)=?([^&#]*)/g;
916 while ( ( m
= re
.exec( hash
) ) ) {
917 params
[ decodeURIComponent( m
[ 1 ] ) ] = decodeURIComponent( m
[ 2 ] );
920 ApiSandbox
.updateUI( params
);
925 * Update the pages in the booklet
927 * @param {Object} [params] Optional query parameters to load
929 updateUI: function ( params
) {
930 var i
, page
, subpages
, j
, removePages
,
933 if ( !$.isPlainObject( params
) ) {
937 if ( updatingBooklet
) {
940 updatingBooklet
= true;
942 if ( params
!== undefined ) {
943 pages
.main
.loadQueryParams( params
);
945 addPages
.push( pages
.main
);
946 if ( resultPage
!== null ) {
947 addPages
.push( resultPage
);
949 pages
.main
.apiCheckValid();
952 while ( addPages
.length
) {
953 page
= addPages
.shift();
954 if ( bookletPages
[ i
] !== page
) {
955 for ( j
= i
; j
< bookletPages
.length
; j
++ ) {
956 if ( bookletPages
[ j
].getName() === page
.getName() ) {
957 bookletPages
.splice( j
, 1 );
960 bookletPages
.splice( i
, 0, page
);
961 booklet
.addPages( [ page
], i
);
965 if ( page
.getSubpages
) {
966 subpages
= page
.getSubpages();
967 for ( j
= 0; j
< subpages
.length
; j
++ ) {
968 if ( !pages
.hasOwnProperty( subpages
[ j
].key
) ) {
969 subpages
[ j
].indentLevel
= page
.indentLevel
+ 1;
970 pages
[ subpages
[ j
].key
] = new ApiSandbox
.PageLayout( subpages
[ j
] );
972 if ( params
!== undefined ) {
973 pages
[ subpages
[ j
].key
].loadQueryParams( params
);
975 addPages
.splice( j
, 0, pages
[ subpages
[ j
].key
] );
976 pages
[ subpages
[ j
].key
].apiCheckValid();
981 if ( bookletPages
.length
> i
) {
982 removePages
= bookletPages
.splice( i
, bookletPages
.length
- i
);
983 booklet
.removePages( removePages
);
986 if ( !booklet
.getCurrentPageName() ) {
987 booklet
.selectFirstSelectablePage();
990 updatingBooklet
= false;
995 * Reset button handler
997 resetUI: function () {
998 suppressErrors
= true;
1000 main
: new ApiSandbox
.PageLayout( { key
: 'main', path
: 'main' } )
1003 ApiSandbox
.updateUI();
1007 * Submit button handler
1009 * @param {Object} [params] Use this set of params instead of those in the form fields.
1010 * The form fields will be updated to match.
1012 sendRequest: function ( params
) {
1013 var page
, subpages
, i
, query
, $result
, $focus
,
1014 progress
, $progressText
, progressLoading
,
1016 paramsAreForced
= !!params
,
1018 checkPages
= [ pages
.main
];
1020 // Blur any focused widget before submit, because
1021 // OO.ui.ButtonWidget doesn't take focus itself (T128054)
1022 $focus
= $( '#mw-apisandbox-ui' ).find( document
.activeElement
);
1023 if ( $focus
.length
) {
1027 suppressErrors
= false;
1029 // save widget state in params (or load from it if we are forced)
1030 if ( paramsAreForced
) {
1031 ApiSandbox
.updateUI( params
);
1034 while ( checkPages
.length
) {
1035 page
= checkPages
.shift();
1036 deferreds
.push( page
.apiCheckValid() );
1037 page
.getQueryParams( params
, displayParams
);
1038 subpages
= page
.getSubpages();
1039 for ( i
= 0; i
< subpages
.length
; i
++ ) {
1040 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
1041 checkPages
.push( pages
[ subpages
[ i
].key
] );
1046 if ( !paramsAreForced
) {
1047 // forced params means we are continuing a query; the base query should be preserved
1048 baseRequestParams
= $.extend( {}, params
);
1051 $.when
.apply( $, deferreds
).done( function () {
1052 var formatItems
, menu
, selectedLabel
;
1054 if ( $.inArray( false, arguments
) !== -1 ) {
1055 windowManager
.openWindow( 'errorAlert', {
1056 title
: Util
.parseMsg( 'apisandbox-submit-invalid-fields-title' ),
1057 message
: Util
.parseMsg( 'apisandbox-submit-invalid-fields-message' ),
1061 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' ),
1069 query
= $.param( displayParams
);
1071 formatItems
= Util
.formatRequest( displayParams
, params
);
1073 // Force a 'fm' format with wrappedhtml=1, if available
1074 if ( params
.format
!== undefined ) {
1075 if ( availableFormats
.hasOwnProperty( params
.format
+ 'fm' ) ) {
1076 params
.format
= params
.format
+ 'fm';
1078 if ( params
.format
.substr( -2 ) === 'fm' ) {
1079 params
.wrappedhtml
= 1;
1083 progressLoading
= false;
1084 $progressText
= $( '<span>' ).text( mw
.message( 'apisandbox-sending-request' ).text() );
1085 progress
= new OO
.ui
.ProgressBarWidget( {
1087 $content
: $progressText
1090 $result
= $( '<div>' )
1091 .append( progress
.$element
);
1093 resultPage
= page
= new OO
.ui
.PageLayout( '|results|' );
1094 page
.setupOutlineItem = function () {
1095 this.outlineItem
.setLabel( mw
.message( 'apisandbox-results' ).text() );
1098 if ( !formatDropdown
) {
1099 formatDropdown
= new OO
.ui
.DropdownWidget( {
1100 menu
: { items
: [] },
1103 formatDropdown
.getMenu().on( 'select', Util
.onFormatDropdownChange
);
1106 menu
= formatDropdown
.getMenu();
1107 selectedLabel
= menu
.findSelectedItem() ? menu
.findSelectedItem().getLabel() : '';
1108 if ( typeof selectedLabel
!== 'string' ) {
1109 selectedLabel
= selectedLabel
.text();
1111 menu
.clearItems().addItems( formatItems
);
1112 menu
.chooseItem( menu
.getItemFromLabel( selectedLabel
) || menu
.findFirstSelectableItem() );
1114 // Fire the event to update field visibilities
1115 Util
.onFormatDropdownChange();
1117 page
.$element
.empty()
1119 new OO
.ui
.FieldLayout(
1121 label
: Util
.parseMsg( 'apisandbox-request-selectformat-label' )
1124 formatItems
.map( function ( item
) {
1125 return item
.getData().$element
;
1129 ApiSandbox
.updateUI();
1130 booklet
.setPage( '|results|' );
1132 location
.href
= oldhash
= '#' + query
;
1135 contentType
: 'multipart/form-data',
1138 var xhr
= new window
.XMLHttpRequest();
1139 xhr
.upload
.addEventListener( 'progress', function ( e
) {
1140 if ( !progressLoading
) {
1141 if ( e
.lengthComputable
) {
1142 progress
.setProgress( e
.loaded
* 100 / e
.total
);
1144 progress
.setProgress( false );
1148 xhr
.addEventListener( 'progress', function ( e
) {
1149 if ( !progressLoading
) {
1150 progressLoading
= true;
1151 $progressText
.text( mw
.message( 'apisandbox-loading-results' ).text() );
1153 if ( e
.lengthComputable
) {
1154 progress
.setProgress( e
.loaded
* 100 / e
.total
);
1156 progress
.setProgress( false );
1162 .catch( function ( code
, data
, result
, jqXHR
) {
1163 var deferred
= $.Deferred();
1165 if ( code
!== 'http' ) {
1166 // Not really an error, work around mw.Api thinking it is.
1167 deferred
.resolve( result
, jqXHR
);
1170 deferred
.reject
.apply( deferred
, arguments
);
1172 return deferred
.promise();
1174 .then( function ( data
, jqXHR
) {
1175 var m
, loadTime
, button
, clear
,
1176 ct
= jqXHR
.getResponseHeader( 'Content-Type' ),
1177 loginSuppressed
= jqXHR
.getResponseHeader( 'MediaWiki-Login-Suppressed' ) || 'false';
1180 if ( loginSuppressed
!== 'false' ) {
1182 .addClass( 'warning' )
1183 .append( Util
.parseMsg( 'apisandbox-results-login-suppressed' ) )
1184 .appendTo( $result
);
1186 if ( /^text\/mediawiki-api-prettyprint-wrapped(?:;|$)/.test( ct
) ) {
1187 data
= JSON
.parse( data
);
1188 if ( data
.modules
.length
) {
1189 mw
.loader
.load( data
.modules
);
1191 if ( data
.status
&& data
.status
!== 200 ) {
1193 .addClass( 'api-pretty-header api-pretty-status' )
1194 .append( Util
.parseMsg( 'api-format-prettyprint-status', data
.status
, data
.statustext
) )
1195 .appendTo( $result
);
1197 $result
.append( Util
.parseHTML( data
.html
) );
1198 loadTime
= data
.time
;
1199 } else if ( ( m
= data
.match( /<pre[ >][\s\S]*<\/pre>/ ) ) ) {
1200 $result
.append( Util
.parseHTML( m
[ 0 ] ) );
1201 if ( ( m
= data
.match( /"wgBackendResponseTime":\s*(\d+)/ ) ) ) {
1202 loadTime
= parseInt( m
[ 1 ], 10 );
1206 .addClass( 'api-pretty-content' )
1208 .appendTo( $result
);
1210 if ( paramsAreForced
|| data
[ 'continue' ] ) {
1212 $( '<div>' ).append(
1213 new OO
.ui
.ButtonWidget( {
1214 label
: mw
.message( 'apisandbox-continue' ).text()
1215 } ).on( 'click', function () {
1216 ApiSandbox
.sendRequest( $.extend( {}, baseRequestParams
, data
[ 'continue' ] ) );
1217 } ).setDisabled( !data
[ 'continue' ] ).$element
,
1218 ( clear
= new OO
.ui
.ButtonWidget( {
1219 label
: mw
.message( 'apisandbox-continue-clear' ).text()
1220 } ).on( 'click', function () {
1221 ApiSandbox
.updateUI( baseRequestParams
);
1222 clear
.setDisabled( true );
1223 booklet
.setPage( '|results|' );
1224 } ).setDisabled( !paramsAreForced
) ).$element
,
1225 new OO
.ui
.PopupButtonWidget( {
1230 $content
: $( '<div>' ).append( Util
.parseMsg( 'apisandbox-continue-help' ) ),
1238 if ( typeof loadTime
=== 'number' ) {
1240 $( '<div>' ).append(
1241 new OO
.ui
.LabelWidget( {
1242 label
: mw
.message( 'apisandbox-request-time', loadTime
).text()
1248 if ( jqXHR
.getResponseHeader( 'MediaWiki-API-Error' ) === 'badtoken' ) {
1249 // Flush all saved tokens in case one of them is the bad one.
1250 Util
.markTokensBad();
1251 button
= new OO
.ui
.ButtonWidget( {
1252 label
: mw
.message( 'apisandbox-results-fixtoken' ).text()
1254 button
.on( 'click', ApiSandbox
.fixTokenAndResend
)
1255 .on( 'click', button
.setDisabled
, [ true ], button
)
1256 .$element
.appendTo( $result
);
1258 }, function ( code
, data
) {
1259 var details
= 'HTTP error: ' + data
.exception
;
1262 new OO
.ui
.LabelWidget( {
1263 label
: mw
.message( 'apisandbox-results-error', details
).text(),
1264 classes
: [ 'error' ]
1272 * Handler for the "Correct token and resubmit" button
1274 * Used on a 'badtoken' error, it re-fetches token parameters for all
1275 * pages and then re-submits the query.
1277 fixTokenAndResend: function () {
1278 var page
, subpages
, i
, k
,
1280 tokenWait
= { dummy
: true },
1281 checkPages
= [ pages
.main
],
1282 success = function ( k
) {
1283 delete tokenWait
[ k
];
1284 if ( ok
&& $.isEmptyObject( tokenWait
) ) {
1285 ApiSandbox
.sendRequest();
1288 failure = function ( k
) {
1289 delete tokenWait
[ k
];
1293 while ( checkPages
.length
) {
1294 page
= checkPages
.shift();
1296 if ( page
.tokenWidget
) {
1297 k
= page
.apiModule
+ page
.tokenWidget
.paramInfo
.name
;
1298 tokenWait
[ k
] = page
.tokenWidget
.fetchToken();
1300 .done( success
.bind( page
.tokenWidget
, k
) )
1301 .fail( failure
.bind( page
.tokenWidget
, k
) );
1304 subpages
= page
.getSubpages();
1305 for ( i
= 0; i
< subpages
.length
; i
++ ) {
1306 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
1307 checkPages
.push( pages
[ subpages
[ i
].key
] );
1312 success( 'dummy', '' );
1316 * Reset validity indicators for all widgets
1318 updateValidityIndicators: function () {
1319 var page
, subpages
, i
,
1320 checkPages
= [ pages
.main
];
1322 while ( checkPages
.length
) {
1323 page
= checkPages
.shift();
1324 page
.apiCheckValid();
1325 subpages
= page
.getSubpages();
1326 for ( i
= 0; i
< subpages
.length
; i
++ ) {
1327 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
1328 checkPages
.push( pages
[ subpages
[ i
].key
] );
1336 * PageLayout for API modules
1340 * @extends OO.ui.PageLayout
1342 * @param {Object} [config] Configuration options
1344 ApiSandbox
.PageLayout = function ( config
) {
1345 config
= $.extend( { prefix
: '' }, config
);
1346 this.displayText
= config
.key
;
1347 this.apiModule
= config
.path
;
1348 this.prefix
= config
.prefix
;
1349 this.paramInfo
= null;
1350 this.apiIsValid
= true;
1351 this.loadFromQueryParams
= null;
1353 this.tokenWidget
= null;
1354 this.indentLevel
= config
.indentLevel
? config
.indentLevel
: 0;
1355 ApiSandbox
.PageLayout
[ 'super' ].call( this, config
.key
, config
);
1356 this.loadParamInfo();
1358 OO
.inheritClass( ApiSandbox
.PageLayout
, OO
.ui
.PageLayout
);
1359 ApiSandbox
.PageLayout
.prototype.setupOutlineItem = function () {
1360 this.outlineItem
.setLevel( this.indentLevel
);
1361 this.outlineItem
.setLabel( this.displayText
);
1362 this.outlineItem
.setIcon( this.apiIsValid
|| suppressErrors
? null : 'alert' );
1363 this.outlineItem
.setIconTitle(
1364 this.apiIsValid
|| suppressErrors
? '' : mw
.message( 'apisandbox-alert-page' ).plain()
1369 * Fetch module information for this page's module, then create UI
1371 ApiSandbox
.PageLayout
.prototype.loadParamInfo = function () {
1372 var dynamicFieldset
, dynamicParamNameWidget
,
1374 removeDynamicParamWidget = function ( name
, layout
) {
1375 dynamicFieldset
.removeItems( [ layout
] );
1376 delete that
.widgets
[ name
];
1378 addDynamicParamWidget = function () {
1379 var name
, layout
, widget
, button
;
1381 // Check name is filled in
1382 name
= dynamicParamNameWidget
.getValue().trim();
1383 if ( name
=== '' ) {
1384 dynamicParamNameWidget
.focus();
1388 if ( that
.widgets
[ name
] !== undefined ) {
1389 windowManager
.openWindow( 'errorAlert', {
1390 title
: Util
.parseMsg( 'apisandbox-dynamic-error-exists', name
),
1394 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' ),
1402 widget
= Util
.createWidgetForParameter( {
1409 button
= new OO
.ui
.ButtonWidget( {
1411 flags
: 'destructive'
1413 layout
= new OO
.ui
.ActionFieldLayout(
1421 button
.on( 'click', removeDynamicParamWidget
, [ name
, layout
] );
1422 that
.widgets
[ name
] = widget
;
1423 dynamicFieldset
.addItems( [ layout
], dynamicFieldset
.getItems().length
- 1 );
1426 dynamicParamNameWidget
.setValue( '' );
1429 this.$element
.empty()
1430 .append( new OO
.ui
.ProgressBarWidget( {
1432 text
: mw
.message( 'apisandbox-loading', this.displayText
).text()
1435 Util
.fetchModuleInfo( this.apiModule
)
1436 .done( function ( pi
) {
1437 var prefix
, i
, j
, descriptionContainer
, widget
, layoutConfig
, button
, widgetField
, helpField
, tmp
, flag
, count
,
1439 deprecatedItems
= [],
1441 filterFmModules = function ( v
) {
1442 return v
.substr( -2 ) !== 'fm' ||
1443 !availableFormats
.hasOwnProperty( v
.substr( 0, v
.length
- 2 ) );
1445 widgetLabelOnClick = function () {
1446 var f
= this.getField();
1447 if ( $.isFunction( f
.setDisabled
) ) {
1448 f
.setDisabled( false );
1450 if ( $.isFunction( f
.focus
) ) {
1455 // This is something of a hack. We always want the 'format' and
1456 // 'action' parameters from the main module to be specified,
1457 // and for 'format' we also want to simplify the dropdown since
1458 // we always send the 'fm' variant.
1459 if ( that
.apiModule
=== 'main' ) {
1460 for ( i
= 0; i
< pi
.parameters
.length
; i
++ ) {
1461 if ( pi
.parameters
[ i
].name
=== 'action' ) {
1462 pi
.parameters
[ i
].required
= true;
1463 delete pi
.parameters
[ i
][ 'default' ];
1465 if ( pi
.parameters
[ i
].name
=== 'format' ) {
1466 tmp
= pi
.parameters
[ i
].type
;
1467 for ( j
= 0; j
< tmp
.length
; j
++ ) {
1468 availableFormats
[ tmp
[ j
] ] = true;
1470 pi
.parameters
[ i
].type
= tmp
.filter( filterFmModules
);
1471 pi
.parameters
[ i
][ 'default' ] = 'json';
1472 pi
.parameters
[ i
].required
= true;
1477 // Hide the 'wrappedhtml' parameter on format modules
1478 if ( pi
.group
=== 'format' ) {
1479 pi
.parameters
= pi
.parameters
.filter( function ( p
) {
1480 return p
.name
!== 'wrappedhtml';
1484 that
.paramInfo
= pi
;
1486 items
.push( new OO
.ui
.FieldLayout(
1487 new OO
.ui
.Widget( {} ).toggle( false ), {
1489 label
: Util
.parseHTML( pi
.description
)
1493 if ( pi
.helpurls
.length
) {
1494 buttons
.push( new OO
.ui
.PopupButtonWidget( {
1496 label
: mw
.message( 'apisandbox-helpurls' ).text(),
1501 $content
: $( '<ul>' ).append( pi
.helpurls
.map( function ( link
) {
1502 return $( '<li>' ).append( $( '<a>' )
1503 .attr( { href
: link
, target
: '_blank' } )
1511 if ( pi
.examples
.length
) {
1512 buttons
.push( new OO
.ui
.PopupButtonWidget( {
1514 label
: mw
.message( 'apisandbox-examples' ).text(),
1519 $content
: $( '<ul>' ).append( pi
.examples
.map( function ( example
) {
1521 .attr( 'href', '#' + example
.query
)
1522 .html( example
.description
);
1523 a
.find( 'a' ).contents().unwrap(); // Can't nest links
1524 return $( '<li>' ).append( a
);
1530 if ( buttons
.length
) {
1531 items
.push( new OO
.ui
.FieldLayout(
1532 new OO
.ui
.ButtonGroupWidget( {
1534 } ), { align
: 'top' }
1538 if ( pi
.parameters
.length
) {
1539 prefix
= that
.prefix
+ pi
.prefix
;
1540 for ( i
= 0; i
< pi
.parameters
.length
; i
++ ) {
1541 widget
= Util
.createWidgetForParameter( pi
.parameters
[ i
] );
1542 that
.widgets
[ prefix
+ pi
.parameters
[ i
].name
] = widget
;
1543 if ( pi
.parameters
[ i
].tokentype
) {
1544 that
.tokenWidget
= widget
;
1547 descriptionContainer
= $( '<div>' );
1549 tmp
= Util
.parseHTML( pi
.parameters
[ i
].description
);
1550 tmp
.filter( 'dl' ).makeCollapsible( {
1552 } ).children( '.mw-collapsible-toggle' ).each( function () {
1553 var $this = $( this );
1554 $this.parent().prev( 'p' ).append( $this );
1556 descriptionContainer
.append( $( '<div>' ).addClass( 'description' ).append( tmp
) );
1558 if ( pi
.parameters
[ i
].info
&& pi
.parameters
[ i
].info
.length
) {
1559 for ( j
= 0; j
< pi
.parameters
[ i
].info
.length
; j
++ ) {
1560 descriptionContainer
.append( $( '<div>' )
1562 .append( Util
.parseHTML( pi
.parameters
[ i
].info
[ j
] ) )
1568 switch ( pi
.parameters
[ i
].type
) {
1571 count
= mw
.config
.get( 'wgFormattedNamespaces' ).length
;
1575 if ( pi
.parameters
[ i
].highmax
!== undefined ) {
1576 descriptionContainer
.append( $( '<div>' )
1580 'api-help-param-limit2', pi
.parameters
[ i
].max
, pi
.parameters
[ i
].highmax
1583 Util
.parseMsg( 'apisandbox-param-limit' )
1587 descriptionContainer
.append( $( '<div>' )
1590 Util
.parseMsg( 'api-help-param-limit', pi
.parameters
[ i
].max
),
1592 Util
.parseMsg( 'apisandbox-param-limit' )
1600 if ( pi
.parameters
[ i
].min
!== undefined ) {
1603 if ( pi
.parameters
[ i
].max
!== undefined ) {
1607 descriptionContainer
.append( $( '<div>' )
1609 .append( Util
.parseMsg(
1610 'api-help-param-integer-' + tmp
,
1611 Util
.apiBool( pi
.parameters
[ i
].multi
) ? 2 : 1,
1612 pi
.parameters
[ i
].min
, pi
.parameters
[ i
].max
1619 if ( Array
.isArray( pi
.parameters
[ i
].type
) ) {
1621 count
= pi
.parameters
[ i
].type
.length
;
1625 if ( Util
.apiBool( pi
.parameters
[ i
].multi
) ) {
1627 if ( flag
&& !( widget
instanceof OO
.ui
.TagMultiselectWidget
) &&
1629 widget
instanceof OptionalWidget
&&
1630 widget
.widget
instanceof OO
.ui
.TagMultiselectWidget
1633 tmp
.push( mw
.message( 'api-help-param-multi-separate' ).parse() );
1635 if ( count
> pi
.parameters
[ i
].lowlimit
) {
1637 mw
.message( 'api-help-param-multi-max',
1638 pi
.parameters
[ i
].lowlimit
, pi
.parameters
[ i
].highlimit
1643 descriptionContainer
.append( $( '<div>' )
1645 .append( Util
.parseHTML( tmp
.join( ' ' ) ) )
1649 if ( 'maxbytes' in pi
.parameters
[ i
] ) {
1650 descriptionContainer
.append( $( '<div>' )
1652 .append( Util
.parseMsg( 'api-help-param-maxbytes', pi
.parameters
[ i
].maxbytes
) )
1655 if ( 'maxchars' in pi
.parameters
[ i
] ) {
1656 descriptionContainer
.append( $( '<div>' )
1658 .append( Util
.parseMsg( 'api-help-param-maxchars', pi
.parameters
[ i
].maxchars
) )
1661 helpField
= new OO
.ui
.FieldLayout(
1664 classes
: [ 'mw-apisandbox-spacer' ]
1667 classes
: [ 'mw-apisandbox-help-field' ],
1668 label
: descriptionContainer
1674 classes
: [ 'mw-apisandbox-widget-field' ],
1675 label
: prefix
+ pi
.parameters
[ i
].name
1678 if ( pi
.parameters
[ i
].tokentype
) {
1679 button
= new OO
.ui
.ButtonWidget( {
1680 label
: mw
.message( 'apisandbox-fetch-token' ).text()
1682 button
.on( 'click', widget
.fetchToken
, [], widget
);
1684 widgetField
= new OO
.ui
.ActionFieldLayout( widget
, button
, layoutConfig
);
1686 widgetField
= new OO
.ui
.FieldLayout( widget
, layoutConfig
);
1689 // We need our own click handler on the widget label to
1690 // turn off the disablement.
1691 widgetField
.$label
.on( 'click', widgetLabelOnClick
.bind( widgetField
) );
1693 // Don't grey out the label when the field is disabled,
1694 // it makes it too hard to read and our "disabled"
1695 // isn't really disabled.
1696 widgetField
.onFieldDisable( false );
1697 widgetField
.onFieldDisable
= $.noop
;
1699 if ( Util
.apiBool( pi
.parameters
[ i
].deprecated
) ) {
1700 deprecatedItems
.push( widgetField
, helpField
);
1702 items
.push( widgetField
, helpField
);
1707 if ( !pi
.parameters
.length
&& !Util
.apiBool( pi
.dynamicparameters
) ) {
1708 items
.push( new OO
.ui
.FieldLayout(
1709 new OO
.ui
.Widget( {} ).toggle( false ), {
1711 label
: Util
.parseMsg( 'apisandbox-no-parameters' )
1716 that
.$element
.empty();
1718 new OO
.ui
.FieldsetLayout( {
1719 label
: that
.displayText
1720 } ).addItems( items
)
1721 .$element
.appendTo( that
.$element
);
1723 if ( Util
.apiBool( pi
.dynamicparameters
) ) {
1724 dynamicFieldset
= new OO
.ui
.FieldsetLayout();
1725 dynamicParamNameWidget
= new OO
.ui
.TextInputWidget( {
1726 placeholder
: mw
.message( 'apisandbox-dynamic-parameters-add-placeholder' ).text()
1727 } ).on( 'enter', addDynamicParamWidget
);
1728 dynamicFieldset
.addItems( [
1729 new OO
.ui
.FieldLayout(
1730 new OO
.ui
.Widget( {} ).toggle( false ), {
1732 label
: Util
.parseHTML( pi
.dynamicparameters
)
1735 new OO
.ui
.ActionFieldLayout(
1736 dynamicParamNameWidget
,
1737 new OO
.ui
.ButtonWidget( {
1739 flags
: 'progressive'
1740 } ).on( 'click', addDynamicParamWidget
),
1742 label
: mw
.message( 'apisandbox-dynamic-parameters-add-label' ).text(),
1749 $( '<legend>' ).text( mw
.message( 'apisandbox-dynamic-parameters' ).text() ),
1750 dynamicFieldset
.$element
1752 .appendTo( that
.$element
);
1755 if ( deprecatedItems
.length
) {
1756 tmp
= new OO
.ui
.FieldsetLayout().addItems( deprecatedItems
).toggle( false );
1759 $( '<legend>' ).append(
1760 new OO
.ui
.ToggleButtonWidget( {
1761 label
: mw
.message( 'apisandbox-deprecated-parameters' ).text()
1762 } ).on( 'change', tmp
.toggle
, [], tmp
).$element
1766 .appendTo( that
.$element
);
1769 // Load stored params, if any, then update the booklet if we
1770 // have subpages (or else just update our valid-indicator).
1771 tmp
= that
.loadFromQueryParams
;
1772 that
.loadFromQueryParams
= null;
1773 if ( $.isPlainObject( tmp
) ) {
1774 that
.loadQueryParams( tmp
);
1776 if ( that
.getSubpages().length
> 0 ) {
1777 ApiSandbox
.updateUI( tmp
);
1779 that
.apiCheckValid();
1781 } ).fail( function ( code
, detail
) {
1782 that
.$element
.empty()
1784 new OO
.ui
.LabelWidget( {
1785 label
: mw
.message( 'apisandbox-load-error', that
.apiModule
, detail
).text(),
1786 classes
: [ 'error' ]
1788 new OO
.ui
.ButtonWidget( {
1789 label
: mw
.message( 'apisandbox-retry' ).text()
1790 } ).on( 'click', that
.loadParamInfo
, [], that
).$element
1796 * Check that all widgets on the page are in a valid state.
1800 ApiSandbox
.PageLayout
.prototype.apiCheckValid = function () {
1803 if ( this.paramInfo
=== null ) {
1804 return $.Deferred().resolve( false ).promise();
1806 return $.when
.apply( $, $.map( this.widgets
, function ( widget
) {
1807 return widget
.apiCheckValid();
1808 } ) ).then( function () {
1809 that
.apiIsValid
= $.inArray( false, arguments
) === -1;
1810 if ( that
.getOutlineItem() ) {
1811 that
.getOutlineItem().setIcon( that
.apiIsValid
|| suppressErrors
? null : 'alert' );
1812 that
.getOutlineItem().setIconTitle(
1813 that
.apiIsValid
|| suppressErrors
? '' : mw
.message( 'apisandbox-alert-page' ).plain()
1816 return $.Deferred().resolve( that
.apiIsValid
).promise();
1822 * Load form fields from query parameters
1824 * @param {Object} params
1826 ApiSandbox
.PageLayout
.prototype.loadQueryParams = function ( params
) {
1827 if ( this.paramInfo
=== null ) {
1828 this.loadFromQueryParams
= params
;
1830 $.each( this.widgets
, function ( name
, widget
) {
1831 var v
= params
.hasOwnProperty( name
) ? params
[ name
] : undefined;
1832 widget
.setApiValue( v
);
1838 * Load query params from form fields
1840 * @param {Object} params Write query parameters into this object
1841 * @param {Object} displayParams Write query parameters for display into this object
1843 ApiSandbox
.PageLayout
.prototype.getQueryParams = function ( params
, displayParams
) {
1844 $.each( this.widgets
, function ( name
, widget
) {
1845 var value
= widget
.getApiValue();
1846 if ( value
!== undefined ) {
1847 params
[ name
] = value
;
1848 if ( $.isFunction( widget
.getApiValueForDisplay
) ) {
1849 value
= widget
.getApiValueForDisplay();
1851 displayParams
[ name
] = value
;
1857 * Fetch a list of subpage names loaded by this page
1861 ApiSandbox
.PageLayout
.prototype.getSubpages = function () {
1863 $.each( this.widgets
, function ( name
, widget
) {
1865 if ( $.isFunction( widget
.getSubmodules
) ) {
1866 submodules
= widget
.getSubmodules();
1867 for ( i
= 0; i
< submodules
.length
; i
++ ) {
1869 key
: name
+ '=' + submodules
[ i
].value
,
1870 path
: submodules
[ i
].path
,
1871 prefix
: widget
.paramInfo
.submoduleparamprefix
|| ''
1879 $( ApiSandbox
.init
);
1881 module
.exports
= ApiSandbox
;
1883 }( jQuery
, mediaWiki
, OO
) );