1 /* eslint-disable no-use-before-define */
2 ( function ( $, mw
, OO
) {
4 var ApiSandbox
, Util
, WidgetMethods
, Validators
,
5 $content
, panel
, booklet
, oldhash
, windowManager
, fullscreenButton
,
11 suppressErrors
= true,
12 updatingBooklet
= false,
19 getApiValue: function () {
20 return this.getValue();
22 setApiValue: function ( v
) {
23 if ( v
=== undefined ) {
24 v
= this.paramInfo
[ 'default' ];
28 apiCheckValid: function () {
30 return this.getValidity().then( function () {
31 return $.Deferred().resolve( true ).promise();
33 return $.Deferred().resolve( false ).promise();
34 } ).done( function ( ok
) {
35 ok
= ok
|| suppressErrors
;
36 that
.setIcon( ok
? null : 'alert' );
37 that
.setIconTitle( ok
? '' : mw
.message( 'apisandbox-alert-field' ).plain() );
42 dateTimeInputWidget
: {
43 getValidity: function () {
44 if ( !Util
.apiBool( this.paramInfo
.required
) || this.getApiValue() !== '' ) {
45 return $.Deferred().resolve().promise();
47 return $.Deferred().reject().promise();
53 alertTokenError: function ( code
, error
) {
54 windowManager
.openWindow( 'errorAlert', {
55 title
: Util
.parseMsg( 'apisandbox-results-fixtoken-fail', this.paramInfo
.tokentype
),
60 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' ),
66 fetchToken: function () {
68 return api
.getToken( this.paramInfo
.tokentype
)
69 .done( this.setApiValue
.bind( this ) )
70 .fail( this.alertTokenError
.bind( this ) )
71 .always( this.popPending
.bind( this ) );
73 setApiValue: function ( v
) {
74 WidgetMethods
.textInputWidget
.setApiValue
.call( this, v
);
75 if ( v
=== '123ABC' ) {
82 getApiValueForDisplay: function () {
88 getApiValue: function () {
89 return this.getValue() ? 1 : undefined;
91 setApiValue: function ( v
) {
92 this.setValue( Util
.apiBool( v
) );
94 apiCheckValid: function () {
95 return $.Deferred().resolve( true ).promise();
100 getApiValue: function () {
101 var item
= this.getMenu().getSelectedItem();
102 return item
=== null ? undefined : item
.getData();
104 setApiValue: function ( v
) {
105 var menu
= this.getMenu();
107 if ( v
=== undefined ) {
108 v
= this.paramInfo
[ 'default' ];
110 if ( v
=== undefined ) {
113 menu
.selectItemByData( String( v
) );
116 apiCheckValid: function () {
117 var ok
= this.getApiValue() !== undefined || suppressErrors
;
118 this.setIcon( ok
? null : 'alert' );
119 this.setIconTitle( ok
? '' : mw
.message( 'apisandbox-alert-field' ).plain() );
120 return $.Deferred().resolve( ok
).promise();
125 getApiValue: function () {
126 var items
= this.getItemsData();
127 if ( items
.join( '' ).indexOf( '|' ) === -1 ) {
128 return items
.join( '|' );
130 return '\x1f' + items
.join( '\x1f' );
133 setApiValue: function ( v
) {
134 if ( v
=== undefined || v
=== '' || v
=== '\x1f' ) {
135 this.setItemsFromData( [] );
138 if ( v
.indexOf( '\x1f' ) !== 0 ) {
139 this.setItemsFromData( v
.split( '|' ) );
141 this.setItemsFromData( v
.substr( 1 ).split( '\x1f' ) );
145 apiCheckValid: function () {
149 if ( !suppressErrors
) {
150 ok
= this.getApiValue() !== undefined && !(
151 pi
.allspecifier
!== undefined &&
152 this.getItemsData().length
> 1 &&
153 this.getItemsData().indexOf( pi
.allspecifier
) !== -1
157 this.setIcon( ok
? null : 'alert' );
158 this.setIconTitle( ok
? '' : mw
.message( 'apisandbox-alert-field' ).plain() );
159 return $.Deferred().resolve( ok
).promise();
161 createItemWidget: function ( data
, label
) {
162 var item
= OO
.ui
.CapsuleMultiselectWidget
.prototype.createItemWidget
.call( this, data
, label
);
163 if ( this.paramInfo
.deprecatedvalues
&&
164 this.paramInfo
.deprecatedvalues
.indexOf( data
) >= 0
166 item
.$element
.addClass( 'apihelp-deprecated-value' );
173 getApiValue: function () {
174 return this.isDisabled() ? undefined : this.widget
.getApiValue();
176 setApiValue: function ( v
) {
177 this.setDisabled( v
=== undefined );
178 this.widget
.setApiValue( v
);
180 apiCheckValid: function () {
181 if ( this.isDisabled() ) {
182 return $.Deferred().resolve( true ).promise();
184 return this.widget
.apiCheckValid();
190 single: function () {
191 var v
= this.isDisabled() ? this.paramInfo
[ 'default' ] : this.getApiValue();
192 return v
=== undefined ? [] : [ { value
: v
, path
: this.paramInfo
.submodules
[ v
] } ];
195 var map
= this.paramInfo
.submodules
,
196 v
= this.isDisabled() ? this.paramInfo
[ 'default' ] : this.getApiValue();
197 return v
=== undefined || v
=== '' ? [] : $.map( String( v
).split( '|' ), function ( v
) {
198 return { value
: v
, path
: map
[ v
] };
204 getApiValueForDisplay: function () {
207 getApiValue: function () {
208 return this.getValue();
210 setApiValue: function () {
213 apiCheckValid: function () {
214 var ok
= this.getValue() !== null || suppressErrors
;
215 this.setIcon( ok
? null : 'alert' );
216 this.setIconTitle( ok
? '' : mw
.message( 'apisandbox-alert-field' ).plain() );
217 return $.Deferred().resolve( ok
).promise();
223 generic: function () {
224 return !Util
.apiBool( this.paramInfo
.required
) || this.getApiValue() !== '';
229 * @class mw.special.ApiSandbox.Util
234 * Fetch API module info
236 * @param {string} module Module to fetch data for
237 * @return {jQuery.Promise}
239 fetchModuleInfo: function ( module
) {
241 deferred
= $.Deferred();
243 if ( moduleInfoCache
.hasOwnProperty( module
) ) {
245 .resolve( moduleInfoCache
[ module
] )
246 .promise( { abort: function () {} } );
248 apiPromise
= api
.post( {
252 uselang
: mw
.config
.get( 'wgUserLanguage' )
253 } ).done( function ( data
) {
256 if ( data
.warnings
&& data
.warnings
.paraminfo
) {
257 deferred
.reject( '???', data
.warnings
.paraminfo
[ '*' ] );
261 info
= data
.paraminfo
.modules
;
262 if ( !info
|| info
.length
!== 1 || info
[ 0 ].path
!== module
) {
263 deferred
.reject( '???', 'No module data returned' );
267 moduleInfoCache
[ module
] = info
[ 0 ];
268 deferred
.resolve( info
[ 0 ] );
269 } ).fail( function ( code
, details
) {
270 if ( code
=== 'http' ) {
271 details
= 'HTTP error: ' + details
.exception
;
272 } else if ( details
.error
) {
273 details
= details
.error
.info
;
275 deferred
.reject( code
, details
);
278 .promise( { abort
: apiPromise
.abort
} );
283 * Mark all currently-in-use tokens as bad
285 markTokensBad: function () {
286 var page
, subpages
, i
,
287 checkPages
= [ pages
.main
];
289 while ( checkPages
.length
) {
290 page
= checkPages
.shift();
292 if ( page
.tokenWidget
) {
293 api
.badToken( page
.tokenWidget
.paramInfo
.tokentype
);
296 subpages
= page
.getSubpages();
297 for ( i
= 0; i
< subpages
.length
; i
++ ) {
298 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
299 checkPages
.push( pages
[ subpages
[ i
].key
] );
306 * Test an API boolean
308 * @param {Mixed} value
311 apiBool: function ( value
) {
312 return value
!== undefined && value
!== false;
316 * Create a widget for a parameter.
318 * @param {Object} pi Parameter info from API
319 * @param {Object} opts Additional options
320 * @return {OO.ui.Widget}
322 createWidgetForParameter: function ( pi
, opts
) {
323 var widget
, innerWidget
, finalWidget
, items
, $button
, $content
, func
,
330 widget
= new OO
.ui
.ToggleSwitchWidget();
331 widget
.paramInfo
= pi
;
332 $.extend( widget
, WidgetMethods
.toggleSwitchWidget
);
333 pi
.required
= true; // Avoid wrapping in the non-required widget
338 if ( pi
.tokentype
) {
339 widget
= new TextInputWithIndicatorWidget( {
341 indicator
: 'previous',
342 indicatorTitle
: mw
.message( 'apisandbox-fetch-token' ).text(),
343 required
: Util
.apiBool( pi
.required
)
346 } else if ( Util
.apiBool( pi
.multi
) ) {
347 widget
= new OO
.ui
.CapsuleMultiselectWidget( {
348 allowArbitrary
: true,
349 allowDuplicates
: Util
.apiBool( pi
.allowsduplicates
),
350 $overlay
: $( '#mw-apisandbox-ui' )
352 widget
.paramInfo
= pi
;
353 $.extend( widget
, WidgetMethods
.capsuleWidget
);
355 widget
= new OO
.ui
.TextInputWidget( {
356 required
: Util
.apiBool( pi
.required
)
359 if ( !Util
.apiBool( pi
.multi
) ) {
360 widget
.paramInfo
= pi
;
361 $.extend( widget
, WidgetMethods
.textInputWidget
);
362 widget
.setValidation( Validators
.generic
);
364 if ( pi
.tokentype
) {
365 $.extend( widget
, WidgetMethods
.tokenWidget
);
366 widget
.input
.paramInfo
= pi
;
367 $.extend( widget
.input
, WidgetMethods
.textInputWidget
);
368 $.extend( widget
.input
, WidgetMethods
.tokenWidget
);
369 widget
.on( 'indicator', widget
.fetchToken
, [], widget
);
374 widget
= new OO
.ui
.TextInputWidget( {
376 required
: Util
.apiBool( pi
.required
)
378 widget
.paramInfo
= pi
;
379 $.extend( widget
, WidgetMethods
.textInputWidget
);
380 widget
.setValidation( Validators
.generic
);
384 widget
= new OO
.ui
.TextInputWidget( {
386 required
: Util
.apiBool( pi
.required
)
388 widget
.paramInfo
= pi
;
389 $.extend( widget
, WidgetMethods
.textInputWidget
);
390 $.extend( widget
, WidgetMethods
.passwordWidget
);
391 widget
.setValidation( Validators
.generic
);
396 widget
= new OO
.ui
.NumberInputWidget( {
397 required
: Util
.apiBool( pi
.required
),
400 widget
.setIcon
= widget
.input
.setIcon
.bind( widget
.input
);
401 widget
.setIconTitle
= widget
.input
.setIconTitle
.bind( widget
.input
);
402 widget
.getValidity
= widget
.input
.getValidity
.bind( widget
.input
);
403 widget
.paramInfo
= pi
;
404 $.extend( widget
, WidgetMethods
.textInputWidget
);
405 if ( Util
.apiBool( pi
.enforcerange
) ) {
406 widget
.setRange( pi
.min
|| -Infinity
, pi
.max
|| Infinity
);
412 widget
= new OO
.ui
.TextInputWidget( {
413 required
: Util
.apiBool( pi
.required
)
415 widget
.setValidation( function ( value
) {
416 var n
, pi
= this.paramInfo
;
418 if ( value
=== 'max' ) {
422 return !isNaN( n
) && isFinite( n
) &&
423 Math
.floor( n
) === n
&&
424 n
>= pi
.min
&& n
<= pi
.apiSandboxMax
;
427 pi
.min
= pi
.min
|| 0;
428 pi
.apiSandboxMax
= mw
.config
.get( 'apihighlimits' ) ? pi
.highmax
: pi
.max
;
429 widget
.paramInfo
= pi
;
430 $.extend( widget
, WidgetMethods
.textInputWidget
);
435 widget
= new mw
.widgets
.datetime
.DateTimeInputWidget( {
437 format
: '${year|0}-${month|0}-${day|0}T${hour|0}:${minute|0}:${second|0}${zone|short}'
439 required
: Util
.apiBool( pi
.required
),
442 widget
.paramInfo
= pi
;
443 $.extend( widget
, WidgetMethods
.textInputWidget
);
444 $.extend( widget
, WidgetMethods
.dateTimeInputWidget
);
445 multiMode
= 'indicator';
449 widget
= new OO
.ui
.SelectFileWidget();
450 widget
.paramInfo
= pi
;
451 $.extend( widget
, WidgetMethods
.uploadWidget
);
455 items
= $.map( mw
.config
.get( 'wgFormattedNamespaces' ), function ( name
, ns
) {
457 name
= mw
.message( 'blanknamespace' ).text();
459 return new OO
.ui
.MenuOptionWidget( { data
: ns
, label
: name
} );
460 } ).sort( function ( a
, b
) {
461 return a
.data
- b
.data
;
463 if ( Util
.apiBool( pi
.multi
) ) {
464 if ( pi
.allspecifier
!== undefined ) {
465 items
.unshift( new OO
.ui
.MenuOptionWidget( {
466 data
: pi
.allspecifier
,
467 label
: mw
.message( 'apisandbox-multivalue-all-namespaces', pi
.allspecifier
).text()
471 widget
= new OO
.ui
.CapsuleMultiselectWidget( {
472 menu
: { items
: items
},
473 $overlay
: $( '#mw-apisandbox-ui' )
475 widget
.paramInfo
= pi
;
476 $.extend( widget
, WidgetMethods
.capsuleWidget
);
478 widget
= new OO
.ui
.DropdownWidget( {
479 menu
: { items
: items
},
480 $overlay
: $( '#mw-apisandbox-ui' )
482 widget
.paramInfo
= pi
;
483 $.extend( widget
, WidgetMethods
.dropdownWidget
);
488 if ( !Array
.isArray( pi
.type
) ) {
489 throw new Error( 'Unknown parameter type ' + pi
.type
);
492 items
= $.map( pi
.type
, function ( v
) {
498 if ( pi
.deprecatedvalues
&& pi
.deprecatedvalues
.indexOf( v
) >= 0 ) {
499 config
.classes
.push( 'apihelp-deprecated-value' );
501 return new OO
.ui
.MenuOptionWidget( config
);
503 if ( Util
.apiBool( pi
.multi
) ) {
504 if ( pi
.allspecifier
!== undefined ) {
505 items
.unshift( new OO
.ui
.MenuOptionWidget( {
506 data
: pi
.allspecifier
,
507 label
: mw
.message( 'apisandbox-multivalue-all-values', pi
.allspecifier
).text()
511 widget
= new OO
.ui
.CapsuleMultiselectWidget( {
512 menu
: { items
: items
},
513 $overlay
: $( '#mw-apisandbox-ui' )
515 widget
.paramInfo
= pi
;
516 $.extend( widget
, WidgetMethods
.capsuleWidget
);
517 if ( Util
.apiBool( pi
.submodules
) ) {
518 widget
.getSubmodules
= WidgetMethods
.submoduleWidget
.multi
;
519 widget
.on( 'change', ApiSandbox
.updateUI
);
522 widget
= new OO
.ui
.DropdownWidget( {
523 menu
: { items
: items
},
524 $overlay
: $( '#mw-apisandbox-ui' )
526 widget
.paramInfo
= pi
;
527 $.extend( widget
, WidgetMethods
.dropdownWidget
);
528 if ( Util
.apiBool( pi
.submodules
) ) {
529 widget
.getSubmodules
= WidgetMethods
.submoduleWidget
.single
;
530 widget
.getMenu().on( 'select', ApiSandbox
.updateUI
);
532 if ( pi
.deprecatedvalues
) {
533 widget
.getMenu().on( 'select', function ( item
) {
534 this.$element
.toggleClass(
535 'apihelp-deprecated-value',
536 pi
.deprecatedvalues
.indexOf( item
.data
) >= 0
545 if ( Util
.apiBool( pi
.multi
) && multiMode
!== 'none' ) {
546 innerWidget
= widget
;
547 switch ( multiMode
) {
549 $content
= innerWidget
.$element
;
553 $button
= innerWidget
.$indicator
;
554 $button
.css( 'cursor', 'pointer' );
555 $button
.attr( 'tabindex', 0 );
556 $button
.parent().append( $button
);
557 innerWidget
.setIndicator( 'next' );
558 $content
= innerWidget
.$element
;
562 throw new Error( 'Unknown multiMode "' + multiMode
+ '"' );
565 widget
= new OO
.ui
.CapsuleMultiselectWidget( {
566 allowArbitrary
: true,
567 allowDuplicates
: Util
.apiBool( pi
.allowsduplicates
),
568 $overlay
: $( '#mw-apisandbox-ui' ),
570 classes
: [ 'mw-apisandbox-popup' ],
574 widget
.paramInfo
= pi
;
575 $.extend( widget
, WidgetMethods
.capsuleWidget
);
578 if ( !innerWidget
.isDisabled() ) {
579 innerWidget
.apiCheckValid().done( function ( ok
) {
581 widget
.addItemsFromData( [ innerWidget
.getApiValue() ] );
582 innerWidget
.setApiValue( undefined );
588 switch ( multiMode
) {
590 innerWidget
.connect( null, { enter
: func
} );
596 keypress: function ( e
) {
597 if ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) {
606 if ( Util
.apiBool( pi
.required
) || opts
.nooptional
) {
607 finalWidget
= widget
;
609 finalWidget
= new OptionalWidget( widget
);
610 finalWidget
.paramInfo
= pi
;
611 $.extend( finalWidget
, WidgetMethods
.optionalWidget
);
612 if ( widget
.getSubmodules
) {
613 finalWidget
.getSubmodules
= widget
.getSubmodules
.bind( widget
);
614 finalWidget
.on( 'disable', function () { setTimeout( ApiSandbox
.updateUI
); } );
616 finalWidget
.setDisabled( true );
619 widget
.setApiValue( pi
[ 'default' ] );
625 * Parse an HTML string and call Util.fixupHTML()
627 * @param {string} html HTML to parse
630 parseHTML: function ( html
) {
631 var $ret
= $( $.parseHTML( html
) );
632 return Util
.fixupHTML( $ret
);
636 * Parse an i18n message and call Util.fixupHTML()
638 * @param {string} key Key of message to get
639 * @param {...Mixed} parameters Values for $N replacements
642 parseMsg: function () {
643 var $ret
= mw
.message
.apply( mw
.message
, arguments
).parseDom();
644 return Util
.fixupHTML( $ret
);
648 * Fix HTML for ApiSandbox display
651 * - Add target="_blank" to any links
653 * @param {jQuery} $html DOM to process
656 fixupHTML: function ( $html
) {
657 $html
.filter( 'a' ).add( $html
.find( 'a' ) )
658 .filter( '[href]:not([target])' )
659 .attr( 'target', '_blank' );
664 * Format a request and return a bunch of menu option widgets
666 * @param {Object} displayParams Query parameters, sanitized for display.
667 * @param {Object} rawParams Query parameters. You should probably use displayParams instead.
668 * @return {OO.ui.MenuOptionWidget[]} Each item's data should be an OO.ui.FieldLayout
670 formatRequest: function ( displayParams
, rawParams
) {
673 new OO
.ui
.MenuOptionWidget( {
674 label
: Util
.parseMsg( 'apisandbox-request-format-url-label' ),
675 data
: new OO
.ui
.FieldLayout(
676 new OO
.ui
.TextInputWidget( {
678 value
: mw
.util
.wikiScript( 'api' ) + '?' + $.param( displayParams
)
680 label
: Util
.parseMsg( 'apisandbox-request-url-label' )
684 new OO
.ui
.MenuOptionWidget( {
685 label
: Util
.parseMsg( 'apisandbox-request-format-json-label' ),
686 data
: new OO
.ui
.FieldLayout(
687 jsonInput
= new OO
.ui
.TextInputWidget( {
688 classes
: [ 'mw-apisandbox-textInputCode' ],
693 value
: JSON
.stringify( displayParams
, null, '\t' )
695 label
: Util
.parseMsg( 'apisandbox-request-json-label' )
697 ).on( 'toggle', function ( visible
) {
699 // Call updatePosition instead of adjustSize
700 // because the latter has weird caching
701 // behavior and the former bypasses it.
702 jsonInput
.updatePosition();
708 mw
.hook( 'apisandbox.formatRequest' ).fire( items
, displayParams
, rawParams
);
714 * Event handler for when formatDropdown's selection changes
716 onFormatDropdownChange: function () {
718 menu
= formatDropdown
.getMenu(),
719 items
= menu
.getItems(),
720 selectedField
= menu
.getSelectedItem() ? menu
.getSelectedItem().getData() : null;
722 for ( i
= 0; i
< items
.length
; i
++ ) {
723 items
[ i
].getData().toggle( items
[ i
].getData() === selectedField
);
729 * Interface to ApiSandbox UI
731 * @class mw.special.ApiSandbox
737 * Automatically called on $.ready()
742 ApiSandbox
.isFullscreen
= false;
744 $content
= $( '#mw-apisandbox' );
746 windowManager
= new OO
.ui
.WindowManager();
747 $( 'body' ).append( windowManager
.$element
);
748 windowManager
.addWindows( {
749 errorAlert
: new OO
.ui
.MessageDialog()
752 fullscreenButton
= new OO
.ui
.ButtonWidget( {
753 label
: mw
.message( 'apisandbox-fullscreen' ).text(),
754 title
: mw
.message( 'apisandbox-fullscreen-tooltip' ).text()
755 } ).on( 'click', ApiSandbox
.toggleFullscreen
);
757 $toolbar
= $( '<div>' )
758 .addClass( 'mw-apisandbox-toolbar' )
760 fullscreenButton
.$element
,
761 new OO
.ui
.ButtonWidget( {
762 label
: mw
.message( 'apisandbox-submit' ).text(),
763 flags
: [ 'primary', 'progressive' ]
764 } ).on( 'click', ApiSandbox
.sendRequest
).$element
,
765 new OO
.ui
.ButtonWidget( {
766 label
: mw
.message( 'apisandbox-reset' ).text(),
768 } ).on( 'click', ApiSandbox
.resetUI
).$element
771 booklet
= new OO
.ui
.BookletLayout( {
776 panel
= new OO
.ui
.PanelLayout( {
777 classes
: [ 'mw-apisandbox-container' ],
778 content
: [ booklet
],
783 pages
.main
= new ApiSandbox
.PageLayout( { key
: 'main', path
: 'main' } );
785 // Parse the current hash string
786 if ( !ApiSandbox
.loadFromHash() ) {
787 ApiSandbox
.updateUI();
790 // If the hashchange event exists, use it. Otherwise, fake it.
791 // And, of course, IE has to be dumb.
792 if ( 'onhashchange' in window
&&
793 ( document
.documentMode
=== undefined || document
.documentMode
>= 8 )
795 $( window
).on( 'hashchange', ApiSandbox
.loadFromHash
);
797 setInterval( function () {
798 if ( oldhash
!== location
.hash
) {
799 ApiSandbox
.loadFromHash();
806 .append( $( '<p>' ).append( Util
.parseMsg( 'apisandbox-intro' ) ) )
808 $( '<div>', { id
: 'mw-apisandbox-ui' } )
810 .append( panel
.$element
)
813 $( window
).on( 'resize', ApiSandbox
.resizePanel
);
815 ApiSandbox
.resizePanel();
819 * Toggle "fullscreen" mode
821 toggleFullscreen: function () {
822 var $body
= $( document
.body
),
823 $ui
= $( '#mw-apisandbox-ui' );
825 ApiSandbox
.isFullscreen
= !ApiSandbox
.isFullscreen
;
827 $body
.toggleClass( 'mw-apisandbox-fullscreen', ApiSandbox
.isFullscreen
);
828 $ui
.toggleClass( 'mw-body-content', ApiSandbox
.isFullscreen
);
829 if ( ApiSandbox
.isFullscreen
) {
830 fullscreenButton
.setLabel( mw
.message( 'apisandbox-unfullscreen' ).text() );
831 fullscreenButton
.setTitle( mw
.message( 'apisandbox-unfullscreen-tooltip' ).text() );
834 fullscreenButton
.setLabel( mw
.message( 'apisandbox-fullscreen' ).text() );
835 fullscreenButton
.setTitle( mw
.message( 'apisandbox-fullscreen-tooltip' ).text() );
836 $content
.append( $ui
);
838 ApiSandbox
.resizePanel();
842 * Set the height of the panel based on the current viewport.
844 resizePanel: function () {
845 var height
= $( window
).height(),
846 contentTop
= $content
.offset().top
;
848 if ( ApiSandbox
.isFullscreen
) {
849 height
-= panel
.$element
.offset().top
- $( '#mw-apisandbox-ui' ).offset().top
;
850 panel
.$element
.height( height
- 1 );
852 // Subtract the height of the intro text
853 height
-= panel
.$element
.offset().top
- contentTop
;
855 panel
.$element
.height( height
- 10 );
856 $( window
).scrollTop( contentTop
- 5 );
861 * Update the current query when the page hash changes
863 * @return {boolean} Successful
865 loadFromHash: function () {
867 hash
= location
.hash
;
869 if ( oldhash
=== hash
) {
877 // I'm surprised this doesn't seem to exist in jQuery or mw.util.
879 hash
= hash
.replace( /\+/g, '%20' );
880 re
= /([^&=#]+)=?([^&#]*)/g;
881 while ( ( m
= re
.exec( hash
) ) ) {
882 params
[ decodeURIComponent( m
[ 1 ] ) ] = decodeURIComponent( m
[ 2 ] );
885 ApiSandbox
.updateUI( params
);
890 * Update the pages in the booklet
892 * @param {Object} [params] Optional query parameters to load
894 updateUI: function ( params
) {
895 var i
, page
, subpages
, j
, removePages
,
898 if ( !$.isPlainObject( params
) ) {
902 if ( updatingBooklet
) {
905 updatingBooklet
= true;
907 if ( params
!== undefined ) {
908 pages
.main
.loadQueryParams( params
);
910 addPages
.push( pages
.main
);
911 if ( resultPage
!== null ) {
912 addPages
.push( resultPage
);
914 pages
.main
.apiCheckValid();
917 while ( addPages
.length
) {
918 page
= addPages
.shift();
919 if ( bookletPages
[ i
] !== page
) {
920 for ( j
= i
; j
< bookletPages
.length
; j
++ ) {
921 if ( bookletPages
[ j
].getName() === page
.getName() ) {
922 bookletPages
.splice( j
, 1 );
925 bookletPages
.splice( i
, 0, page
);
926 booklet
.addPages( [ page
], i
);
930 if ( page
.getSubpages
) {
931 subpages
= page
.getSubpages();
932 for ( j
= 0; j
< subpages
.length
; j
++ ) {
933 if ( !pages
.hasOwnProperty( subpages
[ j
].key
) ) {
934 subpages
[ j
].indentLevel
= page
.indentLevel
+ 1;
935 pages
[ subpages
[ j
].key
] = new ApiSandbox
.PageLayout( subpages
[ j
] );
937 if ( params
!== undefined ) {
938 pages
[ subpages
[ j
].key
].loadQueryParams( params
);
940 addPages
.splice( j
, 0, pages
[ subpages
[ j
].key
] );
941 pages
[ subpages
[ j
].key
].apiCheckValid();
946 if ( bookletPages
.length
> i
) {
947 removePages
= bookletPages
.splice( i
, bookletPages
.length
- i
);
948 booklet
.removePages( removePages
);
951 if ( !booklet
.getCurrentPageName() ) {
952 booklet
.selectFirstSelectablePage();
955 updatingBooklet
= false;
960 * Reset button handler
962 resetUI: function () {
963 suppressErrors
= true;
965 main
: new ApiSandbox
.PageLayout( { key
: 'main', path
: 'main' } )
968 ApiSandbox
.updateUI();
972 * Submit button handler
974 * @param {Object} [params] Use this set of params instead of those in the form fields.
975 * The form fields will be updated to match.
977 sendRequest: function ( params
) {
978 var page
, subpages
, i
, query
, $result
, $focus
,
979 progress
, $progressText
, progressLoading
,
981 paramsAreForced
= !!params
,
983 checkPages
= [ pages
.main
];
985 // Blur any focused widget before submit, because
986 // OO.ui.ButtonWidget doesn't take focus itself (T128054)
987 $focus
= $( '#mw-apisandbox-ui' ).find( document
.activeElement
);
988 if ( $focus
.length
) {
992 suppressErrors
= false;
994 // save widget state in params (or load from it if we are forced)
995 if ( paramsAreForced
) {
996 ApiSandbox
.updateUI( params
);
999 while ( checkPages
.length
) {
1000 page
= checkPages
.shift();
1001 deferreds
.push( page
.apiCheckValid() );
1002 page
.getQueryParams( params
, displayParams
);
1003 subpages
= page
.getSubpages();
1004 for ( i
= 0; i
< subpages
.length
; i
++ ) {
1005 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
1006 checkPages
.push( pages
[ subpages
[ i
].key
] );
1011 if ( !paramsAreForced
) {
1012 // forced params means we are continuing a query; the base query should be preserved
1013 baseRequestParams
= $.extend( {}, params
);
1016 $.when
.apply( $, deferreds
).done( function () {
1017 var formatItems
, menu
, selectedLabel
;
1019 if ( $.inArray( false, arguments
) !== -1 ) {
1020 windowManager
.openWindow( 'errorAlert', {
1021 title
: Util
.parseMsg( 'apisandbox-submit-invalid-fields-title' ),
1022 message
: Util
.parseMsg( 'apisandbox-submit-invalid-fields-message' ),
1026 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' ),
1034 query
= $.param( displayParams
);
1036 formatItems
= Util
.formatRequest( displayParams
, params
);
1038 // Force a 'fm' format with wrappedhtml=1, if available
1039 if ( params
.format
!== undefined ) {
1040 if ( availableFormats
.hasOwnProperty( params
.format
+ 'fm' ) ) {
1041 params
.format
= params
.format
+ 'fm';
1043 if ( params
.format
.substr( -2 ) === 'fm' ) {
1044 params
.wrappedhtml
= 1;
1048 progressLoading
= false;
1049 $progressText
= $( '<span>' ).text( mw
.message( 'apisandbox-sending-request' ).text() );
1050 progress
= new OO
.ui
.ProgressBarWidget( {
1052 $content
: $progressText
1055 $result
= $( '<div>' )
1056 .append( progress
.$element
);
1058 resultPage
= page
= new OO
.ui
.PageLayout( '|results|' );
1059 page
.setupOutlineItem = function () {
1060 this.outlineItem
.setLabel( mw
.message( 'apisandbox-results' ).text() );
1063 if ( !formatDropdown
) {
1064 formatDropdown
= new OO
.ui
.DropdownWidget( {
1065 menu
: { items
: [] },
1066 $overlay
: $( '#mw-apisandbox-ui' )
1068 formatDropdown
.getMenu().on( 'select', Util
.onFormatDropdownChange
);
1071 menu
= formatDropdown
.getMenu();
1072 selectedLabel
= menu
.getSelectedItem() ? menu
.getSelectedItem().getLabel() : '';
1073 if ( typeof selectedLabel
!== 'string' ) {
1074 selectedLabel
= selectedLabel
.text();
1076 menu
.clearItems().addItems( formatItems
);
1077 menu
.chooseItem( menu
.getItemFromLabel( selectedLabel
) || menu
.getFirstSelectableItem() );
1079 // Fire the event to update field visibilities
1080 Util
.onFormatDropdownChange();
1082 page
.$element
.empty()
1084 new OO
.ui
.FieldLayout(
1086 label
: Util
.parseMsg( 'apisandbox-request-selectformat-label' )
1089 $.map( formatItems
, function ( item
) {
1090 return item
.getData().$element
;
1094 ApiSandbox
.updateUI();
1095 booklet
.setPage( '|results|' );
1097 location
.href
= oldhash
= '#' + query
;
1100 contentType
: 'multipart/form-data',
1103 var xhr
= new window
.XMLHttpRequest();
1104 xhr
.upload
.addEventListener( 'progress', function ( e
) {
1105 if ( !progressLoading
) {
1106 if ( e
.lengthComputable
) {
1107 progress
.setProgress( e
.loaded
* 100 / e
.total
);
1109 progress
.setProgress( false );
1113 xhr
.addEventListener( 'progress', function ( e
) {
1114 if ( !progressLoading
) {
1115 progressLoading
= true;
1116 $progressText
.text( mw
.message( 'apisandbox-loading-results' ).text() );
1118 if ( e
.lengthComputable
) {
1119 progress
.setProgress( e
.loaded
* 100 / e
.total
);
1121 progress
.setProgress( false );
1127 .then( null, function ( code
, data
, result
, jqXHR
) {
1128 var deferred
= $.Deferred();
1130 if ( code
!== 'http' ) {
1131 // Not really an error, work around mw.Api thinking it is.
1132 deferred
.resolve( result
, jqXHR
);
1135 deferred
.reject
.apply( deferred
, arguments
);
1137 return deferred
.promise();
1139 .then( function ( data
, jqXHR
) {
1140 var m
, loadTime
, button
, clear
,
1141 ct
= jqXHR
.getResponseHeader( 'Content-Type' ),
1142 loginSuppressed
= jqXHR
.getResponseHeader( 'MediaWiki-Login-Suppressed' ) || 'false';
1145 if ( loginSuppressed
!== 'false' ) {
1147 .addClass( 'warning' )
1148 .append( Util
.parseMsg( 'apisandbox-results-login-suppressed' ) )
1149 .appendTo( $result
);
1151 if ( /^text\/mediawiki-api-prettyprint-wrapped(?:;|$)/.test( ct
) ) {
1152 data
= JSON
.parse( data
);
1153 if ( data
.modules
.length
) {
1154 mw
.loader
.load( data
.modules
);
1156 if ( data
.status
&& data
.status
!== 200 ) {
1158 .addClass( 'api-pretty-header api-pretty-status' )
1159 .append( Util
.parseMsg( 'api-format-prettyprint-status', data
.status
, data
.statustext
) )
1160 .appendTo( $result
);
1162 $result
.append( Util
.parseHTML( data
.html
) );
1163 loadTime
= data
.time
;
1164 } else if ( ( m
= data
.match( /<pre[ >][\s\S]*<\/pre>/ ) ) ) {
1165 $result
.append( Util
.parseHTML( m
[ 0 ] ) );
1166 if ( ( m
= data
.match( /"wgBackendResponseTime":\s*(\d+)/ ) ) ) {
1167 loadTime
= parseInt( m
[ 1 ], 10 );
1171 .addClass( 'api-pretty-content' )
1173 .appendTo( $result
);
1175 if ( paramsAreForced
|| data
[ 'continue' ] ) {
1177 $( '<div>' ).append(
1178 new OO
.ui
.ButtonWidget( {
1179 label
: mw
.message( 'apisandbox-continue' ).text()
1180 } ).on( 'click', function () {
1181 ApiSandbox
.sendRequest( $.extend( {}, baseRequestParams
, data
[ 'continue' ] ) );
1182 } ).setDisabled( !data
[ 'continue' ] ).$element
,
1183 ( clear
= new OO
.ui
.ButtonWidget( {
1184 label
: mw
.message( 'apisandbox-continue-clear' ).text()
1185 } ).on( 'click', function () {
1186 ApiSandbox
.updateUI( baseRequestParams
);
1187 clear
.setDisabled( true );
1188 booklet
.setPage( '|results|' );
1189 } ).setDisabled( !paramsAreForced
) ).$element
,
1190 new OO
.ui
.PopupButtonWidget( {
1191 $overlay
: $( '#mw-apisandbox-ui' ),
1195 $content
: $( '<div>' ).append( Util
.parseMsg( 'apisandbox-continue-help' ) ),
1203 if ( typeof loadTime
=== 'number' ) {
1205 $( '<div>' ).append(
1206 new OO
.ui
.LabelWidget( {
1207 label
: mw
.message( 'apisandbox-request-time', loadTime
).text()
1213 if ( jqXHR
.getResponseHeader( 'MediaWiki-API-Error' ) === 'badtoken' ) {
1214 // Flush all saved tokens in case one of them is the bad one.
1215 Util
.markTokensBad();
1216 button
= new OO
.ui
.ButtonWidget( {
1217 label
: mw
.message( 'apisandbox-results-fixtoken' ).text()
1219 button
.on( 'click', ApiSandbox
.fixTokenAndResend
)
1220 .on( 'click', button
.setDisabled
, [ true ], button
)
1221 .$element
.appendTo( $result
);
1223 }, function ( code
, data
) {
1224 var details
= 'HTTP error: ' + data
.exception
;
1227 new OO
.ui
.LabelWidget( {
1228 label
: mw
.message( 'apisandbox-results-error', details
).text(),
1229 classes
: [ 'error' ]
1237 * Handler for the "Correct token and resubmit" button
1239 * Used on a 'badtoken' error, it re-fetches token parameters for all
1240 * pages and then re-submits the query.
1242 fixTokenAndResend: function () {
1243 var page
, subpages
, i
, k
,
1245 tokenWait
= { dummy
: true },
1246 checkPages
= [ pages
.main
],
1247 success = function ( k
) {
1248 delete tokenWait
[ k
];
1249 if ( ok
&& $.isEmptyObject( tokenWait
) ) {
1250 ApiSandbox
.sendRequest();
1253 failure = function ( k
) {
1254 delete tokenWait
[ k
];
1258 while ( checkPages
.length
) {
1259 page
= checkPages
.shift();
1261 if ( page
.tokenWidget
) {
1262 k
= page
.apiModule
+ page
.tokenWidget
.paramInfo
.name
;
1263 tokenWait
[ k
] = page
.tokenWidget
.fetchToken();
1265 .done( success
.bind( page
.tokenWidget
, k
) )
1266 .fail( failure
.bind( page
.tokenWidget
, k
) );
1269 subpages
= page
.getSubpages();
1270 for ( i
= 0; i
< subpages
.length
; i
++ ) {
1271 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
1272 checkPages
.push( pages
[ subpages
[ i
].key
] );
1277 success( 'dummy', '' );
1281 * Reset validity indicators for all widgets
1283 updateValidityIndicators: function () {
1284 var page
, subpages
, i
,
1285 checkPages
= [ pages
.main
];
1287 while ( checkPages
.length
) {
1288 page
= checkPages
.shift();
1289 page
.apiCheckValid();
1290 subpages
= page
.getSubpages();
1291 for ( i
= 0; i
< subpages
.length
; i
++ ) {
1292 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
1293 checkPages
.push( pages
[ subpages
[ i
].key
] );
1301 * PageLayout for API modules
1305 * @extends OO.ui.PageLayout
1307 * @param {Object} [config] Configuration options
1309 ApiSandbox
.PageLayout = function ( config
) {
1310 config
= $.extend( { prefix
: '' }, config
);
1311 this.displayText
= config
.key
;
1312 this.apiModule
= config
.path
;
1313 this.prefix
= config
.prefix
;
1314 this.paramInfo
= null;
1315 this.apiIsValid
= true;
1316 this.loadFromQueryParams
= null;
1318 this.tokenWidget
= null;
1319 this.indentLevel
= config
.indentLevel
? config
.indentLevel
: 0;
1320 ApiSandbox
.PageLayout
[ 'super' ].call( this, config
.key
, config
);
1321 this.loadParamInfo();
1323 OO
.inheritClass( ApiSandbox
.PageLayout
, OO
.ui
.PageLayout
);
1324 ApiSandbox
.PageLayout
.prototype.setupOutlineItem = function () {
1325 this.outlineItem
.setLevel( this.indentLevel
);
1326 this.outlineItem
.setLabel( this.displayText
);
1327 this.outlineItem
.setIcon( this.apiIsValid
|| suppressErrors
? null : 'alert' );
1328 this.outlineItem
.setIconTitle(
1329 this.apiIsValid
|| suppressErrors
? '' : mw
.message( 'apisandbox-alert-page' ).plain()
1334 * Fetch module information for this page's module, then create UI
1336 ApiSandbox
.PageLayout
.prototype.loadParamInfo = function () {
1337 var dynamicFieldset
, dynamicParamNameWidget
,
1339 removeDynamicParamWidget = function ( name
, layout
) {
1340 dynamicFieldset
.removeItems( [ layout
] );
1341 delete that
.widgets
[ name
];
1343 addDynamicParamWidget = function () {
1344 var name
, layout
, widget
, button
;
1346 // Check name is filled in
1347 name
= dynamicParamNameWidget
.getValue().trim();
1348 if ( name
=== '' ) {
1349 dynamicParamNameWidget
.focus();
1353 if ( that
.widgets
[ name
] !== undefined ) {
1354 windowManager
.openWindow( 'errorAlert', {
1355 title
: Util
.parseMsg( 'apisandbox-dynamic-error-exists', name
),
1359 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' ),
1367 widget
= Util
.createWidgetForParameter( {
1374 button
= new OO
.ui
.ButtonWidget( {
1376 flags
: 'destructive'
1378 layout
= new OO
.ui
.ActionFieldLayout(
1386 button
.on( 'click', removeDynamicParamWidget
, [ name
, layout
] );
1387 that
.widgets
[ name
] = widget
;
1388 dynamicFieldset
.addItems( [ layout
], dynamicFieldset
.getItems().length
- 1 );
1391 dynamicParamNameWidget
.setValue( '' );
1394 this.$element
.empty()
1395 .append( new OO
.ui
.ProgressBarWidget( {
1397 text
: mw
.message( 'apisandbox-loading', this.displayText
).text()
1400 Util
.fetchModuleInfo( this.apiModule
)
1401 .done( function ( pi
) {
1402 var prefix
, i
, j
, descriptionContainer
, widget
, widgetField
, helpField
, tmp
, flag
, count
,
1404 deprecatedItems
= [],
1406 filterFmModules = function ( v
) {
1407 return v
.substr( -2 ) !== 'fm' ||
1408 !availableFormats
.hasOwnProperty( v
.substr( 0, v
.length
- 2 ) );
1410 widgetLabelOnClick = function () {
1411 var f
= this.getField();
1412 if ( $.isFunction( f
.setDisabled
) ) {
1413 f
.setDisabled( false );
1415 if ( $.isFunction( f
.focus
) ) {
1419 doNothing = function () {};
1421 // This is something of a hack. We always want the 'format' and
1422 // 'action' parameters from the main module to be specified,
1423 // and for 'format' we also want to simplify the dropdown since
1424 // we always send the 'fm' variant.
1425 if ( that
.apiModule
=== 'main' ) {
1426 for ( i
= 0; i
< pi
.parameters
.length
; i
++ ) {
1427 if ( pi
.parameters
[ i
].name
=== 'action' ) {
1428 pi
.parameters
[ i
].required
= true;
1429 delete pi
.parameters
[ i
][ 'default' ];
1431 if ( pi
.parameters
[ i
].name
=== 'format' ) {
1432 tmp
= pi
.parameters
[ i
].type
;
1433 for ( j
= 0; j
< tmp
.length
; j
++ ) {
1434 availableFormats
[ tmp
[ j
] ] = true;
1436 pi
.parameters
[ i
].type
= $.grep( tmp
, filterFmModules
);
1437 pi
.parameters
[ i
][ 'default' ] = 'json';
1438 pi
.parameters
[ i
].required
= true;
1443 // Hide the 'wrappedhtml' parameter on format modules
1444 if ( pi
.group
=== 'format' ) {
1445 pi
.parameters
= $.grep( pi
.parameters
, function ( p
) {
1446 return p
.name
!== 'wrappedhtml';
1450 that
.paramInfo
= pi
;
1452 items
.push( new OO
.ui
.FieldLayout(
1453 new OO
.ui
.Widget( {} ).toggle( false ), {
1455 label
: Util
.parseHTML( pi
.description
)
1459 if ( pi
.helpurls
.length
) {
1460 buttons
.push( new OO
.ui
.PopupButtonWidget( {
1461 $overlay
: $( '#mw-apisandbox-ui' ),
1462 label
: mw
.message( 'apisandbox-helpurls' ).text(),
1467 $content
: $( '<ul>' ).append( $.map( pi
.helpurls
, function ( link
) {
1468 return $( '<li>' ).append( $( '<a>', {
1478 if ( pi
.examples
.length
) {
1479 buttons
.push( new OO
.ui
.PopupButtonWidget( {
1480 $overlay
: $( '#mw-apisandbox-ui' ),
1481 label
: mw
.message( 'apisandbox-examples' ).text(),
1486 $content
: $( '<ul>' ).append( $.map( pi
.examples
, function ( example
) {
1488 href
: '#' + example
.query
,
1489 html
: example
.description
1491 a
.find( 'a' ).contents().unwrap(); // Can't nest links
1492 return $( '<li>' ).append( a
);
1498 if ( buttons
.length
) {
1499 items
.push( new OO
.ui
.FieldLayout(
1500 new OO
.ui
.ButtonGroupWidget( {
1502 } ), { align
: 'top' }
1506 if ( pi
.parameters
.length
) {
1507 prefix
= that
.prefix
+ pi
.prefix
;
1508 for ( i
= 0; i
< pi
.parameters
.length
; i
++ ) {
1509 widget
= Util
.createWidgetForParameter( pi
.parameters
[ i
] );
1510 that
.widgets
[ prefix
+ pi
.parameters
[ i
].name
] = widget
;
1511 if ( pi
.parameters
[ i
].tokentype
) {
1512 that
.tokenWidget
= widget
;
1515 descriptionContainer
= $( '<div>' );
1516 descriptionContainer
.append( $( '<div>', {
1517 addClass
: 'description',
1518 append
: Util
.parseHTML( pi
.parameters
[ i
].description
)
1520 if ( pi
.parameters
[ i
].info
&& pi
.parameters
[ i
].info
.length
) {
1521 for ( j
= 0; j
< pi
.parameters
[ i
].info
.length
; j
++ ) {
1522 descriptionContainer
.append( $( '<div>', {
1524 append
: Util
.parseHTML( pi
.parameters
[ i
].info
[ j
] )
1530 switch ( pi
.parameters
[ i
].type
) {
1533 count
= mw
.config
.get( 'wgFormattedNamespaces' ).length
;
1537 if ( pi
.parameters
[ i
].highmax
!== undefined ) {
1538 descriptionContainer
.append( $( '<div>', {
1542 'api-help-param-limit2', pi
.parameters
[ i
].max
, pi
.parameters
[ i
].highmax
1545 Util
.parseMsg( 'apisandbox-param-limit' )
1549 descriptionContainer
.append( $( '<div>', {
1552 Util
.parseMsg( 'api-help-param-limit', pi
.parameters
[ i
].max
),
1554 Util
.parseMsg( 'apisandbox-param-limit' )
1562 if ( pi
.parameters
[ i
].min
!== undefined ) {
1565 if ( pi
.parameters
[ i
].max
!== undefined ) {
1569 descriptionContainer
.append( $( '<div>', {
1571 append
: Util
.parseMsg(
1572 'api-help-param-integer-' + tmp
,
1573 Util
.apiBool( pi
.parameters
[ i
].multi
) ? 2 : 1,
1574 pi
.parameters
[ i
].min
, pi
.parameters
[ i
].max
1581 if ( Array
.isArray( pi
.parameters
[ i
].type
) ) {
1583 count
= pi
.parameters
[ i
].type
.length
;
1587 if ( Util
.apiBool( pi
.parameters
[ i
].multi
) ) {
1589 if ( flag
&& !( widget
instanceof OO
.ui
.CapsuleMultiselectWidget
) &&
1591 widget
instanceof OptionalWidget
&&
1592 widget
.widget
instanceof OO
.ui
.CapsuleMultiselectWidget
1595 tmp
.push( mw
.message( 'api-help-param-multi-separate' ).parse() );
1597 if ( count
> pi
.parameters
[ i
].lowlimit
) {
1599 mw
.message( 'api-help-param-multi-max',
1600 pi
.parameters
[ i
].lowlimit
, pi
.parameters
[ i
].highlimit
1605 descriptionContainer
.append( $( '<div>', {
1607 append
: Util
.parseHTML( tmp
.join( ' ' ) )
1611 helpField
= new OO
.ui
.FieldLayout(
1614 classes
: [ 'mw-apisandbox-spacer' ]
1617 classes
: [ 'mw-apisandbox-help-field' ],
1618 label
: descriptionContainer
1622 widgetField
= new OO
.ui
.FieldLayout(
1626 classes
: [ 'mw-apisandbox-widget-field' ],
1627 label
: prefix
+ pi
.parameters
[ i
].name
1631 // We need our own click handler on the widget label to
1632 // turn off the disablement.
1633 widgetField
.$label
.on( 'click', widgetLabelOnClick
.bind( widgetField
) );
1635 // Don't grey out the label when the field is disabled,
1636 // it makes it too hard to read and our "disabled"
1637 // isn't really disabled.
1638 widgetField
.onFieldDisable( false );
1639 widgetField
.onFieldDisable
= doNothing
;
1641 if ( Util
.apiBool( pi
.parameters
[ i
].deprecated
) ) {
1642 deprecatedItems
.push( widgetField
, helpField
);
1644 items
.push( widgetField
, helpField
);
1649 if ( !pi
.parameters
.length
&& !Util
.apiBool( pi
.dynamicparameters
) ) {
1650 items
.push( new OO
.ui
.FieldLayout(
1651 new OO
.ui
.Widget( {} ).toggle( false ), {
1653 label
: Util
.parseMsg( 'apisandbox-no-parameters' )
1658 that
.$element
.empty();
1660 new OO
.ui
.FieldsetLayout( {
1661 label
: that
.displayText
1662 } ).addItems( items
)
1663 .$element
.appendTo( that
.$element
);
1665 if ( Util
.apiBool( pi
.dynamicparameters
) ) {
1666 dynamicFieldset
= new OO
.ui
.FieldsetLayout();
1667 dynamicParamNameWidget
= new OO
.ui
.TextInputWidget( {
1668 placeholder
: mw
.message( 'apisandbox-dynamic-parameters-add-placeholder' ).text()
1669 } ).on( 'enter', addDynamicParamWidget
);
1670 dynamicFieldset
.addItems( [
1671 new OO
.ui
.FieldLayout(
1672 new OO
.ui
.Widget( {} ).toggle( false ), {
1674 label
: Util
.parseHTML( pi
.dynamicparameters
)
1677 new OO
.ui
.ActionFieldLayout(
1678 dynamicParamNameWidget
,
1679 new OO
.ui
.ButtonWidget( {
1681 flags
: 'progressive'
1682 } ).on( 'click', addDynamicParamWidget
),
1684 label
: mw
.message( 'apisandbox-dynamic-parameters-add-label' ).text(),
1691 $( '<legend>' ).text( mw
.message( 'apisandbox-dynamic-parameters' ).text() ),
1692 dynamicFieldset
.$element
1694 .appendTo( that
.$element
);
1697 if ( deprecatedItems
.length
) {
1698 tmp
= new OO
.ui
.FieldsetLayout().addItems( deprecatedItems
).toggle( false );
1701 $( '<legend>' ).append(
1702 new OO
.ui
.ToggleButtonWidget( {
1703 label
: mw
.message( 'apisandbox-deprecated-parameters' ).text()
1704 } ).on( 'change', tmp
.toggle
, [], tmp
).$element
1708 .appendTo( that
.$element
);
1711 // Load stored params, if any, then update the booklet if we
1712 // have subpages (or else just update our valid-indicator).
1713 tmp
= that
.loadFromQueryParams
;
1714 that
.loadFromQueryParams
= null;
1715 if ( $.isPlainObject( tmp
) ) {
1716 that
.loadQueryParams( tmp
);
1718 if ( that
.getSubpages().length
> 0 ) {
1719 ApiSandbox
.updateUI( tmp
);
1721 that
.apiCheckValid();
1723 } ).fail( function ( code
, detail
) {
1724 that
.$element
.empty()
1726 new OO
.ui
.LabelWidget( {
1727 label
: mw
.message( 'apisandbox-load-error', that
.apiModule
, detail
).text(),
1728 classes
: [ 'error' ]
1730 new OO
.ui
.ButtonWidget( {
1731 label
: mw
.message( 'apisandbox-retry' ).text()
1732 } ).on( 'click', that
.loadParamInfo
, [], that
).$element
1738 * Check that all widgets on the page are in a valid state.
1742 ApiSandbox
.PageLayout
.prototype.apiCheckValid = function () {
1745 if ( this.paramInfo
=== null ) {
1746 return $.Deferred().resolve( false ).promise();
1748 return $.when
.apply( $, $.map( this.widgets
, function ( widget
) {
1749 return widget
.apiCheckValid();
1750 } ) ).then( function () {
1751 that
.apiIsValid
= $.inArray( false, arguments
) === -1;
1752 if ( that
.getOutlineItem() ) {
1753 that
.getOutlineItem().setIcon( that
.apiIsValid
|| suppressErrors
? null : 'alert' );
1754 that
.getOutlineItem().setIconTitle(
1755 that
.apiIsValid
|| suppressErrors
? '' : mw
.message( 'apisandbox-alert-page' ).plain()
1758 return $.Deferred().resolve( that
.apiIsValid
).promise();
1764 * Load form fields from query parameters
1766 * @param {Object} params
1768 ApiSandbox
.PageLayout
.prototype.loadQueryParams = function ( params
) {
1769 if ( this.paramInfo
=== null ) {
1770 this.loadFromQueryParams
= params
;
1772 $.each( this.widgets
, function ( name
, widget
) {
1773 var v
= params
.hasOwnProperty( name
) ? params
[ name
] : undefined;
1774 widget
.setApiValue( v
);
1780 * Load query params from form fields
1782 * @param {Object} params Write query parameters into this object
1783 * @param {Object} displayParams Write query parameters for display into this object
1785 ApiSandbox
.PageLayout
.prototype.getQueryParams = function ( params
, displayParams
) {
1786 $.each( this.widgets
, function ( name
, widget
) {
1787 var value
= widget
.getApiValue();
1788 if ( value
!== undefined ) {
1789 params
[ name
] = value
;
1790 if ( $.isFunction( widget
.getApiValueForDisplay
) ) {
1791 value
= widget
.getApiValueForDisplay();
1793 displayParams
[ name
] = value
;
1799 * Fetch a list of subpage names loaded by this page
1803 ApiSandbox
.PageLayout
.prototype.getSubpages = function () {
1805 $.each( this.widgets
, function ( name
, widget
) {
1807 if ( $.isFunction( widget
.getSubmodules
) ) {
1808 submodules
= widget
.getSubmodules();
1809 for ( i
= 0; i
< submodules
.length
; i
++ ) {
1811 key
: name
+ '=' + submodules
[ i
].value
,
1812 path
: submodules
[ i
].path
,
1813 prefix
: widget
.paramInfo
.submoduleparamprefix
|| ''
1822 * A text input with a clickable indicator
1827 * @param {Object} [config] Configuration options
1829 function TextInputWithIndicatorWidget( config
) {
1832 config
= config
|| {};
1833 TextInputWithIndicatorWidget
[ 'super' ].call( this, config
);
1835 this.$indicator
= $( '<span>' ).addClass( 'mw-apisandbox-clickable-indicator' );
1836 OO
.ui
.mixin
.TabIndexedElement
.call(
1837 this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} )
1840 this.input
= new OO
.ui
.TextInputWidget( $.extend( {
1841 $indicator
: this.$indicator
,
1842 disabled
: this.isDisabled()
1843 }, config
.input
) );
1845 // Forward most methods for convenience
1846 for ( k
in this.input
) {
1847 if ( $.isFunction( this.input
[ k
] ) && !this[ k
] ) {
1848 this[ k
] = this.input
[ k
].bind( this.input
);
1852 this.$indicator
.on( {
1853 click
: this.onIndicatorClick
.bind( this ),
1854 keypress
: this.onIndicatorKeyPress
.bind( this )
1857 this.$element
.append( this.input
.$element
);
1859 OO
.inheritClass( TextInputWithIndicatorWidget
, OO
.ui
.Widget
);
1860 OO
.mixinClass( TextInputWithIndicatorWidget
, OO
.ui
.mixin
.TabIndexedElement
);
1861 TextInputWithIndicatorWidget
.prototype.onIndicatorClick = function ( e
) {
1862 if ( !this.isDisabled() && e
.which
=== 1 ) {
1863 this.emit( 'indicator' );
1867 TextInputWithIndicatorWidget
.prototype.onIndicatorKeyPress = function ( e
) {
1868 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
1869 this.emit( 'indicator' );
1873 TextInputWithIndicatorWidget
.prototype.setDisabled = function ( disabled
) {
1874 TextInputWithIndicatorWidget
[ 'super' ].prototype.setDisabled
.call( this, disabled
);
1876 this.input
.setDisabled( this.isDisabled() );
1882 * A wrapper for a widget that provides an enable/disable button
1887 * @param {OO.ui.Widget} widget
1888 * @param {Object} [config] Configuration options
1890 function OptionalWidget( widget
, config
) {
1893 config
= config
|| {};
1895 this.widget
= widget
;
1896 this.$overlay
= config
.$overlay
||
1897 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-overlay' );
1898 this.checkbox
= new OO
.ui
.CheckboxInputWidget( config
.checkbox
)
1899 .on( 'change', this.onCheckboxChange
, [], this );
1901 OptionalWidget
[ 'super' ].call( this, config
);
1903 // Forward most methods for convenience
1904 for ( k
in this.widget
) {
1905 if ( $.isFunction( this.widget
[ k
] ) && !this[ k
] ) {
1906 this[ k
] = this.widget
[ k
].bind( this.widget
);
1910 this.$overlay
.on( 'click', this.onOverlayClick
.bind( this ) );
1913 .addClass( 'mw-apisandbox-optionalWidget' )
1916 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-fields' ).append(
1917 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-widget' ).append(
1920 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-checkbox' ).append(
1921 this.checkbox
.$element
1926 this.setDisabled( widget
.isDisabled() );
1928 OO
.inheritClass( OptionalWidget
, OO
.ui
.Widget
);
1929 OptionalWidget
.prototype.onCheckboxChange = function ( checked
) {
1930 this.setDisabled( !checked
);
1932 OptionalWidget
.prototype.onOverlayClick = function () {
1933 this.setDisabled( false );
1934 if ( $.isFunction( this.widget
.focus
) ) {
1935 this.widget
.focus();
1938 OptionalWidget
.prototype.setDisabled = function ( disabled
) {
1939 OptionalWidget
[ 'super' ].prototype.setDisabled
.call( this, disabled
);
1940 this.widget
.setDisabled( this.isDisabled() );
1941 this.checkbox
.setSelected( !this.isDisabled() );
1942 this.$overlay
.toggle( this.isDisabled() );
1946 $( ApiSandbox
.init
);
1948 module
.exports
= ApiSandbox
;
1950 }( jQuery
, mediaWiki
, OO
) );