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();
164 getApiValue: function () {
165 return this.isDisabled() ? undefined : this.widget
.getApiValue();
167 setApiValue: function ( v
) {
168 this.setDisabled( v
=== undefined );
169 this.widget
.setApiValue( v
);
171 apiCheckValid: function () {
172 if ( this.isDisabled() ) {
173 return $.Deferred().resolve( true ).promise();
175 return this.widget
.apiCheckValid();
181 single: function () {
182 var v
= this.isDisabled() ? this.paramInfo
[ 'default' ] : this.getApiValue();
183 return v
=== undefined ? [] : [ { value
: v
, path
: this.paramInfo
.submodules
[ v
] } ];
186 var map
= this.paramInfo
.submodules
,
187 v
= this.isDisabled() ? this.paramInfo
[ 'default' ] : this.getApiValue();
188 return v
=== undefined || v
=== '' ? [] : $.map( String( v
).split( '|' ), function ( v
) {
189 return { value
: v
, path
: map
[ v
] };
195 getApiValueForDisplay: function () {
198 getApiValue: function () {
199 return this.getValue();
201 setApiValue: function () {
204 apiCheckValid: function () {
205 var ok
= this.getValue() !== null || suppressErrors
;
206 this.setIcon( ok
? null : 'alert' );
207 this.setIconTitle( ok
? '' : mw
.message( 'apisandbox-alert-field' ).plain() );
208 return $.Deferred().resolve( ok
).promise();
214 generic: function () {
215 return !Util
.apiBool( this.paramInfo
.required
) || this.getApiValue() !== '';
220 * @class mw.special.ApiSandbox.Util
225 * Fetch API module info
227 * @param {string} module Module to fetch data for
228 * @return {jQuery.Promise}
230 fetchModuleInfo: function ( module
) {
232 deferred
= $.Deferred();
234 if ( moduleInfoCache
.hasOwnProperty( module
) ) {
236 .resolve( moduleInfoCache
[ module
] )
237 .promise( { abort: function () {} } );
239 apiPromise
= api
.post( {
243 uselang
: mw
.config
.get( 'wgUserLanguage' )
244 } ).done( function ( data
) {
247 if ( data
.warnings
&& data
.warnings
.paraminfo
) {
248 deferred
.reject( '???', data
.warnings
.paraminfo
[ '*' ] );
252 info
= data
.paraminfo
.modules
;
253 if ( !info
|| info
.length
!== 1 || info
[ 0 ].path
!== module
) {
254 deferred
.reject( '???', 'No module data returned' );
258 moduleInfoCache
[ module
] = info
[ 0 ];
259 deferred
.resolve( info
[ 0 ] );
260 } ).fail( function ( code
, details
) {
261 if ( code
=== 'http' ) {
262 details
= 'HTTP error: ' + details
.exception
;
263 } else if ( details
.error
) {
264 details
= details
.error
.info
;
266 deferred
.reject( code
, details
);
269 .promise( { abort
: apiPromise
.abort
} );
274 * Mark all currently-in-use tokens as bad
276 markTokensBad: function () {
277 var page
, subpages
, i
,
278 checkPages
= [ pages
.main
];
280 while ( checkPages
.length
) {
281 page
= checkPages
.shift();
283 if ( page
.tokenWidget
) {
284 api
.badToken( page
.tokenWidget
.paramInfo
.tokentype
);
287 subpages
= page
.getSubpages();
288 for ( i
= 0; i
< subpages
.length
; i
++ ) {
289 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
290 checkPages
.push( pages
[ subpages
[ i
].key
] );
297 * Test an API boolean
299 * @param {Mixed} value
302 apiBool: function ( value
) {
303 return value
!== undefined && value
!== false;
307 * Create a widget for a parameter.
309 * @param {Object} pi Parameter info from API
310 * @param {Object} opts Additional options
311 * @return {OO.ui.Widget}
313 createWidgetForParameter: function ( pi
, opts
) {
314 var widget
, innerWidget
, finalWidget
, items
, $button
, $content
, func
,
321 widget
= new OO
.ui
.ToggleSwitchWidget();
322 widget
.paramInfo
= pi
;
323 $.extend( widget
, WidgetMethods
.toggleSwitchWidget
);
324 pi
.required
= true; // Avoid wrapping in the non-required widget
329 if ( pi
.tokentype
) {
330 widget
= new TextInputWithIndicatorWidget( {
332 indicator
: 'previous',
333 indicatorTitle
: mw
.message( 'apisandbox-fetch-token' ).text(),
334 required
: Util
.apiBool( pi
.required
)
337 } else if ( Util
.apiBool( pi
.multi
) ) {
338 widget
= new OO
.ui
.CapsuleMultiselectWidget( {
339 allowArbitrary
: true,
340 allowDuplicates
: Util
.apiBool( pi
.allowsduplicates
),
341 $overlay
: $( '#mw-apisandbox-ui' )
343 widget
.paramInfo
= pi
;
344 $.extend( widget
, WidgetMethods
.capsuleWidget
);
346 widget
= new OO
.ui
.TextInputWidget( {
347 required
: Util
.apiBool( pi
.required
)
350 if ( !Util
.apiBool( pi
.multi
) ) {
351 widget
.paramInfo
= pi
;
352 $.extend( widget
, WidgetMethods
.textInputWidget
);
353 widget
.setValidation( Validators
.generic
);
355 if ( pi
.tokentype
) {
356 $.extend( widget
, WidgetMethods
.tokenWidget
);
357 widget
.input
.paramInfo
= pi
;
358 $.extend( widget
.input
, WidgetMethods
.textInputWidget
);
359 $.extend( widget
.input
, WidgetMethods
.tokenWidget
);
360 widget
.on( 'indicator', widget
.fetchToken
, [], widget
);
365 widget
= new OO
.ui
.TextInputWidget( {
367 required
: Util
.apiBool( pi
.required
)
369 widget
.paramInfo
= pi
;
370 $.extend( widget
, WidgetMethods
.textInputWidget
);
371 widget
.setValidation( Validators
.generic
);
375 widget
= new OO
.ui
.TextInputWidget( {
377 required
: Util
.apiBool( pi
.required
)
379 widget
.paramInfo
= pi
;
380 $.extend( widget
, WidgetMethods
.textInputWidget
);
381 $.extend( widget
, WidgetMethods
.passwordWidget
);
382 widget
.setValidation( Validators
.generic
);
387 widget
= new OO
.ui
.NumberInputWidget( {
388 required
: Util
.apiBool( pi
.required
),
391 widget
.setIcon
= widget
.input
.setIcon
.bind( widget
.input
);
392 widget
.setIconTitle
= widget
.input
.setIconTitle
.bind( widget
.input
);
393 widget
.getValidity
= widget
.input
.getValidity
.bind( widget
.input
);
394 widget
.paramInfo
= pi
;
395 $.extend( widget
, WidgetMethods
.textInputWidget
);
396 if ( Util
.apiBool( pi
.enforcerange
) ) {
397 widget
.setRange( pi
.min
|| -Infinity
, pi
.max
|| Infinity
);
403 widget
= new OO
.ui
.TextInputWidget( {
404 required
: Util
.apiBool( pi
.required
)
406 widget
.setValidation( function ( value
) {
407 var n
, pi
= this.paramInfo
;
409 if ( value
=== 'max' ) {
413 return !isNaN( n
) && isFinite( n
) &&
414 Math
.floor( n
) === n
&&
415 n
>= pi
.min
&& n
<= pi
.apiSandboxMax
;
418 pi
.min
= pi
.min
|| 0;
419 pi
.apiSandboxMax
= mw
.config
.get( 'apihighlimits' ) ? pi
.highmax
: pi
.max
;
420 widget
.paramInfo
= pi
;
421 $.extend( widget
, WidgetMethods
.textInputWidget
);
426 widget
= new mw
.widgets
.datetime
.DateTimeInputWidget( {
428 format
: '${year|0}-${month|0}-${day|0}T${hour|0}:${minute|0}:${second|0}${zone|short}'
430 required
: Util
.apiBool( pi
.required
),
433 widget
.paramInfo
= pi
;
434 $.extend( widget
, WidgetMethods
.textInputWidget
);
435 $.extend( widget
, WidgetMethods
.dateTimeInputWidget
);
436 multiMode
= 'indicator';
440 widget
= new OO
.ui
.SelectFileWidget();
441 widget
.paramInfo
= pi
;
442 $.extend( widget
, WidgetMethods
.uploadWidget
);
446 items
= $.map( mw
.config
.get( 'wgFormattedNamespaces' ), function ( name
, ns
) {
448 name
= mw
.message( 'blanknamespace' ).text();
450 return new OO
.ui
.MenuOptionWidget( { data
: ns
, label
: name
} );
451 } ).sort( function ( a
, b
) {
452 return a
.data
- b
.data
;
454 if ( Util
.apiBool( pi
.multi
) ) {
455 if ( pi
.allspecifier
!== undefined ) {
456 items
.unshift( new OO
.ui
.MenuOptionWidget( {
457 data
: pi
.allspecifier
,
458 label
: mw
.message( 'apisandbox-multivalue-all-namespaces', pi
.allspecifier
).text()
462 widget
= new OO
.ui
.CapsuleMultiselectWidget( {
463 menu
: { items
: items
},
464 $overlay
: $( '#mw-apisandbox-ui' )
466 widget
.paramInfo
= pi
;
467 $.extend( widget
, WidgetMethods
.capsuleWidget
);
469 widget
= new OO
.ui
.DropdownWidget( {
470 menu
: { items
: items
},
471 $overlay
: $( '#mw-apisandbox-ui' )
473 widget
.paramInfo
= pi
;
474 $.extend( widget
, WidgetMethods
.dropdownWidget
);
479 if ( !Array
.isArray( pi
.type
) ) {
480 throw new Error( 'Unknown parameter type ' + pi
.type
);
483 items
= $.map( pi
.type
, function ( v
) {
484 return new OO
.ui
.MenuOptionWidget( { data
: String( v
), label
: String( v
) } );
486 if ( Util
.apiBool( pi
.multi
) ) {
487 if ( pi
.allspecifier
!== undefined ) {
488 items
.unshift( new OO
.ui
.MenuOptionWidget( {
489 data
: pi
.allspecifier
,
490 label
: mw
.message( 'apisandbox-multivalue-all-values', pi
.allspecifier
).text()
494 widget
= new OO
.ui
.CapsuleMultiselectWidget( {
495 menu
: { items
: items
},
496 $overlay
: $( '#mw-apisandbox-ui' )
498 widget
.paramInfo
= pi
;
499 $.extend( widget
, WidgetMethods
.capsuleWidget
);
500 if ( Util
.apiBool( pi
.submodules
) ) {
501 widget
.getSubmodules
= WidgetMethods
.submoduleWidget
.multi
;
502 widget
.on( 'change', ApiSandbox
.updateUI
);
505 widget
= new OO
.ui
.DropdownWidget( {
506 menu
: { items
: items
},
507 $overlay
: $( '#mw-apisandbox-ui' )
509 widget
.paramInfo
= pi
;
510 $.extend( widget
, WidgetMethods
.dropdownWidget
);
511 if ( Util
.apiBool( pi
.submodules
) ) {
512 widget
.getSubmodules
= WidgetMethods
.submoduleWidget
.single
;
513 widget
.getMenu().on( 'choose', ApiSandbox
.updateUI
);
520 if ( Util
.apiBool( pi
.multi
) && multiMode
!== 'none' ) {
521 innerWidget
= widget
;
522 switch ( multiMode
) {
524 $content
= innerWidget
.$element
;
528 $button
= innerWidget
.$indicator
;
529 $button
.css( 'cursor', 'pointer' );
530 $button
.attr( 'tabindex', 0 );
531 $button
.parent().append( $button
);
532 innerWidget
.setIndicator( 'next' );
533 $content
= innerWidget
.$element
;
537 throw new Error( 'Unknown multiMode "' + multiMode
+ '"' );
540 widget
= new OO
.ui
.CapsuleMultiselectWidget( {
541 allowArbitrary
: true,
542 allowDuplicates
: Util
.apiBool( pi
.allowsduplicates
),
543 $overlay
: $( '#mw-apisandbox-ui' ),
545 classes
: [ 'mw-apisandbox-popup' ],
549 widget
.paramInfo
= pi
;
550 $.extend( widget
, WidgetMethods
.capsuleWidget
);
553 if ( !innerWidget
.isDisabled() ) {
554 innerWidget
.apiCheckValid().done( function ( ok
) {
556 widget
.addItemsFromData( [ innerWidget
.getApiValue() ] );
557 innerWidget
.setApiValue( undefined );
563 switch ( multiMode
) {
565 innerWidget
.connect( null, { enter
: func
} );
571 keypress: function ( e
) {
572 if ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) {
581 if ( Util
.apiBool( pi
.required
) || opts
.nooptional
) {
582 finalWidget
= widget
;
584 finalWidget
= new OptionalWidget( widget
);
585 finalWidget
.paramInfo
= pi
;
586 $.extend( finalWidget
, WidgetMethods
.optionalWidget
);
587 if ( widget
.getSubmodules
) {
588 finalWidget
.getSubmodules
= widget
.getSubmodules
.bind( widget
);
589 finalWidget
.on( 'disable', function () { setTimeout( ApiSandbox
.updateUI
); } );
591 finalWidget
.setDisabled( true );
594 widget
.setApiValue( pi
[ 'default' ] );
600 * Parse an HTML string and call Util.fixupHTML()
602 * @param {string} html HTML to parse
605 parseHTML: function ( html
) {
606 var $ret
= $( $.parseHTML( html
) );
607 return Util
.fixupHTML( $ret
);
611 * Parse an i18n message and call Util.fixupHTML()
613 * @param {string} key Key of message to get
614 * @param {...Mixed} parameters Values for $N replacements
617 parseMsg: function () {
618 var $ret
= mw
.message
.apply( mw
.message
, arguments
).parseDom();
619 return Util
.fixupHTML( $ret
);
623 * Fix HTML for ApiSandbox display
626 * - Add target="_blank" to any links
628 * @param {jQuery} $html DOM to process
631 fixupHTML: function ( $html
) {
632 $html
.filter( 'a' ).add( $html
.find( 'a' ) )
633 .filter( '[href]:not([target])' )
634 .attr( 'target', '_blank' );
639 * Format a request and return a bunch of menu option widgets
641 * @param {Object} displayParams Query parameters, sanitized for display.
642 * @param {Object} rawParams Query parameters. You should probably use displayParams instead.
643 * @return {OO.ui.MenuOptionWidget[]} Each item's data should be an OO.ui.FieldLayout
645 formatRequest: function ( displayParams
, rawParams
) {
648 new OO
.ui
.MenuOptionWidget( {
649 label
: Util
.parseMsg( 'apisandbox-request-format-url-label' ),
650 data
: new OO
.ui
.FieldLayout(
651 new OO
.ui
.TextInputWidget( {
653 value
: mw
.util
.wikiScript( 'api' ) + '?' + $.param( displayParams
)
655 label
: Util
.parseMsg( 'apisandbox-request-url-label' )
659 new OO
.ui
.MenuOptionWidget( {
660 label
: Util
.parseMsg( 'apisandbox-request-format-json-label' ),
661 data
: new OO
.ui
.FieldLayout(
662 jsonInput
= new OO
.ui
.TextInputWidget( {
663 classes
: [ 'mw-apisandbox-textInputCode' ],
668 value
: JSON
.stringify( displayParams
, null, '\t' )
670 label
: Util
.parseMsg( 'apisandbox-request-json-label' )
672 ).on( 'toggle', function ( visible
) {
674 // Call updatePosition instead of adjustSize
675 // because the latter has weird caching
676 // behavior and the former bypasses it.
677 jsonInput
.updatePosition();
683 mw
.hook( 'apisandbox.formatRequest' ).fire( items
, displayParams
, rawParams
);
689 * Event handler for when formatDropdown's selection changes
691 onFormatDropdownChange: function () {
693 menu
= formatDropdown
.getMenu(),
694 items
= menu
.getItems(),
695 selectedField
= menu
.getSelectedItem() ? menu
.getSelectedItem().getData() : null;
697 for ( i
= 0; i
< items
.length
; i
++ ) {
698 items
[ i
].getData().toggle( items
[ i
].getData() === selectedField
);
704 * Interface to ApiSandbox UI
706 * @class mw.special.ApiSandbox
712 * Automatically called on $.ready()
717 ApiSandbox
.isFullscreen
= false;
719 $content
= $( '#mw-apisandbox' );
721 windowManager
= new OO
.ui
.WindowManager();
722 $( 'body' ).append( windowManager
.$element
);
723 windowManager
.addWindows( {
724 errorAlert
: new OO
.ui
.MessageDialog()
727 fullscreenButton
= new OO
.ui
.ButtonWidget( {
728 label
: mw
.message( 'apisandbox-fullscreen' ).text(),
729 title
: mw
.message( 'apisandbox-fullscreen-tooltip' ).text()
730 } ).on( 'click', ApiSandbox
.toggleFullscreen
);
732 $toolbar
= $( '<div>' )
733 .addClass( 'mw-apisandbox-toolbar' )
735 fullscreenButton
.$element
,
736 new OO
.ui
.ButtonWidget( {
737 label
: mw
.message( 'apisandbox-submit' ).text(),
738 flags
: [ 'primary', 'progressive' ]
739 } ).on( 'click', ApiSandbox
.sendRequest
).$element
,
740 new OO
.ui
.ButtonWidget( {
741 label
: mw
.message( 'apisandbox-reset' ).text(),
743 } ).on( 'click', ApiSandbox
.resetUI
).$element
746 booklet
= new OO
.ui
.BookletLayout( {
751 panel
= new OO
.ui
.PanelLayout( {
752 classes
: [ 'mw-apisandbox-container' ],
753 content
: [ booklet
],
758 pages
.main
= new ApiSandbox
.PageLayout( { key
: 'main', path
: 'main' } );
760 // Parse the current hash string
761 if ( !ApiSandbox
.loadFromHash() ) {
762 ApiSandbox
.updateUI();
765 // If the hashchange event exists, use it. Otherwise, fake it.
766 // And, of course, IE has to be dumb.
767 if ( 'onhashchange' in window
&&
768 ( document
.documentMode
=== undefined || document
.documentMode
>= 8 )
770 $( window
).on( 'hashchange', ApiSandbox
.loadFromHash
);
772 setInterval( function () {
773 if ( oldhash
!== location
.hash
) {
774 ApiSandbox
.loadFromHash();
781 .append( $( '<p>' ).append( Util
.parseMsg( 'apisandbox-intro' ) ) )
783 $( '<div>', { id
: 'mw-apisandbox-ui' } )
785 .append( panel
.$element
)
788 $( window
).on( 'resize', ApiSandbox
.resizePanel
);
790 ApiSandbox
.resizePanel();
794 * Toggle "fullscreen" mode
796 toggleFullscreen: function () {
797 var $body
= $( document
.body
),
798 $ui
= $( '#mw-apisandbox-ui' );
800 ApiSandbox
.isFullscreen
= !ApiSandbox
.isFullscreen
;
802 $body
.toggleClass( 'mw-apisandbox-fullscreen', ApiSandbox
.isFullscreen
);
803 $ui
.toggleClass( 'mw-body-content', ApiSandbox
.isFullscreen
);
804 if ( ApiSandbox
.isFullscreen
) {
805 fullscreenButton
.setLabel( mw
.message( 'apisandbox-unfullscreen' ).text() );
806 fullscreenButton
.setTitle( mw
.message( 'apisandbox-unfullscreen-tooltip' ).text() );
809 fullscreenButton
.setLabel( mw
.message( 'apisandbox-fullscreen' ).text() );
810 fullscreenButton
.setTitle( mw
.message( 'apisandbox-fullscreen-tooltip' ).text() );
811 $content
.append( $ui
);
813 ApiSandbox
.resizePanel();
817 * Set the height of the panel based on the current viewport.
819 resizePanel: function () {
820 var height
= $( window
).height(),
821 contentTop
= $content
.offset().top
;
823 if ( ApiSandbox
.isFullscreen
) {
824 height
-= panel
.$element
.offset().top
- $( '#mw-apisandbox-ui' ).offset().top
;
825 panel
.$element
.height( height
- 1 );
827 // Subtract the height of the intro text
828 height
-= panel
.$element
.offset().top
- contentTop
;
830 panel
.$element
.height( height
- 10 );
831 $( window
).scrollTop( contentTop
- 5 );
836 * Update the current query when the page hash changes
838 * @return {boolean} Successful
840 loadFromHash: function () {
842 hash
= location
.hash
;
844 if ( oldhash
=== hash
) {
852 // I'm surprised this doesn't seem to exist in jQuery or mw.util.
854 hash
= hash
.replace( /\+/g, '%20' );
855 re
= /([^&=#]+)=?([^&#]*)/g;
856 while ( ( m
= re
.exec( hash
) ) ) {
857 params
[ decodeURIComponent( m
[ 1 ] ) ] = decodeURIComponent( m
[ 2 ] );
860 ApiSandbox
.updateUI( params
);
865 * Update the pages in the booklet
867 * @param {Object} [params] Optional query parameters to load
869 updateUI: function ( params
) {
870 var i
, page
, subpages
, j
, removePages
,
873 if ( !$.isPlainObject( params
) ) {
877 if ( updatingBooklet
) {
880 updatingBooklet
= true;
882 if ( params
!== undefined ) {
883 pages
.main
.loadQueryParams( params
);
885 addPages
.push( pages
.main
);
886 if ( resultPage
!== null ) {
887 addPages
.push( resultPage
);
889 pages
.main
.apiCheckValid();
892 while ( addPages
.length
) {
893 page
= addPages
.shift();
894 if ( bookletPages
[ i
] !== page
) {
895 for ( j
= i
; j
< bookletPages
.length
; j
++ ) {
896 if ( bookletPages
[ j
].getName() === page
.getName() ) {
897 bookletPages
.splice( j
, 1 );
900 bookletPages
.splice( i
, 0, page
);
901 booklet
.addPages( [ page
], i
);
905 if ( page
.getSubpages
) {
906 subpages
= page
.getSubpages();
907 for ( j
= 0; j
< subpages
.length
; j
++ ) {
908 if ( !pages
.hasOwnProperty( subpages
[ j
].key
) ) {
909 subpages
[ j
].indentLevel
= page
.indentLevel
+ 1;
910 pages
[ subpages
[ j
].key
] = new ApiSandbox
.PageLayout( subpages
[ j
] );
912 if ( params
!== undefined ) {
913 pages
[ subpages
[ j
].key
].loadQueryParams( params
);
915 addPages
.splice( j
, 0, pages
[ subpages
[ j
].key
] );
916 pages
[ subpages
[ j
].key
].apiCheckValid();
921 if ( bookletPages
.length
> i
) {
922 removePages
= bookletPages
.splice( i
, bookletPages
.length
- i
);
923 booklet
.removePages( removePages
);
926 if ( !booklet
.getCurrentPageName() ) {
927 booklet
.selectFirstSelectablePage();
930 updatingBooklet
= false;
935 * Reset button handler
937 resetUI: function () {
938 suppressErrors
= true;
940 main
: new ApiSandbox
.PageLayout( { key
: 'main', path
: 'main' } )
943 ApiSandbox
.updateUI();
947 * Submit button handler
949 * @param {Object} [params] Use this set of params instead of those in the form fields.
950 * The form fields will be updated to match.
952 sendRequest: function ( params
) {
953 var page
, subpages
, i
, query
, $result
, $focus
,
954 progress
, $progressText
, progressLoading
,
956 paramsAreForced
= !!params
,
958 checkPages
= [ pages
.main
];
960 // Blur any focused widget before submit, because
961 // OO.ui.ButtonWidget doesn't take focus itself (T128054)
962 $focus
= $( '#mw-apisandbox-ui' ).find( document
.activeElement
);
963 if ( $focus
.length
) {
967 suppressErrors
= false;
969 // save widget state in params (or load from it if we are forced)
970 if ( paramsAreForced
) {
971 ApiSandbox
.updateUI( params
);
974 while ( checkPages
.length
) {
975 page
= checkPages
.shift();
976 deferreds
.push( page
.apiCheckValid() );
977 page
.getQueryParams( params
, displayParams
);
978 subpages
= page
.getSubpages();
979 for ( i
= 0; i
< subpages
.length
; i
++ ) {
980 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
981 checkPages
.push( pages
[ subpages
[ i
].key
] );
986 if ( !paramsAreForced
) {
987 // forced params means we are continuing a query; the base query should be preserved
988 baseRequestParams
= $.extend( {}, params
);
991 $.when
.apply( $, deferreds
).done( function () {
992 var formatItems
, menu
, selectedLabel
;
994 if ( $.inArray( false, arguments
) !== -1 ) {
995 windowManager
.openWindow( 'errorAlert', {
996 title
: Util
.parseMsg( 'apisandbox-submit-invalid-fields-title' ),
997 message
: Util
.parseMsg( 'apisandbox-submit-invalid-fields-message' ),
1001 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' ),
1009 query
= $.param( displayParams
);
1011 formatItems
= Util
.formatRequest( displayParams
, params
);
1013 // Force a 'fm' format with wrappedhtml=1, if available
1014 if ( params
.format
!== undefined ) {
1015 if ( availableFormats
.hasOwnProperty( params
.format
+ 'fm' ) ) {
1016 params
.format
= params
.format
+ 'fm';
1018 if ( params
.format
.substr( -2 ) === 'fm' ) {
1019 params
.wrappedhtml
= 1;
1023 progressLoading
= false;
1024 $progressText
= $( '<span>' ).text( mw
.message( 'apisandbox-sending-request' ).text() );
1025 progress
= new OO
.ui
.ProgressBarWidget( {
1027 $content
: $progressText
1030 $result
= $( '<div>' )
1031 .append( progress
.$element
);
1033 resultPage
= page
= new OO
.ui
.PageLayout( '|results|' );
1034 page
.setupOutlineItem = function () {
1035 this.outlineItem
.setLabel( mw
.message( 'apisandbox-results' ).text() );
1038 if ( !formatDropdown
) {
1039 formatDropdown
= new OO
.ui
.DropdownWidget( {
1040 menu
: { items
: [] },
1041 $overlay
: $( '#mw-apisandbox-ui' )
1043 formatDropdown
.getMenu().on( 'choose', Util
.onFormatDropdownChange
);
1046 menu
= formatDropdown
.getMenu();
1047 selectedLabel
= menu
.getSelectedItem() ? menu
.getSelectedItem().getLabel() : '';
1048 if ( typeof selectedLabel
!== 'string' ) {
1049 selectedLabel
= selectedLabel
.text();
1051 menu
.clearItems().addItems( formatItems
);
1052 menu
.chooseItem( menu
.getItemFromLabel( selectedLabel
) || menu
.getFirstSelectableItem() );
1054 // Fire the event to update field visibilities
1055 Util
.onFormatDropdownChange();
1057 page
.$element
.empty()
1059 new OO
.ui
.FieldLayout(
1061 label
: Util
.parseMsg( 'apisandbox-request-selectformat-label' )
1064 $.map( formatItems
, function ( item
) {
1065 return item
.getData().$element
;
1069 ApiSandbox
.updateUI();
1070 booklet
.setPage( '|results|' );
1072 location
.href
= oldhash
= '#' + query
;
1075 contentType
: 'multipart/form-data',
1078 var xhr
= new window
.XMLHttpRequest();
1079 xhr
.upload
.addEventListener( 'progress', function ( e
) {
1080 if ( !progressLoading
) {
1081 if ( e
.lengthComputable
) {
1082 progress
.setProgress( e
.loaded
* 100 / e
.total
);
1084 progress
.setProgress( false );
1088 xhr
.addEventListener( 'progress', function ( e
) {
1089 if ( !progressLoading
) {
1090 progressLoading
= true;
1091 $progressText
.text( mw
.message( 'apisandbox-loading-results' ).text() );
1093 if ( e
.lengthComputable
) {
1094 progress
.setProgress( e
.loaded
* 100 / e
.total
);
1096 progress
.setProgress( false );
1102 .then( null, function ( code
, data
, result
, jqXHR
) {
1103 if ( code
!== 'http' ) {
1104 // Not really an error, work around mw.Api thinking it is.
1106 .resolve( result
, jqXHR
)
1111 .fail( function ( code
, data
) {
1112 var details
= 'HTTP error: ' + data
.exception
;
1115 new OO
.ui
.LabelWidget( {
1116 label
: mw
.message( 'apisandbox-results-error', details
).text(),
1117 classes
: [ 'error' ]
1121 .done( function ( data
, jqXHR
) {
1122 var m
, loadTime
, button
, clear
,
1123 ct
= jqXHR
.getResponseHeader( 'Content-Type' ),
1124 loginSuppressed
= jqXHR
.getResponseHeader( 'MediaWiki-Login-Suppressed' ) || 'false';
1127 if ( loginSuppressed
!== 'false' ) {
1129 .addClass( 'warning' )
1130 .append( Util
.parseMsg( 'apisandbox-results-login-suppressed' ) )
1131 .appendTo( $result
);
1133 if ( /^text\/mediawiki-api-prettyprint-wrapped(?:;|$)/.test( ct
) ) {
1134 data
= JSON
.parse( data
);
1135 if ( data
.modules
.length
) {
1136 mw
.loader
.load( data
.modules
);
1138 if ( data
.status
&& data
.status
!== 200 ) {
1140 .addClass( 'api-pretty-header api-pretty-status' )
1141 .append( Util
.parseMsg( 'api-format-prettyprint-status', data
.status
, data
.statustext
) )
1142 .appendTo( $result
);
1144 $result
.append( Util
.parseHTML( data
.html
) );
1145 loadTime
= data
.time
;
1146 } else if ( ( m
= data
.match( /<pre[ >][\s\S]*<\/pre>/ ) ) ) {
1147 $result
.append( Util
.parseHTML( m
[ 0 ] ) );
1148 if ( ( m
= data
.match( /"wgBackendResponseTime":\s*(\d+)/ ) ) ) {
1149 loadTime
= parseInt( m
[ 1 ], 10 );
1153 .addClass( 'api-pretty-content' )
1155 .appendTo( $result
);
1157 if ( paramsAreForced
|| data
[ 'continue' ] ) {
1159 $( '<div>' ).append(
1160 new OO
.ui
.ButtonWidget( {
1161 label
: mw
.message( 'apisandbox-continue' ).text()
1162 } ).on( 'click', function () {
1163 ApiSandbox
.sendRequest( $.extend( {}, baseRequestParams
, data
[ 'continue' ] ) );
1164 } ).setDisabled( !data
[ 'continue' ] ).$element
,
1165 ( clear
= new OO
.ui
.ButtonWidget( {
1166 label
: mw
.message( 'apisandbox-continue-clear' ).text()
1167 } ).on( 'click', function () {
1168 ApiSandbox
.updateUI( baseRequestParams
);
1169 clear
.setDisabled( true );
1170 booklet
.setPage( '|results|' );
1171 } ).setDisabled( !paramsAreForced
) ).$element
,
1172 new OO
.ui
.PopupButtonWidget( {
1173 $overlay
: $( '#mw-apisandbox-ui' ),
1177 $content
: $( '<div>' ).append( Util
.parseMsg( 'apisandbox-continue-help' ) ),
1185 if ( typeof loadTime
=== 'number' ) {
1187 $( '<div>' ).append(
1188 new OO
.ui
.LabelWidget( {
1189 label
: mw
.message( 'apisandbox-request-time', loadTime
).text()
1195 if ( jqXHR
.getResponseHeader( 'MediaWiki-API-Error' ) === 'badtoken' ) {
1196 // Flush all saved tokens in case one of them is the bad one.
1197 Util
.markTokensBad();
1198 button
= new OO
.ui
.ButtonWidget( {
1199 label
: mw
.message( 'apisandbox-results-fixtoken' ).text()
1201 button
.on( 'click', ApiSandbox
.fixTokenAndResend
)
1202 .on( 'click', button
.setDisabled
, [ true ], button
)
1203 .$element
.appendTo( $result
);
1210 * Handler for the "Correct token and resubmit" button
1212 * Used on a 'badtoken' error, it re-fetches token parameters for all
1213 * pages and then re-submits the query.
1215 fixTokenAndResend: function () {
1216 var page
, subpages
, i
, k
,
1218 tokenWait
= { dummy
: true },
1219 checkPages
= [ pages
.main
],
1220 success = function ( k
) {
1221 delete tokenWait
[ k
];
1222 if ( ok
&& $.isEmptyObject( tokenWait
) ) {
1223 ApiSandbox
.sendRequest();
1226 failure = function ( k
) {
1227 delete tokenWait
[ k
];
1231 while ( checkPages
.length
) {
1232 page
= checkPages
.shift();
1234 if ( page
.tokenWidget
) {
1235 k
= page
.apiModule
+ page
.tokenWidget
.paramInfo
.name
;
1236 tokenWait
[ k
] = page
.tokenWidget
.fetchToken();
1238 .done( success
.bind( page
.tokenWidget
, k
) )
1239 .fail( failure
.bind( page
.tokenWidget
, k
) );
1242 subpages
= page
.getSubpages();
1243 for ( i
= 0; i
< subpages
.length
; i
++ ) {
1244 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
1245 checkPages
.push( pages
[ subpages
[ i
].key
] );
1250 success( 'dummy', '' );
1254 * Reset validity indicators for all widgets
1256 updateValidityIndicators: function () {
1257 var page
, subpages
, i
,
1258 checkPages
= [ pages
.main
];
1260 while ( checkPages
.length
) {
1261 page
= checkPages
.shift();
1262 page
.apiCheckValid();
1263 subpages
= page
.getSubpages();
1264 for ( i
= 0; i
< subpages
.length
; i
++ ) {
1265 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
1266 checkPages
.push( pages
[ subpages
[ i
].key
] );
1274 * PageLayout for API modules
1278 * @extends OO.ui.PageLayout
1280 * @param {Object} [config] Configuration options
1282 ApiSandbox
.PageLayout = function ( config
) {
1283 config
= $.extend( { prefix
: '' }, config
);
1284 this.displayText
= config
.key
;
1285 this.apiModule
= config
.path
;
1286 this.prefix
= config
.prefix
;
1287 this.paramInfo
= null;
1288 this.apiIsValid
= true;
1289 this.loadFromQueryParams
= null;
1291 this.tokenWidget
= null;
1292 this.indentLevel
= config
.indentLevel
? config
.indentLevel
: 0;
1293 ApiSandbox
.PageLayout
[ 'super' ].call( this, config
.key
, config
);
1294 this.loadParamInfo();
1296 OO
.inheritClass( ApiSandbox
.PageLayout
, OO
.ui
.PageLayout
);
1297 ApiSandbox
.PageLayout
.prototype.setupOutlineItem = function () {
1298 this.outlineItem
.setLevel( this.indentLevel
);
1299 this.outlineItem
.setLabel( this.displayText
);
1300 this.outlineItem
.setIcon( this.apiIsValid
|| suppressErrors
? null : 'alert' );
1301 this.outlineItem
.setIconTitle(
1302 this.apiIsValid
|| suppressErrors
? '' : mw
.message( 'apisandbox-alert-page' ).plain()
1307 * Fetch module information for this page's module, then create UI
1309 ApiSandbox
.PageLayout
.prototype.loadParamInfo = function () {
1310 var dynamicFieldset
, dynamicParamNameWidget
,
1312 removeDynamicParamWidget = function ( name
, layout
) {
1313 dynamicFieldset
.removeItems( [ layout
] );
1314 delete that
.widgets
[ name
];
1316 addDynamicParamWidget = function () {
1317 var name
, layout
, widget
, button
;
1319 // Check name is filled in
1320 name
= dynamicParamNameWidget
.getValue().trim();
1321 if ( name
=== '' ) {
1322 dynamicParamNameWidget
.focus();
1326 if ( that
.widgets
[ name
] !== undefined ) {
1327 windowManager
.openWindow( 'errorAlert', {
1328 title
: Util
.parseMsg( 'apisandbox-dynamic-error-exists', name
),
1332 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' ),
1340 widget
= Util
.createWidgetForParameter( {
1347 button
= new OO
.ui
.ButtonWidget( {
1349 flags
: 'destructive'
1351 layout
= new OO
.ui
.ActionFieldLayout(
1359 button
.on( 'click', removeDynamicParamWidget
, [ name
, layout
] );
1360 that
.widgets
[ name
] = widget
;
1361 dynamicFieldset
.addItems( [ layout
], dynamicFieldset
.getItems().length
- 1 );
1364 dynamicParamNameWidget
.setValue( '' );
1367 this.$element
.empty()
1368 .append( new OO
.ui
.ProgressBarWidget( {
1370 text
: mw
.message( 'apisandbox-loading', this.displayText
).text()
1373 Util
.fetchModuleInfo( this.apiModule
)
1374 .done( function ( pi
) {
1375 var prefix
, i
, j
, descriptionContainer
, widget
, widgetField
, helpField
, tmp
, flag
, count
,
1377 deprecatedItems
= [],
1379 filterFmModules = function ( v
) {
1380 return v
.substr( -2 ) !== 'fm' ||
1381 !availableFormats
.hasOwnProperty( v
.substr( 0, v
.length
- 2 ) );
1383 widgetLabelOnClick = function () {
1384 var f
= this.getField();
1385 if ( $.isFunction( f
.setDisabled
) ) {
1386 f
.setDisabled( false );
1388 if ( $.isFunction( f
.focus
) ) {
1392 doNothing = function () {};
1394 // This is something of a hack. We always want the 'format' and
1395 // 'action' parameters from the main module to be specified,
1396 // and for 'format' we also want to simplify the dropdown since
1397 // we always send the 'fm' variant.
1398 if ( that
.apiModule
=== 'main' ) {
1399 for ( i
= 0; i
< pi
.parameters
.length
; i
++ ) {
1400 if ( pi
.parameters
[ i
].name
=== 'action' ) {
1401 pi
.parameters
[ i
].required
= true;
1402 delete pi
.parameters
[ i
][ 'default' ];
1404 if ( pi
.parameters
[ i
].name
=== 'format' ) {
1405 tmp
= pi
.parameters
[ i
].type
;
1406 for ( j
= 0; j
< tmp
.length
; j
++ ) {
1407 availableFormats
[ tmp
[ j
] ] = true;
1409 pi
.parameters
[ i
].type
= $.grep( tmp
, filterFmModules
);
1410 pi
.parameters
[ i
][ 'default' ] = 'json';
1411 pi
.parameters
[ i
].required
= true;
1416 // Hide the 'wrappedhtml' parameter on format modules
1417 if ( pi
.group
=== 'format' ) {
1418 pi
.parameters
= $.grep( pi
.parameters
, function ( p
) {
1419 return p
.name
!== 'wrappedhtml';
1423 that
.paramInfo
= pi
;
1425 items
.push( new OO
.ui
.FieldLayout(
1426 new OO
.ui
.Widget( {} ).toggle( false ), {
1428 label
: Util
.parseHTML( pi
.description
)
1432 if ( pi
.helpurls
.length
) {
1433 buttons
.push( new OO
.ui
.PopupButtonWidget( {
1434 $overlay
: $( '#mw-apisandbox-ui' ),
1435 label
: mw
.message( 'apisandbox-helpurls' ).text(),
1440 $content
: $( '<ul>' ).append( $.map( pi
.helpurls
, function ( link
) {
1441 return $( '<li>' ).append( $( '<a>', {
1451 if ( pi
.examples
.length
) {
1452 buttons
.push( new OO
.ui
.PopupButtonWidget( {
1453 $overlay
: $( '#mw-apisandbox-ui' ),
1454 label
: mw
.message( 'apisandbox-examples' ).text(),
1459 $content
: $( '<ul>' ).append( $.map( pi
.examples
, function ( example
) {
1461 href
: '#' + example
.query
,
1462 html
: example
.description
1464 a
.find( 'a' ).contents().unwrap(); // Can't nest links
1465 return $( '<li>' ).append( a
);
1471 if ( buttons
.length
) {
1472 items
.push( new OO
.ui
.FieldLayout(
1473 new OO
.ui
.ButtonGroupWidget( {
1475 } ), { align
: 'top' }
1479 if ( pi
.parameters
.length
) {
1480 prefix
= that
.prefix
+ pi
.prefix
;
1481 for ( i
= 0; i
< pi
.parameters
.length
; i
++ ) {
1482 widget
= Util
.createWidgetForParameter( pi
.parameters
[ i
] );
1483 that
.widgets
[ prefix
+ pi
.parameters
[ i
].name
] = widget
;
1484 if ( pi
.parameters
[ i
].tokentype
) {
1485 that
.tokenWidget
= widget
;
1488 descriptionContainer
= $( '<div>' );
1489 descriptionContainer
.append( $( '<div>', {
1490 addClass
: 'description',
1491 append
: Util
.parseHTML( pi
.parameters
[ i
].description
)
1493 if ( pi
.parameters
[ i
].info
&& pi
.parameters
[ i
].info
.length
) {
1494 for ( j
= 0; j
< pi
.parameters
[ i
].info
.length
; j
++ ) {
1495 descriptionContainer
.append( $( '<div>', {
1497 append
: Util
.parseHTML( pi
.parameters
[ i
].info
[ j
] )
1503 switch ( pi
.parameters
[ i
].type
) {
1506 count
= mw
.config
.get( 'wgFormattedNamespaces' ).length
;
1510 if ( pi
.parameters
[ i
].highmax
!== undefined ) {
1511 descriptionContainer
.append( $( '<div>', {
1515 'api-help-param-limit2', pi
.parameters
[ i
].max
, pi
.parameters
[ i
].highmax
1518 Util
.parseMsg( 'apisandbox-param-limit' )
1522 descriptionContainer
.append( $( '<div>', {
1525 Util
.parseMsg( 'api-help-param-limit', pi
.parameters
[ i
].max
),
1527 Util
.parseMsg( 'apisandbox-param-limit' )
1535 if ( pi
.parameters
[ i
].min
!== undefined ) {
1538 if ( pi
.parameters
[ i
].max
!== undefined ) {
1542 descriptionContainer
.append( $( '<div>', {
1544 append
: Util
.parseMsg(
1545 'api-help-param-integer-' + tmp
,
1546 Util
.apiBool( pi
.parameters
[ i
].multi
) ? 2 : 1,
1547 pi
.parameters
[ i
].min
, pi
.parameters
[ i
].max
1554 if ( Array
.isArray( pi
.parameters
[ i
].type
) ) {
1556 count
= pi
.parameters
[ i
].type
.length
;
1560 if ( Util
.apiBool( pi
.parameters
[ i
].multi
) ) {
1562 if ( flag
&& !( widget
instanceof OO
.ui
.CapsuleMultiselectWidget
) &&
1564 widget
instanceof OptionalWidget
&&
1565 widget
.widget
instanceof OO
.ui
.CapsuleMultiselectWidget
1568 tmp
.push( mw
.message( 'api-help-param-multi-separate' ).parse() );
1570 if ( count
> pi
.parameters
[ i
].lowlimit
) {
1572 mw
.message( 'api-help-param-multi-max',
1573 pi
.parameters
[ i
].lowlimit
, pi
.parameters
[ i
].highlimit
1578 descriptionContainer
.append( $( '<div>', {
1580 append
: Util
.parseHTML( tmp
.join( ' ' ) )
1584 helpField
= new OO
.ui
.FieldLayout(
1587 classes
: [ 'mw-apisandbox-spacer' ]
1590 classes
: [ 'mw-apisandbox-help-field' ],
1591 label
: descriptionContainer
1595 widgetField
= new OO
.ui
.FieldLayout(
1599 classes
: [ 'mw-apisandbox-widget-field' ],
1600 label
: prefix
+ pi
.parameters
[ i
].name
1604 // We need our own click handler on the widget label to
1605 // turn off the disablement.
1606 widgetField
.$label
.on( 'click', widgetLabelOnClick
.bind( widgetField
) );
1608 // Don't grey out the label when the field is disabled,
1609 // it makes it too hard to read and our "disabled"
1610 // isn't really disabled.
1611 widgetField
.onFieldDisable( false );
1612 widgetField
.onFieldDisable
= doNothing
;
1614 if ( Util
.apiBool( pi
.parameters
[ i
].deprecated
) ) {
1615 deprecatedItems
.push( widgetField
, helpField
);
1617 items
.push( widgetField
, helpField
);
1622 if ( !pi
.parameters
.length
&& !Util
.apiBool( pi
.dynamicparameters
) ) {
1623 items
.push( new OO
.ui
.FieldLayout(
1624 new OO
.ui
.Widget( {} ).toggle( false ), {
1626 label
: Util
.parseMsg( 'apisandbox-no-parameters' )
1631 that
.$element
.empty();
1633 new OO
.ui
.FieldsetLayout( {
1634 label
: that
.displayText
1635 } ).addItems( items
)
1636 .$element
.appendTo( that
.$element
);
1638 if ( Util
.apiBool( pi
.dynamicparameters
) ) {
1639 dynamicFieldset
= new OO
.ui
.FieldsetLayout();
1640 dynamicParamNameWidget
= new OO
.ui
.TextInputWidget( {
1641 placeholder
: mw
.message( 'apisandbox-dynamic-parameters-add-placeholder' ).text()
1642 } ).on( 'enter', addDynamicParamWidget
);
1643 dynamicFieldset
.addItems( [
1644 new OO
.ui
.FieldLayout(
1645 new OO
.ui
.Widget( {} ).toggle( false ), {
1647 label
: Util
.parseHTML( pi
.dynamicparameters
)
1650 new OO
.ui
.ActionFieldLayout(
1651 dynamicParamNameWidget
,
1652 new OO
.ui
.ButtonWidget( {
1654 flags
: 'progressive'
1655 } ).on( 'click', addDynamicParamWidget
),
1657 label
: mw
.message( 'apisandbox-dynamic-parameters-add-label' ).text(),
1664 $( '<legend>' ).text( mw
.message( 'apisandbox-dynamic-parameters' ).text() ),
1665 dynamicFieldset
.$element
1667 .appendTo( that
.$element
);
1670 if ( deprecatedItems
.length
) {
1671 tmp
= new OO
.ui
.FieldsetLayout().addItems( deprecatedItems
).toggle( false );
1674 $( '<legend>' ).append(
1675 new OO
.ui
.ToggleButtonWidget( {
1676 label
: mw
.message( 'apisandbox-deprecated-parameters' ).text()
1677 } ).on( 'change', tmp
.toggle
, [], tmp
).$element
1681 .appendTo( that
.$element
);
1684 // Load stored params, if any, then update the booklet if we
1685 // have subpages (or else just update our valid-indicator).
1686 tmp
= that
.loadFromQueryParams
;
1687 that
.loadFromQueryParams
= null;
1688 if ( $.isPlainObject( tmp
) ) {
1689 that
.loadQueryParams( tmp
);
1691 if ( that
.getSubpages().length
> 0 ) {
1692 ApiSandbox
.updateUI( tmp
);
1694 that
.apiCheckValid();
1696 } ).fail( function ( code
, detail
) {
1697 that
.$element
.empty()
1699 new OO
.ui
.LabelWidget( {
1700 label
: mw
.message( 'apisandbox-load-error', that
.apiModule
, detail
).text(),
1701 classes
: [ 'error' ]
1703 new OO
.ui
.ButtonWidget( {
1704 label
: mw
.message( 'apisandbox-retry' ).text()
1705 } ).on( 'click', that
.loadParamInfo
, [], that
).$element
1711 * Check that all widgets on the page are in a valid state.
1715 ApiSandbox
.PageLayout
.prototype.apiCheckValid = function () {
1718 if ( this.paramInfo
=== null ) {
1719 return $.Deferred().resolve( false ).promise();
1721 return $.when
.apply( $, $.map( this.widgets
, function ( widget
) {
1722 return widget
.apiCheckValid();
1723 } ) ).then( function () {
1724 that
.apiIsValid
= $.inArray( false, arguments
) === -1;
1725 if ( that
.getOutlineItem() ) {
1726 that
.getOutlineItem().setIcon( that
.apiIsValid
|| suppressErrors
? null : 'alert' );
1727 that
.getOutlineItem().setIconTitle(
1728 that
.apiIsValid
|| suppressErrors
? '' : mw
.message( 'apisandbox-alert-page' ).plain()
1731 return $.Deferred().resolve( that
.apiIsValid
).promise();
1737 * Load form fields from query parameters
1739 * @param {Object} params
1741 ApiSandbox
.PageLayout
.prototype.loadQueryParams = function ( params
) {
1742 if ( this.paramInfo
=== null ) {
1743 this.loadFromQueryParams
= params
;
1745 $.each( this.widgets
, function ( name
, widget
) {
1746 var v
= params
.hasOwnProperty( name
) ? params
[ name
] : undefined;
1747 widget
.setApiValue( v
);
1753 * Load query params from form fields
1755 * @param {Object} params Write query parameters into this object
1756 * @param {Object} displayParams Write query parameters for display into this object
1758 ApiSandbox
.PageLayout
.prototype.getQueryParams = function ( params
, displayParams
) {
1759 $.each( this.widgets
, function ( name
, widget
) {
1760 var value
= widget
.getApiValue();
1761 if ( value
!== undefined ) {
1762 params
[ name
] = value
;
1763 if ( $.isFunction( widget
.getApiValueForDisplay
) ) {
1764 value
= widget
.getApiValueForDisplay();
1766 displayParams
[ name
] = value
;
1772 * Fetch a list of subpage names loaded by this page
1776 ApiSandbox
.PageLayout
.prototype.getSubpages = function () {
1778 $.each( this.widgets
, function ( name
, widget
) {
1780 if ( $.isFunction( widget
.getSubmodules
) ) {
1781 submodules
= widget
.getSubmodules();
1782 for ( i
= 0; i
< submodules
.length
; i
++ ) {
1784 key
: name
+ '=' + submodules
[ i
].value
,
1785 path
: submodules
[ i
].path
,
1786 prefix
: widget
.paramInfo
.submoduleparamprefix
|| ''
1795 * A text input with a clickable indicator
1800 * @param {Object} [config] Configuration options
1802 function TextInputWithIndicatorWidget( config
) {
1805 config
= config
|| {};
1806 TextInputWithIndicatorWidget
[ 'super' ].call( this, config
);
1808 this.$indicator
= $( '<span>' ).addClass( 'mw-apisandbox-clickable-indicator' );
1809 OO
.ui
.mixin
.TabIndexedElement
.call(
1810 this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} )
1813 this.input
= new OO
.ui
.TextInputWidget( $.extend( {
1814 $indicator
: this.$indicator
,
1815 disabled
: this.isDisabled()
1816 }, config
.input
) );
1818 // Forward most methods for convenience
1819 for ( k
in this.input
) {
1820 if ( $.isFunction( this.input
[ k
] ) && !this[ k
] ) {
1821 this[ k
] = this.input
[ k
].bind( this.input
);
1825 this.$indicator
.on( {
1826 click
: this.onIndicatorClick
.bind( this ),
1827 keypress
: this.onIndicatorKeyPress
.bind( this )
1830 this.$element
.append( this.input
.$element
);
1832 OO
.inheritClass( TextInputWithIndicatorWidget
, OO
.ui
.Widget
);
1833 OO
.mixinClass( TextInputWithIndicatorWidget
, OO
.ui
.mixin
.TabIndexedElement
);
1834 TextInputWithIndicatorWidget
.prototype.onIndicatorClick = function ( e
) {
1835 if ( !this.isDisabled() && e
.which
=== 1 ) {
1836 this.emit( 'indicator' );
1840 TextInputWithIndicatorWidget
.prototype.onIndicatorKeyPress = function ( e
) {
1841 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
1842 this.emit( 'indicator' );
1846 TextInputWithIndicatorWidget
.prototype.setDisabled = function ( disabled
) {
1847 TextInputWithIndicatorWidget
[ 'super' ].prototype.setDisabled
.call( this, disabled
);
1849 this.input
.setDisabled( this.isDisabled() );
1855 * A wrapper for a widget that provides an enable/disable button
1860 * @param {OO.ui.Widget} widget
1861 * @param {Object} [config] Configuration options
1863 function OptionalWidget( widget
, config
) {
1866 config
= config
|| {};
1868 this.widget
= widget
;
1869 this.$overlay
= config
.$overlay
||
1870 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-overlay' );
1871 this.checkbox
= new OO
.ui
.CheckboxInputWidget( config
.checkbox
)
1872 .on( 'change', this.onCheckboxChange
, [], this );
1874 OptionalWidget
[ 'super' ].call( this, config
);
1876 // Forward most methods for convenience
1877 for ( k
in this.widget
) {
1878 if ( $.isFunction( this.widget
[ k
] ) && !this[ k
] ) {
1879 this[ k
] = this.widget
[ k
].bind( this.widget
);
1883 this.$overlay
.on( 'click', this.onOverlayClick
.bind( this ) );
1886 .addClass( 'mw-apisandbox-optionalWidget' )
1889 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-fields' ).append(
1890 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-widget' ).append(
1893 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-checkbox' ).append(
1894 this.checkbox
.$element
1899 this.setDisabled( widget
.isDisabled() );
1901 OO
.inheritClass( OptionalWidget
, OO
.ui
.Widget
);
1902 OptionalWidget
.prototype.onCheckboxChange = function ( checked
) {
1903 this.setDisabled( !checked
);
1905 OptionalWidget
.prototype.onOverlayClick = function () {
1906 this.setDisabled( false );
1907 if ( $.isFunction( this.widget
.focus
) ) {
1908 this.widget
.focus();
1911 OptionalWidget
.prototype.setDisabled = function ( disabled
) {
1912 OptionalWidget
[ 'super' ].prototype.setDisabled
.call( this, disabled
);
1913 this.widget
.setDisabled( this.isDisabled() );
1914 this.checkbox
.setSelected( !this.isDisabled() );
1915 this.$overlay
.toggle( this.isDisabled() );
1919 $( ApiSandbox
.init
);
1921 module
.exports
= ApiSandbox
;
1923 }( jQuery
, mediaWiki
, OO
) );