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
.MultilineTextInputWidget( {
375 required
: Util
.apiBool( pi
.required
)
377 widget
.paramInfo
= pi
;
378 $.extend( widget
, WidgetMethods
.textInputWidget
);
379 widget
.setValidation( Validators
.generic
);
383 widget
= new OO
.ui
.TextInputWidget( {
385 required
: Util
.apiBool( pi
.required
)
387 widget
.paramInfo
= pi
;
388 $.extend( widget
, WidgetMethods
.textInputWidget
);
389 $.extend( widget
, WidgetMethods
.passwordWidget
);
390 widget
.setValidation( Validators
.generic
);
395 widget
= new OO
.ui
.NumberInputWidget( {
396 required
: Util
.apiBool( pi
.required
),
399 widget
.setIcon
= widget
.input
.setIcon
.bind( widget
.input
);
400 widget
.setIconTitle
= widget
.input
.setIconTitle
.bind( widget
.input
);
401 widget
.getValidity
= widget
.input
.getValidity
.bind( widget
.input
);
402 widget
.paramInfo
= pi
;
403 $.extend( widget
, WidgetMethods
.textInputWidget
);
404 if ( Util
.apiBool( pi
.enforcerange
) ) {
405 widget
.setRange( pi
.min
|| -Infinity
, pi
.max
|| Infinity
);
411 widget
= new OO
.ui
.TextInputWidget( {
412 required
: Util
.apiBool( pi
.required
)
414 widget
.setValidation( function ( value
) {
415 var n
, pi
= this.paramInfo
;
417 if ( value
=== 'max' ) {
421 return !isNaN( n
) && isFinite( n
) &&
422 Math
.floor( n
) === n
&&
423 n
>= pi
.min
&& n
<= pi
.apiSandboxMax
;
426 pi
.min
= pi
.min
|| 0;
427 pi
.apiSandboxMax
= mw
.config
.get( 'apihighlimits' ) ? pi
.highmax
: pi
.max
;
428 widget
.paramInfo
= pi
;
429 $.extend( widget
, WidgetMethods
.textInputWidget
);
434 widget
= new mw
.widgets
.datetime
.DateTimeInputWidget( {
436 format
: '${year|0}-${month|0}-${day|0}T${hour|0}:${minute|0}:${second|0}${zone|short}'
438 required
: Util
.apiBool( pi
.required
),
441 widget
.paramInfo
= pi
;
442 $.extend( widget
, WidgetMethods
.textInputWidget
);
443 $.extend( widget
, WidgetMethods
.dateTimeInputWidget
);
444 multiMode
= 'indicator';
448 widget
= new OO
.ui
.SelectFileWidget();
449 widget
.paramInfo
= pi
;
450 $.extend( widget
, WidgetMethods
.uploadWidget
);
454 items
= $.map( mw
.config
.get( 'wgFormattedNamespaces' ), function ( name
, ns
) {
456 name
= mw
.message( 'blanknamespace' ).text();
458 return new OO
.ui
.MenuOptionWidget( { data
: ns
, label
: name
} );
459 } ).sort( function ( a
, b
) {
460 return a
.data
- b
.data
;
462 if ( Util
.apiBool( pi
.multi
) ) {
463 if ( pi
.allspecifier
!== undefined ) {
464 items
.unshift( new OO
.ui
.MenuOptionWidget( {
465 data
: pi
.allspecifier
,
466 label
: mw
.message( 'apisandbox-multivalue-all-namespaces', pi
.allspecifier
).text()
470 widget
= new OO
.ui
.CapsuleMultiselectWidget( {
471 menu
: { items
: items
},
472 $overlay
: $( '#mw-apisandbox-ui' )
474 widget
.paramInfo
= pi
;
475 $.extend( widget
, WidgetMethods
.capsuleWidget
);
477 widget
= new OO
.ui
.DropdownWidget( {
478 menu
: { items
: items
},
479 $overlay
: $( '#mw-apisandbox-ui' )
481 widget
.paramInfo
= pi
;
482 $.extend( widget
, WidgetMethods
.dropdownWidget
);
487 if ( !Array
.isArray( pi
.type
) ) {
488 throw new Error( 'Unknown parameter type ' + pi
.type
);
491 items
= $.map( pi
.type
, function ( v
) {
497 if ( pi
.deprecatedvalues
&& pi
.deprecatedvalues
.indexOf( v
) >= 0 ) {
498 config
.classes
.push( 'apihelp-deprecated-value' );
500 return new OO
.ui
.MenuOptionWidget( config
);
502 if ( Util
.apiBool( pi
.multi
) ) {
503 if ( pi
.allspecifier
!== undefined ) {
504 items
.unshift( new OO
.ui
.MenuOptionWidget( {
505 data
: pi
.allspecifier
,
506 label
: mw
.message( 'apisandbox-multivalue-all-values', pi
.allspecifier
).text()
510 widget
= new OO
.ui
.CapsuleMultiselectWidget( {
511 menu
: { items
: items
},
512 $overlay
: $( '#mw-apisandbox-ui' )
514 widget
.paramInfo
= pi
;
515 $.extend( widget
, WidgetMethods
.capsuleWidget
);
516 if ( Util
.apiBool( pi
.submodules
) ) {
517 widget
.getSubmodules
= WidgetMethods
.submoduleWidget
.multi
;
518 widget
.on( 'change', ApiSandbox
.updateUI
);
521 widget
= new OO
.ui
.DropdownWidget( {
522 menu
: { items
: items
},
523 $overlay
: $( '#mw-apisandbox-ui' )
525 widget
.paramInfo
= pi
;
526 $.extend( widget
, WidgetMethods
.dropdownWidget
);
527 if ( Util
.apiBool( pi
.submodules
) ) {
528 widget
.getSubmodules
= WidgetMethods
.submoduleWidget
.single
;
529 widget
.getMenu().on( 'select', ApiSandbox
.updateUI
);
531 if ( pi
.deprecatedvalues
) {
532 widget
.getMenu().on( 'select', function ( item
) {
533 this.$element
.toggleClass(
534 'apihelp-deprecated-value',
535 pi
.deprecatedvalues
.indexOf( item
.data
) >= 0
544 if ( Util
.apiBool( pi
.multi
) && multiMode
!== 'none' ) {
545 innerWidget
= widget
;
546 switch ( multiMode
) {
548 $content
= innerWidget
.$element
;
552 $button
= innerWidget
.$indicator
;
553 $button
.css( 'cursor', 'pointer' );
554 $button
.attr( 'tabindex', 0 );
555 $button
.parent().append( $button
);
556 innerWidget
.setIndicator( 'next' );
557 $content
= innerWidget
.$element
;
561 throw new Error( 'Unknown multiMode "' + multiMode
+ '"' );
564 widget
= new OO
.ui
.CapsuleMultiselectWidget( {
565 allowArbitrary
: true,
566 allowDuplicates
: Util
.apiBool( pi
.allowsduplicates
),
567 $overlay
: $( '#mw-apisandbox-ui' ),
569 classes
: [ 'mw-apisandbox-popup' ],
573 widget
.paramInfo
= pi
;
574 $.extend( widget
, WidgetMethods
.capsuleWidget
);
577 if ( !innerWidget
.isDisabled() ) {
578 innerWidget
.apiCheckValid().done( function ( ok
) {
580 widget
.addItemsFromData( [ innerWidget
.getApiValue() ] );
581 innerWidget
.setApiValue( undefined );
587 switch ( multiMode
) {
589 innerWidget
.connect( null, { enter
: func
} );
595 keypress: function ( e
) {
596 if ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) {
605 if ( Util
.apiBool( pi
.required
) || opts
.nooptional
) {
606 finalWidget
= widget
;
608 finalWidget
= new OptionalWidget( widget
);
609 finalWidget
.paramInfo
= pi
;
610 $.extend( finalWidget
, WidgetMethods
.optionalWidget
);
611 if ( widget
.getSubmodules
) {
612 finalWidget
.getSubmodules
= widget
.getSubmodules
.bind( widget
);
613 finalWidget
.on( 'disable', function () { setTimeout( ApiSandbox
.updateUI
); } );
615 finalWidget
.setDisabled( true );
618 widget
.setApiValue( pi
[ 'default' ] );
624 * Parse an HTML string and call Util.fixupHTML()
626 * @param {string} html HTML to parse
629 parseHTML: function ( html
) {
630 var $ret
= $( $.parseHTML( html
) );
631 return Util
.fixupHTML( $ret
);
635 * Parse an i18n message and call Util.fixupHTML()
637 * @param {string} key Key of message to get
638 * @param {...Mixed} parameters Values for $N replacements
641 parseMsg: function () {
642 var $ret
= mw
.message
.apply( mw
.message
, arguments
).parseDom();
643 return Util
.fixupHTML( $ret
);
647 * Fix HTML for ApiSandbox display
650 * - Add target="_blank" to any links
652 * @param {jQuery} $html DOM to process
655 fixupHTML: function ( $html
) {
656 $html
.filter( 'a' ).add( $html
.find( 'a' ) )
657 .filter( '[href]:not([target])' )
658 .attr( 'target', '_blank' );
663 * Format a request and return a bunch of menu option widgets
665 * @param {Object} displayParams Query parameters, sanitized for display.
666 * @param {Object} rawParams Query parameters. You should probably use displayParams instead.
667 * @return {OO.ui.MenuOptionWidget[]} Each item's data should be an OO.ui.FieldLayout
669 formatRequest: function ( displayParams
, rawParams
) {
672 new OO
.ui
.MenuOptionWidget( {
673 label
: Util
.parseMsg( 'apisandbox-request-format-url-label' ),
674 data
: new OO
.ui
.FieldLayout(
675 new OO
.ui
.TextInputWidget( {
677 value
: mw
.util
.wikiScript( 'api' ) + '?' + $.param( displayParams
)
679 label
: Util
.parseMsg( 'apisandbox-request-url-label' )
683 new OO
.ui
.MenuOptionWidget( {
684 label
: Util
.parseMsg( 'apisandbox-request-format-json-label' ),
685 data
: new OO
.ui
.FieldLayout(
686 jsonInput
= new OO
.ui
.MultilineTextInputWidget( {
687 classes
: [ 'mw-apisandbox-textInputCode' ],
691 value
: JSON
.stringify( displayParams
, null, '\t' )
693 label
: Util
.parseMsg( 'apisandbox-request-json-label' )
695 ).on( 'toggle', function ( visible
) {
697 // Call updatePosition instead of adjustSize
698 // because the latter has weird caching
699 // behavior and the former bypasses it.
700 jsonInput
.updatePosition();
706 mw
.hook( 'apisandbox.formatRequest' ).fire( items
, displayParams
, rawParams
);
712 * Event handler for when formatDropdown's selection changes
714 onFormatDropdownChange: function () {
716 menu
= formatDropdown
.getMenu(),
717 items
= menu
.getItems(),
718 selectedField
= menu
.getSelectedItem() ? menu
.getSelectedItem().getData() : null;
720 for ( i
= 0; i
< items
.length
; i
++ ) {
721 items
[ i
].getData().toggle( items
[ i
].getData() === selectedField
);
727 * Interface to ApiSandbox UI
729 * @class mw.special.ApiSandbox
735 * Automatically called on $.ready()
740 ApiSandbox
.isFullscreen
= false;
742 $content
= $( '#mw-apisandbox' );
744 windowManager
= new OO
.ui
.WindowManager();
745 $( 'body' ).append( windowManager
.$element
);
746 windowManager
.addWindows( {
747 errorAlert
: new OO
.ui
.MessageDialog()
750 fullscreenButton
= new OO
.ui
.ButtonWidget( {
751 label
: mw
.message( 'apisandbox-fullscreen' ).text(),
752 title
: mw
.message( 'apisandbox-fullscreen-tooltip' ).text()
753 } ).on( 'click', ApiSandbox
.toggleFullscreen
);
755 $toolbar
= $( '<div>' )
756 .addClass( 'mw-apisandbox-toolbar' )
758 fullscreenButton
.$element
,
759 new OO
.ui
.ButtonWidget( {
760 label
: mw
.message( 'apisandbox-submit' ).text(),
761 flags
: [ 'primary', 'progressive' ]
762 } ).on( 'click', ApiSandbox
.sendRequest
).$element
,
763 new OO
.ui
.ButtonWidget( {
764 label
: mw
.message( 'apisandbox-reset' ).text(),
766 } ).on( 'click', ApiSandbox
.resetUI
).$element
769 booklet
= new OO
.ui
.BookletLayout( {
774 panel
= new OO
.ui
.PanelLayout( {
775 classes
: [ 'mw-apisandbox-container' ],
776 content
: [ booklet
],
781 pages
.main
= new ApiSandbox
.PageLayout( { key
: 'main', path
: 'main' } );
783 // Parse the current hash string
784 if ( !ApiSandbox
.loadFromHash() ) {
785 ApiSandbox
.updateUI();
788 // If the hashchange event exists, use it. Otherwise, fake it.
789 // And, of course, IE has to be dumb.
790 if ( 'onhashchange' in window
&&
791 ( document
.documentMode
=== undefined || document
.documentMode
>= 8 )
793 $( window
).on( 'hashchange', ApiSandbox
.loadFromHash
);
795 setInterval( function () {
796 if ( oldhash
!== location
.hash
) {
797 ApiSandbox
.loadFromHash();
804 .append( $( '<p>' ).append( Util
.parseMsg( 'apisandbox-intro' ) ) )
806 $( '<div>', { id
: 'mw-apisandbox-ui' } )
808 .append( panel
.$element
)
811 $( window
).on( 'resize', ApiSandbox
.resizePanel
);
813 ApiSandbox
.resizePanel();
817 * Toggle "fullscreen" mode
819 toggleFullscreen: function () {
820 var $body
= $( document
.body
),
821 $ui
= $( '#mw-apisandbox-ui' );
823 ApiSandbox
.isFullscreen
= !ApiSandbox
.isFullscreen
;
825 $body
.toggleClass( 'mw-apisandbox-fullscreen', ApiSandbox
.isFullscreen
);
826 $ui
.toggleClass( 'mw-body-content', ApiSandbox
.isFullscreen
);
827 if ( ApiSandbox
.isFullscreen
) {
828 fullscreenButton
.setLabel( mw
.message( 'apisandbox-unfullscreen' ).text() );
829 fullscreenButton
.setTitle( mw
.message( 'apisandbox-unfullscreen-tooltip' ).text() );
832 fullscreenButton
.setLabel( mw
.message( 'apisandbox-fullscreen' ).text() );
833 fullscreenButton
.setTitle( mw
.message( 'apisandbox-fullscreen-tooltip' ).text() );
834 $content
.append( $ui
);
836 ApiSandbox
.resizePanel();
840 * Set the height of the panel based on the current viewport.
842 resizePanel: function () {
843 var height
= $( window
).height(),
844 contentTop
= $content
.offset().top
;
846 if ( ApiSandbox
.isFullscreen
) {
847 height
-= panel
.$element
.offset().top
- $( '#mw-apisandbox-ui' ).offset().top
;
848 panel
.$element
.height( height
- 1 );
850 // Subtract the height of the intro text
851 height
-= panel
.$element
.offset().top
- contentTop
;
853 panel
.$element
.height( height
- 10 );
854 $( window
).scrollTop( contentTop
- 5 );
859 * Update the current query when the page hash changes
861 * @return {boolean} Successful
863 loadFromHash: function () {
865 hash
= location
.hash
;
867 if ( oldhash
=== hash
) {
875 // I'm surprised this doesn't seem to exist in jQuery or mw.util.
877 hash
= hash
.replace( /\+/g, '%20' );
878 re
= /([^&=#]+)=?([^&#]*)/g;
879 while ( ( m
= re
.exec( hash
) ) ) {
880 params
[ decodeURIComponent( m
[ 1 ] ) ] = decodeURIComponent( m
[ 2 ] );
883 ApiSandbox
.updateUI( params
);
888 * Update the pages in the booklet
890 * @param {Object} [params] Optional query parameters to load
892 updateUI: function ( params
) {
893 var i
, page
, subpages
, j
, removePages
,
896 if ( !$.isPlainObject( params
) ) {
900 if ( updatingBooklet
) {
903 updatingBooklet
= true;
905 if ( params
!== undefined ) {
906 pages
.main
.loadQueryParams( params
);
908 addPages
.push( pages
.main
);
909 if ( resultPage
!== null ) {
910 addPages
.push( resultPage
);
912 pages
.main
.apiCheckValid();
915 while ( addPages
.length
) {
916 page
= addPages
.shift();
917 if ( bookletPages
[ i
] !== page
) {
918 for ( j
= i
; j
< bookletPages
.length
; j
++ ) {
919 if ( bookletPages
[ j
].getName() === page
.getName() ) {
920 bookletPages
.splice( j
, 1 );
923 bookletPages
.splice( i
, 0, page
);
924 booklet
.addPages( [ page
], i
);
928 if ( page
.getSubpages
) {
929 subpages
= page
.getSubpages();
930 for ( j
= 0; j
< subpages
.length
; j
++ ) {
931 if ( !pages
.hasOwnProperty( subpages
[ j
].key
) ) {
932 subpages
[ j
].indentLevel
= page
.indentLevel
+ 1;
933 pages
[ subpages
[ j
].key
] = new ApiSandbox
.PageLayout( subpages
[ j
] );
935 if ( params
!== undefined ) {
936 pages
[ subpages
[ j
].key
].loadQueryParams( params
);
938 addPages
.splice( j
, 0, pages
[ subpages
[ j
].key
] );
939 pages
[ subpages
[ j
].key
].apiCheckValid();
944 if ( bookletPages
.length
> i
) {
945 removePages
= bookletPages
.splice( i
, bookletPages
.length
- i
);
946 booklet
.removePages( removePages
);
949 if ( !booklet
.getCurrentPageName() ) {
950 booklet
.selectFirstSelectablePage();
953 updatingBooklet
= false;
958 * Reset button handler
960 resetUI: function () {
961 suppressErrors
= true;
963 main
: new ApiSandbox
.PageLayout( { key
: 'main', path
: 'main' } )
966 ApiSandbox
.updateUI();
970 * Submit button handler
972 * @param {Object} [params] Use this set of params instead of those in the form fields.
973 * The form fields will be updated to match.
975 sendRequest: function ( params
) {
976 var page
, subpages
, i
, query
, $result
, $focus
,
977 progress
, $progressText
, progressLoading
,
979 paramsAreForced
= !!params
,
981 checkPages
= [ pages
.main
];
983 // Blur any focused widget before submit, because
984 // OO.ui.ButtonWidget doesn't take focus itself (T128054)
985 $focus
= $( '#mw-apisandbox-ui' ).find( document
.activeElement
);
986 if ( $focus
.length
) {
990 suppressErrors
= false;
992 // save widget state in params (or load from it if we are forced)
993 if ( paramsAreForced
) {
994 ApiSandbox
.updateUI( params
);
997 while ( checkPages
.length
) {
998 page
= checkPages
.shift();
999 deferreds
.push( page
.apiCheckValid() );
1000 page
.getQueryParams( params
, displayParams
);
1001 subpages
= page
.getSubpages();
1002 for ( i
= 0; i
< subpages
.length
; i
++ ) {
1003 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
1004 checkPages
.push( pages
[ subpages
[ i
].key
] );
1009 if ( !paramsAreForced
) {
1010 // forced params means we are continuing a query; the base query should be preserved
1011 baseRequestParams
= $.extend( {}, params
);
1014 $.when
.apply( $, deferreds
).done( function () {
1015 var formatItems
, menu
, selectedLabel
;
1017 if ( $.inArray( false, arguments
) !== -1 ) {
1018 windowManager
.openWindow( 'errorAlert', {
1019 title
: Util
.parseMsg( 'apisandbox-submit-invalid-fields-title' ),
1020 message
: Util
.parseMsg( 'apisandbox-submit-invalid-fields-message' ),
1024 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' ),
1032 query
= $.param( displayParams
);
1034 formatItems
= Util
.formatRequest( displayParams
, params
);
1036 // Force a 'fm' format with wrappedhtml=1, if available
1037 if ( params
.format
!== undefined ) {
1038 if ( availableFormats
.hasOwnProperty( params
.format
+ 'fm' ) ) {
1039 params
.format
= params
.format
+ 'fm';
1041 if ( params
.format
.substr( -2 ) === 'fm' ) {
1042 params
.wrappedhtml
= 1;
1046 progressLoading
= false;
1047 $progressText
= $( '<span>' ).text( mw
.message( 'apisandbox-sending-request' ).text() );
1048 progress
= new OO
.ui
.ProgressBarWidget( {
1050 $content
: $progressText
1053 $result
= $( '<div>' )
1054 .append( progress
.$element
);
1056 resultPage
= page
= new OO
.ui
.PageLayout( '|results|' );
1057 page
.setupOutlineItem = function () {
1058 this.outlineItem
.setLabel( mw
.message( 'apisandbox-results' ).text() );
1061 if ( !formatDropdown
) {
1062 formatDropdown
= new OO
.ui
.DropdownWidget( {
1063 menu
: { items
: [] },
1064 $overlay
: $( '#mw-apisandbox-ui' )
1066 formatDropdown
.getMenu().on( 'select', Util
.onFormatDropdownChange
);
1069 menu
= formatDropdown
.getMenu();
1070 selectedLabel
= menu
.getSelectedItem() ? menu
.getSelectedItem().getLabel() : '';
1071 if ( typeof selectedLabel
!== 'string' ) {
1072 selectedLabel
= selectedLabel
.text();
1074 menu
.clearItems().addItems( formatItems
);
1075 menu
.chooseItem( menu
.getItemFromLabel( selectedLabel
) || menu
.getFirstSelectableItem() );
1077 // Fire the event to update field visibilities
1078 Util
.onFormatDropdownChange();
1080 page
.$element
.empty()
1082 new OO
.ui
.FieldLayout(
1084 label
: Util
.parseMsg( 'apisandbox-request-selectformat-label' )
1087 $.map( formatItems
, function ( item
) {
1088 return item
.getData().$element
;
1092 ApiSandbox
.updateUI();
1093 booklet
.setPage( '|results|' );
1095 location
.href
= oldhash
= '#' + query
;
1098 contentType
: 'multipart/form-data',
1101 var xhr
= new window
.XMLHttpRequest();
1102 xhr
.upload
.addEventListener( 'progress', function ( e
) {
1103 if ( !progressLoading
) {
1104 if ( e
.lengthComputable
) {
1105 progress
.setProgress( e
.loaded
* 100 / e
.total
);
1107 progress
.setProgress( false );
1111 xhr
.addEventListener( 'progress', function ( e
) {
1112 if ( !progressLoading
) {
1113 progressLoading
= true;
1114 $progressText
.text( mw
.message( 'apisandbox-loading-results' ).text() );
1116 if ( e
.lengthComputable
) {
1117 progress
.setProgress( e
.loaded
* 100 / e
.total
);
1119 progress
.setProgress( false );
1125 .then( null, function ( code
, data
, result
, jqXHR
) {
1126 var deferred
= $.Deferred();
1128 if ( code
!== 'http' ) {
1129 // Not really an error, work around mw.Api thinking it is.
1130 deferred
.resolve( result
, jqXHR
);
1133 deferred
.reject
.apply( deferred
, arguments
);
1135 return deferred
.promise();
1137 .then( function ( data
, jqXHR
) {
1138 var m
, loadTime
, button
, clear
,
1139 ct
= jqXHR
.getResponseHeader( 'Content-Type' ),
1140 loginSuppressed
= jqXHR
.getResponseHeader( 'MediaWiki-Login-Suppressed' ) || 'false';
1143 if ( loginSuppressed
!== 'false' ) {
1145 .addClass( 'warning' )
1146 .append( Util
.parseMsg( 'apisandbox-results-login-suppressed' ) )
1147 .appendTo( $result
);
1149 if ( /^text\/mediawiki-api-prettyprint-wrapped(?:;|$)/.test( ct
) ) {
1150 data
= JSON
.parse( data
);
1151 if ( data
.modules
.length
) {
1152 mw
.loader
.load( data
.modules
);
1154 if ( data
.status
&& data
.status
!== 200 ) {
1156 .addClass( 'api-pretty-header api-pretty-status' )
1157 .append( Util
.parseMsg( 'api-format-prettyprint-status', data
.status
, data
.statustext
) )
1158 .appendTo( $result
);
1160 $result
.append( Util
.parseHTML( data
.html
) );
1161 loadTime
= data
.time
;
1162 } else if ( ( m
= data
.match( /<pre[ >][\s\S]*<\/pre>/ ) ) ) {
1163 $result
.append( Util
.parseHTML( m
[ 0 ] ) );
1164 if ( ( m
= data
.match( /"wgBackendResponseTime":\s*(\d+)/ ) ) ) {
1165 loadTime
= parseInt( m
[ 1 ], 10 );
1169 .addClass( 'api-pretty-content' )
1171 .appendTo( $result
);
1173 if ( paramsAreForced
|| data
[ 'continue' ] ) {
1175 $( '<div>' ).append(
1176 new OO
.ui
.ButtonWidget( {
1177 label
: mw
.message( 'apisandbox-continue' ).text()
1178 } ).on( 'click', function () {
1179 ApiSandbox
.sendRequest( $.extend( {}, baseRequestParams
, data
[ 'continue' ] ) );
1180 } ).setDisabled( !data
[ 'continue' ] ).$element
,
1181 ( clear
= new OO
.ui
.ButtonWidget( {
1182 label
: mw
.message( 'apisandbox-continue-clear' ).text()
1183 } ).on( 'click', function () {
1184 ApiSandbox
.updateUI( baseRequestParams
);
1185 clear
.setDisabled( true );
1186 booklet
.setPage( '|results|' );
1187 } ).setDisabled( !paramsAreForced
) ).$element
,
1188 new OO
.ui
.PopupButtonWidget( {
1189 $overlay
: $( '#mw-apisandbox-ui' ),
1193 $content
: $( '<div>' ).append( Util
.parseMsg( 'apisandbox-continue-help' ) ),
1201 if ( typeof loadTime
=== 'number' ) {
1203 $( '<div>' ).append(
1204 new OO
.ui
.LabelWidget( {
1205 label
: mw
.message( 'apisandbox-request-time', loadTime
).text()
1211 if ( jqXHR
.getResponseHeader( 'MediaWiki-API-Error' ) === 'badtoken' ) {
1212 // Flush all saved tokens in case one of them is the bad one.
1213 Util
.markTokensBad();
1214 button
= new OO
.ui
.ButtonWidget( {
1215 label
: mw
.message( 'apisandbox-results-fixtoken' ).text()
1217 button
.on( 'click', ApiSandbox
.fixTokenAndResend
)
1218 .on( 'click', button
.setDisabled
, [ true ], button
)
1219 .$element
.appendTo( $result
);
1221 }, function ( code
, data
) {
1222 var details
= 'HTTP error: ' + data
.exception
;
1225 new OO
.ui
.LabelWidget( {
1226 label
: mw
.message( 'apisandbox-results-error', details
).text(),
1227 classes
: [ 'error' ]
1235 * Handler for the "Correct token and resubmit" button
1237 * Used on a 'badtoken' error, it re-fetches token parameters for all
1238 * pages and then re-submits the query.
1240 fixTokenAndResend: function () {
1241 var page
, subpages
, i
, k
,
1243 tokenWait
= { dummy
: true },
1244 checkPages
= [ pages
.main
],
1245 success = function ( k
) {
1246 delete tokenWait
[ k
];
1247 if ( ok
&& $.isEmptyObject( tokenWait
) ) {
1248 ApiSandbox
.sendRequest();
1251 failure = function ( k
) {
1252 delete tokenWait
[ k
];
1256 while ( checkPages
.length
) {
1257 page
= checkPages
.shift();
1259 if ( page
.tokenWidget
) {
1260 k
= page
.apiModule
+ page
.tokenWidget
.paramInfo
.name
;
1261 tokenWait
[ k
] = page
.tokenWidget
.fetchToken();
1263 .done( success
.bind( page
.tokenWidget
, k
) )
1264 .fail( failure
.bind( page
.tokenWidget
, k
) );
1267 subpages
= page
.getSubpages();
1268 for ( i
= 0; i
< subpages
.length
; i
++ ) {
1269 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
1270 checkPages
.push( pages
[ subpages
[ i
].key
] );
1275 success( 'dummy', '' );
1279 * Reset validity indicators for all widgets
1281 updateValidityIndicators: function () {
1282 var page
, subpages
, i
,
1283 checkPages
= [ pages
.main
];
1285 while ( checkPages
.length
) {
1286 page
= checkPages
.shift();
1287 page
.apiCheckValid();
1288 subpages
= page
.getSubpages();
1289 for ( i
= 0; i
< subpages
.length
; i
++ ) {
1290 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
1291 checkPages
.push( pages
[ subpages
[ i
].key
] );
1299 * PageLayout for API modules
1303 * @extends OO.ui.PageLayout
1305 * @param {Object} [config] Configuration options
1307 ApiSandbox
.PageLayout = function ( config
) {
1308 config
= $.extend( { prefix
: '' }, config
);
1309 this.displayText
= config
.key
;
1310 this.apiModule
= config
.path
;
1311 this.prefix
= config
.prefix
;
1312 this.paramInfo
= null;
1313 this.apiIsValid
= true;
1314 this.loadFromQueryParams
= null;
1316 this.tokenWidget
= null;
1317 this.indentLevel
= config
.indentLevel
? config
.indentLevel
: 0;
1318 ApiSandbox
.PageLayout
[ 'super' ].call( this, config
.key
, config
);
1319 this.loadParamInfo();
1321 OO
.inheritClass( ApiSandbox
.PageLayout
, OO
.ui
.PageLayout
);
1322 ApiSandbox
.PageLayout
.prototype.setupOutlineItem = function () {
1323 this.outlineItem
.setLevel( this.indentLevel
);
1324 this.outlineItem
.setLabel( this.displayText
);
1325 this.outlineItem
.setIcon( this.apiIsValid
|| suppressErrors
? null : 'alert' );
1326 this.outlineItem
.setIconTitle(
1327 this.apiIsValid
|| suppressErrors
? '' : mw
.message( 'apisandbox-alert-page' ).plain()
1332 * Fetch module information for this page's module, then create UI
1334 ApiSandbox
.PageLayout
.prototype.loadParamInfo = function () {
1335 var dynamicFieldset
, dynamicParamNameWidget
,
1337 removeDynamicParamWidget = function ( name
, layout
) {
1338 dynamicFieldset
.removeItems( [ layout
] );
1339 delete that
.widgets
[ name
];
1341 addDynamicParamWidget = function () {
1342 var name
, layout
, widget
, button
;
1344 // Check name is filled in
1345 name
= dynamicParamNameWidget
.getValue().trim();
1346 if ( name
=== '' ) {
1347 dynamicParamNameWidget
.focus();
1351 if ( that
.widgets
[ name
] !== undefined ) {
1352 windowManager
.openWindow( 'errorAlert', {
1353 title
: Util
.parseMsg( 'apisandbox-dynamic-error-exists', name
),
1357 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' ),
1365 widget
= Util
.createWidgetForParameter( {
1372 button
= new OO
.ui
.ButtonWidget( {
1374 flags
: 'destructive'
1376 layout
= new OO
.ui
.ActionFieldLayout(
1384 button
.on( 'click', removeDynamicParamWidget
, [ name
, layout
] );
1385 that
.widgets
[ name
] = widget
;
1386 dynamicFieldset
.addItems( [ layout
], dynamicFieldset
.getItems().length
- 1 );
1389 dynamicParamNameWidget
.setValue( '' );
1392 this.$element
.empty()
1393 .append( new OO
.ui
.ProgressBarWidget( {
1395 text
: mw
.message( 'apisandbox-loading', this.displayText
).text()
1398 Util
.fetchModuleInfo( this.apiModule
)
1399 .done( function ( pi
) {
1400 var prefix
, i
, j
, descriptionContainer
, widget
, widgetField
, helpField
, tmp
, flag
, count
,
1402 deprecatedItems
= [],
1404 filterFmModules = function ( v
) {
1405 return v
.substr( -2 ) !== 'fm' ||
1406 !availableFormats
.hasOwnProperty( v
.substr( 0, v
.length
- 2 ) );
1408 widgetLabelOnClick = function () {
1409 var f
= this.getField();
1410 if ( $.isFunction( f
.setDisabled
) ) {
1411 f
.setDisabled( false );
1413 if ( $.isFunction( f
.focus
) ) {
1418 // This is something of a hack. We always want the 'format' and
1419 // 'action' parameters from the main module to be specified,
1420 // and for 'format' we also want to simplify the dropdown since
1421 // we always send the 'fm' variant.
1422 if ( that
.apiModule
=== 'main' ) {
1423 for ( i
= 0; i
< pi
.parameters
.length
; i
++ ) {
1424 if ( pi
.parameters
[ i
].name
=== 'action' ) {
1425 pi
.parameters
[ i
].required
= true;
1426 delete pi
.parameters
[ i
][ 'default' ];
1428 if ( pi
.parameters
[ i
].name
=== 'format' ) {
1429 tmp
= pi
.parameters
[ i
].type
;
1430 for ( j
= 0; j
< tmp
.length
; j
++ ) {
1431 availableFormats
[ tmp
[ j
] ] = true;
1433 pi
.parameters
[ i
].type
= $.grep( tmp
, filterFmModules
);
1434 pi
.parameters
[ i
][ 'default' ] = 'json';
1435 pi
.parameters
[ i
].required
= true;
1440 // Hide the 'wrappedhtml' parameter on format modules
1441 if ( pi
.group
=== 'format' ) {
1442 pi
.parameters
= $.grep( pi
.parameters
, function ( p
) {
1443 return p
.name
!== 'wrappedhtml';
1447 that
.paramInfo
= pi
;
1449 items
.push( new OO
.ui
.FieldLayout(
1450 new OO
.ui
.Widget( {} ).toggle( false ), {
1452 label
: Util
.parseHTML( pi
.description
)
1456 if ( pi
.helpurls
.length
) {
1457 buttons
.push( new OO
.ui
.PopupButtonWidget( {
1458 $overlay
: $( '#mw-apisandbox-ui' ),
1459 label
: mw
.message( 'apisandbox-helpurls' ).text(),
1464 $content
: $( '<ul>' ).append( $.map( pi
.helpurls
, function ( link
) {
1465 return $( '<li>' ).append( $( '<a>', {
1475 if ( pi
.examples
.length
) {
1476 buttons
.push( new OO
.ui
.PopupButtonWidget( {
1477 $overlay
: $( '#mw-apisandbox-ui' ),
1478 label
: mw
.message( 'apisandbox-examples' ).text(),
1483 $content
: $( '<ul>' ).append( $.map( pi
.examples
, function ( example
) {
1485 href
: '#' + example
.query
,
1486 html
: example
.description
1488 a
.find( 'a' ).contents().unwrap(); // Can't nest links
1489 return $( '<li>' ).append( a
);
1495 if ( buttons
.length
) {
1496 items
.push( new OO
.ui
.FieldLayout(
1497 new OO
.ui
.ButtonGroupWidget( {
1499 } ), { align
: 'top' }
1503 if ( pi
.parameters
.length
) {
1504 prefix
= that
.prefix
+ pi
.prefix
;
1505 for ( i
= 0; i
< pi
.parameters
.length
; i
++ ) {
1506 widget
= Util
.createWidgetForParameter( pi
.parameters
[ i
] );
1507 that
.widgets
[ prefix
+ pi
.parameters
[ i
].name
] = widget
;
1508 if ( pi
.parameters
[ i
].tokentype
) {
1509 that
.tokenWidget
= widget
;
1512 descriptionContainer
= $( '<div>' );
1514 tmp
= Util
.parseHTML( pi
.parameters
[ i
].description
);
1515 tmp
.filter( 'dl' ).makeCollapsible( {
1517 } ).children( '.mw-collapsible-toggle' ).each( function () {
1518 var $this = $( this );
1519 $this.parent().prev( 'p' ).append( $this );
1521 descriptionContainer
.append( $( '<div>', { addClass
: 'description', append
: tmp
} ) );
1523 if ( pi
.parameters
[ i
].info
&& pi
.parameters
[ i
].info
.length
) {
1524 for ( j
= 0; j
< pi
.parameters
[ i
].info
.length
; j
++ ) {
1525 descriptionContainer
.append( $( '<div>', {
1527 append
: Util
.parseHTML( pi
.parameters
[ i
].info
[ j
] )
1533 switch ( pi
.parameters
[ i
].type
) {
1536 count
= mw
.config
.get( 'wgFormattedNamespaces' ).length
;
1540 if ( pi
.parameters
[ i
].highmax
!== undefined ) {
1541 descriptionContainer
.append( $( '<div>', {
1545 'api-help-param-limit2', pi
.parameters
[ i
].max
, pi
.parameters
[ i
].highmax
1548 Util
.parseMsg( 'apisandbox-param-limit' )
1552 descriptionContainer
.append( $( '<div>', {
1555 Util
.parseMsg( 'api-help-param-limit', pi
.parameters
[ i
].max
),
1557 Util
.parseMsg( 'apisandbox-param-limit' )
1565 if ( pi
.parameters
[ i
].min
!== undefined ) {
1568 if ( pi
.parameters
[ i
].max
!== undefined ) {
1572 descriptionContainer
.append( $( '<div>', {
1574 append
: Util
.parseMsg(
1575 'api-help-param-integer-' + tmp
,
1576 Util
.apiBool( pi
.parameters
[ i
].multi
) ? 2 : 1,
1577 pi
.parameters
[ i
].min
, pi
.parameters
[ i
].max
1584 if ( Array
.isArray( pi
.parameters
[ i
].type
) ) {
1586 count
= pi
.parameters
[ i
].type
.length
;
1590 if ( Util
.apiBool( pi
.parameters
[ i
].multi
) ) {
1592 if ( flag
&& !( widget
instanceof OO
.ui
.CapsuleMultiselectWidget
) &&
1594 widget
instanceof OptionalWidget
&&
1595 widget
.widget
instanceof OO
.ui
.CapsuleMultiselectWidget
1598 tmp
.push( mw
.message( 'api-help-param-multi-separate' ).parse() );
1600 if ( count
> pi
.parameters
[ i
].lowlimit
) {
1602 mw
.message( 'api-help-param-multi-max',
1603 pi
.parameters
[ i
].lowlimit
, pi
.parameters
[ i
].highlimit
1608 descriptionContainer
.append( $( '<div>', {
1610 append
: Util
.parseHTML( tmp
.join( ' ' ) )
1614 helpField
= new OO
.ui
.FieldLayout(
1617 classes
: [ 'mw-apisandbox-spacer' ]
1620 classes
: [ 'mw-apisandbox-help-field' ],
1621 label
: descriptionContainer
1625 widgetField
= new OO
.ui
.FieldLayout(
1629 classes
: [ 'mw-apisandbox-widget-field' ],
1630 label
: prefix
+ pi
.parameters
[ i
].name
1634 // We need our own click handler on the widget label to
1635 // turn off the disablement.
1636 widgetField
.$label
.on( 'click', widgetLabelOnClick
.bind( widgetField
) );
1638 // Don't grey out the label when the field is disabled,
1639 // it makes it too hard to read and our "disabled"
1640 // isn't really disabled.
1641 widgetField
.onFieldDisable( false );
1642 widgetField
.onFieldDisable
= $.noop
;
1644 if ( Util
.apiBool( pi
.parameters
[ i
].deprecated
) ) {
1645 deprecatedItems
.push( widgetField
, helpField
);
1647 items
.push( widgetField
, helpField
);
1652 if ( !pi
.parameters
.length
&& !Util
.apiBool( pi
.dynamicparameters
) ) {
1653 items
.push( new OO
.ui
.FieldLayout(
1654 new OO
.ui
.Widget( {} ).toggle( false ), {
1656 label
: Util
.parseMsg( 'apisandbox-no-parameters' )
1661 that
.$element
.empty();
1663 new OO
.ui
.FieldsetLayout( {
1664 label
: that
.displayText
1665 } ).addItems( items
)
1666 .$element
.appendTo( that
.$element
);
1668 if ( Util
.apiBool( pi
.dynamicparameters
) ) {
1669 dynamicFieldset
= new OO
.ui
.FieldsetLayout();
1670 dynamicParamNameWidget
= new OO
.ui
.TextInputWidget( {
1671 placeholder
: mw
.message( 'apisandbox-dynamic-parameters-add-placeholder' ).text()
1672 } ).on( 'enter', addDynamicParamWidget
);
1673 dynamicFieldset
.addItems( [
1674 new OO
.ui
.FieldLayout(
1675 new OO
.ui
.Widget( {} ).toggle( false ), {
1677 label
: Util
.parseHTML( pi
.dynamicparameters
)
1680 new OO
.ui
.ActionFieldLayout(
1681 dynamicParamNameWidget
,
1682 new OO
.ui
.ButtonWidget( {
1684 flags
: 'progressive'
1685 } ).on( 'click', addDynamicParamWidget
),
1687 label
: mw
.message( 'apisandbox-dynamic-parameters-add-label' ).text(),
1694 $( '<legend>' ).text( mw
.message( 'apisandbox-dynamic-parameters' ).text() ),
1695 dynamicFieldset
.$element
1697 .appendTo( that
.$element
);
1700 if ( deprecatedItems
.length
) {
1701 tmp
= new OO
.ui
.FieldsetLayout().addItems( deprecatedItems
).toggle( false );
1704 $( '<legend>' ).append(
1705 new OO
.ui
.ToggleButtonWidget( {
1706 label
: mw
.message( 'apisandbox-deprecated-parameters' ).text()
1707 } ).on( 'change', tmp
.toggle
, [], tmp
).$element
1711 .appendTo( that
.$element
);
1714 // Load stored params, if any, then update the booklet if we
1715 // have subpages (or else just update our valid-indicator).
1716 tmp
= that
.loadFromQueryParams
;
1717 that
.loadFromQueryParams
= null;
1718 if ( $.isPlainObject( tmp
) ) {
1719 that
.loadQueryParams( tmp
);
1721 if ( that
.getSubpages().length
> 0 ) {
1722 ApiSandbox
.updateUI( tmp
);
1724 that
.apiCheckValid();
1726 } ).fail( function ( code
, detail
) {
1727 that
.$element
.empty()
1729 new OO
.ui
.LabelWidget( {
1730 label
: mw
.message( 'apisandbox-load-error', that
.apiModule
, detail
).text(),
1731 classes
: [ 'error' ]
1733 new OO
.ui
.ButtonWidget( {
1734 label
: mw
.message( 'apisandbox-retry' ).text()
1735 } ).on( 'click', that
.loadParamInfo
, [], that
).$element
1741 * Check that all widgets on the page are in a valid state.
1745 ApiSandbox
.PageLayout
.prototype.apiCheckValid = function () {
1748 if ( this.paramInfo
=== null ) {
1749 return $.Deferred().resolve( false ).promise();
1751 return $.when
.apply( $, $.map( this.widgets
, function ( widget
) {
1752 return widget
.apiCheckValid();
1753 } ) ).then( function () {
1754 that
.apiIsValid
= $.inArray( false, arguments
) === -1;
1755 if ( that
.getOutlineItem() ) {
1756 that
.getOutlineItem().setIcon( that
.apiIsValid
|| suppressErrors
? null : 'alert' );
1757 that
.getOutlineItem().setIconTitle(
1758 that
.apiIsValid
|| suppressErrors
? '' : mw
.message( 'apisandbox-alert-page' ).plain()
1761 return $.Deferred().resolve( that
.apiIsValid
).promise();
1767 * Load form fields from query parameters
1769 * @param {Object} params
1771 ApiSandbox
.PageLayout
.prototype.loadQueryParams = function ( params
) {
1772 if ( this.paramInfo
=== null ) {
1773 this.loadFromQueryParams
= params
;
1775 $.each( this.widgets
, function ( name
, widget
) {
1776 var v
= params
.hasOwnProperty( name
) ? params
[ name
] : undefined;
1777 widget
.setApiValue( v
);
1783 * Load query params from form fields
1785 * @param {Object} params Write query parameters into this object
1786 * @param {Object} displayParams Write query parameters for display into this object
1788 ApiSandbox
.PageLayout
.prototype.getQueryParams = function ( params
, displayParams
) {
1789 $.each( this.widgets
, function ( name
, widget
) {
1790 var value
= widget
.getApiValue();
1791 if ( value
!== undefined ) {
1792 params
[ name
] = value
;
1793 if ( $.isFunction( widget
.getApiValueForDisplay
) ) {
1794 value
= widget
.getApiValueForDisplay();
1796 displayParams
[ name
] = value
;
1802 * Fetch a list of subpage names loaded by this page
1806 ApiSandbox
.PageLayout
.prototype.getSubpages = function () {
1808 $.each( this.widgets
, function ( name
, widget
) {
1810 if ( $.isFunction( widget
.getSubmodules
) ) {
1811 submodules
= widget
.getSubmodules();
1812 for ( i
= 0; i
< submodules
.length
; i
++ ) {
1814 key
: name
+ '=' + submodules
[ i
].value
,
1815 path
: submodules
[ i
].path
,
1816 prefix
: widget
.paramInfo
.submoduleparamprefix
|| ''
1825 * A text input with a clickable indicator
1830 * @param {Object} [config] Configuration options
1832 function TextInputWithIndicatorWidget( config
) {
1835 config
= config
|| {};
1836 TextInputWithIndicatorWidget
[ 'super' ].call( this, config
);
1838 this.$indicator
= $( '<span>' ).addClass( 'mw-apisandbox-clickable-indicator' );
1839 OO
.ui
.mixin
.TabIndexedElement
.call(
1840 this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} )
1843 this.input
= new OO
.ui
.TextInputWidget( $.extend( {
1844 $indicator
: this.$indicator
,
1845 disabled
: this.isDisabled()
1846 }, config
.input
) );
1848 // Forward most methods for convenience
1849 for ( k
in this.input
) {
1850 if ( $.isFunction( this.input
[ k
] ) && !this[ k
] ) {
1851 this[ k
] = this.input
[ k
].bind( this.input
);
1855 this.$indicator
.on( {
1856 click
: this.onIndicatorClick
.bind( this ),
1857 keypress
: this.onIndicatorKeyPress
.bind( this )
1860 this.$element
.append( this.input
.$element
);
1862 OO
.inheritClass( TextInputWithIndicatorWidget
, OO
.ui
.Widget
);
1863 OO
.mixinClass( TextInputWithIndicatorWidget
, OO
.ui
.mixin
.TabIndexedElement
);
1864 TextInputWithIndicatorWidget
.prototype.onIndicatorClick = function ( e
) {
1865 if ( !this.isDisabled() && e
.which
=== 1 ) {
1866 this.emit( 'indicator' );
1870 TextInputWithIndicatorWidget
.prototype.onIndicatorKeyPress = function ( e
) {
1871 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
1872 this.emit( 'indicator' );
1876 TextInputWithIndicatorWidget
.prototype.setDisabled = function ( disabled
) {
1877 TextInputWithIndicatorWidget
[ 'super' ].prototype.setDisabled
.call( this, disabled
);
1879 this.input
.setDisabled( this.isDisabled() );
1885 * A wrapper for a widget that provides an enable/disable button
1890 * @param {OO.ui.Widget} widget
1891 * @param {Object} [config] Configuration options
1893 function OptionalWidget( widget
, config
) {
1896 config
= config
|| {};
1898 this.widget
= widget
;
1899 this.$overlay
= config
.$overlay
||
1900 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-overlay' );
1901 this.checkbox
= new OO
.ui
.CheckboxInputWidget( config
.checkbox
)
1902 .on( 'change', this.onCheckboxChange
, [], this );
1904 OptionalWidget
[ 'super' ].call( this, config
);
1906 // Forward most methods for convenience
1907 for ( k
in this.widget
) {
1908 if ( $.isFunction( this.widget
[ k
] ) && !this[ k
] ) {
1909 this[ k
] = this.widget
[ k
].bind( this.widget
);
1913 this.$overlay
.on( 'click', this.onOverlayClick
.bind( this ) );
1916 .addClass( 'mw-apisandbox-optionalWidget' )
1919 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-fields' ).append(
1920 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-widget' ).append(
1923 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-checkbox' ).append(
1924 this.checkbox
.$element
1929 this.setDisabled( widget
.isDisabled() );
1931 OO
.inheritClass( OptionalWidget
, OO
.ui
.Widget
);
1932 OptionalWidget
.prototype.onCheckboxChange = function ( checked
) {
1933 this.setDisabled( !checked
);
1935 OptionalWidget
.prototype.onOverlayClick = function () {
1936 this.setDisabled( false );
1937 if ( $.isFunction( this.widget
.focus
) ) {
1938 this.widget
.focus();
1941 OptionalWidget
.prototype.setDisabled = function ( disabled
) {
1942 OptionalWidget
[ 'super' ].prototype.setDisabled
.call( this, disabled
);
1943 this.widget
.setDisabled( this.isDisabled() );
1944 this.checkbox
.setSelected( !this.isDisabled() );
1945 this.$overlay
.toggle( this.isDisabled() );
1949 $( ApiSandbox
.init
);
1951 module
.exports
= ApiSandbox
;
1953 }( jQuery
, mediaWiki
, OO
) );