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 var deferred
= $.Deferred();
1105 if ( code
!== 'http' ) {
1106 // Not really an error, work around mw.Api thinking it is.
1107 deferred
.resolve( result
, jqXHR
);
1110 deferred
.reject
.apply( deferred
, arguments
);
1112 return deferred
.promise();
1114 .then( function ( data
, jqXHR
) {
1115 var m
, loadTime
, button
, clear
,
1116 ct
= jqXHR
.getResponseHeader( 'Content-Type' );
1119 if ( /^text\/mediawiki-api-prettyprint-wrapped(?:;|$)/.test( ct
) ) {
1120 data
= JSON
.parse( data
);
1121 if ( data
.modules
.length
) {
1122 mw
.loader
.load( data
.modules
);
1124 if ( data
.status
&& data
.status
!== 200 ) {
1126 .addClass( 'api-pretty-header api-pretty-status' )
1127 .append( Util
.parseMsg( 'api-format-prettyprint-status', data
.status
, data
.statustext
) )
1128 .appendTo( $result
);
1130 $result
.append( Util
.parseHTML( data
.html
) );
1131 loadTime
= data
.time
;
1132 } else if ( ( m
= data
.match( /<pre[ >][\s\S]*<\/pre>/ ) ) ) {
1133 $result
.append( Util
.parseHTML( m
[ 0 ] ) );
1134 if ( ( m
= data
.match( /"wgBackendResponseTime":\s*(\d+)/ ) ) ) {
1135 loadTime
= parseInt( m
[ 1 ], 10 );
1139 .addClass( 'api-pretty-content' )
1141 .appendTo( $result
);
1143 if ( paramsAreForced
|| data
[ 'continue' ] ) {
1145 $( '<div>' ).append(
1146 new OO
.ui
.ButtonWidget( {
1147 label
: mw
.message( 'apisandbox-continue' ).text()
1148 } ).on( 'click', function () {
1149 ApiSandbox
.sendRequest( $.extend( {}, baseRequestParams
, data
[ 'continue' ] ) );
1150 } ).setDisabled( !data
[ 'continue' ] ).$element
,
1151 ( clear
= new OO
.ui
.ButtonWidget( {
1152 label
: mw
.message( 'apisandbox-continue-clear' ).text()
1153 } ).on( 'click', function () {
1154 ApiSandbox
.updateUI( baseRequestParams
);
1155 clear
.setDisabled( true );
1156 booklet
.setPage( '|results|' );
1157 } ).setDisabled( !paramsAreForced
) ).$element
,
1158 new OO
.ui
.PopupButtonWidget( {
1159 $overlay
: $( '#mw-apisandbox-ui' ),
1163 $content
: $( '<div>' ).append( Util
.parseMsg( 'apisandbox-continue-help' ) ),
1171 if ( typeof loadTime
=== 'number' ) {
1173 $( '<div>' ).append(
1174 new OO
.ui
.LabelWidget( {
1175 label
: mw
.message( 'apisandbox-request-time', loadTime
).text()
1181 if ( jqXHR
.getResponseHeader( 'MediaWiki-API-Error' ) === 'badtoken' ) {
1182 // Flush all saved tokens in case one of them is the bad one.
1183 Util
.markTokensBad();
1184 button
= new OO
.ui
.ButtonWidget( {
1185 label
: mw
.message( 'apisandbox-results-fixtoken' ).text()
1187 button
.on( 'click', ApiSandbox
.fixTokenAndResend
)
1188 .on( 'click', button
.setDisabled
, [ true ], button
)
1189 .$element
.appendTo( $result
);
1191 }, function ( code
, data
) {
1192 var details
= 'HTTP error: ' + data
.exception
;
1195 new OO
.ui
.LabelWidget( {
1196 label
: mw
.message( 'apisandbox-results-error', details
).text(),
1197 classes
: [ 'error' ]
1205 * Handler for the "Correct token and resubmit" button
1207 * Used on a 'badtoken' error, it re-fetches token parameters for all
1208 * pages and then re-submits the query.
1210 fixTokenAndResend: function () {
1211 var page
, subpages
, i
, k
,
1213 tokenWait
= { dummy
: true },
1214 checkPages
= [ pages
.main
],
1215 success = function ( k
) {
1216 delete tokenWait
[ k
];
1217 if ( ok
&& $.isEmptyObject( tokenWait
) ) {
1218 ApiSandbox
.sendRequest();
1221 failure = function ( k
) {
1222 delete tokenWait
[ k
];
1226 while ( checkPages
.length
) {
1227 page
= checkPages
.shift();
1229 if ( page
.tokenWidget
) {
1230 k
= page
.apiModule
+ page
.tokenWidget
.paramInfo
.name
;
1231 tokenWait
[ k
] = page
.tokenWidget
.fetchToken();
1233 .done( success
.bind( page
.tokenWidget
, k
) )
1234 .fail( failure
.bind( page
.tokenWidget
, k
) );
1237 subpages
= page
.getSubpages();
1238 for ( i
= 0; i
< subpages
.length
; i
++ ) {
1239 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
1240 checkPages
.push( pages
[ subpages
[ i
].key
] );
1245 success( 'dummy', '' );
1249 * Reset validity indicators for all widgets
1251 updateValidityIndicators: function () {
1252 var page
, subpages
, i
,
1253 checkPages
= [ pages
.main
];
1255 while ( checkPages
.length
) {
1256 page
= checkPages
.shift();
1257 page
.apiCheckValid();
1258 subpages
= page
.getSubpages();
1259 for ( i
= 0; i
< subpages
.length
; i
++ ) {
1260 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
1261 checkPages
.push( pages
[ subpages
[ i
].key
] );
1269 * PageLayout for API modules
1273 * @extends OO.ui.PageLayout
1275 * @param {Object} [config] Configuration options
1277 ApiSandbox
.PageLayout = function ( config
) {
1278 config
= $.extend( { prefix
: '' }, config
);
1279 this.displayText
= config
.key
;
1280 this.apiModule
= config
.path
;
1281 this.prefix
= config
.prefix
;
1282 this.paramInfo
= null;
1283 this.apiIsValid
= true;
1284 this.loadFromQueryParams
= null;
1286 this.tokenWidget
= null;
1287 this.indentLevel
= config
.indentLevel
? config
.indentLevel
: 0;
1288 ApiSandbox
.PageLayout
[ 'super' ].call( this, config
.key
, config
);
1289 this.loadParamInfo();
1291 OO
.inheritClass( ApiSandbox
.PageLayout
, OO
.ui
.PageLayout
);
1292 ApiSandbox
.PageLayout
.prototype.setupOutlineItem = function () {
1293 this.outlineItem
.setLevel( this.indentLevel
);
1294 this.outlineItem
.setLabel( this.displayText
);
1295 this.outlineItem
.setIcon( this.apiIsValid
|| suppressErrors
? null : 'alert' );
1296 this.outlineItem
.setIconTitle(
1297 this.apiIsValid
|| suppressErrors
? '' : mw
.message( 'apisandbox-alert-page' ).plain()
1302 * Fetch module information for this page's module, then create UI
1304 ApiSandbox
.PageLayout
.prototype.loadParamInfo = function () {
1305 var dynamicFieldset
, dynamicParamNameWidget
,
1307 removeDynamicParamWidget = function ( name
, layout
) {
1308 dynamicFieldset
.removeItems( [ layout
] );
1309 delete that
.widgets
[ name
];
1311 addDynamicParamWidget = function () {
1312 var name
, layout
, widget
, button
;
1314 // Check name is filled in
1315 name
= dynamicParamNameWidget
.getValue().trim();
1316 if ( name
=== '' ) {
1317 dynamicParamNameWidget
.focus();
1321 if ( that
.widgets
[ name
] !== undefined ) {
1322 windowManager
.openWindow( 'errorAlert', {
1323 title
: Util
.parseMsg( 'apisandbox-dynamic-error-exists', name
),
1327 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' ),
1335 widget
= Util
.createWidgetForParameter( {
1342 button
= new OO
.ui
.ButtonWidget( {
1344 flags
: 'destructive'
1346 layout
= new OO
.ui
.ActionFieldLayout(
1354 button
.on( 'click', removeDynamicParamWidget
, [ name
, layout
] );
1355 that
.widgets
[ name
] = widget
;
1356 dynamicFieldset
.addItems( [ layout
], dynamicFieldset
.getItems().length
- 1 );
1359 dynamicParamNameWidget
.setValue( '' );
1362 this.$element
.empty()
1363 .append( new OO
.ui
.ProgressBarWidget( {
1365 text
: mw
.message( 'apisandbox-loading', this.displayText
).text()
1368 Util
.fetchModuleInfo( this.apiModule
)
1369 .done( function ( pi
) {
1370 var prefix
, i
, j
, descriptionContainer
, widget
, widgetField
, helpField
, tmp
, flag
, count
,
1372 deprecatedItems
= [],
1374 filterFmModules = function ( v
) {
1375 return v
.substr( -2 ) !== 'fm' ||
1376 !availableFormats
.hasOwnProperty( v
.substr( 0, v
.length
- 2 ) );
1378 widgetLabelOnClick = function () {
1379 var f
= this.getField();
1380 if ( $.isFunction( f
.setDisabled
) ) {
1381 f
.setDisabled( false );
1383 if ( $.isFunction( f
.focus
) ) {
1387 doNothing = function () {};
1389 // This is something of a hack. We always want the 'format' and
1390 // 'action' parameters from the main module to be specified,
1391 // and for 'format' we also want to simplify the dropdown since
1392 // we always send the 'fm' variant.
1393 if ( that
.apiModule
=== 'main' ) {
1394 for ( i
= 0; i
< pi
.parameters
.length
; i
++ ) {
1395 if ( pi
.parameters
[ i
].name
=== 'action' ) {
1396 pi
.parameters
[ i
].required
= true;
1397 delete pi
.parameters
[ i
][ 'default' ];
1399 if ( pi
.parameters
[ i
].name
=== 'format' ) {
1400 tmp
= pi
.parameters
[ i
].type
;
1401 for ( j
= 0; j
< tmp
.length
; j
++ ) {
1402 availableFormats
[ tmp
[ j
] ] = true;
1404 pi
.parameters
[ i
].type
= $.grep( tmp
, filterFmModules
);
1405 pi
.parameters
[ i
][ 'default' ] = 'json';
1406 pi
.parameters
[ i
].required
= true;
1411 // Hide the 'wrappedhtml' parameter on format modules
1412 if ( pi
.group
=== 'format' ) {
1413 pi
.parameters
= $.grep( pi
.parameters
, function ( p
) {
1414 return p
.name
!== 'wrappedhtml';
1418 that
.paramInfo
= pi
;
1420 items
.push( new OO
.ui
.FieldLayout(
1421 new OO
.ui
.Widget( {} ).toggle( false ), {
1423 label
: Util
.parseHTML( pi
.description
)
1427 if ( pi
.helpurls
.length
) {
1428 buttons
.push( new OO
.ui
.PopupButtonWidget( {
1429 $overlay
: $( '#mw-apisandbox-ui' ),
1430 label
: mw
.message( 'apisandbox-helpurls' ).text(),
1435 $content
: $( '<ul>' ).append( $.map( pi
.helpurls
, function ( link
) {
1436 return $( '<li>' ).append( $( '<a>', {
1446 if ( pi
.examples
.length
) {
1447 buttons
.push( new OO
.ui
.PopupButtonWidget( {
1448 $overlay
: $( '#mw-apisandbox-ui' ),
1449 label
: mw
.message( 'apisandbox-examples' ).text(),
1454 $content
: $( '<ul>' ).append( $.map( pi
.examples
, function ( example
) {
1456 href
: '#' + example
.query
,
1457 html
: example
.description
1459 a
.find( 'a' ).contents().unwrap(); // Can't nest links
1460 return $( '<li>' ).append( a
);
1466 if ( buttons
.length
) {
1467 items
.push( new OO
.ui
.FieldLayout(
1468 new OO
.ui
.ButtonGroupWidget( {
1470 } ), { align
: 'top' }
1474 if ( pi
.parameters
.length
) {
1475 prefix
= that
.prefix
+ pi
.prefix
;
1476 for ( i
= 0; i
< pi
.parameters
.length
; i
++ ) {
1477 widget
= Util
.createWidgetForParameter( pi
.parameters
[ i
] );
1478 that
.widgets
[ prefix
+ pi
.parameters
[ i
].name
] = widget
;
1479 if ( pi
.parameters
[ i
].tokentype
) {
1480 that
.tokenWidget
= widget
;
1483 descriptionContainer
= $( '<div>' );
1484 descriptionContainer
.append( $( '<div>', {
1485 addClass
: 'description',
1486 append
: Util
.parseHTML( pi
.parameters
[ i
].description
)
1488 if ( pi
.parameters
[ i
].info
&& pi
.parameters
[ i
].info
.length
) {
1489 for ( j
= 0; j
< pi
.parameters
[ i
].info
.length
; j
++ ) {
1490 descriptionContainer
.append( $( '<div>', {
1492 append
: Util
.parseHTML( pi
.parameters
[ i
].info
[ j
] )
1498 switch ( pi
.parameters
[ i
].type
) {
1501 count
= mw
.config
.get( 'wgFormattedNamespaces' ).length
;
1505 if ( pi
.parameters
[ i
].highmax
!== undefined ) {
1506 descriptionContainer
.append( $( '<div>', {
1510 'api-help-param-limit2', pi
.parameters
[ i
].max
, pi
.parameters
[ i
].highmax
1513 Util
.parseMsg( 'apisandbox-param-limit' )
1517 descriptionContainer
.append( $( '<div>', {
1520 Util
.parseMsg( 'api-help-param-limit', pi
.parameters
[ i
].max
),
1522 Util
.parseMsg( 'apisandbox-param-limit' )
1530 if ( pi
.parameters
[ i
].min
!== undefined ) {
1533 if ( pi
.parameters
[ i
].max
!== undefined ) {
1537 descriptionContainer
.append( $( '<div>', {
1539 append
: Util
.parseMsg(
1540 'api-help-param-integer-' + tmp
,
1541 Util
.apiBool( pi
.parameters
[ i
].multi
) ? 2 : 1,
1542 pi
.parameters
[ i
].min
, pi
.parameters
[ i
].max
1549 if ( Array
.isArray( pi
.parameters
[ i
].type
) ) {
1551 count
= pi
.parameters
[ i
].type
.length
;
1555 if ( Util
.apiBool( pi
.parameters
[ i
].multi
) ) {
1557 if ( flag
&& !( widget
instanceof OO
.ui
.CapsuleMultiselectWidget
) &&
1559 widget
instanceof OptionalWidget
&&
1560 widget
.widget
instanceof OO
.ui
.CapsuleMultiselectWidget
1563 tmp
.push( mw
.message( 'api-help-param-multi-separate' ).parse() );
1565 if ( count
> pi
.parameters
[ i
].lowlimit
) {
1567 mw
.message( 'api-help-param-multi-max',
1568 pi
.parameters
[ i
].lowlimit
, pi
.parameters
[ i
].highlimit
1573 descriptionContainer
.append( $( '<div>', {
1575 append
: Util
.parseHTML( tmp
.join( ' ' ) )
1579 helpField
= new OO
.ui
.FieldLayout(
1582 classes
: [ 'mw-apisandbox-spacer' ]
1585 classes
: [ 'mw-apisandbox-help-field' ],
1586 label
: descriptionContainer
1590 widgetField
= new OO
.ui
.FieldLayout(
1594 classes
: [ 'mw-apisandbox-widget-field' ],
1595 label
: prefix
+ pi
.parameters
[ i
].name
1599 // We need our own click handler on the widget label to
1600 // turn off the disablement.
1601 widgetField
.$label
.on( 'click', widgetLabelOnClick
.bind( widgetField
) );
1603 // Don't grey out the label when the field is disabled,
1604 // it makes it too hard to read and our "disabled"
1605 // isn't really disabled.
1606 widgetField
.onFieldDisable( false );
1607 widgetField
.onFieldDisable
= doNothing
;
1609 if ( Util
.apiBool( pi
.parameters
[ i
].deprecated
) ) {
1610 deprecatedItems
.push( widgetField
, helpField
);
1612 items
.push( widgetField
, helpField
);
1617 if ( !pi
.parameters
.length
&& !Util
.apiBool( pi
.dynamicparameters
) ) {
1618 items
.push( new OO
.ui
.FieldLayout(
1619 new OO
.ui
.Widget( {} ).toggle( false ), {
1621 label
: Util
.parseMsg( 'apisandbox-no-parameters' )
1626 that
.$element
.empty();
1628 new OO
.ui
.FieldsetLayout( {
1629 label
: that
.displayText
1630 } ).addItems( items
)
1631 .$element
.appendTo( that
.$element
);
1633 if ( Util
.apiBool( pi
.dynamicparameters
) ) {
1634 dynamicFieldset
= new OO
.ui
.FieldsetLayout();
1635 dynamicParamNameWidget
= new OO
.ui
.TextInputWidget( {
1636 placeholder
: mw
.message( 'apisandbox-dynamic-parameters-add-placeholder' ).text()
1637 } ).on( 'enter', addDynamicParamWidget
);
1638 dynamicFieldset
.addItems( [
1639 new OO
.ui
.FieldLayout(
1640 new OO
.ui
.Widget( {} ).toggle( false ), {
1642 label
: Util
.parseHTML( pi
.dynamicparameters
)
1645 new OO
.ui
.ActionFieldLayout(
1646 dynamicParamNameWidget
,
1647 new OO
.ui
.ButtonWidget( {
1649 flags
: 'progressive'
1650 } ).on( 'click', addDynamicParamWidget
),
1652 label
: mw
.message( 'apisandbox-dynamic-parameters-add-label' ).text(),
1659 $( '<legend>' ).text( mw
.message( 'apisandbox-dynamic-parameters' ).text() ),
1660 dynamicFieldset
.$element
1662 .appendTo( that
.$element
);
1665 if ( deprecatedItems
.length
) {
1666 tmp
= new OO
.ui
.FieldsetLayout().addItems( deprecatedItems
).toggle( false );
1669 $( '<legend>' ).append(
1670 new OO
.ui
.ToggleButtonWidget( {
1671 label
: mw
.message( 'apisandbox-deprecated-parameters' ).text()
1672 } ).on( 'change', tmp
.toggle
, [], tmp
).$element
1676 .appendTo( that
.$element
);
1679 // Load stored params, if any, then update the booklet if we
1680 // have subpages (or else just update our valid-indicator).
1681 tmp
= that
.loadFromQueryParams
;
1682 that
.loadFromQueryParams
= null;
1683 if ( $.isPlainObject( tmp
) ) {
1684 that
.loadQueryParams( tmp
);
1686 if ( that
.getSubpages().length
> 0 ) {
1687 ApiSandbox
.updateUI( tmp
);
1689 that
.apiCheckValid();
1691 } ).fail( function ( code
, detail
) {
1692 that
.$element
.empty()
1694 new OO
.ui
.LabelWidget( {
1695 label
: mw
.message( 'apisandbox-load-error', that
.apiModule
, detail
).text(),
1696 classes
: [ 'error' ]
1698 new OO
.ui
.ButtonWidget( {
1699 label
: mw
.message( 'apisandbox-retry' ).text()
1700 } ).on( 'click', that
.loadParamInfo
, [], that
).$element
1706 * Check that all widgets on the page are in a valid state.
1710 ApiSandbox
.PageLayout
.prototype.apiCheckValid = function () {
1713 if ( this.paramInfo
=== null ) {
1714 return $.Deferred().resolve( false ).promise();
1716 return $.when
.apply( $, $.map( this.widgets
, function ( widget
) {
1717 return widget
.apiCheckValid();
1718 } ) ).then( function () {
1719 that
.apiIsValid
= $.inArray( false, arguments
) === -1;
1720 if ( that
.getOutlineItem() ) {
1721 that
.getOutlineItem().setIcon( that
.apiIsValid
|| suppressErrors
? null : 'alert' );
1722 that
.getOutlineItem().setIconTitle(
1723 that
.apiIsValid
|| suppressErrors
? '' : mw
.message( 'apisandbox-alert-page' ).plain()
1726 return $.Deferred().resolve( that
.apiIsValid
).promise();
1732 * Load form fields from query parameters
1734 * @param {Object} params
1736 ApiSandbox
.PageLayout
.prototype.loadQueryParams = function ( params
) {
1737 if ( this.paramInfo
=== null ) {
1738 this.loadFromQueryParams
= params
;
1740 $.each( this.widgets
, function ( name
, widget
) {
1741 var v
= params
.hasOwnProperty( name
) ? params
[ name
] : undefined;
1742 widget
.setApiValue( v
);
1748 * Load query params from form fields
1750 * @param {Object} params Write query parameters into this object
1751 * @param {Object} displayParams Write query parameters for display into this object
1753 ApiSandbox
.PageLayout
.prototype.getQueryParams = function ( params
, displayParams
) {
1754 $.each( this.widgets
, function ( name
, widget
) {
1755 var value
= widget
.getApiValue();
1756 if ( value
!== undefined ) {
1757 params
[ name
] = value
;
1758 if ( $.isFunction( widget
.getApiValueForDisplay
) ) {
1759 value
= widget
.getApiValueForDisplay();
1761 displayParams
[ name
] = value
;
1767 * Fetch a list of subpage names loaded by this page
1771 ApiSandbox
.PageLayout
.prototype.getSubpages = function () {
1773 $.each( this.widgets
, function ( name
, widget
) {
1775 if ( $.isFunction( widget
.getSubmodules
) ) {
1776 submodules
= widget
.getSubmodules();
1777 for ( i
= 0; i
< submodules
.length
; i
++ ) {
1779 key
: name
+ '=' + submodules
[ i
].value
,
1780 path
: submodules
[ i
].path
,
1781 prefix
: widget
.paramInfo
.submoduleparamprefix
|| ''
1790 * A text input with a clickable indicator
1795 * @param {Object} [config] Configuration options
1797 function TextInputWithIndicatorWidget( config
) {
1800 config
= config
|| {};
1801 TextInputWithIndicatorWidget
[ 'super' ].call( this, config
);
1803 this.$indicator
= $( '<span>' ).addClass( 'mw-apisandbox-clickable-indicator' );
1804 OO
.ui
.mixin
.TabIndexedElement
.call(
1805 this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} )
1808 this.input
= new OO
.ui
.TextInputWidget( $.extend( {
1809 $indicator
: this.$indicator
,
1810 disabled
: this.isDisabled()
1811 }, config
.input
) );
1813 // Forward most methods for convenience
1814 for ( k
in this.input
) {
1815 if ( $.isFunction( this.input
[ k
] ) && !this[ k
] ) {
1816 this[ k
] = this.input
[ k
].bind( this.input
);
1820 this.$indicator
.on( {
1821 click
: this.onIndicatorClick
.bind( this ),
1822 keypress
: this.onIndicatorKeyPress
.bind( this )
1825 this.$element
.append( this.input
.$element
);
1827 OO
.inheritClass( TextInputWithIndicatorWidget
, OO
.ui
.Widget
);
1828 OO
.mixinClass( TextInputWithIndicatorWidget
, OO
.ui
.mixin
.TabIndexedElement
);
1829 TextInputWithIndicatorWidget
.prototype.onIndicatorClick = function ( e
) {
1830 if ( !this.isDisabled() && e
.which
=== 1 ) {
1831 this.emit( 'indicator' );
1835 TextInputWithIndicatorWidget
.prototype.onIndicatorKeyPress = function ( e
) {
1836 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
1837 this.emit( 'indicator' );
1841 TextInputWithIndicatorWidget
.prototype.setDisabled = function ( disabled
) {
1842 TextInputWithIndicatorWidget
[ 'super' ].prototype.setDisabled
.call( this, disabled
);
1844 this.input
.setDisabled( this.isDisabled() );
1850 * A wrapper for a widget that provides an enable/disable button
1855 * @param {OO.ui.Widget} widget
1856 * @param {Object} [config] Configuration options
1858 function OptionalWidget( widget
, config
) {
1861 config
= config
|| {};
1863 this.widget
= widget
;
1864 this.$overlay
= config
.$overlay
||
1865 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-overlay' );
1866 this.checkbox
= new OO
.ui
.CheckboxInputWidget( config
.checkbox
)
1867 .on( 'change', this.onCheckboxChange
, [], this );
1869 OptionalWidget
[ 'super' ].call( this, config
);
1871 // Forward most methods for convenience
1872 for ( k
in this.widget
) {
1873 if ( $.isFunction( this.widget
[ k
] ) && !this[ k
] ) {
1874 this[ k
] = this.widget
[ k
].bind( this.widget
);
1878 this.$overlay
.on( 'click', this.onOverlayClick
.bind( this ) );
1881 .addClass( 'mw-apisandbox-optionalWidget' )
1884 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-fields' ).append(
1885 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-widget' ).append(
1888 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-checkbox' ).append(
1889 this.checkbox
.$element
1894 this.setDisabled( widget
.isDisabled() );
1896 OO
.inheritClass( OptionalWidget
, OO
.ui
.Widget
);
1897 OptionalWidget
.prototype.onCheckboxChange = function ( checked
) {
1898 this.setDisabled( !checked
);
1900 OptionalWidget
.prototype.onOverlayClick = function () {
1901 this.setDisabled( false );
1902 if ( $.isFunction( this.widget
.focus
) ) {
1903 this.widget
.focus();
1906 OptionalWidget
.prototype.setDisabled = function ( disabled
) {
1907 OptionalWidget
[ 'super' ].prototype.setDisabled
.call( this, disabled
);
1908 this.widget
.setDisabled( this.isDisabled() );
1909 this.checkbox
.setSelected( !this.isDisabled() );
1910 this.$overlay
.toggle( this.isDisabled() );
1914 $( ApiSandbox
.init
);
1916 module
.exports
= ApiSandbox
;
1918 }( jQuery
, mediaWiki
, OO
) );