3 * https://www.mediawiki.org/wiki/OOjs_UI
5 * Copyright 2011–2015 OOjs Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2015-06-17T00:58:56Z
16 * Namespace for all classes, static methods and static properties.
53 * Generate a unique ID for element
55 * @return {String} [id]
57 OO
.ui
.generateElementId = function () {
59 return 'oojsui-' + OO
.ui
.elementId
;
63 * Check if an element is focusable.
64 * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14
66 * @param {jQuery} element Element to test
67 * @return {Boolean} [description]
69 OO
.ui
.isFocusableElement = function ( $element
) {
70 var node
= $element
[0],
71 nodeName
= node
.nodeName
.toLowerCase(),
72 // Check if the element have tabindex set
73 isInElementGroup
= /^(input|select|textarea|button|object)$/.test( nodeName
),
74 // Check if the element is a link with href or if it has tabindex
76 ( nodeName
=== 'a' && node
.href
) ||
77 !isNaN( $element
.attr( 'tabindex' ) )
79 // Check if the element is visible
81 // This is quicker than calling $element.is( ':visible' )
82 $.expr
.filters
.visible( node
) &&
83 // Check that all parents are visible
84 !$element
.parents().addBack().filter( function () {
85 return $.css( this, 'visibility' ) === 'hidden';
90 ( isInElementGroup
? !node
.disabled
: isOtherElement
) &&
96 * Get the user's language and any fallback languages.
98 * These language codes are used to localize user interface elements in the user's language.
100 * In environments that provide a localization system, this function should be overridden to
101 * return the user's language(s). The default implementation returns English (en) only.
103 * @return {string[]} Language codes, in descending order of priority
105 OO
.ui
.getUserLanguages = function () {
110 * Get a value in an object keyed by language code.
112 * @param {Object.<string,Mixed>} obj Object keyed by language code
113 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
114 * @param {string} [fallback] Fallback code, used if no matching language can be found
115 * @return {Mixed} Local value
117 OO
.ui
.getLocalValue = function ( obj
, lang
, fallback
) {
120 // Requested language
124 // Known user language
125 langs
= OO
.ui
.getUserLanguages();
126 for ( i
= 0, len
= langs
.length
; i
< len
; i
++ ) {
133 if ( obj
[ fallback
] ) {
134 return obj
[ fallback
];
136 // First existing language
137 for ( lang
in obj
) {
145 * Check if a node is contained within another node
147 * Similar to jQuery#contains except a list of containers can be supplied
148 * and a boolean argument allows you to include the container in the match list
150 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
151 * @param {HTMLElement} contained Node to find
152 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
153 * @return {boolean} The node is in the list of target nodes
155 OO
.ui
.contains = function ( containers
, contained
, matchContainers
) {
157 if ( !Array
.isArray( containers
) ) {
158 containers
= [ containers
];
160 for ( i
= containers
.length
- 1; i
>= 0; i
-- ) {
161 if ( ( matchContainers
&& contained
=== containers
[ i
] ) || $.contains( containers
[ i
], contained
) ) {
169 * Return a function, that, as long as it continues to be invoked, will not
170 * be triggered. The function will be called after it stops being called for
171 * N milliseconds. If `immediate` is passed, trigger the function on the
172 * leading edge, instead of the trailing.
174 * Ported from: http://underscorejs.org/underscore.js
176 * @param {Function} func
177 * @param {number} wait
178 * @param {boolean} immediate
181 OO
.ui
.debounce = function ( func
, wait
, immediate
) {
186 later = function () {
189 func
.apply( context
, args
);
192 if ( immediate
&& !timeout
) {
193 func
.apply( context
, args
);
195 clearTimeout( timeout
);
196 timeout
= setTimeout( later
, wait
);
201 * Reconstitute a JavaScript object corresponding to a widget created by
202 * the PHP implementation.
204 * This is an alias for `OO.ui.Element.static.infuse()`.
206 * @param {string|HTMLElement|jQuery} idOrNode
207 * A DOM id (if a string) or node for the widget to infuse.
208 * @return {OO.ui.Element}
209 * The `OO.ui.Element` corresponding to this (infusable) document node.
211 OO
.ui
.infuse = function ( idOrNode
) {
212 return OO
.ui
.Element
.static.infuse( idOrNode
);
217 * Message store for the default implementation of OO.ui.msg
219 * Environments that provide a localization system should not use this, but should override
220 * OO.ui.msg altogether.
225 // Tool tip for a button that moves items in a list down one place
226 'ooui-outline-control-move-down': 'Move item down',
227 // Tool tip for a button that moves items in a list up one place
228 'ooui-outline-control-move-up': 'Move item up',
229 // Tool tip for a button that removes items from a list
230 'ooui-outline-control-remove': 'Remove item',
231 // Label for the toolbar group that contains a list of all other available tools
232 'ooui-toolbar-more': 'More',
233 // Label for the fake tool that expands the full list of tools in a toolbar group
234 'ooui-toolgroup-expand': 'More',
235 // Label for the fake tool that collapses the full list of tools in a toolbar group
236 'ooui-toolgroup-collapse': 'Fewer',
237 // Default label for the accept button of a confirmation dialog
238 'ooui-dialog-message-accept': 'OK',
239 // Default label for the reject button of a confirmation dialog
240 'ooui-dialog-message-reject': 'Cancel',
241 // Title for process dialog error description
242 'ooui-dialog-process-error': 'Something went wrong',
243 // Label for process dialog dismiss error button, visible when describing errors
244 'ooui-dialog-process-dismiss': 'Dismiss',
245 // Label for process dialog retry action button, visible when describing only recoverable errors
246 'ooui-dialog-process-retry': 'Try again',
247 // Label for process dialog retry action button, visible when describing only warnings
248 'ooui-dialog-process-continue': 'Continue',
249 // Default placeholder for file selection widgets
250 'ooui-selectfile-not-supported': 'File selection is not supported',
251 // Default placeholder for file selection widgets
252 'ooui-selectfile-placeholder': 'No file is selected',
253 // Semicolon separator
254 'ooui-semicolon-separator': '; '
258 * Get a localized message.
260 * In environments that provide a localization system, this function should be overridden to
261 * return the message translated in the user's language. The default implementation always returns
264 * After the message key, message parameters may optionally be passed. In the default implementation,
265 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
266 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
267 * they support unnamed, ordered message parameters.
270 * @param {string} key Message key
271 * @param {Mixed...} [params] Message parameters
272 * @return {string} Translated message with parameters substituted
274 OO
.ui
.msg = function ( key
) {
275 var message
= messages
[ key
],
276 params
= Array
.prototype.slice
.call( arguments
, 1 );
277 if ( typeof message
=== 'string' ) {
278 // Perform $1 substitution
279 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
280 var i
= parseInt( n
, 10 );
281 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
284 // Return placeholder if message not found
285 message
= '[' + key
+ ']';
291 * Package a message and arguments for deferred resolution.
293 * Use this when you are statically specifying a message and the message may not yet be present.
295 * @param {string} key Message key
296 * @param {Mixed...} [params] Message parameters
297 * @return {Function} Function that returns the resolved message when executed
299 OO
.ui
.deferMsg = function () {
300 var args
= arguments
;
302 return OO
.ui
.msg
.apply( OO
.ui
, args
);
309 * If the message is a function it will be executed, otherwise it will pass through directly.
311 * @param {Function|string} msg Deferred message, or message text
312 * @return {string} Resolved message
314 OO
.ui
.resolveMsg = function ( msg
) {
315 if ( $.isFunction( msg
) ) {
328 * Namespace for OOjs UI mixins.
330 * Mixins are named according to the type of object they are intended to
331 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
332 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
333 * is intended to be mixed in to an instance of OO.ui.Widget.
341 * PendingElement is a mixin that is used to create elements that notify users that something is happening
342 * and that they should wait before proceeding. The pending state is visually represented with a pending
343 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
344 * field of a {@link OO.ui.TextInputWidget text input widget}.
346 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
347 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
348 * in process dialogs.
351 * function MessageDialog( config ) {
352 * MessageDialog.super.call( this, config );
354 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
356 * MessageDialog.static.actions = [
357 * { action: 'save', label: 'Done', flags: 'primary' },
358 * { label: 'Cancel', flags: 'safe' }
361 * MessageDialog.prototype.initialize = function () {
362 * MessageDialog.super.prototype.initialize.apply( this, arguments );
363 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
364 * this.content.$element.append( '<p>Click the \'Done\' action widget to see its pending state. Note that action widgets can be marked pending in message dialogs but not process dialogs.</p>' );
365 * this.$body.append( this.content.$element );
367 * MessageDialog.prototype.getBodyHeight = function () {
370 * MessageDialog.prototype.getActionProcess = function ( action ) {
372 * if ( action === 'save' ) {
373 * dialog.getActions().get({actions: 'save'})[0].pushPending();
374 * return new OO.ui.Process()
376 * .next( function () {
377 * dialog.getActions().get({actions: 'save'})[0].popPending();
380 * return MessageDialog.super.prototype.getActionProcess.call( this, action );
383 * var windowManager = new OO.ui.WindowManager();
384 * $( 'body' ).append( windowManager.$element );
386 * var dialog = new MessageDialog();
387 * windowManager.addWindows( [ dialog ] );
388 * windowManager.openWindow( dialog );
394 * @param {Object} [config] Configuration options
395 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
397 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
398 // Configuration initialization
399 config
= config
|| {};
403 this.$pending
= null;
406 this.setPendingElement( config
.$pending
|| this.$element
);
411 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
416 * Set the pending element (and clean up any existing one).
418 * @param {jQuery} $pending The element to set to pending.
420 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
421 if ( this.$pending
) {
422 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
425 this.$pending
= $pending
;
426 if ( this.pending
> 0 ) {
427 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
432 * Check if an element is pending.
434 * @return {boolean} Element is pending
436 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
437 return !!this.pending
;
441 * Increase the pending counter. The pending state will remain active until the counter is zero
442 * (i.e., the number of calls to #pushPending and #popPending is the same).
446 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
447 if ( this.pending
=== 0 ) {
448 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
449 this.updateThemeClasses();
457 * Decrease the pending counter. The pending state will remain active until the counter is zero
458 * (i.e., the number of calls to #pushPending and #popPending is the same).
462 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
463 if ( this.pending
=== 1 ) {
464 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
465 this.updateThemeClasses();
467 this.pending
= Math
.max( 0, this.pending
- 1 );
473 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
474 * Actions can be made available for specific contexts (modes) and circumstances
475 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
477 * ActionSets contain two types of actions:
479 * - Special: Special actions are the first visible actions with special flags, such as 'safe' and 'primary', the default special flags. Additional special flags can be configured in subclasses with the static #specialFlags property.
480 * - Other: Other actions include all non-special visible actions.
482 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
485 * // Example: An action set used in a process dialog
486 * function MyProcessDialog( config ) {
487 * MyProcessDialog.super.call( this, config );
489 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
490 * MyProcessDialog.static.title = 'An action set in a process dialog';
491 * // An action set that uses modes ('edit' and 'help' mode, in this example).
492 * MyProcessDialog.static.actions = [
493 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
494 * { action: 'help', modes: 'edit', label: 'Help' },
495 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
496 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
499 * MyProcessDialog.prototype.initialize = function () {
500 * MyProcessDialog.super.prototype.initialize.apply( this, arguments );
501 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
502 * this.panel1.$element.append( '<p>This dialog uses an action set (continue, help, cancel, back) configured with modes. This is edit mode. Click \'help\' to see help mode.</p>' );
503 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
504 * this.panel2.$element.append( '<p>This is help mode. Only the \'back\' action widget is configured to be visible here. Click \'back\' to return to \'edit\' mode.</p>' );
505 * this.stackLayout = new OO.ui.StackLayout( {
506 * items: [ this.panel1, this.panel2 ]
508 * this.$body.append( this.stackLayout.$element );
510 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
511 * return MyProcessDialog.super.prototype.getSetupProcess.call( this, data )
512 * .next( function () {
513 * this.actions.setMode( 'edit' );
516 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
517 * if ( action === 'help' ) {
518 * this.actions.setMode( 'help' );
519 * this.stackLayout.setItem( this.panel2 );
520 * } else if ( action === 'back' ) {
521 * this.actions.setMode( 'edit' );
522 * this.stackLayout.setItem( this.panel1 );
523 * } else if ( action === 'continue' ) {
525 * return new OO.ui.Process( function () {
529 * return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
531 * MyProcessDialog.prototype.getBodyHeight = function () {
532 * return this.panel1.$element.outerHeight( true );
534 * var windowManager = new OO.ui.WindowManager();
535 * $( 'body' ).append( windowManager.$element );
536 * var dialog = new MyProcessDialog( {
539 * windowManager.addWindows( [ dialog ] );
540 * windowManager.openWindow( dialog );
542 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
546 * @mixins OO.EventEmitter
549 * @param {Object} [config] Configuration options
551 OO
.ui
.ActionSet
= function OoUiActionSet( config
) {
552 // Configuration initialization
553 config
= config
|| {};
555 // Mixin constructors
556 OO
.EventEmitter
.call( this );
561 actions
: 'getAction',
565 this.categorized
= {};
568 this.organized
= false;
569 this.changing
= false;
570 this.changed
= false;
575 OO
.mixinClass( OO
.ui
.ActionSet
, OO
.EventEmitter
);
577 /* Static Properties */
580 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
581 * header of a {@link OO.ui.ProcessDialog process dialog}.
582 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
584 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
591 OO
.ui
.ActionSet
.static.specialFlags
= [ 'safe', 'primary' ];
598 * A 'click' event is emitted when an action is clicked.
600 * @param {OO.ui.ActionWidget} action Action that was clicked
606 * A 'resize' event is emitted when an action widget is resized.
608 * @param {OO.ui.ActionWidget} action Action that was resized
614 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
616 * @param {OO.ui.ActionWidget[]} added Actions added
622 * A 'remove' event is emitted when actions are {@link #method-remove removed}
623 * or {@link #clear cleared}.
625 * @param {OO.ui.ActionWidget[]} added Actions removed
631 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
632 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
639 * Handle action change events.
644 OO
.ui
.ActionSet
.prototype.onActionChange = function () {
645 this.organized
= false;
646 if ( this.changing
) {
649 this.emit( 'change' );
654 * Check if an action is one of the special actions.
656 * @param {OO.ui.ActionWidget} action Action to check
657 * @return {boolean} Action is special
659 OO
.ui
.ActionSet
.prototype.isSpecial = function ( action
) {
662 for ( flag
in this.special
) {
663 if ( action
=== this.special
[ flag
] ) {
672 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
675 * @param {Object} [filters] Filters to use, omit to get all actions
676 * @param {string|string[]} [filters.actions] Actions that action widgets must have
677 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
678 * @param {string|string[]} [filters.modes] Modes that action widgets must have
679 * @param {boolean} [filters.visible] Action widgets must be visible
680 * @param {boolean} [filters.disabled] Action widgets must be disabled
681 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
683 OO
.ui
.ActionSet
.prototype.get = function ( filters
) {
684 var i
, len
, list
, category
, actions
, index
, match
, matches
;
689 // Collect category candidates
691 for ( category
in this.categorized
) {
692 list
= filters
[ category
];
694 if ( !Array
.isArray( list
) ) {
697 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
698 actions
= this.categorized
[ category
][ list
[ i
] ];
699 if ( Array
.isArray( actions
) ) {
700 matches
.push
.apply( matches
, actions
);
705 // Remove by boolean filters
706 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
707 match
= matches
[ i
];
709 ( filters
.visible
!== undefined && match
.isVisible() !== filters
.visible
) ||
710 ( filters
.disabled
!== undefined && match
.isDisabled() !== filters
.disabled
)
712 matches
.splice( i
, 1 );
718 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
719 match
= matches
[ i
];
720 index
= matches
.lastIndexOf( match
);
721 while ( index
!== i
) {
722 matches
.splice( index
, 1 );
724 index
= matches
.lastIndexOf( match
);
729 return this.list
.slice();
733 * Get 'special' actions.
735 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
736 * Special flags can be configured in subclasses by changing the static #specialFlags property.
738 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
740 OO
.ui
.ActionSet
.prototype.getSpecial = function () {
742 return $.extend( {}, this.special
);
746 * Get 'other' actions.
748 * Other actions include all non-special visible action widgets.
750 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
752 OO
.ui
.ActionSet
.prototype.getOthers = function () {
754 return this.others
.slice();
758 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
759 * to be available in the specified mode will be made visible. All other actions will be hidden.
761 * @param {string} mode The mode. Only actions configured to be available in the specified
762 * mode will be made visible.
767 OO
.ui
.ActionSet
.prototype.setMode = function ( mode
) {
770 this.changing
= true;
771 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
772 action
= this.list
[ i
];
773 action
.toggle( action
.hasMode( mode
) );
776 this.organized
= false;
777 this.changing
= false;
778 this.emit( 'change' );
784 * Set the abilities of the specified actions.
786 * Action widgets that are configured with the specified actions will be enabled
787 * or disabled based on the boolean values specified in the `actions`
790 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
791 * values that indicate whether or not the action should be enabled.
794 OO
.ui
.ActionSet
.prototype.setAbilities = function ( actions
) {
795 var i
, len
, action
, item
;
797 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
798 item
= this.list
[ i
];
799 action
= item
.getAction();
800 if ( actions
[ action
] !== undefined ) {
801 item
.setDisabled( !actions
[ action
] );
809 * Executes a function once per action.
811 * When making changes to multiple actions, use this method instead of iterating over the actions
812 * manually to defer emitting a #change event until after all actions have been changed.
814 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
815 * @param {Function} callback Callback to run for each action; callback is invoked with three
816 * arguments: the action, the action's index, the list of actions being iterated over
819 OO
.ui
.ActionSet
.prototype.forEach = function ( filter
, callback
) {
820 this.changed
= false;
821 this.changing
= true;
822 this.get( filter
).forEach( callback
);
823 this.changing
= false;
824 if ( this.changed
) {
825 this.emit( 'change' );
832 * Add action widgets to the action set.
834 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
839 OO
.ui
.ActionSet
.prototype.add = function ( actions
) {
842 this.changing
= true;
843 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
844 action
= actions
[ i
];
845 action
.connect( this, {
846 click
: [ 'emit', 'click', action
],
847 resize
: [ 'emit', 'resize', action
],
848 toggle
: [ 'onActionChange' ]
850 this.list
.push( action
);
852 this.organized
= false;
853 this.emit( 'add', actions
);
854 this.changing
= false;
855 this.emit( 'change' );
861 * Remove action widgets from the set.
863 * To remove all actions, you may wish to use the #clear method instead.
865 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
870 OO
.ui
.ActionSet
.prototype.remove = function ( actions
) {
871 var i
, len
, index
, action
;
873 this.changing
= true;
874 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
875 action
= actions
[ i
];
876 index
= this.list
.indexOf( action
);
877 if ( index
!== -1 ) {
878 action
.disconnect( this );
879 this.list
.splice( index
, 1 );
882 this.organized
= false;
883 this.emit( 'remove', actions
);
884 this.changing
= false;
885 this.emit( 'change' );
891 * Remove all action widets from the set.
893 * To remove only specified actions, use the {@link #method-remove remove} method instead.
899 OO
.ui
.ActionSet
.prototype.clear = function () {
901 removed
= this.list
.slice();
903 this.changing
= true;
904 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
905 action
= this.list
[ i
];
906 action
.disconnect( this );
911 this.organized
= false;
912 this.emit( 'remove', removed
);
913 this.changing
= false;
914 this.emit( 'change' );
922 * This is called whenever organized information is requested. It will only reorganize the actions
923 * if something has changed since the last time it ran.
928 OO
.ui
.ActionSet
.prototype.organize = function () {
929 var i
, iLen
, j
, jLen
, flag
, action
, category
, list
, item
, special
,
930 specialFlags
= this.constructor.static.specialFlags
;
932 if ( !this.organized
) {
933 this.categorized
= {};
936 for ( i
= 0, iLen
= this.list
.length
; i
< iLen
; i
++ ) {
937 action
= this.list
[ i
];
938 if ( action
.isVisible() ) {
939 // Populate categories
940 for ( category
in this.categories
) {
941 if ( !this.categorized
[ category
] ) {
942 this.categorized
[ category
] = {};
944 list
= action
[ this.categories
[ category
] ]();
945 if ( !Array
.isArray( list
) ) {
948 for ( j
= 0, jLen
= list
.length
; j
< jLen
; j
++ ) {
950 if ( !this.categorized
[ category
][ item
] ) {
951 this.categorized
[ category
][ item
] = [];
953 this.categorized
[ category
][ item
].push( action
);
956 // Populate special/others
958 for ( j
= 0, jLen
= specialFlags
.length
; j
< jLen
; j
++ ) {
959 flag
= specialFlags
[ j
];
960 if ( !this.special
[ flag
] && action
.hasFlag( flag
) ) {
961 this.special
[ flag
] = action
;
967 this.others
.push( action
);
971 this.organized
= true;
978 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
979 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
980 * connected to them and can't be interacted with.
986 * @param {Object} [config] Configuration options
987 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
988 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
990 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
991 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
992 * @cfg {string} [text] Text to insert
993 * @cfg {Array} [content] An array of content elements to append (after #text).
994 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
995 * Instances of OO.ui.Element will have their $element appended.
996 * @cfg {jQuery} [$content] Content elements to append (after #text)
997 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
998 * Data can also be specified with the #setData method.
1000 OO
.ui
.Element
= function OoUiElement( config
) {
1001 // Configuration initialization
1002 config
= config
|| {};
1006 this.visible
= true;
1007 this.data
= config
.data
;
1008 this.$element
= config
.$element
||
1009 $( document
.createElement( this.getTagName() ) );
1010 this.elementGroup
= null;
1011 this.debouncedUpdateThemeClassesHandler
= this.debouncedUpdateThemeClasses
.bind( this );
1012 this.updateThemeClassesPending
= false;
1015 if ( Array
.isArray( config
.classes
) ) {
1016 this.$element
.addClass( config
.classes
.join( ' ' ) );
1019 this.$element
.attr( 'id', config
.id
);
1021 if ( config
.text
) {
1022 this.$element
.text( config
.text
);
1024 if ( config
.content
) {
1025 // The `content` property treats plain strings as text; use an
1026 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
1027 // appropriate $element appended.
1028 this.$element
.append( config
.content
.map( function ( v
) {
1029 if ( typeof v
=== 'string' ) {
1030 // Escape string so it is properly represented in HTML.
1031 return document
.createTextNode( v
);
1032 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
1034 return v
.toString();
1035 } else if ( v
instanceof OO
.ui
.Element
) {
1041 if ( config
.$content
) {
1042 // The `$content` property treats plain strings as HTML.
1043 this.$element
.append( config
.$content
);
1049 OO
.initClass( OO
.ui
.Element
);
1051 /* Static Properties */
1054 * The name of the HTML tag used by the element.
1056 * The static value may be ignored if the #getTagName method is overridden.
1060 * @property {string}
1062 OO
.ui
.Element
.static.tagName
= 'div';
1064 /* Static Methods */
1067 * Reconstitute a JavaScript object corresponding to a widget created
1068 * by the PHP implementation.
1070 * @param {string|HTMLElement|jQuery} idOrNode
1071 * A DOM id (if a string) or node for the widget to infuse.
1072 * @return {OO.ui.Element}
1073 * The `OO.ui.Element` corresponding to this (infusable) document node.
1074 * For `Tag` objects emitted on the HTML side (used occasionally for content)
1075 * the value returned is a newly-created Element wrapping around the existing
1078 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
1079 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, true );
1080 // Verify that the type matches up.
1081 // FIXME: uncomment after T89721 is fixed (see T90929)
1083 if ( !( obj instanceof this['class'] ) ) {
1084 throw new Error( 'Infusion type mismatch!' );
1091 * Implementation helper for `infuse`; skips the type check and has an
1092 * extra property so that only the top-level invocation touches the DOM.
1094 * @param {string|HTMLElement|jQuery} idOrNode
1095 * @param {boolean} top True only for top-level invocation.
1096 * @return {OO.ui.Element}
1098 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, top
) {
1099 // look for a cached result of a previous infusion.
1100 var id
, $elem
, data
, cls
, obj
;
1101 if ( typeof idOrNode
=== 'string' ) {
1103 $elem
= $( document
.getElementById( id
) );
1105 $elem
= $( idOrNode
);
1106 id
= $elem
.attr( 'id' );
1108 data
= $elem
.data( 'ooui-infused' );
1111 if ( data
=== true ) {
1112 throw new Error( 'Circular dependency! ' + id
);
1116 if ( !$elem
.length
) {
1117 throw new Error( 'Widget not found: ' + id
);
1119 data
= $elem
.attr( 'data-ooui' );
1121 throw new Error( 'No infusion data found: ' + id
);
1124 data
= $.parseJSON( data
);
1128 if ( !( data
&& data
._
) ) {
1129 throw new Error( 'No valid infusion data found: ' + id
);
1131 if ( data
._
=== 'Tag' ) {
1132 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1133 return new OO
.ui
.Element( { $element
: $elem
} );
1135 cls
= OO
.ui
[data
._
];
1137 throw new Error( 'Unknown widget type: ' + id
);
1139 $elem
.data( 'ooui-infused', true ); // prevent loops
1140 data
.id
= id
; // implicit
1141 data
= OO
.copy( data
, null, function deserialize( value
) {
1142 if ( OO
.isPlainObject( value
) ) {
1144 return OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, false );
1147 return new OO
.ui
.HtmlSnippet( value
.html
);
1151 // jscs:disable requireCapitalizedConstructors
1152 obj
= new cls( data
); // rebuild widget
1153 // now replace old DOM with this new DOM.
1155 $elem
.replaceWith( obj
.$element
);
1157 obj
.$element
.data( 'ooui-infused', obj
);
1158 // set the 'data-ooui' attribute so we can identify infused widgets
1159 obj
.$element
.attr( 'data-ooui', '' );
1164 * Get a jQuery function within a specific document.
1167 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1168 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1170 * @return {Function} Bound jQuery function
1172 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
1173 function wrapper( selector
) {
1174 return $( selector
, wrapper
.context
);
1177 wrapper
.context
= this.getDocument( context
);
1180 wrapper
.$iframe
= $iframe
;
1187 * Get the document of an element.
1190 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1191 * @return {HTMLDocument|null} Document object
1193 OO
.ui
.Element
.static.getDocument = function ( obj
) {
1194 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1195 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
1196 // Empty jQuery selections might have a context
1199 obj
.ownerDocument
||
1203 ( obj
.nodeType
=== 9 && obj
) ||
1208 * Get the window of an element or document.
1211 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1212 * @return {Window} Window object
1214 OO
.ui
.Element
.static.getWindow = function ( obj
) {
1215 var doc
= this.getDocument( obj
);
1216 return doc
.parentWindow
|| doc
.defaultView
;
1220 * Get the direction of an element or document.
1223 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1224 * @return {string} Text direction, either 'ltr' or 'rtl'
1226 OO
.ui
.Element
.static.getDir = function ( obj
) {
1229 if ( obj
instanceof jQuery
) {
1232 isDoc
= obj
.nodeType
=== 9;
1233 isWin
= obj
.document
!== undefined;
1234 if ( isDoc
|| isWin
) {
1240 return $( obj
).css( 'direction' );
1244 * Get the offset between two frames.
1246 * TODO: Make this function not use recursion.
1249 * @param {Window} from Window of the child frame
1250 * @param {Window} [to=window] Window of the parent frame
1251 * @param {Object} [offset] Offset to start with, used internally
1252 * @return {Object} Offset object, containing left and top properties
1254 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
1255 var i
, len
, frames
, frame
, rect
;
1261 offset
= { top
: 0, left
: 0 };
1263 if ( from.parent
=== from ) {
1267 // Get iframe element
1268 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
1269 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
1270 if ( frames
[ i
].contentWindow
=== from ) {
1271 frame
= frames
[ i
];
1276 // Recursively accumulate offset values
1278 rect
= frame
.getBoundingClientRect();
1279 offset
.left
+= rect
.left
;
1280 offset
.top
+= rect
.top
;
1281 if ( from !== to
) {
1282 this.getFrameOffset( from.parent
, offset
);
1289 * Get the offset between two elements.
1291 * The two elements may be in a different frame, but in that case the frame $element is in must
1292 * be contained in the frame $anchor is in.
1295 * @param {jQuery} $element Element whose position to get
1296 * @param {jQuery} $anchor Element to get $element's position relative to
1297 * @return {Object} Translated position coordinates, containing top and left properties
1299 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
1300 var iframe
, iframePos
,
1301 pos
= $element
.offset(),
1302 anchorPos
= $anchor
.offset(),
1303 elementDocument
= this.getDocument( $element
),
1304 anchorDocument
= this.getDocument( $anchor
);
1306 // If $element isn't in the same document as $anchor, traverse up
1307 while ( elementDocument
!== anchorDocument
) {
1308 iframe
= elementDocument
.defaultView
.frameElement
;
1310 throw new Error( '$element frame is not contained in $anchor frame' );
1312 iframePos
= $( iframe
).offset();
1313 pos
.left
+= iframePos
.left
;
1314 pos
.top
+= iframePos
.top
;
1315 elementDocument
= iframe
.ownerDocument
;
1317 pos
.left
-= anchorPos
.left
;
1318 pos
.top
-= anchorPos
.top
;
1323 * Get element border sizes.
1326 * @param {HTMLElement} el Element to measure
1327 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1329 OO
.ui
.Element
.static.getBorders = function ( el
) {
1330 var doc
= el
.ownerDocument
,
1331 win
= doc
.parentWindow
|| doc
.defaultView
,
1332 style
= win
&& win
.getComputedStyle
?
1333 win
.getComputedStyle( el
, null ) :
1336 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1337 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1338 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1339 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1350 * Get dimensions of an element or window.
1353 * @param {HTMLElement|Window} el Element to measure
1354 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1356 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1358 doc
= el
.ownerDocument
|| el
.document
,
1359 win
= doc
.parentWindow
|| doc
.defaultView
;
1361 if ( win
=== el
|| el
=== doc
.documentElement
) {
1364 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1366 top
: $win
.scrollTop(),
1367 left
: $win
.scrollLeft()
1369 scrollbar
: { right
: 0, bottom
: 0 },
1373 bottom
: $win
.innerHeight(),
1374 right
: $win
.innerWidth()
1380 borders
: this.getBorders( el
),
1382 top
: $el
.scrollTop(),
1383 left
: $el
.scrollLeft()
1386 right
: $el
.innerWidth() - el
.clientWidth
,
1387 bottom
: $el
.innerHeight() - el
.clientHeight
1389 rect
: el
.getBoundingClientRect()
1395 * Get scrollable object parent
1397 * documentElement can't be used to get or set the scrollTop
1398 * property on Blink. Changing and testing its value lets us
1399 * use 'body' or 'documentElement' based on what is working.
1401 * https://code.google.com/p/chromium/issues/detail?id=303131
1404 * @param {HTMLElement} el Element to find scrollable parent for
1405 * @return {HTMLElement} Scrollable parent
1407 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1408 var scrollTop
, body
;
1410 if ( OO
.ui
.scrollableElement
=== undefined ) {
1411 body
= el
.ownerDocument
.body
;
1412 scrollTop
= body
.scrollTop
;
1415 if ( body
.scrollTop
=== 1 ) {
1416 body
.scrollTop
= scrollTop
;
1417 OO
.ui
.scrollableElement
= 'body';
1419 OO
.ui
.scrollableElement
= 'documentElement';
1423 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1427 * Get closest scrollable container.
1429 * Traverses up until either a scrollable element or the root is reached, in which case the window
1433 * @param {HTMLElement} el Element to find scrollable container for
1434 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1435 * @return {HTMLElement} Closest scrollable container
1437 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1439 props
= [ 'overflow' ],
1440 $parent
= $( el
).parent();
1442 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1443 props
.push( 'overflow-' + dimension
);
1446 while ( $parent
.length
) {
1447 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1448 return $parent
[ 0 ];
1452 val
= $parent
.css( props
[ i
] );
1453 if ( val
=== 'auto' || val
=== 'scroll' ) {
1454 return $parent
[ 0 ];
1457 $parent
= $parent
.parent();
1459 return this.getDocument( el
).body
;
1463 * Scroll element into view.
1466 * @param {HTMLElement} el Element to scroll into view
1467 * @param {Object} [config] Configuration options
1468 * @param {string} [config.duration] jQuery animation duration value
1469 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1470 * to scroll in both directions
1471 * @param {Function} [config.complete] Function to call when scrolling completes
1473 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1474 // Configuration initialization
1475 config
= config
|| {};
1478 callback
= typeof config
.complete
=== 'function' && config
.complete
,
1479 sc
= this.getClosestScrollableContainer( el
, config
.direction
),
1481 eld
= this.getDimensions( el
),
1482 scd
= this.getDimensions( sc
),
1483 $win
= $( this.getWindow( el
) );
1485 // Compute the distances between the edges of el and the edges of the scroll viewport
1486 if ( $sc
.is( 'html, body' ) ) {
1487 // If the scrollable container is the root, this is easy
1490 bottom
: $win
.innerHeight() - eld
.rect
.bottom
,
1491 left
: eld
.rect
.left
,
1492 right
: $win
.innerWidth() - eld
.rect
.right
1495 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1497 top
: eld
.rect
.top
- ( scd
.rect
.top
+ scd
.borders
.top
),
1498 bottom
: scd
.rect
.bottom
- scd
.borders
.bottom
- scd
.scrollbar
.bottom
- eld
.rect
.bottom
,
1499 left
: eld
.rect
.left
- ( scd
.rect
.left
+ scd
.borders
.left
),
1500 right
: scd
.rect
.right
- scd
.borders
.right
- scd
.scrollbar
.right
- eld
.rect
.right
1504 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1505 if ( rel
.top
< 0 ) {
1506 anim
.scrollTop
= scd
.scroll
.top
+ rel
.top
;
1507 } else if ( rel
.top
> 0 && rel
.bottom
< 0 ) {
1508 anim
.scrollTop
= scd
.scroll
.top
+ Math
.min( rel
.top
, -rel
.bottom
);
1511 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1512 if ( rel
.left
< 0 ) {
1513 anim
.scrollLeft
= scd
.scroll
.left
+ rel
.left
;
1514 } else if ( rel
.left
> 0 && rel
.right
< 0 ) {
1515 anim
.scrollLeft
= scd
.scroll
.left
+ Math
.min( rel
.left
, -rel
.right
);
1518 if ( !$.isEmptyObject( anim
) ) {
1519 $sc
.stop( true ).animate( anim
, config
.duration
|| 'fast' );
1521 $sc
.queue( function ( next
) {
1534 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1535 * and reserve space for them, because it probably doesn't.
1537 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1538 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1539 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1540 * and then reattach (or show) them back.
1543 * @param {HTMLElement} el Element to reconsider the scrollbars on
1545 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1546 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1547 // Save scroll position
1548 scrollLeft
= el
.scrollLeft
;
1549 scrollTop
= el
.scrollTop
;
1550 // Detach all children
1551 while ( el
.firstChild
) {
1552 nodes
.push( el
.firstChild
);
1553 el
.removeChild( el
.firstChild
);
1556 void el
.offsetHeight
;
1557 // Reattach all children
1558 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1559 el
.appendChild( nodes
[ i
] );
1561 // Restore scroll position (no-op if scrollbars disappeared)
1562 el
.scrollLeft
= scrollLeft
;
1563 el
.scrollTop
= scrollTop
;
1569 * Toggle visibility of an element.
1571 * @param {boolean} [show] Make element visible, omit to toggle visibility
1575 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1576 show
= show
=== undefined ? !this.visible
: !!show
;
1578 if ( show
!== this.isVisible() ) {
1579 this.visible
= show
;
1580 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1581 this.emit( 'toggle', show
);
1588 * Check if element is visible.
1590 * @return {boolean} element is visible
1592 OO
.ui
.Element
.prototype.isVisible = function () {
1593 return this.visible
;
1599 * @return {Mixed} Element data
1601 OO
.ui
.Element
.prototype.getData = function () {
1608 * @param {Mixed} Element data
1611 OO
.ui
.Element
.prototype.setData = function ( data
) {
1617 * Check if element supports one or more methods.
1619 * @param {string|string[]} methods Method or list of methods to check
1620 * @return {boolean} All methods are supported
1622 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1626 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1627 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1628 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1633 return methods
.length
=== support
;
1637 * Update the theme-provided classes.
1639 * @localdoc This is called in element mixins and widget classes any time state changes.
1640 * Updating is debounced, minimizing overhead of changing multiple attributes and
1641 * guaranteeing that theme updates do not occur within an element's constructor
1643 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1644 if ( !this.updateThemeClassesPending
) {
1645 this.updateThemeClassesPending
= true;
1646 setTimeout( this.debouncedUpdateThemeClassesHandler
);
1653 OO
.ui
.Element
.prototype.debouncedUpdateThemeClasses = function () {
1654 OO
.ui
.theme
.updateElementClasses( this );
1655 this.updateThemeClassesPending
= false;
1659 * Get the HTML tag name.
1661 * Override this method to base the result on instance information.
1663 * @return {string} HTML tag name
1665 OO
.ui
.Element
.prototype.getTagName = function () {
1666 return this.constructor.static.tagName
;
1670 * Check if the element is attached to the DOM
1671 * @return {boolean} The element is attached to the DOM
1673 OO
.ui
.Element
.prototype.isElementAttached = function () {
1674 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1678 * Get the DOM document.
1680 * @return {HTMLDocument} Document object
1682 OO
.ui
.Element
.prototype.getElementDocument = function () {
1683 // Don't cache this in other ways either because subclasses could can change this.$element
1684 return OO
.ui
.Element
.static.getDocument( this.$element
);
1688 * Get the DOM window.
1690 * @return {Window} Window object
1692 OO
.ui
.Element
.prototype.getElementWindow = function () {
1693 return OO
.ui
.Element
.static.getWindow( this.$element
);
1697 * Get closest scrollable container.
1699 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1700 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1704 * Get group element is in.
1706 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1708 OO
.ui
.Element
.prototype.getElementGroup = function () {
1709 return this.elementGroup
;
1713 * Set group element is in.
1715 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1718 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1719 this.elementGroup
= group
;
1724 * Scroll element into view.
1726 * @param {Object} [config] Configuration options
1728 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1729 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1733 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1734 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1735 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1736 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1737 * and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1741 * @extends OO.ui.Element
1742 * @mixins OO.EventEmitter
1745 * @param {Object} [config] Configuration options
1747 OO
.ui
.Layout
= function OoUiLayout( config
) {
1748 // Configuration initialization
1749 config
= config
|| {};
1751 // Parent constructor
1752 OO
.ui
.Layout
.super.call( this, config
);
1754 // Mixin constructors
1755 OO
.EventEmitter
.call( this );
1758 this.$element
.addClass( 'oo-ui-layout' );
1763 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1764 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1767 * Widgets are compositions of one or more OOjs UI elements that users can both view
1768 * and interact with. All widgets can be configured and modified via a standard API,
1769 * and their state can change dynamically according to a model.
1773 * @extends OO.ui.Element
1774 * @mixins OO.EventEmitter
1777 * @param {Object} [config] Configuration options
1778 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1779 * appearance reflects this state.
1781 OO
.ui
.Widget
= function OoUiWidget( config
) {
1782 // Initialize config
1783 config
= $.extend( { disabled
: false }, config
);
1785 // Parent constructor
1786 OO
.ui
.Widget
.super.call( this, config
);
1788 // Mixin constructors
1789 OO
.EventEmitter
.call( this );
1792 this.disabled
= null;
1793 this.wasDisabled
= null;
1796 this.$element
.addClass( 'oo-ui-widget' );
1797 this.setDisabled( !!config
.disabled
);
1802 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1803 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1805 /* Static Properties */
1808 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
1809 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
1814 * @property {boolean}
1816 OO
.ui
.Widget
.static.supportsSimpleLabel
= false;
1823 * A 'disable' event is emitted when a widget is disabled.
1825 * @param {boolean} disabled Widget is disabled
1831 * A 'toggle' event is emitted when the visibility of the widget changes.
1833 * @param {boolean} visible Widget is visible
1839 * Check if the widget is disabled.
1841 * @return {boolean} Widget is disabled
1843 OO
.ui
.Widget
.prototype.isDisabled = function () {
1844 return this.disabled
;
1848 * Set the 'disabled' state of the widget.
1850 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1852 * @param {boolean} disabled Disable widget
1855 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1858 this.disabled
= !!disabled
;
1859 isDisabled
= this.isDisabled();
1860 if ( isDisabled
!== this.wasDisabled
) {
1861 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1862 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1863 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1864 this.emit( 'disable', isDisabled
);
1865 this.updateThemeClasses();
1867 this.wasDisabled
= isDisabled
;
1873 * Update the disabled state, in case of changes in parent widget.
1877 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1878 this.setDisabled( this.disabled
);
1883 * A window is a container for elements that are in a child frame. They are used with
1884 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
1885 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
1886 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
1887 * the window manager will choose a sensible fallback.
1889 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
1890 * different processes are executed:
1892 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
1893 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
1896 * - {@link #getSetupProcess} method is called and its result executed
1897 * - {@link #getReadyProcess} method is called and its result executed
1899 * **opened**: The window is now open
1901 * **closing**: The closing stage begins when the window manager's
1902 * {@link OO.ui.WindowManager#closeWindow closeWindow}
1903 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
1905 * - {@link #getHoldProcess} method is called and its result executed
1906 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
1908 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
1909 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
1910 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
1911 * processing can complete. Always assume window processes are executed asynchronously.
1913 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
1915 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
1919 * @extends OO.ui.Element
1920 * @mixins OO.EventEmitter
1923 * @param {Object} [config] Configuration options
1924 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
1925 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
1927 OO
.ui
.Window
= function OoUiWindow( config
) {
1928 // Configuration initialization
1929 config
= config
|| {};
1931 // Parent constructor
1932 OO
.ui
.Window
.super.call( this, config
);
1934 // Mixin constructors
1935 OO
.EventEmitter
.call( this );
1938 this.manager
= null;
1939 this.size
= config
.size
|| this.constructor.static.size
;
1940 this.$frame
= $( '<div>' );
1941 this.$overlay
= $( '<div>' );
1942 this.$content
= $( '<div>' );
1945 this.$overlay
.addClass( 'oo-ui-window-overlay' );
1947 .addClass( 'oo-ui-window-content' )
1948 .attr( 'tabindex', 0 );
1950 .addClass( 'oo-ui-window-frame' )
1951 .append( this.$content
);
1954 .addClass( 'oo-ui-window' )
1955 .append( this.$frame
, this.$overlay
);
1957 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
1958 // that reference properties not initialized at that time of parent class construction
1959 // TODO: Find a better way to handle post-constructor setup
1960 this.visible
= false;
1961 this.$element
.addClass( 'oo-ui-element-hidden' );
1966 OO
.inheritClass( OO
.ui
.Window
, OO
.ui
.Element
);
1967 OO
.mixinClass( OO
.ui
.Window
, OO
.EventEmitter
);
1969 /* Static Properties */
1972 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
1974 * The static size is used if no #size is configured during construction.
1978 * @property {string}
1980 OO
.ui
.Window
.static.size
= 'medium';
1985 * Handle mouse down events.
1988 * @param {jQuery.Event} e Mouse down event
1990 OO
.ui
.Window
.prototype.onMouseDown = function ( e
) {
1991 // Prevent clicking on the click-block from stealing focus
1992 if ( e
.target
=== this.$element
[ 0 ] ) {
1998 * Check if the window has been initialized.
2000 * Initialization occurs when a window is added to a manager.
2002 * @return {boolean} Window has been initialized
2004 OO
.ui
.Window
.prototype.isInitialized = function () {
2005 return !!this.manager
;
2009 * Check if the window is visible.
2011 * @return {boolean} Window is visible
2013 OO
.ui
.Window
.prototype.isVisible = function () {
2014 return this.visible
;
2018 * Check if the window is opening.
2020 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2023 * @return {boolean} Window is opening
2025 OO
.ui
.Window
.prototype.isOpening = function () {
2026 return this.manager
.isOpening( this );
2030 * Check if the window is closing.
2032 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2034 * @return {boolean} Window is closing
2036 OO
.ui
.Window
.prototype.isClosing = function () {
2037 return this.manager
.isClosing( this );
2041 * Check if the window is opened.
2043 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2045 * @return {boolean} Window is opened
2047 OO
.ui
.Window
.prototype.isOpened = function () {
2048 return this.manager
.isOpened( this );
2052 * Get the window manager.
2054 * All windows must be attached to a window manager, which is used to open
2055 * and close the window and control its presentation.
2057 * @return {OO.ui.WindowManager} Manager of window
2059 OO
.ui
.Window
.prototype.getManager = function () {
2060 return this.manager
;
2064 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2066 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2068 OO
.ui
.Window
.prototype.getSize = function () {
2073 * Disable transitions on window's frame for the duration of the callback function, then enable them
2077 * @param {Function} callback Function to call while transitions are disabled
2079 OO
.ui
.Window
.prototype.withoutSizeTransitions = function ( callback
) {
2080 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2081 // Disable transitions first, otherwise we'll get values from when the window was animating.
2083 styleObj
= this.$frame
[ 0 ].style
;
2084 oldTransition
= styleObj
.transition
|| styleObj
.OTransition
|| styleObj
.MsTransition
||
2085 styleObj
.MozTransition
|| styleObj
.WebkitTransition
;
2086 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
2087 styleObj
.MozTransition
= styleObj
.WebkitTransition
= 'none';
2089 // Force reflow to make sure the style changes done inside callback really are not transitioned
2090 this.$frame
.height();
2091 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
2092 styleObj
.MozTransition
= styleObj
.WebkitTransition
= oldTransition
;
2096 * Get the height of the full window contents (i.e., the window head, body and foot together).
2098 * What consistitutes the head, body, and foot varies depending on the window type.
2099 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2100 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2101 * and special actions in the head, and dialog content in the body.
2103 * To get just the height of the dialog body, use the #getBodyHeight method.
2105 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2107 OO
.ui
.Window
.prototype.getContentHeight = function () {
2110 bodyStyleObj
= this.$body
[ 0 ].style
,
2111 frameStyleObj
= this.$frame
[ 0 ].style
;
2113 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2114 // Disable transitions first, otherwise we'll get values from when the window was animating.
2115 this.withoutSizeTransitions( function () {
2116 var oldHeight
= frameStyleObj
.height
,
2117 oldPosition
= bodyStyleObj
.position
;
2118 frameStyleObj
.height
= '1px';
2119 // Force body to resize to new width
2120 bodyStyleObj
.position
= 'relative';
2121 bodyHeight
= win
.getBodyHeight();
2122 frameStyleObj
.height
= oldHeight
;
2123 bodyStyleObj
.position
= oldPosition
;
2127 // Add buffer for border
2128 ( this.$frame
.outerHeight() - this.$frame
.innerHeight() ) +
2129 // Use combined heights of children
2130 ( this.$head
.outerHeight( true ) + bodyHeight
+ this.$foot
.outerHeight( true ) )
2135 * Get the height of the window body.
2137 * To get the height of the full window contents (the window body, head, and foot together),
2138 * use #getContentHeight.
2140 * When this function is called, the window will temporarily have been resized
2141 * to height=1px, so .scrollHeight measurements can be taken accurately.
2143 * @return {number} Height of the window body in pixels
2145 OO
.ui
.Window
.prototype.getBodyHeight = function () {
2146 return this.$body
[ 0 ].scrollHeight
;
2150 * Get the directionality of the frame (right-to-left or left-to-right).
2152 * @return {string} Directionality: `'ltr'` or `'rtl'`
2154 OO
.ui
.Window
.prototype.getDir = function () {
2159 * Get the 'setup' process.
2161 * The setup process is used to set up a window for use in a particular context,
2162 * based on the `data` argument. This method is called during the opening phase of the window’s
2165 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2166 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2169 * To add window content that persists between openings, you may wish to use the #initialize method
2173 * @param {Object} [data] Window opening data
2174 * @return {OO.ui.Process} Setup process
2176 OO
.ui
.Window
.prototype.getSetupProcess = function () {
2177 return new OO
.ui
.Process();
2181 * Get the ‘ready’ process.
2183 * The ready process is used to ready a window for use in a particular
2184 * context, based on the `data` argument. This method is called during the opening phase of
2185 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2187 * Override this method to add additional steps to the ‘ready’ process the parent method
2188 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2189 * methods of OO.ui.Process.
2192 * @param {Object} [data] Window opening data
2193 * @return {OO.ui.Process} Ready process
2195 OO
.ui
.Window
.prototype.getReadyProcess = function () {
2196 return new OO
.ui
.Process();
2200 * Get the 'hold' process.
2202 * The hold proccess is used to keep a window from being used in a particular context,
2203 * based on the `data` argument. This method is called during the closing phase of the window’s
2206 * Override this method to add additional steps to the 'hold' process the parent method provides
2207 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2211 * @param {Object} [data] Window closing data
2212 * @return {OO.ui.Process} Hold process
2214 OO
.ui
.Window
.prototype.getHoldProcess = function () {
2215 return new OO
.ui
.Process();
2219 * Get the ‘teardown’ process.
2221 * The teardown process is used to teardown a window after use. During teardown,
2222 * user interactions within the window are conveyed and the window is closed, based on the `data`
2223 * argument. This method is called during the closing phase of the window’s lifecycle.
2225 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2226 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2230 * @param {Object} [data] Window closing data
2231 * @return {OO.ui.Process} Teardown process
2233 OO
.ui
.Window
.prototype.getTeardownProcess = function () {
2234 return new OO
.ui
.Process();
2238 * Set the window manager.
2240 * This will cause the window to initialize. Calling it more than once will cause an error.
2242 * @param {OO.ui.WindowManager} manager Manager for this window
2243 * @throws {Error} An error is thrown if the method is called more than once
2246 OO
.ui
.Window
.prototype.setManager = function ( manager
) {
2247 if ( this.manager
) {
2248 throw new Error( 'Cannot set window manager, window already has a manager' );
2251 this.manager
= manager
;
2258 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2260 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2264 OO
.ui
.Window
.prototype.setSize = function ( size
) {
2271 * Update the window size.
2273 * @throws {Error} An error is thrown if the window is not attached to a window manager
2276 OO
.ui
.Window
.prototype.updateSize = function () {
2277 if ( !this.manager
) {
2278 throw new Error( 'Cannot update window size, must be attached to a manager' );
2281 this.manager
.updateWindowSize( this );
2287 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2288 * when the window is opening. In general, setDimensions should not be called directly.
2290 * To set the size of the window, use the #setSize method.
2292 * @param {Object} dim CSS dimension properties
2293 * @param {string|number} [dim.width] Width
2294 * @param {string|number} [dim.minWidth] Minimum width
2295 * @param {string|number} [dim.maxWidth] Maximum width
2296 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2297 * @param {string|number} [dim.minWidth] Minimum height
2298 * @param {string|number} [dim.maxWidth] Maximum height
2301 OO
.ui
.Window
.prototype.setDimensions = function ( dim
) {
2304 styleObj
= this.$frame
[ 0 ].style
;
2306 // Calculate the height we need to set using the correct width
2307 if ( dim
.height
=== undefined ) {
2308 this.withoutSizeTransitions( function () {
2309 var oldWidth
= styleObj
.width
;
2310 win
.$frame
.css( 'width', dim
.width
|| '' );
2311 height
= win
.getContentHeight();
2312 styleObj
.width
= oldWidth
;
2315 height
= dim
.height
;
2319 width
: dim
.width
|| '',
2320 minWidth
: dim
.minWidth
|| '',
2321 maxWidth
: dim
.maxWidth
|| '',
2322 height
: height
|| '',
2323 minHeight
: dim
.minHeight
|| '',
2324 maxHeight
: dim
.maxHeight
|| ''
2331 * Initialize window contents.
2333 * Before the window is opened for the first time, #initialize is called so that content that
2334 * persists between openings can be added to the window.
2336 * To set up a window with new content each time the window opens, use #getSetupProcess.
2338 * @throws {Error} An error is thrown if the window is not attached to a window manager
2341 OO
.ui
.Window
.prototype.initialize = function () {
2342 if ( !this.manager
) {
2343 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2347 this.$head
= $( '<div>' );
2348 this.$body
= $( '<div>' );
2349 this.$foot
= $( '<div>' );
2350 this.dir
= OO
.ui
.Element
.static.getDir( this.$content
) || 'ltr';
2351 this.$document
= $( this.getElementDocument() );
2354 this.$element
.on( 'mousedown', this.onMouseDown
.bind( this ) );
2357 this.$head
.addClass( 'oo-ui-window-head' );
2358 this.$body
.addClass( 'oo-ui-window-body' );
2359 this.$foot
.addClass( 'oo-ui-window-foot' );
2360 this.$content
.append( this.$head
, this.$body
, this.$foot
);
2368 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2369 * method, which returns a promise resolved when the window is done opening.
2371 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2373 * @param {Object} [data] Window opening data
2374 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2375 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2376 * value is a new promise, which is resolved when the window begins closing.
2377 * @throws {Error} An error is thrown if the window is not attached to a window manager
2379 OO
.ui
.Window
.prototype.open = function ( data
) {
2380 if ( !this.manager
) {
2381 throw new Error( 'Cannot open window, must be attached to a manager' );
2384 return this.manager
.openWindow( this, data
);
2390 * This method is a wrapper around a call to the window
2391 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2392 * which returns a closing promise resolved when the window is done closing.
2394 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2395 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2396 * the window closes.
2398 * @param {Object} [data] Window closing data
2399 * @return {jQuery.Promise} Promise resolved when window is closed
2400 * @throws {Error} An error is thrown if the window is not attached to a window manager
2402 OO
.ui
.Window
.prototype.close = function ( data
) {
2403 if ( !this.manager
) {
2404 throw new Error( 'Cannot close window, must be attached to a manager' );
2407 return this.manager
.closeWindow( this, data
);
2413 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2416 * @param {Object} [data] Window opening data
2417 * @return {jQuery.Promise} Promise resolved when window is setup
2419 OO
.ui
.Window
.prototype.setup = function ( data
) {
2421 deferred
= $.Deferred();
2423 this.toggle( true );
2425 this.getSetupProcess( data
).execute().done( function () {
2426 // Force redraw by asking the browser to measure the elements' widths
2427 win
.$element
.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2428 win
.$content
.addClass( 'oo-ui-window-content-setup' ).width();
2432 return deferred
.promise();
2438 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2441 * @param {Object} [data] Window opening data
2442 * @return {jQuery.Promise} Promise resolved when window is ready
2444 OO
.ui
.Window
.prototype.ready = function ( data
) {
2446 deferred
= $.Deferred();
2448 this.$content
.focus();
2449 this.getReadyProcess( data
).execute().done( function () {
2450 // Force redraw by asking the browser to measure the elements' widths
2451 win
.$element
.addClass( 'oo-ui-window-ready' ).width();
2452 win
.$content
.addClass( 'oo-ui-window-content-ready' ).width();
2456 return deferred
.promise();
2462 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2465 * @param {Object} [data] Window closing data
2466 * @return {jQuery.Promise} Promise resolved when window is held
2468 OO
.ui
.Window
.prototype.hold = function ( data
) {
2470 deferred
= $.Deferred();
2472 this.getHoldProcess( data
).execute().done( function () {
2473 // Get the focused element within the window's content
2474 var $focus
= win
.$content
.find( OO
.ui
.Element
.static.getDocument( win
.$content
).activeElement
);
2476 // Blur the focused element
2477 if ( $focus
.length
) {
2481 // Force redraw by asking the browser to measure the elements' widths
2482 win
.$element
.removeClass( 'oo-ui-window-ready' ).width();
2483 win
.$content
.removeClass( 'oo-ui-window-content-ready' ).width();
2487 return deferred
.promise();
2493 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2496 * @param {Object} [data] Window closing data
2497 * @return {jQuery.Promise} Promise resolved when window is torn down
2499 OO
.ui
.Window
.prototype.teardown = function ( data
) {
2502 return this.getTeardownProcess( data
).execute()
2503 .done( function () {
2504 // Force redraw by asking the browser to measure the elements' widths
2505 win
.$element
.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2506 win
.$content
.removeClass( 'oo-ui-window-content-setup' ).width();
2507 win
.toggle( false );
2512 * The Dialog class serves as the base class for the other types of dialogs.
2513 * Unless extended to include controls, the rendered dialog box is a simple window
2514 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2515 * which opens, closes, and controls the presentation of the window. See the
2516 * [OOjs UI documentation on MediaWiki] [1] for more information.
2519 * // A simple dialog window.
2520 * function MyDialog( config ) {
2521 * MyDialog.super.call( this, config );
2523 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2524 * MyDialog.prototype.initialize = function () {
2525 * MyDialog.super.prototype.initialize.call( this );
2526 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2527 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2528 * this.$body.append( this.content.$element );
2530 * MyDialog.prototype.getBodyHeight = function () {
2531 * return this.content.$element.outerHeight( true );
2533 * var myDialog = new MyDialog( {
2536 * // Create and append a window manager, which opens and closes the window.
2537 * var windowManager = new OO.ui.WindowManager();
2538 * $( 'body' ).append( windowManager.$element );
2539 * windowManager.addWindows( [ myDialog ] );
2540 * // Open the window!
2541 * windowManager.openWindow( myDialog );
2543 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2547 * @extends OO.ui.Window
2548 * @mixins OO.ui.mixin.PendingElement
2551 * @param {Object} [config] Configuration options
2553 OO
.ui
.Dialog
= function OoUiDialog( config
) {
2554 // Parent constructor
2555 OO
.ui
.Dialog
.super.call( this, config
);
2557 // Mixin constructors
2558 OO
.ui
.mixin
.PendingElement
.call( this );
2561 this.actions
= new OO
.ui
.ActionSet();
2562 this.attachedActions
= [];
2563 this.currentAction
= null;
2564 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
2567 this.actions
.connect( this, {
2568 click
: 'onActionClick',
2569 resize
: 'onActionResize',
2570 change
: 'onActionsChange'
2575 .addClass( 'oo-ui-dialog' )
2576 .attr( 'role', 'dialog' );
2581 OO
.inheritClass( OO
.ui
.Dialog
, OO
.ui
.Window
);
2582 OO
.mixinClass( OO
.ui
.Dialog
, OO
.ui
.mixin
.PendingElement
);
2584 /* Static Properties */
2587 * Symbolic name of dialog.
2589 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2590 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2592 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2597 * @property {string}
2599 OO
.ui
.Dialog
.static.name
= '';
2604 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2605 * that will produce a Label node or string. The title can also be specified with data passed to the
2606 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2611 * @property {jQuery|string|Function}
2613 OO
.ui
.Dialog
.static.title
= '';
2616 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2618 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2619 * value will be overriden.
2621 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2625 * @property {Object[]}
2627 OO
.ui
.Dialog
.static.actions
= [];
2630 * Close the dialog when the 'Esc' key is pressed.
2635 * @property {boolean}
2637 OO
.ui
.Dialog
.static.escapable
= true;
2642 * Handle frame document key down events.
2645 * @param {jQuery.Event} e Key down event
2647 OO
.ui
.Dialog
.prototype.onDocumentKeyDown = function ( e
) {
2648 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
2651 e
.stopPropagation();
2656 * Handle action resized events.
2659 * @param {OO.ui.ActionWidget} action Action that was resized
2661 OO
.ui
.Dialog
.prototype.onActionResize = function () {
2662 // Override in subclass
2666 * Handle action click events.
2669 * @param {OO.ui.ActionWidget} action Action that was clicked
2671 OO
.ui
.Dialog
.prototype.onActionClick = function ( action
) {
2672 if ( !this.isPending() ) {
2673 this.executeAction( action
.getAction() );
2678 * Handle actions change event.
2682 OO
.ui
.Dialog
.prototype.onActionsChange = function () {
2683 this.detachActions();
2684 if ( !this.isClosing() ) {
2685 this.attachActions();
2690 * Get the set of actions used by the dialog.
2692 * @return {OO.ui.ActionSet}
2694 OO
.ui
.Dialog
.prototype.getActions = function () {
2695 return this.actions
;
2699 * Get a process for taking action.
2701 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2702 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2703 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2706 * @param {string} [action] Symbolic name of action
2707 * @return {OO.ui.Process} Action process
2709 OO
.ui
.Dialog
.prototype.getActionProcess = function ( action
) {
2710 return new OO
.ui
.Process()
2711 .next( function () {
2713 // An empty action always closes the dialog without data, which should always be
2714 // safe and make no changes
2723 * @param {Object} [data] Dialog opening data
2724 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2725 * the {@link #static-title static title}
2726 * @param {Object[]} [data.actions] List of configuration options for each
2727 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2729 OO
.ui
.Dialog
.prototype.getSetupProcess = function ( data
) {
2733 return OO
.ui
.Dialog
.super.prototype.getSetupProcess
.call( this, data
)
2734 .next( function () {
2735 var config
= this.constructor.static,
2736 actions
= data
.actions
!== undefined ? data
.actions
: config
.actions
;
2738 this.title
.setLabel(
2739 data
.title
!== undefined ? data
.title
: this.constructor.static.title
2741 this.actions
.add( this.getActionWidgets( actions
) );
2743 if ( this.constructor.static.escapable
) {
2744 this.$document
.on( 'keydown', this.onDocumentKeyDownHandler
);
2752 OO
.ui
.Dialog
.prototype.getTeardownProcess = function ( data
) {
2754 return OO
.ui
.Dialog
.super.prototype.getTeardownProcess
.call( this, data
)
2755 .first( function () {
2756 if ( this.constructor.static.escapable
) {
2757 this.$document
.off( 'keydown', this.onDocumentKeyDownHandler
);
2760 this.actions
.clear();
2761 this.currentAction
= null;
2768 OO
.ui
.Dialog
.prototype.initialize = function () {
2770 OO
.ui
.Dialog
.super.prototype.initialize
.call( this );
2772 var titleId
= OO
.ui
.generateElementId();
2775 this.title
= new OO
.ui
.LabelWidget( {
2780 this.$content
.addClass( 'oo-ui-dialog-content' );
2781 this.$element
.attr( 'aria-labelledby', titleId
);
2782 this.setPendingElement( this.$head
);
2786 * Get action widgets from a list of configs
2788 * @param {Object[]} actions Action widget configs
2789 * @return {OO.ui.ActionWidget[]} Action widgets
2791 OO
.ui
.Dialog
.prototype.getActionWidgets = function ( actions
) {
2792 var i
, len
, widgets
= [];
2793 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
2795 new OO
.ui
.ActionWidget( actions
[ i
] )
2802 * Attach action actions.
2806 OO
.ui
.Dialog
.prototype.attachActions = function () {
2807 // Remember the list of potentially attached actions
2808 this.attachedActions
= this.actions
.get();
2812 * Detach action actions.
2817 OO
.ui
.Dialog
.prototype.detachActions = function () {
2820 // Detach all actions that may have been previously attached
2821 for ( i
= 0, len
= this.attachedActions
.length
; i
< len
; i
++ ) {
2822 this.attachedActions
[ i
].$element
.detach();
2824 this.attachedActions
= [];
2828 * Execute an action.
2830 * @param {string} action Symbolic name of action to execute
2831 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2833 OO
.ui
.Dialog
.prototype.executeAction = function ( action
) {
2835 this.currentAction
= action
;
2836 return this.getActionProcess( action
).execute()
2837 .always( this.popPending
.bind( this ) );
2841 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
2842 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
2843 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
2844 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
2845 * pertinent data and reused.
2847 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
2848 * `opened`, and `closing`, which represent the primary stages of the cycle:
2850 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
2851 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
2853 * - an `opening` event is emitted with an `opening` promise
2854 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
2855 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
2856 * window and its result executed
2857 * - a `setup` progress notification is emitted from the `opening` promise
2858 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
2859 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
2860 * window and its result executed
2861 * - a `ready` progress notification is emitted from the `opening` promise
2862 * - the `opening` promise is resolved with an `opened` promise
2864 * **Opened**: the window is now open.
2866 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
2867 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
2868 * to close the window.
2870 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
2871 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
2872 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
2873 * window and its result executed
2874 * - a `hold` progress notification is emitted from the `closing` promise
2875 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
2876 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
2877 * window and its result executed
2878 * - a `teardown` progress notification is emitted from the `closing` promise
2879 * - the `closing` promise is resolved. The window is now closed
2881 * See the [OOjs UI documentation on MediaWiki][1] for more information.
2883 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2886 * @extends OO.ui.Element
2887 * @mixins OO.EventEmitter
2890 * @param {Object} [config] Configuration options
2891 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
2892 * Note that window classes that are instantiated with a factory must have
2893 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
2894 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
2896 OO
.ui
.WindowManager
= function OoUiWindowManager( config
) {
2897 // Configuration initialization
2898 config
= config
|| {};
2900 // Parent constructor
2901 OO
.ui
.WindowManager
.super.call( this, config
);
2903 // Mixin constructors
2904 OO
.EventEmitter
.call( this );
2907 this.factory
= config
.factory
;
2908 this.modal
= config
.modal
=== undefined || !!config
.modal
;
2910 this.opening
= null;
2912 this.closing
= null;
2913 this.preparingToOpen
= null;
2914 this.preparingToClose
= null;
2915 this.currentWindow
= null;
2916 this.globalEvents
= false;
2917 this.$ariaHidden
= null;
2918 this.onWindowResizeTimeout
= null;
2919 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
2920 this.afterWindowResizeHandler
= this.afterWindowResize
.bind( this );
2924 .addClass( 'oo-ui-windowManager' )
2925 .toggleClass( 'oo-ui-windowManager-modal', this.modal
);
2930 OO
.inheritClass( OO
.ui
.WindowManager
, OO
.ui
.Element
);
2931 OO
.mixinClass( OO
.ui
.WindowManager
, OO
.EventEmitter
);
2936 * An 'opening' event is emitted when the window begins to be opened.
2939 * @param {OO.ui.Window} win Window that's being opened
2940 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
2941 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
2942 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
2943 * @param {Object} data Window opening data
2947 * A 'closing' event is emitted when the window begins to be closed.
2950 * @param {OO.ui.Window} win Window that's being closed
2951 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
2952 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
2953 * processes are complete. When the `closing` promise is resolved, the first argument of its value
2954 * is the closing data.
2955 * @param {Object} data Window closing data
2959 * A 'resize' event is emitted when a window is resized.
2962 * @param {OO.ui.Window} win Window that was resized
2965 /* Static Properties */
2968 * Map of the symbolic name of each window size and its CSS properties.
2972 * @property {Object}
2974 OO
.ui
.WindowManager
.static.sizes
= {
2988 // These can be non-numeric because they are never used in calculations
2995 * Symbolic name of the default window size.
2997 * The default size is used if the window's requested size is not recognized.
3001 * @property {string}
3003 OO
.ui
.WindowManager
.static.defaultSize
= 'medium';
3008 * Handle window resize events.
3011 * @param {jQuery.Event} e Window resize event
3013 OO
.ui
.WindowManager
.prototype.onWindowResize = function () {
3014 clearTimeout( this.onWindowResizeTimeout
);
3015 this.onWindowResizeTimeout
= setTimeout( this.afterWindowResizeHandler
, 200 );
3019 * Handle window resize events.
3022 * @param {jQuery.Event} e Window resize event
3024 OO
.ui
.WindowManager
.prototype.afterWindowResize = function () {
3025 if ( this.currentWindow
) {
3026 this.updateWindowSize( this.currentWindow
);
3031 * Check if window is opening.
3033 * @return {boolean} Window is opening
3035 OO
.ui
.WindowManager
.prototype.isOpening = function ( win
) {
3036 return win
=== this.currentWindow
&& !!this.opening
&& this.opening
.state() === 'pending';
3040 * Check if window is closing.
3042 * @return {boolean} Window is closing
3044 OO
.ui
.WindowManager
.prototype.isClosing = function ( win
) {
3045 return win
=== this.currentWindow
&& !!this.closing
&& this.closing
.state() === 'pending';
3049 * Check if window is opened.
3051 * @return {boolean} Window is opened
3053 OO
.ui
.WindowManager
.prototype.isOpened = function ( win
) {
3054 return win
=== this.currentWindow
&& !!this.opened
&& this.opened
.state() === 'pending';
3058 * Check if a window is being managed.
3060 * @param {OO.ui.Window} win Window to check
3061 * @return {boolean} Window is being managed
3063 OO
.ui
.WindowManager
.prototype.hasWindow = function ( win
) {
3066 for ( name
in this.windows
) {
3067 if ( this.windows
[ name
] === win
) {
3076 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
3078 * @param {OO.ui.Window} win Window being opened
3079 * @param {Object} [data] Window opening data
3080 * @return {number} Milliseconds to wait
3082 OO
.ui
.WindowManager
.prototype.getSetupDelay = function () {
3087 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3089 * @param {OO.ui.Window} win Window being opened
3090 * @param {Object} [data] Window opening data
3091 * @return {number} Milliseconds to wait
3093 OO
.ui
.WindowManager
.prototype.getReadyDelay = function () {
3098 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3100 * @param {OO.ui.Window} win Window being closed
3101 * @param {Object} [data] Window closing data
3102 * @return {number} Milliseconds to wait
3104 OO
.ui
.WindowManager
.prototype.getHoldDelay = function () {
3109 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3110 * executing the ‘teardown’ process.
3112 * @param {OO.ui.Window} win Window being closed
3113 * @param {Object} [data] Window closing data
3114 * @return {number} Milliseconds to wait
3116 OO
.ui
.WindowManager
.prototype.getTeardownDelay = function () {
3117 return this.modal
? 250 : 0;
3121 * Get a window by its symbolic name.
3123 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3124 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3125 * for more information about using factories.
3126 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3128 * @param {string} name Symbolic name of the window
3129 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3130 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3131 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3133 OO
.ui
.WindowManager
.prototype.getWindow = function ( name
) {
3134 var deferred
= $.Deferred(),
3135 win
= this.windows
[ name
];
3137 if ( !( win
instanceof OO
.ui
.Window
) ) {
3138 if ( this.factory
) {
3139 if ( !this.factory
.lookup( name
) ) {
3140 deferred
.reject( new OO
.ui
.Error(
3141 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3144 win
= this.factory
.create( name
);
3145 this.addWindows( [ win
] );
3146 deferred
.resolve( win
);
3149 deferred
.reject( new OO
.ui
.Error(
3150 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3154 deferred
.resolve( win
);
3157 return deferred
.promise();
3161 * Get current window.
3163 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3165 OO
.ui
.WindowManager
.prototype.getCurrentWindow = function () {
3166 return this.currentWindow
;
3172 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3173 * @param {Object} [data] Window opening data
3174 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3175 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3178 OO
.ui
.WindowManager
.prototype.openWindow = function ( win
, data
) {
3180 opening
= $.Deferred();
3182 // Argument handling
3183 if ( typeof win
=== 'string' ) {
3184 return this.getWindow( win
).then( function ( win
) {
3185 return manager
.openWindow( win
, data
);
3190 if ( !this.hasWindow( win
) ) {
3191 opening
.reject( new OO
.ui
.Error(
3192 'Cannot open window: window is not attached to manager'
3194 } else if ( this.preparingToOpen
|| this.opening
|| this.opened
) {
3195 opening
.reject( new OO
.ui
.Error(
3196 'Cannot open window: another window is opening or open'
3201 if ( opening
.state() !== 'rejected' ) {
3202 // If a window is currently closing, wait for it to complete
3203 this.preparingToOpen
= $.when( this.closing
);
3204 // Ensure handlers get called after preparingToOpen is set
3205 this.preparingToOpen
.done( function () {
3206 if ( manager
.modal
) {
3207 manager
.toggleGlobalEvents( true );
3208 manager
.toggleAriaIsolation( true );
3210 manager
.currentWindow
= win
;
3211 manager
.opening
= opening
;
3212 manager
.preparingToOpen
= null;
3213 manager
.emit( 'opening', win
, opening
, data
);
3214 setTimeout( function () {
3215 win
.setup( data
).then( function () {
3216 manager
.updateWindowSize( win
);
3217 manager
.opening
.notify( { state
: 'setup' } );
3218 setTimeout( function () {
3219 win
.ready( data
).then( function () {
3220 manager
.opening
.notify( { state
: 'ready' } );
3221 manager
.opening
= null;
3222 manager
.opened
= $.Deferred();
3223 opening
.resolve( manager
.opened
.promise(), data
);
3225 }, manager
.getReadyDelay() );
3227 }, manager
.getSetupDelay() );
3231 return opening
.promise();
3237 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3238 * @param {Object} [data] Window closing data
3239 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3240 * See {@link #event-closing 'closing' event} for more information about closing promises.
3241 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3244 OO
.ui
.WindowManager
.prototype.closeWindow = function ( win
, data
) {
3246 closing
= $.Deferred(),
3249 // Argument handling
3250 if ( typeof win
=== 'string' ) {
3251 win
= this.windows
[ win
];
3252 } else if ( !this.hasWindow( win
) ) {
3258 closing
.reject( new OO
.ui
.Error(
3259 'Cannot close window: window is not attached to manager'
3261 } else if ( win
!== this.currentWindow
) {
3262 closing
.reject( new OO
.ui
.Error(
3263 'Cannot close window: window already closed with different data'
3265 } else if ( this.preparingToClose
|| this.closing
) {
3266 closing
.reject( new OO
.ui
.Error(
3267 'Cannot close window: window already closing with different data'
3272 if ( closing
.state() !== 'rejected' ) {
3273 // If the window is currently opening, close it when it's done
3274 this.preparingToClose
= $.when( this.opening
);
3275 // Ensure handlers get called after preparingToClose is set
3276 this.preparingToClose
.done( function () {
3277 manager
.closing
= closing
;
3278 manager
.preparingToClose
= null;
3279 manager
.emit( 'closing', win
, closing
, data
);
3280 opened
= manager
.opened
;
3281 manager
.opened
= null;
3282 opened
.resolve( closing
.promise(), data
);
3283 setTimeout( function () {
3284 win
.hold( data
).then( function () {
3285 closing
.notify( { state
: 'hold' } );
3286 setTimeout( function () {
3287 win
.teardown( data
).then( function () {
3288 closing
.notify( { state
: 'teardown' } );
3289 if ( manager
.modal
) {
3290 manager
.toggleGlobalEvents( false );
3291 manager
.toggleAriaIsolation( false );
3293 manager
.closing
= null;
3294 manager
.currentWindow
= null;
3295 closing
.resolve( data
);
3297 }, manager
.getTeardownDelay() );
3299 }, manager
.getHoldDelay() );
3303 return closing
.promise();
3307 * Add windows to the window manager.
3309 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3310 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3311 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3313 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3314 * by reference, symbolic name, or explicitly defined symbolic names.
3315 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3316 * explicit nor a statically configured symbolic name.
3318 OO
.ui
.WindowManager
.prototype.addWindows = function ( windows
) {
3319 var i
, len
, win
, name
, list
;
3321 if ( Array
.isArray( windows
) ) {
3322 // Convert to map of windows by looking up symbolic names from static configuration
3324 for ( i
= 0, len
= windows
.length
; i
< len
; i
++ ) {
3325 name
= windows
[ i
].constructor.static.name
;
3326 if ( typeof name
!== 'string' ) {
3327 throw new Error( 'Cannot add window' );
3329 list
[ name
] = windows
[ i
];
3331 } else if ( OO
.isPlainObject( windows
) ) {
3336 for ( name
in list
) {
3338 this.windows
[ name
] = win
.toggle( false );
3339 this.$element
.append( win
.$element
);
3340 win
.setManager( this );
3345 * Remove the specified windows from the windows manager.
3347 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3348 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3349 * longer listens to events, use the #destroy method.
3351 * @param {string[]} names Symbolic names of windows to remove
3352 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3353 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3355 OO
.ui
.WindowManager
.prototype.removeWindows = function ( names
) {
3356 var i
, len
, win
, name
, cleanupWindow
,
3359 cleanup = function ( name
, win
) {
3360 delete manager
.windows
[ name
];
3361 win
.$element
.detach();
3364 for ( i
= 0, len
= names
.length
; i
< len
; i
++ ) {
3366 win
= this.windows
[ name
];
3368 throw new Error( 'Cannot remove window' );
3370 cleanupWindow
= cleanup
.bind( null, name
, win
);
3371 promises
.push( this.closeWindow( name
).then( cleanupWindow
, cleanupWindow
) );
3374 return $.when
.apply( $, promises
);
3378 * Remove all windows from the window manager.
3380 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3381 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3382 * To remove just a subset of windows, use the #removeWindows method.
3384 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3386 OO
.ui
.WindowManager
.prototype.clearWindows = function () {
3387 return this.removeWindows( Object
.keys( this.windows
) );
3391 * Set dialog size. In general, this method should not be called directly.
3393 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3397 OO
.ui
.WindowManager
.prototype.updateWindowSize = function ( win
) {
3398 // Bypass for non-current, and thus invisible, windows
3399 if ( win
!== this.currentWindow
) {
3403 var viewport
= OO
.ui
.Element
.static.getDimensions( win
.getElementWindow() ),
3404 sizes
= this.constructor.static.sizes
,
3405 size
= win
.getSize();
3407 if ( !sizes
[ size
] ) {
3408 size
= this.constructor.static.defaultSize
;
3410 if ( size
!== 'full' && viewport
.rect
.right
- viewport
.rect
.left
< sizes
[ size
].width
) {
3414 this.$element
.toggleClass( 'oo-ui-windowManager-fullscreen', size
=== 'full' );
3415 this.$element
.toggleClass( 'oo-ui-windowManager-floating', size
!== 'full' );
3416 win
.setDimensions( sizes
[ size
] );
3418 this.emit( 'resize', win
);
3424 * Bind or unbind global events for scrolling.
3427 * @param {boolean} [on] Bind global events
3430 OO
.ui
.WindowManager
.prototype.toggleGlobalEvents = function ( on
) {
3431 on
= on
=== undefined ? !!this.globalEvents
: !!on
;
3433 var scrollWidth
, bodyMargin
,
3434 $body
= $( this.getElementDocument().body
),
3435 // We could have multiple window managers open so only modify
3436 // the body css at the bottom of the stack
3437 stackDepth
= $body
.data( 'windowManagerGlobalEvents' ) || 0 ;
3440 if ( !this.globalEvents
) {
3441 $( this.getElementWindow() ).on( {
3442 // Start listening for top-level window dimension changes
3443 'orientationchange resize': this.onWindowResizeHandler
3445 if ( stackDepth
=== 0 ) {
3446 scrollWidth
= window
.innerWidth
- document
.documentElement
.clientWidth
;
3447 bodyMargin
= parseFloat( $body
.css( 'margin-right' ) ) || 0;
3450 'margin-right': bodyMargin
+ scrollWidth
3454 this.globalEvents
= true;
3456 } else if ( this.globalEvents
) {
3457 $( this.getElementWindow() ).off( {
3458 // Stop listening for top-level window dimension changes
3459 'orientationchange resize': this.onWindowResizeHandler
3462 if ( stackDepth
=== 0 ) {
3468 this.globalEvents
= false;
3470 $body
.data( 'windowManagerGlobalEvents', stackDepth
);
3476 * Toggle screen reader visibility of content other than the window manager.
3479 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3482 OO
.ui
.WindowManager
.prototype.toggleAriaIsolation = function ( isolate
) {
3483 isolate
= isolate
=== undefined ? !this.$ariaHidden
: !!isolate
;
3486 if ( !this.$ariaHidden
) {
3487 // Hide everything other than the window manager from screen readers
3488 this.$ariaHidden
= $( 'body' )
3490 .not( this.$element
.parentsUntil( 'body' ).last() )
3491 .attr( 'aria-hidden', '' );
3493 } else if ( this.$ariaHidden
) {
3494 // Restore screen reader visibility
3495 this.$ariaHidden
.removeAttr( 'aria-hidden' );
3496 this.$ariaHidden
= null;
3503 * Destroy the window manager.
3505 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3506 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3509 OO
.ui
.WindowManager
.prototype.destroy = function () {
3510 this.toggleGlobalEvents( false );
3511 this.toggleAriaIsolation( false );
3512 this.clearWindows();
3513 this.$element
.remove();
3517 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3518 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3519 * appearance and functionality of the error interface.
3521 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3522 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3523 * that initiated the failed process will be disabled.
3525 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3528 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3530 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3535 * @param {string|jQuery} message Description of error
3536 * @param {Object} [config] Configuration options
3537 * @cfg {boolean} [recoverable=true] Error is recoverable.
3538 * By default, errors are recoverable, and users can try the process again.
3539 * @cfg {boolean} [warning=false] Error is a warning.
3540 * If the error is a warning, the error interface will include a
3541 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3542 * is not triggered a second time if the user chooses to continue.
3544 OO
.ui
.Error
= function OoUiError( message
, config
) {
3545 // Allow passing positional parameters inside the config object
3546 if ( OO
.isPlainObject( message
) && config
=== undefined ) {
3548 message
= config
.message
;
3551 // Configuration initialization
3552 config
= config
|| {};
3555 this.message
= message
instanceof jQuery
? message
: String( message
);
3556 this.recoverable
= config
.recoverable
=== undefined || !!config
.recoverable
;
3557 this.warning
= !!config
.warning
;
3562 OO
.initClass( OO
.ui
.Error
);
3567 * Check if the error is recoverable.
3569 * If the error is recoverable, users are able to try the process again.
3571 * @return {boolean} Error is recoverable
3573 OO
.ui
.Error
.prototype.isRecoverable = function () {
3574 return this.recoverable
;
3578 * Check if the error is a warning.
3580 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3582 * @return {boolean} Error is warning
3584 OO
.ui
.Error
.prototype.isWarning = function () {
3585 return this.warning
;
3589 * Get error message as DOM nodes.
3591 * @return {jQuery} Error message in DOM nodes
3593 OO
.ui
.Error
.prototype.getMessage = function () {
3594 return this.message
instanceof jQuery
?
3595 this.message
.clone() :
3596 $( '<div>' ).text( this.message
).contents();
3600 * Get the error message text.
3602 * @return {string} Error message
3604 OO
.ui
.Error
.prototype.getMessageText = function () {
3605 return this.message
instanceof jQuery
? this.message
.text() : this.message
;
3609 * Wraps an HTML snippet for use with configuration values which default
3610 * to strings. This bypasses the default html-escaping done to string
3616 * @param {string} [content] HTML content
3618 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
3620 this.content
= content
;
3625 OO
.initClass( OO
.ui
.HtmlSnippet
);
3632 * @return {string} Unchanged HTML snippet.
3634 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
3635 return this.content
;
3639 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3642 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3643 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3644 * or stop if the promise is rejected.
3645 * - **function**: the process will execute the function. The process will stop if the function returns
3646 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3647 * will wait for that number of milliseconds before proceeding.
3649 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3650 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3651 * its remaining steps will not be performed.
3656 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3657 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3658 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3659 * a number or promise.
3660 * @return {Object} Step object, with `callback` and `context` properties
3662 OO
.ui
.Process = function ( step
, context
) {
3667 if ( step
!== undefined ) {
3668 this.next( step
, context
);
3674 OO
.initClass( OO
.ui
.Process
);
3679 * Start the process.
3681 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3682 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3683 * and any remaining steps are not performed.
3685 OO
.ui
.Process
.prototype.execute = function () {
3686 var i
, len
, promise
;
3689 * Continue execution.
3692 * @param {Array} step A function and the context it should be called in
3693 * @return {Function} Function that continues the process
3695 function proceed( step
) {
3696 return function () {
3697 // Execute step in the correct context
3699 result
= step
.callback
.call( step
.context
);
3701 if ( result
=== false ) {
3702 // Use rejected promise for boolean false results
3703 return $.Deferred().reject( [] ).promise();
3705 if ( typeof result
=== 'number' ) {
3707 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3709 // Use a delayed promise for numbers, expecting them to be in milliseconds
3710 deferred
= $.Deferred();
3711 setTimeout( deferred
.resolve
, result
);
3712 return deferred
.promise();
3714 if ( result
instanceof OO
.ui
.Error
) {
3715 // Use rejected promise for error
3716 return $.Deferred().reject( [ result
] ).promise();
3718 if ( Array
.isArray( result
) && result
.length
&& result
[ 0 ] instanceof OO
.ui
.Error
) {
3719 // Use rejected promise for list of errors
3720 return $.Deferred().reject( result
).promise();
3722 // Duck-type the object to see if it can produce a promise
3723 if ( result
&& $.isFunction( result
.promise
) ) {
3724 // Use a promise generated from the result
3725 return result
.promise();
3727 // Use resolved promise for other results
3728 return $.Deferred().resolve().promise();
3732 if ( this.steps
.length
) {
3733 // Generate a chain reaction of promises
3734 promise
= proceed( this.steps
[ 0 ] )();
3735 for ( i
= 1, len
= this.steps
.length
; i
< len
; i
++ ) {
3736 promise
= promise
.then( proceed( this.steps
[ i
] ) );
3739 promise
= $.Deferred().resolve().promise();
3746 * Create a process step.
3749 * @param {number|jQuery.Promise|Function} step
3751 * - Number of milliseconds to wait before proceeding
3752 * - Promise that must be resolved before proceeding
3753 * - Function to execute
3754 * - If the function returns a boolean false the process will stop
3755 * - If the function returns a promise, the process will continue to the next
3756 * step when the promise is resolved or stop if the promise is rejected
3757 * - If the function returns a number, the process will wait for that number of
3758 * milliseconds before proceeding
3759 * @param {Object} [context=null] Execution context of the function. The context is
3760 * ignored if the step is a number or promise.
3761 * @return {Object} Step object, with `callback` and `context` properties
3763 OO
.ui
.Process
.prototype.createStep = function ( step
, context
) {
3764 if ( typeof step
=== 'number' || $.isFunction( step
.promise
) ) {
3766 callback: function () {
3772 if ( $.isFunction( step
) ) {
3778 throw new Error( 'Cannot create process step: number, promise or function expected' );
3782 * Add step to the beginning of the process.
3784 * @inheritdoc #createStep
3785 * @return {OO.ui.Process} this
3788 OO
.ui
.Process
.prototype.first = function ( step
, context
) {
3789 this.steps
.unshift( this.createStep( step
, context
) );
3794 * Add step to the end of the process.
3796 * @inheritdoc #createStep
3797 * @return {OO.ui.Process} this
3800 OO
.ui
.Process
.prototype.next = function ( step
, context
) {
3801 this.steps
.push( this.createStep( step
, context
) );
3806 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
3807 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
3808 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
3810 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
3812 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
3815 * @extends OO.Factory
3818 OO
.ui
.ToolFactory
= function OoUiToolFactory() {
3819 // Parent constructor
3820 OO
.ui
.ToolFactory
.super.call( this );
3825 OO
.inheritClass( OO
.ui
.ToolFactory
, OO
.Factory
);
3830 * Get tools from the factory
3832 * @param {Array} include Included tools
3833 * @param {Array} exclude Excluded tools
3834 * @param {Array} promote Promoted tools
3835 * @param {Array} demote Demoted tools
3836 * @return {string[]} List of tools
3838 OO
.ui
.ToolFactory
.prototype.getTools = function ( include
, exclude
, promote
, demote
) {
3839 var i
, len
, included
, promoted
, demoted
,
3843 // Collect included and not excluded tools
3844 included
= OO
.simpleArrayDifference( this.extract( include
), this.extract( exclude
) );
3847 promoted
= this.extract( promote
, used
);
3848 demoted
= this.extract( demote
, used
);
3851 for ( i
= 0, len
= included
.length
; i
< len
; i
++ ) {
3852 if ( !used
[ included
[ i
] ] ) {
3853 auto
.push( included
[ i
] );
3857 return promoted
.concat( auto
).concat( demoted
);
3861 * Get a flat list of names from a list of names or groups.
3863 * Tools can be specified in the following ways:
3865 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
3866 * - All tools in a group: `{ group: 'group-name' }`
3867 * - All tools: `'*'`
3870 * @param {Array|string} collection List of tools
3871 * @param {Object} [used] Object with names that should be skipped as properties; extracted
3872 * names will be added as properties
3873 * @return {string[]} List of extracted names
3875 OO
.ui
.ToolFactory
.prototype.extract = function ( collection
, used
) {
3876 var i
, len
, item
, name
, tool
,
3879 if ( collection
=== '*' ) {
3880 for ( name
in this.registry
) {
3881 tool
= this.registry
[ name
];
3883 // Only add tools by group name when auto-add is enabled
3884 tool
.static.autoAddToCatchall
&&
3885 // Exclude already used tools
3886 ( !used
|| !used
[ name
] )
3890 used
[ name
] = true;
3894 } else if ( Array
.isArray( collection
) ) {
3895 for ( i
= 0, len
= collection
.length
; i
< len
; i
++ ) {
3896 item
= collection
[ i
];
3897 // Allow plain strings as shorthand for named tools
3898 if ( typeof item
=== 'string' ) {
3899 item
= { name
: item
};
3901 if ( OO
.isPlainObject( item
) ) {
3903 for ( name
in this.registry
) {
3904 tool
= this.registry
[ name
];
3906 // Include tools with matching group
3907 tool
.static.group
=== item
.group
&&
3908 // Only add tools by group name when auto-add is enabled
3909 tool
.static.autoAddToGroup
&&
3910 // Exclude already used tools
3911 ( !used
|| !used
[ name
] )
3915 used
[ name
] = true;
3919 // Include tools with matching name and exclude already used tools
3920 } else if ( item
.name
&& ( !used
|| !used
[ item
.name
] ) ) {
3921 names
.push( item
.name
);
3923 used
[ item
.name
] = true;
3933 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
3934 * specify a symbolic name and be registered with the factory. The following classes are registered by
3937 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
3938 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
3939 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
3941 * See {@link OO.ui.Toolbar toolbars} for an example.
3943 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
3945 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
3947 * @extends OO.Factory
3950 OO
.ui
.ToolGroupFactory
= function OoUiToolGroupFactory() {
3951 // Parent constructor
3952 OO
.Factory
.call( this );
3955 defaultClasses
= this.constructor.static.getDefaultClasses();
3957 // Register default toolgroups
3958 for ( i
= 0, l
= defaultClasses
.length
; i
< l
; i
++ ) {
3959 this.register( defaultClasses
[ i
] );
3965 OO
.inheritClass( OO
.ui
.ToolGroupFactory
, OO
.Factory
);
3967 /* Static Methods */
3970 * Get a default set of classes to be registered on construction.
3972 * @return {Function[]} Default classes
3974 OO
.ui
.ToolGroupFactory
.static.getDefaultClasses = function () {
3977 OO
.ui
.ListToolGroup
,
3989 * @param {Object} [config] Configuration options
3991 OO
.ui
.Theme
= function OoUiTheme( config
) {
3992 // Configuration initialization
3993 config
= config
|| {};
3998 OO
.initClass( OO
.ui
.Theme
);
4003 * Get a list of classes to be applied to a widget.
4005 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4006 * otherwise state transitions will not work properly.
4008 * @param {OO.ui.Element} element Element for which to get classes
4009 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4011 OO
.ui
.Theme
.prototype.getElementClasses = function ( /* element */ ) {
4012 return { on
: [], off
: [] };
4016 * Update CSS classes provided by the theme.
4018 * For elements with theme logic hooks, this should be called any time there's a state change.
4020 * @param {OO.ui.Element} element Element for which to update classes
4021 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4023 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
4024 var classes
= this.getElementClasses( element
);
4027 .removeClass( classes
.off
.join( ' ' ) )
4028 .addClass( classes
.on
.join( ' ' ) );
4032 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4033 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4034 * order in which users will navigate through the focusable elements via the "tab" key.
4037 * // TabIndexedElement is mixed into the ButtonWidget class
4038 * // to provide a tabIndex property.
4039 * var button1 = new OO.ui.ButtonWidget( {
4043 * var button2 = new OO.ui.ButtonWidget( {
4047 * var button3 = new OO.ui.ButtonWidget( {
4051 * var button4 = new OO.ui.ButtonWidget( {
4055 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4061 * @param {Object} [config] Configuration options
4062 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4063 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4064 * functionality will be applied to it instead.
4065 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4066 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4067 * to remove the element from the tab-navigation flow.
4069 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
4070 // Configuration initialization
4071 config
= $.extend( { tabIndex
: 0 }, config
);
4074 this.$tabIndexed
= null;
4075 this.tabIndex
= null;
4078 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
4081 this.setTabIndex( config
.tabIndex
);
4082 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
4087 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
4092 * Set the element that should use the tabindex functionality.
4094 * This method is used to retarget a tabindex mixin so that its functionality applies
4095 * to the specified element. If an element is currently using the functionality, the mixin’s
4096 * effect on that element is removed before the new element is set up.
4098 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4101 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
4102 var tabIndex
= this.tabIndex
;
4103 // Remove attributes from old $tabIndexed
4104 this.setTabIndex( null );
4105 // Force update of new $tabIndexed
4106 this.$tabIndexed
= $tabIndexed
;
4107 this.tabIndex
= tabIndex
;
4108 return this.updateTabIndex();
4112 * Set the value of the tabindex.
4114 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4117 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
4118 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
4120 if ( this.tabIndex
!== tabIndex
) {
4121 this.tabIndex
= tabIndex
;
4122 this.updateTabIndex();
4129 * Update the `tabindex` attribute, in case of changes to tab index or
4135 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
4136 if ( this.$tabIndexed
) {
4137 if ( this.tabIndex
!== null ) {
4138 // Do not index over disabled elements
4139 this.$tabIndexed
.attr( {
4140 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
4141 // ChromeVox and NVDA do not seem to inherit this from parent elements
4142 'aria-disabled': this.isDisabled().toString()
4145 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
4152 * Handle disable events.
4155 * @param {boolean} disabled Element is disabled
4157 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
4158 this.updateTabIndex();
4162 * Get the value of the tabindex.
4164 * @return {number|null} Tabindex value
4166 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
4167 return this.tabIndex
;
4171 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4172 * interface element that can be configured with access keys for accessibility.
4173 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4175 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4180 * @param {Object} [config] Configuration options
4181 * @cfg {jQuery} [$button] The button element created by the class.
4182 * If this configuration is omitted, the button element will use a generated `<a>`.
4183 * @cfg {boolean} [framed=true] Render the button with a frame
4184 * @cfg {string} [accessKey] Button's access key
4186 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
4187 // Configuration initialization
4188 config
= config
|| {};
4191 this.$button
= null;
4193 this.accessKey
= null;
4194 this.active
= false;
4195 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
4196 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4197 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
4198 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
4199 this.onClickHandler
= this.onClick
.bind( this );
4200 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
4203 this.$element
.addClass( 'oo-ui-buttonElement' );
4204 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
4205 this.setAccessKey( config
.accessKey
);
4206 this.setButtonElement( config
.$button
|| $( '<a>' ) );
4211 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
4213 /* Static Properties */
4216 * Cancel mouse down events.
4218 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4219 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4220 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4225 * @property {boolean}
4227 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
4232 * A 'click' event is emitted when the button element is clicked.
4240 * Set the button element.
4242 * This method is used to retarget a button mixin so that its functionality applies to
4243 * the specified button element instead of the one created by the class. If a button element
4244 * is already set, the method will remove the mixin’s effect on that element.
4246 * @param {jQuery} $button Element to use as button
4248 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
4249 if ( this.$button
) {
4251 .removeClass( 'oo-ui-buttonElement-button' )
4252 .removeAttr( 'role accesskey' )
4254 mousedown
: this.onMouseDownHandler
,
4255 keydown
: this.onKeyDownHandler
,
4256 click
: this.onClickHandler
,
4257 keypress
: this.onKeyPressHandler
4261 this.$button
= $button
4262 .addClass( 'oo-ui-buttonElement-button' )
4263 .attr( { role
: 'button', accesskey
: this.accessKey
} )
4265 mousedown
: this.onMouseDownHandler
,
4266 keydown
: this.onKeyDownHandler
,
4267 click
: this.onClickHandler
,
4268 keypress
: this.onKeyPressHandler
4273 * Handles mouse down events.
4276 * @param {jQuery.Event} e Mouse down event
4278 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
4279 if ( this.isDisabled() || e
.which
!== 1 ) {
4282 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4283 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4284 // reliably remove the pressed class
4285 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
4286 // Prevent change of focus unless specifically configured otherwise
4287 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
4293 * Handles mouse up events.
4296 * @param {jQuery.Event} e Mouse up event
4298 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
4299 if ( this.isDisabled() || e
.which
!== 1 ) {
4302 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4303 // Stop listening for mouseup, since we only needed this once
4304 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
4308 * Handles mouse click events.
4311 * @param {jQuery.Event} e Mouse click event
4314 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
4315 if ( !this.isDisabled() && e
.which
=== 1 ) {
4316 if ( this.emit( 'click' ) ) {
4323 * Handles key down events.
4326 * @param {jQuery.Event} e Key down event
4328 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
4329 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4332 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4333 // Run the keyup handler no matter where the key is when the button is let go, so we can
4334 // reliably remove the pressed class
4335 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler
, true );
4339 * Handles key up events.
4342 * @param {jQuery.Event} e Key up event
4344 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
4345 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4348 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4349 // Stop listening for keyup, since we only needed this once
4350 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler
, true );
4354 * Handles key press events.
4357 * @param {jQuery.Event} e Key press event
4360 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
4361 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
4362 if ( this.emit( 'click' ) ) {
4369 * Check if button has a frame.
4371 * @return {boolean} Button is framed
4373 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
4378 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4380 * @param {boolean} [framed] Make button framed, omit to toggle
4383 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
4384 framed
= framed
=== undefined ? !this.framed
: !!framed
;
4385 if ( framed
!== this.framed
) {
4386 this.framed
= framed
;
4388 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
4389 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
4390 this.updateThemeClasses();
4397 * Set the button's access key.
4399 * @param {string} accessKey Button's access key, use empty string to remove
4402 OO
.ui
.mixin
.ButtonElement
.prototype.setAccessKey = function ( accessKey
) {
4403 accessKey
= typeof accessKey
=== 'string' && accessKey
.length
? accessKey
: null;
4405 if ( this.accessKey
!== accessKey
) {
4406 if ( this.$button
) {
4407 if ( accessKey
!== null ) {
4408 this.$button
.attr( 'accesskey', accessKey
);
4410 this.$button
.removeAttr( 'accesskey' );
4413 this.accessKey
= accessKey
;
4420 * Set the button to its 'active' state.
4422 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4423 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4424 * for other button types.
4426 * @param {boolean} [value] Make button active
4429 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
4430 this.$element
.toggleClass( 'oo-ui-buttonElement-active', !!value
);
4435 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4436 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4437 * items from the group is done through the interface the class provides.
4438 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4440 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4446 * @param {Object} [config] Configuration options
4447 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4448 * is omitted, the group element will use a generated `<div>`.
4450 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
4451 // Configuration initialization
4452 config
= config
|| {};
4457 this.aggregateItemEvents
= {};
4460 this.setGroupElement( config
.$group
|| $( '<div>' ) );
4466 * Set the group element.
4468 * If an element is already set, items will be moved to the new element.
4470 * @param {jQuery} $group Element to use as group
4472 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
4475 this.$group
= $group
;
4476 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4477 this.$group
.append( this.items
[ i
].$element
);
4482 * Check if a group contains no items.
4484 * @return {boolean} Group is empty
4486 OO
.ui
.mixin
.GroupElement
.prototype.isEmpty = function () {
4487 return !this.items
.length
;
4491 * Get all items in the group.
4493 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4494 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4497 * @return {OO.ui.Element[]} An array of items.
4499 OO
.ui
.mixin
.GroupElement
.prototype.getItems = function () {
4500 return this.items
.slice( 0 );
4504 * Get an item by its data.
4506 * Only the first item with matching data will be returned. To return all matching items,
4507 * use the #getItemsFromData method.
4509 * @param {Object} data Item data to search for
4510 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4512 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
4514 hash
= OO
.getHash( data
);
4516 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4517 item
= this.items
[ i
];
4518 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4527 * Get items by their data.
4529 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4531 * @param {Object} data Item data to search for
4532 * @return {OO.ui.Element[]} Items with equivalent data
4534 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
4536 hash
= OO
.getHash( data
),
4539 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4540 item
= this.items
[ i
];
4541 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4550 * Aggregate the events emitted by the group.
4552 * When events are aggregated, the group will listen to all contained items for the event,
4553 * and then emit the event under a new name. The new event will contain an additional leading
4554 * parameter containing the item that emitted the original event. Other arguments emitted from
4555 * the original event are passed through.
4557 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4558 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4559 * A `null` value will remove aggregated events.
4561 * @throws {Error} An error is thrown if aggregation already exists.
4563 OO
.ui
.mixin
.GroupElement
.prototype.aggregate = function ( events
) {
4564 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
4566 for ( itemEvent
in events
) {
4567 groupEvent
= events
[ itemEvent
];
4569 // Remove existing aggregated event
4570 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4571 // Don't allow duplicate aggregations
4573 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
4575 // Remove event aggregation from existing items
4576 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4577 item
= this.items
[ i
];
4578 if ( item
.connect
&& item
.disconnect
) {
4580 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[itemEvent
], item
];
4581 item
.disconnect( this, remove
);
4584 // Prevent future items from aggregating event
4585 delete this.aggregateItemEvents
[ itemEvent
];
4588 // Add new aggregate event
4590 // Make future items aggregate event
4591 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
4592 // Add event aggregation to existing items
4593 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4594 item
= this.items
[ i
];
4595 if ( item
.connect
&& item
.disconnect
) {
4597 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
4598 item
.connect( this, add
);
4606 * Add items to the group.
4608 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4609 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4611 * @param {OO.ui.Element[]} items An array of items to add to the group
4612 * @param {number} [index] Index of the insertion point
4615 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
4616 var i
, len
, item
, event
, events
, currentIndex
,
4619 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4622 // Check if item exists then remove it first, effectively "moving" it
4623 currentIndex
= $.inArray( item
, this.items
);
4624 if ( currentIndex
>= 0 ) {
4625 this.removeItems( [ item
] );
4626 // Adjust index to compensate for removal
4627 if ( currentIndex
< index
) {
4632 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
4634 for ( event
in this.aggregateItemEvents
) {
4635 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
4637 item
.connect( this, events
);
4639 item
.setElementGroup( this );
4640 itemElements
.push( item
.$element
.get( 0 ) );
4643 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
4644 this.$group
.append( itemElements
);
4645 this.items
.push
.apply( this.items
, items
);
4646 } else if ( index
=== 0 ) {
4647 this.$group
.prepend( itemElements
);
4648 this.items
.unshift
.apply( this.items
, items
);
4650 this.items
[ index
].$element
.before( itemElements
);
4651 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
4658 * Remove the specified items from a group.
4660 * Removed items are detached (not removed) from the DOM so that they may be reused.
4661 * To remove all items from a group, you may wish to use the #clearItems method instead.
4663 * @param {OO.ui.Element[]} items An array of items to remove
4666 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
4667 var i
, len
, item
, index
, remove
, itemEvent
;
4669 // Remove specific items
4670 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4672 index
= $.inArray( item
, this.items
);
4673 if ( index
!== -1 ) {
4675 item
.connect
&& item
.disconnect
&&
4676 !$.isEmptyObject( this.aggregateItemEvents
)
4679 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4680 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4682 item
.disconnect( this, remove
);
4684 item
.setElementGroup( null );
4685 this.items
.splice( index
, 1 );
4686 item
.$element
.detach();
4694 * Clear all items from the group.
4696 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4697 * To remove only a subset of items from a group, use the #removeItems method.
4701 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
4702 var i
, len
, item
, remove
, itemEvent
;
4705 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4706 item
= this.items
[ i
];
4708 item
.connect
&& item
.disconnect
&&
4709 !$.isEmptyObject( this.aggregateItemEvents
)
4712 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4713 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4715 item
.disconnect( this, remove
);
4717 item
.setElementGroup( null );
4718 item
.$element
.detach();
4726 * DraggableElement is a mixin class used to create elements that can be clicked
4727 * and dragged by a mouse to a new position within a group. This class must be used
4728 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
4729 * the draggable elements.
4736 OO
.ui
.mixin
.DraggableElement
= function OoUiMixinDraggableElement() {
4740 // Initialize and events
4742 .attr( 'draggable', true )
4743 .addClass( 'oo-ui-draggableElement' )
4745 dragstart
: this.onDragStart
.bind( this ),
4746 dragover
: this.onDragOver
.bind( this ),
4747 dragend
: this.onDragEnd
.bind( this ),
4748 drop
: this.onDrop
.bind( this )
4752 OO
.initClass( OO
.ui
.mixin
.DraggableElement
);
4759 * A dragstart event is emitted when the user clicks and begins dragging an item.
4760 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4765 * A dragend event is emitted when the user drags an item and releases the mouse,
4766 * thus terminating the drag operation.
4771 * A drop event is emitted when the user drags an item and then releases the mouse button
4772 * over a valid target.
4775 /* Static Properties */
4778 * @inheritdoc OO.ui.mixin.ButtonElement
4780 OO
.ui
.mixin
.DraggableElement
.static.cancelButtonMouseDownEvents
= false;
4785 * Respond to dragstart event.
4788 * @param {jQuery.Event} event jQuery event
4791 OO
.ui
.mixin
.DraggableElement
.prototype.onDragStart = function ( e
) {
4792 var dataTransfer
= e
.originalEvent
.dataTransfer
;
4793 // Define drop effect
4794 dataTransfer
.dropEffect
= 'none';
4795 dataTransfer
.effectAllowed
= 'move';
4796 // We must set up a dataTransfer data property or Firefox seems to
4797 // ignore the fact the element is draggable.
4799 dataTransfer
.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4801 // The above is only for firefox. No need to set a catch clause
4802 // if it fails, move on.
4804 // Add dragging class
4805 this.$element
.addClass( 'oo-ui-draggableElement-dragging' );
4807 this.emit( 'dragstart', this );
4812 * Respond to dragend event.
4817 OO
.ui
.mixin
.DraggableElement
.prototype.onDragEnd = function () {
4818 this.$element
.removeClass( 'oo-ui-draggableElement-dragging' );
4819 this.emit( 'dragend' );
4823 * Handle drop event.
4826 * @param {jQuery.Event} event jQuery event
4829 OO
.ui
.mixin
.DraggableElement
.prototype.onDrop = function ( e
) {
4831 this.emit( 'drop', e
);
4835 * In order for drag/drop to work, the dragover event must
4836 * return false and stop propogation.
4840 OO
.ui
.mixin
.DraggableElement
.prototype.onDragOver = function ( e
) {
4846 * Store it in the DOM so we can access from the widget drag event
4849 * @param {number} Item index
4851 OO
.ui
.mixin
.DraggableElement
.prototype.setIndex = function ( index
) {
4852 if ( this.index
!== index
) {
4854 this.$element
.data( 'index', index
);
4862 * @return {number} Item index
4864 OO
.ui
.mixin
.DraggableElement
.prototype.getIndex = function () {
4869 * DraggableGroupElement is a mixin class used to create a group element to
4870 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
4871 * The class is used with OO.ui.mixin.DraggableElement.
4875 * @mixins OO.ui.mixin.GroupElement
4878 * @param {Object} [config] Configuration options
4879 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
4880 * should match the layout of the items. Items displayed in a single row
4881 * or in several rows should use horizontal orientation. The vertical orientation should only be
4882 * used when the items are displayed in a single column. Defaults to 'vertical'
4884 OO
.ui
.mixin
.DraggableGroupElement
= function OoUiMixinDraggableGroupElement( config
) {
4885 // Configuration initialization
4886 config
= config
|| {};
4888 // Parent constructor
4889 OO
.ui
.mixin
.GroupElement
.call( this, config
);
4892 this.orientation
= config
.orientation
|| 'vertical';
4893 this.dragItem
= null;
4894 this.itemDragOver
= null;
4896 this.sideInsertion
= '';
4900 dragstart
: 'itemDragStart',
4901 dragend
: 'itemDragEnd',
4904 this.connect( this, {
4905 itemDragStart
: 'onItemDragStart',
4906 itemDrop
: 'onItemDrop',
4907 itemDragEnd
: 'onItemDragEnd'
4910 dragover
: $.proxy( this.onDragOver
, this ),
4911 dragleave
: $.proxy( this.onDragLeave
, this )
4915 if ( Array
.isArray( config
.items
) ) {
4916 this.addItems( config
.items
);
4918 this.$placeholder
= $( '<div>' )
4919 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
4921 .addClass( 'oo-ui-draggableGroupElement' )
4922 .append( this.$status
)
4923 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation
=== 'horizontal' )
4924 .prepend( this.$placeholder
);
4928 OO
.mixinClass( OO
.ui
.mixin
.DraggableGroupElement
, OO
.ui
.mixin
.GroupElement
);
4933 * A 'reorder' event is emitted when the order of items in the group changes.
4936 * @param {OO.ui.mixin.DraggableElement} item Reordered item
4937 * @param {number} [newIndex] New index for the item
4943 * Respond to item drag start event
4946 * @param {OO.ui.mixin.DraggableElement} item Dragged item
4948 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDragStart = function ( item
) {
4951 // Map the index of each object
4952 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4953 this.items
[ i
].setIndex( i
);
4956 if ( this.orientation
=== 'horizontal' ) {
4957 // Set the height of the indicator
4958 this.$placeholder
.css( {
4959 height
: item
.$element
.outerHeight(),
4963 // Set the width of the indicator
4964 this.$placeholder
.css( {
4966 width
: item
.$element
.outerWidth()
4969 this.setDragItem( item
);
4973 * Respond to item drag end event
4977 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDragEnd = function () {
4978 this.unsetDragItem();
4983 * Handle drop event and switch the order of the items accordingly
4986 * @param {OO.ui.mixin.DraggableElement} item Dropped item
4989 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDrop = function ( item
) {
4990 var toIndex
= item
.getIndex();
4991 // Check if the dropped item is from the current group
4992 // TODO: Figure out a way to configure a list of legally droppable
4993 // elements even if they are not yet in the list
4994 if ( this.getDragItem() ) {
4995 // If the insertion point is 'after', the insertion index
4996 // is shifted to the right (or to the left in RTL, hence 'after')
4997 if ( this.sideInsertion
=== 'after' ) {
5000 // Emit change event
5001 this.emit( 'reorder', this.getDragItem(), toIndex
);
5003 this.unsetDragItem();
5004 // Return false to prevent propogation
5009 * Handle dragleave event.
5013 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onDragLeave = function () {
5014 // This means the item was dragged outside the widget
5017 .addClass( 'oo-ui-element-hidden' );
5021 * Respond to dragover event
5024 * @param {jQuery.Event} event Event details
5026 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onDragOver = function ( e
) {
5027 var dragOverObj
, $optionWidget
, itemOffset
, itemMidpoint
, itemBoundingRect
,
5028 itemSize
, cssOutput
, dragPosition
, itemIndex
, itemPosition
,
5029 clientX
= e
.originalEvent
.clientX
,
5030 clientY
= e
.originalEvent
.clientY
;
5032 // Get the OptionWidget item we are dragging over
5033 dragOverObj
= this.getElementDocument().elementFromPoint( clientX
, clientY
);
5034 $optionWidget
= $( dragOverObj
).closest( '.oo-ui-draggableElement' );
5035 if ( $optionWidget
[ 0 ] ) {
5036 itemOffset
= $optionWidget
.offset();
5037 itemBoundingRect
= $optionWidget
[ 0 ].getBoundingClientRect();
5038 itemPosition
= $optionWidget
.position();
5039 itemIndex
= $optionWidget
.data( 'index' );
5044 this.isDragging() &&
5045 itemIndex
!== this.getDragItem().getIndex()
5047 if ( this.orientation
=== 'horizontal' ) {
5048 // Calculate where the mouse is relative to the item width
5049 itemSize
= itemBoundingRect
.width
;
5050 itemMidpoint
= itemBoundingRect
.left
+ itemSize
/ 2;
5051 dragPosition
= clientX
;
5052 // Which side of the item we hover over will dictate
5053 // where the placeholder will appear, on the left or
5056 left
: dragPosition
< itemMidpoint
? itemPosition
.left
: itemPosition
.left
+ itemSize
,
5057 top
: itemPosition
.top
5060 // Calculate where the mouse is relative to the item height
5061 itemSize
= itemBoundingRect
.height
;
5062 itemMidpoint
= itemBoundingRect
.top
+ itemSize
/ 2;
5063 dragPosition
= clientY
;
5064 // Which side of the item we hover over will dictate
5065 // where the placeholder will appear, on the top or
5068 top
: dragPosition
< itemMidpoint
? itemPosition
.top
: itemPosition
.top
+ itemSize
,
5069 left
: itemPosition
.left
5072 // Store whether we are before or after an item to rearrange
5073 // For horizontal layout, we need to account for RTL, as this is flipped
5074 if ( this.orientation
=== 'horizontal' && this.$element
.css( 'direction' ) === 'rtl' ) {
5075 this.sideInsertion
= dragPosition
< itemMidpoint
? 'after' : 'before';
5077 this.sideInsertion
= dragPosition
< itemMidpoint
? 'before' : 'after';
5079 // Add drop indicator between objects
5082 .removeClass( 'oo-ui-element-hidden' );
5084 // This means the item was dragged outside the widget
5087 .addClass( 'oo-ui-element-hidden' );
5094 * Set a dragged item
5096 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5098 OO
.ui
.mixin
.DraggableGroupElement
.prototype.setDragItem = function ( item
) {
5099 this.dragItem
= item
;
5103 * Unset the current dragged item
5105 OO
.ui
.mixin
.DraggableGroupElement
.prototype.unsetDragItem = function () {
5106 this.dragItem
= null;
5107 this.itemDragOver
= null;
5108 this.$placeholder
.addClass( 'oo-ui-element-hidden' );
5109 this.sideInsertion
= '';
5113 * Get the item that is currently being dragged.
5115 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5117 OO
.ui
.mixin
.DraggableGroupElement
.prototype.getDragItem = function () {
5118 return this.dragItem
;
5122 * Check if an item in the group is currently being dragged.
5124 * @return {Boolean} Item is being dragged
5126 OO
.ui
.mixin
.DraggableGroupElement
.prototype.isDragging = function () {
5127 return this.getDragItem() !== null;
5131 * IconElement is often mixed into other classes to generate an icon.
5132 * Icons are graphics, about the size of normal text. They are used to aid the user
5133 * in locating a control or to convey information in a space-efficient way. See the
5134 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5135 * included in the library.
5137 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5143 * @param {Object} [config] Configuration options
5144 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5145 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5146 * the icon element be set to an existing icon instead of the one generated by this class, set a
5147 * value using a jQuery selection. For example:
5149 * // Use a <div> tag instead of a <span>
5151 * // Use an existing icon element instead of the one generated by the class
5152 * $icon: this.$element
5153 * // Use an icon element from a child widget
5154 * $icon: this.childwidget.$element
5155 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5156 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5157 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5158 * by the user's language.
5160 * Example of an i18n map:
5162 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5163 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5164 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5165 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5166 * text. The icon title is displayed when users move the mouse over the icon.
5168 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
5169 // Configuration initialization
5170 config
= config
|| {};
5175 this.iconTitle
= null;
5178 this.setIcon( config
.icon
|| this.constructor.static.icon
);
5179 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
5180 this.setIconElement( config
.$icon
|| $( '<span>' ) );
5185 OO
.initClass( OO
.ui
.mixin
.IconElement
);
5187 /* Static Properties */
5190 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5191 * for i18n purposes and contains a `default` icon name and additional names keyed by
5192 * language code. The `default` name is used when no icon is keyed by the user's language.
5194 * Example of an i18n map:
5196 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5198 * Note: the static property will be overridden if the #icon configuration is used.
5202 * @property {Object|string}
5204 OO
.ui
.mixin
.IconElement
.static.icon
= null;
5207 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5208 * function that returns title text, or `null` for no title.
5210 * The static property will be overridden if the #iconTitle configuration is used.
5214 * @property {string|Function|null}
5216 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
5221 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5222 * applies to the specified icon element instead of the one created by the class. If an icon
5223 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5224 * and mixin methods will no longer affect the element.
5226 * @param {jQuery} $icon Element to use as icon
5228 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
5231 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
5232 .removeAttr( 'title' );
5236 .addClass( 'oo-ui-iconElement-icon' )
5237 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
5238 if ( this.iconTitle
!== null ) {
5239 this.$icon
.attr( 'title', this.iconTitle
);
5244 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5245 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5248 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5249 * by language code, or `null` to remove the icon.
5252 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
5253 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
5254 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
5256 if ( this.icon
!== icon
) {
5258 if ( this.icon
!== null ) {
5259 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
5261 if ( icon
!== null ) {
5262 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
5268 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
5269 this.updateThemeClasses();
5275 * Set the icon title. Use `null` to remove the title.
5277 * @param {string|Function|null} iconTitle A text string used as the icon title,
5278 * a function that returns title text, or `null` for no title.
5281 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
5282 iconTitle
= typeof iconTitle
=== 'function' ||
5283 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
5284 OO
.ui
.resolveMsg( iconTitle
) : null;
5286 if ( this.iconTitle
!== iconTitle
) {
5287 this.iconTitle
= iconTitle
;
5289 if ( this.iconTitle
!== null ) {
5290 this.$icon
.attr( 'title', iconTitle
);
5292 this.$icon
.removeAttr( 'title' );
5301 * Get the symbolic name of the icon.
5303 * @return {string} Icon name
5305 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
5310 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5312 * @return {string} Icon title text
5314 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
5315 return this.iconTitle
;
5319 * IndicatorElement is often mixed into other classes to generate an indicator.
5320 * Indicators are small graphics that are generally used in two ways:
5322 * - To draw attention to the status of an item. For example, an indicator might be
5323 * used to show that an item in a list has errors that need to be resolved.
5324 * - To clarify the function of a control that acts in an exceptional way (a button
5325 * that opens a menu instead of performing an action directly, for example).
5327 * For a list of indicators included in the library, please see the
5328 * [OOjs UI documentation on MediaWiki] [1].
5330 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5336 * @param {Object} [config] Configuration options
5337 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5338 * configuration is omitted, the indicator element will use a generated `<span>`.
5339 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5340 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5342 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5343 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5344 * or a function that returns title text. The indicator title is displayed when users move
5345 * the mouse over the indicator.
5347 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
5348 // Configuration initialization
5349 config
= config
|| {};
5352 this.$indicator
= null;
5353 this.indicator
= null;
5354 this.indicatorTitle
= null;
5357 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
5358 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
5359 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
5364 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
5366 /* Static Properties */
5369 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5370 * The static property will be overridden if the #indicator configuration is used.
5374 * @property {string|null}
5376 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
5379 * A text string used as the indicator title, a function that returns title text, or `null`
5380 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5384 * @property {string|Function|null}
5386 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
5391 * Set the indicator element.
5393 * If an element is already set, it will be cleaned up before setting up the new element.
5395 * @param {jQuery} $indicator Element to use as indicator
5397 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
5398 if ( this.$indicator
) {
5400 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
5401 .removeAttr( 'title' );
5404 this.$indicator
= $indicator
5405 .addClass( 'oo-ui-indicatorElement-indicator' )
5406 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
5407 if ( this.indicatorTitle
!== null ) {
5408 this.$indicator
.attr( 'title', this.indicatorTitle
);
5413 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5415 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5418 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
5419 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
5421 if ( this.indicator
!== indicator
) {
5422 if ( this.$indicator
) {
5423 if ( this.indicator
!== null ) {
5424 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
5426 if ( indicator
!== null ) {
5427 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
5430 this.indicator
= indicator
;
5433 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
5434 this.updateThemeClasses();
5440 * Set the indicator title.
5442 * The title is displayed when a user moves the mouse over the indicator.
5444 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5445 * `null` for no indicator title
5448 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
5449 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
5450 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
5451 OO
.ui
.resolveMsg( indicatorTitle
) : null;
5453 if ( this.indicatorTitle
!== indicatorTitle
) {
5454 this.indicatorTitle
= indicatorTitle
;
5455 if ( this.$indicator
) {
5456 if ( this.indicatorTitle
!== null ) {
5457 this.$indicator
.attr( 'title', indicatorTitle
);
5459 this.$indicator
.removeAttr( 'title' );
5468 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5470 * @return {string} Symbolic name of indicator
5472 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
5473 return this.indicator
;
5477 * Get the indicator title.
5479 * The title is displayed when a user moves the mouse over the indicator.
5481 * @return {string} Indicator title text
5483 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
5484 return this.indicatorTitle
;
5488 * LabelElement is often mixed into other classes to generate a label, which
5489 * helps identify the function of an interface element.
5490 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5492 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5498 * @param {Object} [config] Configuration options
5499 * @cfg {jQuery} [$label] The label element created by the class. If this
5500 * configuration is omitted, the label element will use a generated `<span>`.
5501 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5502 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5503 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5504 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5505 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5506 * The label will be truncated to fit if necessary.
5508 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
5509 // Configuration initialization
5510 config
= config
|| {};
5515 this.autoFitLabel
= config
.autoFitLabel
=== undefined || !!config
.autoFitLabel
;
5518 this.setLabel( config
.label
|| this.constructor.static.label
);
5519 this.setLabelElement( config
.$label
|| $( '<span>' ) );
5524 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
5529 * @event labelChange
5530 * @param {string} value
5533 /* Static Properties */
5536 * The label text. The label can be specified as a plaintext string, a function that will
5537 * produce a string in the future, or `null` for no label. The static value will
5538 * be overridden if a label is specified with the #label config option.
5542 * @property {string|Function|null}
5544 OO
.ui
.mixin
.LabelElement
.static.label
= null;
5549 * Set the label element.
5551 * If an element is already set, it will be cleaned up before setting up the new element.
5553 * @param {jQuery} $label Element to use as label
5555 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
5556 if ( this.$label
) {
5557 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
5560 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
5561 this.setLabelContent( this.label
);
5567 * An empty string will result in the label being hidden. A string containing only whitespace will
5568 * be converted to a single ` `.
5570 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5571 * text; or null for no label
5574 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
5575 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
5576 label
= ( ( typeof label
=== 'string' && label
.length
) || label
instanceof jQuery
|| label
instanceof OO
.ui
.HtmlSnippet
) ? label
: null;
5578 this.$element
.toggleClass( 'oo-ui-labelElement', !!label
);
5580 if ( this.label
!== label
) {
5581 if ( this.$label
) {
5582 this.setLabelContent( label
);
5585 this.emit( 'labelChange' );
5594 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5595 * text; or null for no label
5597 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
5606 OO
.ui
.mixin
.LabelElement
.prototype.fitLabel = function () {
5607 if ( this.$label
&& this.$label
.autoEllipsis
&& this.autoFitLabel
) {
5608 this.$label
.autoEllipsis( { hasSpan
: false, tooltip
: true } );
5615 * Set the content of the label.
5617 * Do not call this method until after the label element has been set by #setLabelElement.
5620 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5621 * text; or null for no label
5623 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
5624 if ( typeof label
=== 'string' ) {
5625 if ( label
.match( /^\s*$/ ) ) {
5626 // Convert whitespace only string to a single non-breaking space
5627 this.$label
.html( ' ' );
5629 this.$label
.text( label
);
5631 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
5632 this.$label
.html( label
.toString() );
5633 } else if ( label
instanceof jQuery
) {
5634 this.$label
.empty().append( label
);
5636 this.$label
.empty();
5641 * LookupElement is a mixin that creates a {@link OO.ui.TextInputMenuSelectWidget menu} of suggested values for
5642 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5643 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5644 * from the lookup menu, that value becomes the value of the input field.
5646 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5647 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5648 * re-enable lookups.
5650 * See the [OOjs UI demos][1] for an example.
5652 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5658 * @param {Object} [config] Configuration options
5659 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5660 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5661 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5662 * By default, the lookup menu is not generated and displayed until the user begins to type.
5664 OO
.ui
.mixin
.LookupElement
= function OoUiMixinLookupElement( config
) {
5665 // Configuration initialization
5666 config
= config
|| {};
5669 this.$overlay
= config
.$overlay
|| this.$element
;
5670 this.lookupMenu
= new OO
.ui
.TextInputMenuSelectWidget( this, {
5673 $container
: config
.$container
5676 this.allowSuggestionsWhenEmpty
= config
.allowSuggestionsWhenEmpty
|| false;
5678 this.lookupCache
= {};
5679 this.lookupQuery
= null;
5680 this.lookupRequest
= null;
5681 this.lookupsDisabled
= false;
5682 this.lookupInputFocused
= false;
5686 focus
: this.onLookupInputFocus
.bind( this ),
5687 blur
: this.onLookupInputBlur
.bind( this ),
5688 mousedown
: this.onLookupInputMouseDown
.bind( this )
5690 this.connect( this, { change
: 'onLookupInputChange' } );
5691 this.lookupMenu
.connect( this, {
5692 toggle
: 'onLookupMenuToggle',
5693 choose
: 'onLookupMenuItemChoose'
5697 this.$element
.addClass( 'oo-ui-lookupElement' );
5698 this.lookupMenu
.$element
.addClass( 'oo-ui-lookupElement-menu' );
5699 this.$overlay
.append( this.lookupMenu
.$element
);
5705 * Handle input focus event.
5708 * @param {jQuery.Event} e Input focus event
5710 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputFocus = function () {
5711 this.lookupInputFocused
= true;
5712 this.populateLookupMenu();
5716 * Handle input blur event.
5719 * @param {jQuery.Event} e Input blur event
5721 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputBlur = function () {
5722 this.closeLookupMenu();
5723 this.lookupInputFocused
= false;
5727 * Handle input mouse down event.
5730 * @param {jQuery.Event} e Input mouse down event
5732 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputMouseDown = function () {
5733 // Only open the menu if the input was already focused.
5734 // This way we allow the user to open the menu again after closing it with Esc
5735 // by clicking in the input. Opening (and populating) the menu when initially
5736 // clicking into the input is handled by the focus handler.
5737 if ( this.lookupInputFocused
&& !this.lookupMenu
.isVisible() ) {
5738 this.populateLookupMenu();
5743 * Handle input change event.
5746 * @param {string} value New input value
5748 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputChange = function () {
5749 if ( this.lookupInputFocused
) {
5750 this.populateLookupMenu();
5755 * Handle the lookup menu being shown/hidden.
5758 * @param {boolean} visible Whether the lookup menu is now visible.
5760 OO
.ui
.mixin
.LookupElement
.prototype.onLookupMenuToggle = function ( visible
) {
5762 // When the menu is hidden, abort any active request and clear the menu.
5763 // This has to be done here in addition to closeLookupMenu(), because
5764 // MenuSelectWidget will close itself when the user presses Esc.
5765 this.abortLookupRequest();
5766 this.lookupMenu
.clearItems();
5771 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5774 * @param {OO.ui.MenuOptionWidget} item Selected item
5776 OO
.ui
.mixin
.LookupElement
.prototype.onLookupMenuItemChoose = function ( item
) {
5777 this.setValue( item
.getData() );
5784 * @return {OO.ui.TextInputMenuSelectWidget}
5786 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenu = function () {
5787 return this.lookupMenu
;
5791 * Disable or re-enable lookups.
5793 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
5795 * @param {boolean} disabled Disable lookups
5797 OO
.ui
.mixin
.LookupElement
.prototype.setLookupsDisabled = function ( disabled
) {
5798 this.lookupsDisabled
= !!disabled
;
5802 * Open the menu. If there are no entries in the menu, this does nothing.
5807 OO
.ui
.mixin
.LookupElement
.prototype.openLookupMenu = function () {
5808 if ( !this.lookupMenu
.isEmpty() ) {
5809 this.lookupMenu
.toggle( true );
5815 * Close the menu, empty it, and abort any pending request.
5820 OO
.ui
.mixin
.LookupElement
.prototype.closeLookupMenu = function () {
5821 this.lookupMenu
.toggle( false );
5822 this.abortLookupRequest();
5823 this.lookupMenu
.clearItems();
5828 * Request menu items based on the input's current value, and when they arrive,
5829 * populate the menu with these items and show the menu.
5831 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
5836 OO
.ui
.mixin
.LookupElement
.prototype.populateLookupMenu = function () {
5838 value
= this.getValue();
5840 if ( this.lookupsDisabled
) {
5844 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
5845 if ( !this.allowSuggestionsWhenEmpty
&& value
=== '' ) {
5846 this.closeLookupMenu();
5847 // Skip population if there is already a request pending for the current value
5848 } else if ( value
!== this.lookupQuery
) {
5849 this.getLookupMenuItems()
5850 .done( function ( items
) {
5851 widget
.lookupMenu
.clearItems();
5852 if ( items
.length
) {
5856 widget
.initializeLookupMenuSelection();
5858 widget
.lookupMenu
.toggle( false );
5861 .fail( function () {
5862 widget
.lookupMenu
.clearItems();
5870 * Highlight the first selectable item in the menu.
5875 OO
.ui
.mixin
.LookupElement
.prototype.initializeLookupMenuSelection = function () {
5876 if ( !this.lookupMenu
.getSelectedItem() ) {
5877 this.lookupMenu
.highlightItem( this.lookupMenu
.getFirstSelectableItem() );
5882 * Get lookup menu items for the current query.
5885 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
5886 * the done event. If the request was aborted to make way for a subsequent request, this promise
5887 * will not be rejected: it will remain pending forever.
5889 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenuItems = function () {
5891 value
= this.getValue(),
5892 deferred
= $.Deferred(),
5895 this.abortLookupRequest();
5896 if ( Object
.prototype.hasOwnProperty
.call( this.lookupCache
, value
) ) {
5897 deferred
.resolve( this.getLookupMenuOptionsFromData( this.lookupCache
[ value
] ) );
5900 this.lookupQuery
= value
;
5901 ourRequest
= this.lookupRequest
= this.getLookupRequest();
5903 .always( function () {
5904 // We need to pop pending even if this is an old request, otherwise
5905 // the widget will remain pending forever.
5906 // TODO: this assumes that an aborted request will fail or succeed soon after
5907 // being aborted, or at least eventually. It would be nice if we could popPending()
5908 // at abort time, but only if we knew that we hadn't already called popPending()
5909 // for that request.
5910 widget
.popPending();
5912 .done( function ( response
) {
5913 // If this is an old request (and aborting it somehow caused it to still succeed),
5914 // ignore its success completely
5915 if ( ourRequest
=== widget
.lookupRequest
) {
5916 widget
.lookupQuery
= null;
5917 widget
.lookupRequest
= null;
5918 widget
.lookupCache
[ value
] = widget
.getLookupCacheDataFromResponse( response
);
5919 deferred
.resolve( widget
.getLookupMenuOptionsFromData( widget
.lookupCache
[ value
] ) );
5922 .fail( function () {
5923 // If this is an old request (or a request failing because it's being aborted),
5924 // ignore its failure completely
5925 if ( ourRequest
=== widget
.lookupRequest
) {
5926 widget
.lookupQuery
= null;
5927 widget
.lookupRequest
= null;
5932 return deferred
.promise();
5936 * Abort the currently pending lookup request, if any.
5940 OO
.ui
.mixin
.LookupElement
.prototype.abortLookupRequest = function () {
5941 var oldRequest
= this.lookupRequest
;
5943 // First unset this.lookupRequest to the fail handler will notice
5944 // that the request is no longer current
5945 this.lookupRequest
= null;
5946 this.lookupQuery
= null;
5952 * Get a new request object of the current lookup query value.
5956 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
5958 OO
.ui
.mixin
.LookupElement
.prototype.getLookupRequest = function () {
5959 // Stub, implemented in subclass
5964 * Pre-process data returned by the request from #getLookupRequest.
5966 * The return value of this function will be cached, and any further queries for the given value
5967 * will use the cache rather than doing API requests.
5971 * @param {Mixed} response Response from server
5972 * @return {Mixed} Cached result data
5974 OO
.ui
.mixin
.LookupElement
.prototype.getLookupCacheDataFromResponse = function () {
5975 // Stub, implemented in subclass
5980 * Get a list of menu option widgets from the (possibly cached) data returned by
5981 * #getLookupCacheDataFromResponse.
5985 * @param {Mixed} data Cached result data, usually an array
5986 * @return {OO.ui.MenuOptionWidget[]} Menu items
5988 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenuOptionsFromData = function () {
5989 // Stub, implemented in subclass
5994 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5995 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5996 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5997 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
6003 * @param {Object} [config] Configuration options
6004 * @cfg {Object} [popup] Configuration to pass to popup
6005 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
6007 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
6008 // Configuration initialization
6009 config
= config
|| {};
6012 this.popup
= new OO
.ui
.PopupWidget( $.extend(
6013 { autoClose
: true },
6015 { $autoCloseIgnore
: this.$element
}
6024 * @return {OO.ui.PopupWidget} Popup widget
6026 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
6031 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
6032 * additional functionality to an element created by another class. The class provides
6033 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
6034 * which are used to customize the look and feel of a widget to better describe its
6035 * importance and functionality.
6037 * The library currently contains the following styling flags for general use:
6039 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
6040 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
6041 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
6043 * The flags affect the appearance of the buttons:
6046 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
6047 * var button1 = new OO.ui.ButtonWidget( {
6048 * label: 'Constructive',
6049 * flags: 'constructive'
6051 * var button2 = new OO.ui.ButtonWidget( {
6052 * label: 'Destructive',
6053 * flags: 'destructive'
6055 * var button3 = new OO.ui.ButtonWidget( {
6056 * label: 'Progressive',
6057 * flags: 'progressive'
6059 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
6061 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
6062 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6064 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6070 * @param {Object} [config] Configuration options
6071 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
6072 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
6073 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6074 * @cfg {jQuery} [$flagged] The flagged element. By default,
6075 * the flagged functionality is applied to the element created by the class ($element).
6076 * If a different element is specified, the flagged functionality will be applied to it instead.
6078 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
6079 // Configuration initialization
6080 config
= config
|| {};
6084 this.$flagged
= null;
6087 this.setFlags( config
.flags
);
6088 this.setFlaggedElement( config
.$flagged
|| this.$element
);
6095 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
6096 * parameter contains the name of each modified flag and indicates whether it was
6099 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
6100 * that the flag was added, `false` that the flag was removed.
6106 * Set the flagged element.
6108 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
6109 * If an element is already set, the method will remove the mixin’s effect on that element.
6111 * @param {jQuery} $flagged Element that should be flagged
6113 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
6114 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
6115 return 'oo-ui-flaggedElement-' + flag
;
6118 if ( this.$flagged
) {
6119 this.$flagged
.removeClass( classNames
);
6122 this.$flagged
= $flagged
.addClass( classNames
);
6126 * Check if the specified flag is set.
6128 * @param {string} flag Name of flag
6129 * @return {boolean} The flag is set
6131 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
6132 return flag
in this.flags
;
6136 * Get the names of all flags set.
6138 * @return {string[]} Flag names
6140 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
6141 return Object
.keys( this.flags
);
6150 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
6151 var flag
, className
,
6154 classPrefix
= 'oo-ui-flaggedElement-';
6156 for ( flag
in this.flags
) {
6157 className
= classPrefix
+ flag
;
6158 changes
[ flag
] = false;
6159 delete this.flags
[ flag
];
6160 remove
.push( className
);
6163 if ( this.$flagged
) {
6164 this.$flagged
.removeClass( remove
.join( ' ' ) );
6167 this.updateThemeClasses();
6168 this.emit( 'flag', changes
);
6174 * Add one or more flags.
6176 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6177 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6178 * be added (`true`) or removed (`false`).
6182 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
6183 var i
, len
, flag
, className
,
6187 classPrefix
= 'oo-ui-flaggedElement-';
6189 if ( typeof flags
=== 'string' ) {
6190 className
= classPrefix
+ flags
;
6192 if ( !this.flags
[ flags
] ) {
6193 this.flags
[ flags
] = true;
6194 add
.push( className
);
6196 } else if ( Array
.isArray( flags
) ) {
6197 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
6199 className
= classPrefix
+ flag
;
6201 if ( !this.flags
[ flag
] ) {
6202 changes
[ flag
] = true;
6203 this.flags
[ flag
] = true;
6204 add
.push( className
);
6207 } else if ( OO
.isPlainObject( flags
) ) {
6208 for ( flag
in flags
) {
6209 className
= classPrefix
+ flag
;
6210 if ( flags
[ flag
] ) {
6212 if ( !this.flags
[ flag
] ) {
6213 changes
[ flag
] = true;
6214 this.flags
[ flag
] = true;
6215 add
.push( className
);
6219 if ( this.flags
[ flag
] ) {
6220 changes
[ flag
] = false;
6221 delete this.flags
[ flag
];
6222 remove
.push( className
);
6228 if ( this.$flagged
) {
6230 .addClass( add
.join( ' ' ) )
6231 .removeClass( remove
.join( ' ' ) );
6234 this.updateThemeClasses();
6235 this.emit( 'flag', changes
);
6241 * TitledElement is mixed into other classes to provide a `title` attribute.
6242 * Titles are rendered by the browser and are made visible when the user moves
6243 * the mouse over the element. Titles are not visible on touch devices.
6246 * // TitledElement provides a 'title' attribute to the
6247 * // ButtonWidget class
6248 * var button = new OO.ui.ButtonWidget( {
6249 * label: 'Button with Title',
6250 * title: 'I am a button'
6252 * $( 'body' ).append( button.$element );
6258 * @param {Object} [config] Configuration options
6259 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6260 * If this config is omitted, the title functionality is applied to $element, the
6261 * element created by the class.
6262 * @cfg {string|Function} [title] The title text or a function that returns text. If
6263 * this config is omitted, the value of the {@link #static-title static title} property is used.
6265 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
6266 // Configuration initialization
6267 config
= config
|| {};
6270 this.$titled
= null;
6274 this.setTitle( config
.title
|| this.constructor.static.title
);
6275 this.setTitledElement( config
.$titled
|| this.$element
);
6280 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
6282 /* Static Properties */
6285 * The title text, a function that returns text, or `null` for no title. The value of the static property
6286 * is overridden if the #title config option is used.
6290 * @property {string|Function|null}
6292 OO
.ui
.mixin
.TitledElement
.static.title
= null;
6297 * Set the titled element.
6299 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6300 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6302 * @param {jQuery} $titled Element that should use the 'titled' functionality
6304 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
6305 if ( this.$titled
) {
6306 this.$titled
.removeAttr( 'title' );
6309 this.$titled
= $titled
;
6311 this.$titled
.attr( 'title', this.title
);
6318 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6321 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
6322 title
= typeof title
=== 'string' ? OO
.ui
.resolveMsg( title
) : null;
6324 if ( this.title
!== title
) {
6325 if ( this.$titled
) {
6326 if ( title
!== null ) {
6327 this.$titled
.attr( 'title', title
);
6329 this.$titled
.removeAttr( 'title' );
6341 * @return {string} Title string
6343 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
6348 * Element that can be automatically clipped to visible boundaries.
6350 * Whenever the element's natural height changes, you have to call
6351 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
6352 * clipping correctly.
6358 * @param {Object} [config] Configuration options
6359 * @cfg {jQuery} [$clippable] Nodes to clip, assigned to #$clippable, omit to use #$element
6361 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
6362 // Configuration initialization
6363 config
= config
|| {};
6366 this.$clippable
= null;
6367 this.clipping
= false;
6368 this.clippedHorizontally
= false;
6369 this.clippedVertically
= false;
6370 this.$clippableContainer
= null;
6371 this.$clippableScroller
= null;
6372 this.$clippableWindow
= null;
6373 this.idealWidth
= null;
6374 this.idealHeight
= null;
6375 this.onClippableContainerScrollHandler
= this.clip
.bind( this );
6376 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
6379 this.setClippableElement( config
.$clippable
|| this.$element
);
6385 * Set clippable element.
6387 * If an element is already set, it will be cleaned up before setting up the new element.
6389 * @param {jQuery} $clippable Element to make clippable
6391 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
6392 if ( this.$clippable
) {
6393 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
6394 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6395 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6398 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
6405 * Do not turn clipping on until after the element is attached to the DOM and visible.
6407 * @param {boolean} [clipping] Enable clipping, omit to toggle
6410 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
6411 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
6413 if ( this.clipping
!== clipping
) {
6414 this.clipping
= clipping
;
6416 this.$clippableContainer
= $( this.getClosestScrollableElementContainer() );
6417 // If the clippable container is the root, we have to listen to scroll events and check
6418 // jQuery.scrollTop on the window because of browser inconsistencies
6419 this.$clippableScroller
= this.$clippableContainer
.is( 'html, body' ) ?
6420 $( OO
.ui
.Element
.static.getWindow( this.$clippableContainer
) ) :
6421 this.$clippableContainer
;
6422 this.$clippableScroller
.on( 'scroll', this.onClippableContainerScrollHandler
);
6423 this.$clippableWindow
= $( this.getElementWindow() )
6424 .on( 'resize', this.onClippableWindowResizeHandler
);
6425 // Initial clip after visible
6428 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6429 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6431 this.$clippableContainer
= null;
6432 this.$clippableScroller
.off( 'scroll', this.onClippableContainerScrollHandler
);
6433 this.$clippableScroller
= null;
6434 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
6435 this.$clippableWindow
= null;
6443 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6445 * @return {boolean} Element will be clipped to the visible area
6447 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
6448 return this.clipping
;
6452 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6454 * @return {boolean} Part of the element is being clipped
6456 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
6457 return this.clippedHorizontally
|| this.clippedVertically
;
6461 * Check if the right of the element is being clipped by the nearest scrollable container.
6463 * @return {boolean} Part of the element is being clipped
6465 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
6466 return this.clippedHorizontally
;
6470 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6472 * @return {boolean} Part of the element is being clipped
6474 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
6475 return this.clippedVertically
;
6479 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6481 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6482 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6484 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
6485 this.idealWidth
= width
;
6486 this.idealHeight
= height
;
6488 if ( !this.clipping
) {
6489 // Update dimensions
6490 this.$clippable
.css( { width
: width
, height
: height
} );
6492 // While clipping, idealWidth and idealHeight are not considered
6496 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6497 * the element's natural height changes.
6499 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6500 * overlapped by, the visible area of the nearest scrollable container.
6504 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
6505 if ( !this.clipping
) {
6506 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
6510 var buffer
= 7, // Chosen by fair dice roll
6511 cOffset
= this.$clippable
.offset(),
6512 $container
= this.$clippableContainer
.is( 'html, body' ) ?
6513 this.$clippableWindow
: this.$clippableContainer
,
6514 ccOffset
= $container
.offset() || { top
: 0, left
: 0 },
6515 ccHeight
= $container
.innerHeight() - buffer
,
6516 ccWidth
= $container
.innerWidth() - buffer
,
6517 cWidth
= this.$clippable
.outerWidth() + buffer
,
6518 scrollTop
= this.$clippableScroller
[0] === this.$clippableWindow
[0] ? this.$clippableScroller
.scrollTop() : 0,
6519 scrollLeft
= this.$clippableScroller
.scrollLeft(),
6520 desiredWidth
= cOffset
.left
< 0 ?
6521 cWidth
+ cOffset
.left
:
6522 ( ccOffset
.left
+ scrollLeft
+ ccWidth
) - cOffset
.left
,
6523 desiredHeight
= ( ccOffset
.top
+ scrollTop
+ ccHeight
) - cOffset
.top
,
6524 naturalWidth
= this.$clippable
.prop( 'scrollWidth' ),
6525 naturalHeight
= this.$clippable
.prop( 'scrollHeight' ),
6526 clipWidth
= desiredWidth
< naturalWidth
,
6527 clipHeight
= desiredHeight
< naturalHeight
;
6530 this.$clippable
.css( { overflowX
: 'scroll', width
: desiredWidth
} );
6532 this.$clippable
.css( { width
: this.idealWidth
|| '', overflowX
: '' } );
6535 this.$clippable
.css( { overflowY
: 'scroll', height
: desiredHeight
} );
6537 this.$clippable
.css( { height
: this.idealHeight
|| '', overflowY
: '' } );
6540 // If we stopped clipping in at least one of the dimensions
6541 if ( !clipWidth
|| !clipHeight
) {
6542 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6545 this.clippedHorizontally
= clipWidth
;
6546 this.clippedVertically
= clipHeight
;
6552 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
6553 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
6554 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
6555 * which creates the tools on demand.
6557 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
6558 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
6559 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
6561 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
6562 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
6566 * @extends OO.ui.Widget
6567 * @mixins OO.ui.mixin.IconElement
6568 * @mixins OO.ui.mixin.FlaggedElement
6569 * @mixins OO.ui.mixin.TabIndexedElement
6572 * @param {OO.ui.ToolGroup} toolGroup
6573 * @param {Object} [config] Configuration options
6574 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
6575 * the {@link #static-title static title} property is used.
6577 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
6578 * title is used as a tooltip if the tool is part of a {@link OO.ui.BarToolGroup bar} toolgroup, or as the label text if the tool is
6579 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
6581 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
6582 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
6583 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
6585 OO
.ui
.Tool
= function OoUiTool( toolGroup
, config
) {
6586 // Allow passing positional parameters inside the config object
6587 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
6589 toolGroup
= config
.toolGroup
;
6592 // Configuration initialization
6593 config
= config
|| {};
6595 // Parent constructor
6596 OO
.ui
.Tool
.super.call( this, config
);
6599 this.toolGroup
= toolGroup
;
6600 this.toolbar
= this.toolGroup
.getToolbar();
6601 this.active
= false;
6602 this.$title
= $( '<span>' );
6603 this.$accel
= $( '<span>' );
6604 this.$link
= $( '<a>' );
6607 // Mixin constructors
6608 OO
.ui
.mixin
.IconElement
.call( this, config
);
6609 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
6610 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$link
} ) );
6613 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
6616 this.$title
.addClass( 'oo-ui-tool-title' );
6618 .addClass( 'oo-ui-tool-accel' )
6620 // This may need to be changed if the key names are ever localized,
6621 // but for now they are essentially written in English
6626 .addClass( 'oo-ui-tool-link' )
6627 .append( this.$icon
, this.$title
, this.$accel
)
6628 .attr( 'role', 'button' );
6630 .data( 'oo-ui-tool', this )
6632 'oo-ui-tool ' + 'oo-ui-tool-name-' +
6633 this.constructor.static.name
.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
6635 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel
)
6636 .append( this.$link
);
6637 this.setTitle( config
.title
|| this.constructor.static.title
);
6642 OO
.inheritClass( OO
.ui
.Tool
, OO
.ui
.Widget
);
6643 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.IconElement
);
6644 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.FlaggedElement
);
6645 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.TabIndexedElement
);
6647 /* Static Properties */
6653 OO
.ui
.Tool
.static.tagName
= 'span';
6656 * Symbolic name of tool.
6658 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
6659 * also be used when adding tools to toolgroups.
6664 * @property {string}
6666 OO
.ui
.Tool
.static.name
= '';
6669 * Symbolic name of the group.
6671 * The group name is used to associate tools with each other so that they can be selected later by
6672 * a {@link OO.ui.ToolGroup toolgroup}.
6677 * @property {string}
6679 OO
.ui
.Tool
.static.group
= '';
6682 * Tool title text or a function that returns title text. The value of the static property is overridden if the #title config option is used.
6687 * @property {string|Function}
6689 OO
.ui
.Tool
.static.title
= '';
6692 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
6693 * Normally only the icon is displayed, or only the label if no icon is given.
6697 * @property {boolean}
6699 OO
.ui
.Tool
.static.displayBothIconAndLabel
= false;
6702 * Add tool to catch-all groups automatically.
6704 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
6705 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
6709 * @property {boolean}
6711 OO
.ui
.Tool
.static.autoAddToCatchall
= true;
6714 * Add tool to named groups automatically.
6716 * By default, tools that are configured with a static ‘group’ property are added
6717 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
6718 * toolgroups include tools by group name).
6721 * @property {boolean}
6724 OO
.ui
.Tool
.static.autoAddToGroup
= true;
6727 * Check if this tool is compatible with given data.
6729 * This is a stub that can be overriden to provide support for filtering tools based on an
6730 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
6731 * must also call this method so that the compatibility check can be performed.
6735 * @param {Mixed} data Data to check
6736 * @return {boolean} Tool can be used with data
6738 OO
.ui
.Tool
.static.isCompatibleWith = function () {
6745 * Handle the toolbar state being updated.
6747 * This is an abstract method that must be overridden in a concrete subclass.
6752 OO
.ui
.Tool
.prototype.onUpdateState = function () {
6754 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
6759 * Handle the tool being selected.
6761 * This is an abstract method that must be overridden in a concrete subclass.
6766 OO
.ui
.Tool
.prototype.onSelect = function () {
6768 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
6773 * Check if the tool is active.
6775 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
6776 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
6778 * @return {boolean} Tool is active
6780 OO
.ui
.Tool
.prototype.isActive = function () {
6785 * Make the tool appear active or inactive.
6787 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
6788 * appear pressed or not.
6790 * @param {boolean} state Make tool appear active
6792 OO
.ui
.Tool
.prototype.setActive = function ( state
) {
6793 this.active
= !!state
;
6794 if ( this.active
) {
6795 this.$element
.addClass( 'oo-ui-tool-active' );
6797 this.$element
.removeClass( 'oo-ui-tool-active' );
6802 * Set the tool #title.
6804 * @param {string|Function} title Title text or a function that returns text
6807 OO
.ui
.Tool
.prototype.setTitle = function ( title
) {
6808 this.title
= OO
.ui
.resolveMsg( title
);
6814 * Get the tool #title.
6816 * @return {string} Title text
6818 OO
.ui
.Tool
.prototype.getTitle = function () {
6823 * Get the tool's symbolic name.
6825 * @return {string} Symbolic name of tool
6827 OO
.ui
.Tool
.prototype.getName = function () {
6828 return this.constructor.static.name
;
6834 OO
.ui
.Tool
.prototype.updateTitle = function () {
6835 var titleTooltips
= this.toolGroup
.constructor.static.titleTooltips
,
6836 accelTooltips
= this.toolGroup
.constructor.static.accelTooltips
,
6837 accel
= this.toolbar
.getToolAccelerator( this.constructor.static.name
),
6840 this.$title
.text( this.title
);
6841 this.$accel
.text( accel
);
6843 if ( titleTooltips
&& typeof this.title
=== 'string' && this.title
.length
) {
6844 tooltipParts
.push( this.title
);
6846 if ( accelTooltips
&& typeof accel
=== 'string' && accel
.length
) {
6847 tooltipParts
.push( accel
);
6849 if ( tooltipParts
.length
) {
6850 this.$link
.attr( 'title', tooltipParts
.join( ' ' ) );
6852 this.$link
.removeAttr( 'title' );
6859 * Destroying the tool removes all event handlers and the tool’s DOM elements.
6860 * Call this method whenever you are done using a tool.
6862 OO
.ui
.Tool
.prototype.destroy = function () {
6863 this.toolbar
.disconnect( this );
6864 this.$element
.remove();
6868 * Toolbars are complex interface components that permit users to easily access a variety
6869 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
6870 * part of the toolbar, but not configured as tools.
6872 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
6873 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
6874 * picture’), and an icon.
6876 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
6877 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
6878 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
6879 * any order, but each can only appear once in the toolbar.
6881 * The following is an example of a basic toolbar.
6884 * // Example of a toolbar
6885 * // Create the toolbar
6886 * var toolFactory = new OO.ui.ToolFactory();
6887 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
6888 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
6890 * // We will be placing status text in this element when tools are used
6891 * var $area = $( '<p>' ).text( 'Toolbar example' );
6893 * // Define the tools that we're going to place in our toolbar
6895 * // Create a class inheriting from OO.ui.Tool
6896 * function PictureTool() {
6897 * PictureTool.super.apply( this, arguments );
6899 * OO.inheritClass( PictureTool, OO.ui.Tool );
6900 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
6901 * // of 'icon' and 'title' (displayed icon and text).
6902 * PictureTool.static.name = 'picture';
6903 * PictureTool.static.icon = 'picture';
6904 * PictureTool.static.title = 'Insert picture';
6905 * // Defines the action that will happen when this tool is selected (clicked).
6906 * PictureTool.prototype.onSelect = function () {
6907 * $area.text( 'Picture tool clicked!' );
6908 * // Never display this tool as "active" (selected).
6909 * this.setActive( false );
6911 * // Make this tool available in our toolFactory and thus our toolbar
6912 * toolFactory.register( PictureTool );
6914 * // Register two more tools, nothing interesting here
6915 * function SettingsTool() {
6916 * SettingsTool.super.apply( this, arguments );
6918 * OO.inheritClass( SettingsTool, OO.ui.Tool );
6919 * SettingsTool.static.name = 'settings';
6920 * SettingsTool.static.icon = 'settings';
6921 * SettingsTool.static.title = 'Change settings';
6922 * SettingsTool.prototype.onSelect = function () {
6923 * $area.text( 'Settings tool clicked!' );
6924 * this.setActive( false );
6926 * toolFactory.register( SettingsTool );
6928 * // Register two more tools, nothing interesting here
6929 * function StuffTool() {
6930 * StuffTool.super.apply( this, arguments );
6932 * OO.inheritClass( StuffTool, OO.ui.Tool );
6933 * StuffTool.static.name = 'stuff';
6934 * StuffTool.static.icon = 'ellipsis';
6935 * StuffTool.static.title = 'More stuff';
6936 * StuffTool.prototype.onSelect = function () {
6937 * $area.text( 'More stuff tool clicked!' );
6938 * this.setActive( false );
6940 * toolFactory.register( StuffTool );
6942 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
6943 * // little popup window (a PopupWidget).
6944 * function HelpTool( toolGroup, config ) {
6945 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
6950 * this.popup.$body.append( '<p>I am helpful!</p>' );
6952 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
6953 * HelpTool.static.name = 'help';
6954 * HelpTool.static.icon = 'help';
6955 * HelpTool.static.title = 'Help';
6956 * toolFactory.register( HelpTool );
6958 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
6959 * // used once (but not all defined tools must be used).
6962 * // 'bar' tool groups display tools' icons only, side-by-side.
6964 * include: [ 'picture', 'help' ]
6967 * // 'list' tool groups display both the titles and icons, in a dropdown list.
6969 * indicator: 'down',
6971 * include: [ 'settings', 'stuff' ]
6973 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
6974 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
6975 * // since it's more complicated to use. (See the next example snippet on this page.)
6978 * // Create some UI around the toolbar and place it in the document
6979 * var frame = new OO.ui.PanelLayout( {
6983 * var contentFrame = new OO.ui.PanelLayout( {
6987 * frame.$element.append(
6989 * contentFrame.$element.append( $area )
6991 * $( 'body' ).append( frame.$element );
6993 * // Here is where the toolbar is actually built. This must be done after inserting it into the
6995 * toolbar.initialize();
6997 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
6998 * 'updateState' event.
7001 * // Create the toolbar
7002 * var toolFactory = new OO.ui.ToolFactory();
7003 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7004 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7006 * // We will be placing status text in this element when tools are used
7007 * var $area = $( '<p>' ).text( 'Toolbar example' );
7009 * // Define the tools that we're going to place in our toolbar
7011 * // Create a class inheriting from OO.ui.Tool
7012 * function PictureTool() {
7013 * PictureTool.super.apply( this, arguments );
7015 * OO.inheritClass( PictureTool, OO.ui.Tool );
7016 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7017 * // of 'icon' and 'title' (displayed icon and text).
7018 * PictureTool.static.name = 'picture';
7019 * PictureTool.static.icon = 'picture';
7020 * PictureTool.static.title = 'Insert picture';
7021 * // Defines the action that will happen when this tool is selected (clicked).
7022 * PictureTool.prototype.onSelect = function () {
7023 * $area.text( 'Picture tool clicked!' );
7024 * // Never display this tool as "active" (selected).
7025 * this.setActive( false );
7027 * // The toolbar can be synchronized with the state of some external stuff, like a text
7028 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
7029 * // when the text cursor was inside bolded text). Here we simply disable this feature.
7030 * PictureTool.prototype.onUpdateState = function () {
7032 * // Make this tool available in our toolFactory and thus our toolbar
7033 * toolFactory.register( PictureTool );
7035 * // Register two more tools, nothing interesting here
7036 * function SettingsTool() {
7037 * SettingsTool.super.apply( this, arguments );
7038 * this.reallyActive = false;
7040 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7041 * SettingsTool.static.name = 'settings';
7042 * SettingsTool.static.icon = 'settings';
7043 * SettingsTool.static.title = 'Change settings';
7044 * SettingsTool.prototype.onSelect = function () {
7045 * $area.text( 'Settings tool clicked!' );
7046 * // Toggle the active state on each click
7047 * this.reallyActive = !this.reallyActive;
7048 * this.setActive( this.reallyActive );
7049 * // To update the menu label
7050 * this.toolbar.emit( 'updateState' );
7052 * SettingsTool.prototype.onUpdateState = function () {
7054 * toolFactory.register( SettingsTool );
7056 * // Register two more tools, nothing interesting here
7057 * function StuffTool() {
7058 * StuffTool.super.apply( this, arguments );
7059 * this.reallyActive = false;
7061 * OO.inheritClass( StuffTool, OO.ui.Tool );
7062 * StuffTool.static.name = 'stuff';
7063 * StuffTool.static.icon = 'ellipsis';
7064 * StuffTool.static.title = 'More stuff';
7065 * StuffTool.prototype.onSelect = function () {
7066 * $area.text( 'More stuff tool clicked!' );
7067 * // Toggle the active state on each click
7068 * this.reallyActive = !this.reallyActive;
7069 * this.setActive( this.reallyActive );
7070 * // To update the menu label
7071 * this.toolbar.emit( 'updateState' );
7073 * StuffTool.prototype.onUpdateState = function () {
7075 * toolFactory.register( StuffTool );
7077 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7078 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7079 * function HelpTool( toolGroup, config ) {
7080 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7085 * this.popup.$body.append( '<p>I am helpful!</p>' );
7087 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7088 * HelpTool.static.name = 'help';
7089 * HelpTool.static.icon = 'help';
7090 * HelpTool.static.title = 'Help';
7091 * toolFactory.register( HelpTool );
7093 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7094 * // used once (but not all defined tools must be used).
7097 * // 'bar' tool groups display tools' icons only, side-by-side.
7099 * include: [ 'picture', 'help' ]
7102 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7103 * // Menu label indicates which items are selected.
7105 * indicator: 'down',
7106 * include: [ 'settings', 'stuff' ]
7110 * // Create some UI around the toolbar and place it in the document
7111 * var frame = new OO.ui.PanelLayout( {
7115 * var contentFrame = new OO.ui.PanelLayout( {
7119 * frame.$element.append(
7121 * contentFrame.$element.append( $area )
7123 * $( 'body' ).append( frame.$element );
7125 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7127 * toolbar.initialize();
7128 * toolbar.emit( 'updateState' );
7131 * @extends OO.ui.Element
7132 * @mixins OO.EventEmitter
7133 * @mixins OO.ui.mixin.GroupElement
7136 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7137 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7138 * @param {Object} [config] Configuration options
7139 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7140 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7142 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7144 OO
.ui
.Toolbar
= function OoUiToolbar( toolFactory
, toolGroupFactory
, config
) {
7145 // Allow passing positional parameters inside the config object
7146 if ( OO
.isPlainObject( toolFactory
) && config
=== undefined ) {
7147 config
= toolFactory
;
7148 toolFactory
= config
.toolFactory
;
7149 toolGroupFactory
= config
.toolGroupFactory
;
7152 // Configuration initialization
7153 config
= config
|| {};
7155 // Parent constructor
7156 OO
.ui
.Toolbar
.super.call( this, config
);
7158 // Mixin constructors
7159 OO
.EventEmitter
.call( this );
7160 OO
.ui
.mixin
.GroupElement
.call( this, config
);
7163 this.toolFactory
= toolFactory
;
7164 this.toolGroupFactory
= toolGroupFactory
;
7167 this.$bar
= $( '<div>' );
7168 this.$actions
= $( '<div>' );
7169 this.initialized
= false;
7170 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
7174 .add( this.$bar
).add( this.$group
).add( this.$actions
)
7175 .on( 'mousedown keydown', this.onPointerDown
.bind( this ) );
7178 this.$group
.addClass( 'oo-ui-toolbar-tools' );
7179 if ( config
.actions
) {
7180 this.$bar
.append( this.$actions
.addClass( 'oo-ui-toolbar-actions' ) );
7183 .addClass( 'oo-ui-toolbar-bar' )
7184 .append( this.$group
, '<div style="clear:both"></div>' );
7185 if ( config
.shadow
) {
7186 this.$bar
.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7188 this.$element
.addClass( 'oo-ui-toolbar' ).append( this.$bar
);
7193 OO
.inheritClass( OO
.ui
.Toolbar
, OO
.ui
.Element
);
7194 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.EventEmitter
);
7195 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.ui
.mixin
.GroupElement
);
7200 * Get the tool factory.
7202 * @return {OO.ui.ToolFactory} Tool factory
7204 OO
.ui
.Toolbar
.prototype.getToolFactory = function () {
7205 return this.toolFactory
;
7209 * Get the toolgroup factory.
7211 * @return {OO.Factory} Toolgroup factory
7213 OO
.ui
.Toolbar
.prototype.getToolGroupFactory = function () {
7214 return this.toolGroupFactory
;
7218 * Handles mouse down events.
7221 * @param {jQuery.Event} e Mouse down event
7223 OO
.ui
.Toolbar
.prototype.onPointerDown = function ( e
) {
7224 var $closestWidgetToEvent
= $( e
.target
).closest( '.oo-ui-widget' ),
7225 $closestWidgetToToolbar
= this.$element
.closest( '.oo-ui-widget' );
7226 if ( !$closestWidgetToEvent
.length
|| $closestWidgetToEvent
[ 0 ] === $closestWidgetToToolbar
[ 0 ] ) {
7232 * Handle window resize event.
7235 * @param {jQuery.Event} e Window resize event
7237 OO
.ui
.Toolbar
.prototype.onWindowResize = function () {
7238 this.$element
.toggleClass(
7239 'oo-ui-toolbar-narrow',
7240 this.$bar
.width() <= this.narrowThreshold
7245 * Sets up handles and preloads required information for the toolbar to work.
7246 * This must be called after it is attached to a visible document and before doing anything else.
7248 OO
.ui
.Toolbar
.prototype.initialize = function () {
7249 this.initialized
= true;
7250 this.narrowThreshold
= this.$group
.width() + this.$actions
.width();
7251 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
7252 this.onWindowResize();
7256 * Set up the toolbar.
7258 * The toolbar is set up with a list of toolgroup configurations that specify the type of
7259 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
7260 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
7261 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
7263 * @param {Object.<string,Array>} groups List of toolgroup configurations
7264 * @param {Array|string} [groups.include] Tools to include in the toolgroup
7265 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
7266 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
7267 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
7269 OO
.ui
.Toolbar
.prototype.setup = function ( groups
) {
7270 var i
, len
, type
, group
,
7272 defaultType
= 'bar';
7274 // Cleanup previous groups
7277 // Build out new groups
7278 for ( i
= 0, len
= groups
.length
; i
< len
; i
++ ) {
7279 group
= groups
[ i
];
7280 if ( group
.include
=== '*' ) {
7281 // Apply defaults to catch-all groups
7282 if ( group
.type
=== undefined ) {
7283 group
.type
= 'list';
7285 if ( group
.label
=== undefined ) {
7286 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
7289 // Check type has been registered
7290 type
= this.getToolGroupFactory().lookup( group
.type
) ? group
.type
: defaultType
;
7292 this.getToolGroupFactory().create( type
, this, group
)
7295 this.addItems( items
);
7299 * Remove all tools and toolgroups from the toolbar.
7301 OO
.ui
.Toolbar
.prototype.reset = function () {
7306 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7307 this.items
[ i
].destroy();
7313 * Destroy the toolbar.
7315 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
7316 * this method whenever you are done using a toolbar.
7318 OO
.ui
.Toolbar
.prototype.destroy = function () {
7319 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
7321 this.$element
.remove();
7325 * Check if the tool is available.
7327 * Available tools are ones that have not yet been added to the toolbar.
7329 * @param {string} name Symbolic name of tool
7330 * @return {boolean} Tool is available
7332 OO
.ui
.Toolbar
.prototype.isToolAvailable = function ( name
) {
7333 return !this.tools
[ name
];
7337 * Prevent tool from being used again.
7339 * @param {OO.ui.Tool} tool Tool to reserve
7341 OO
.ui
.Toolbar
.prototype.reserveTool = function ( tool
) {
7342 this.tools
[ tool
.getName() ] = tool
;
7346 * Allow tool to be used again.
7348 * @param {OO.ui.Tool} tool Tool to release
7350 OO
.ui
.Toolbar
.prototype.releaseTool = function ( tool
) {
7351 delete this.tools
[ tool
.getName() ];
7355 * Get accelerator label for tool.
7357 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
7358 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
7359 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
7361 * @param {string} name Symbolic name of tool
7362 * @return {string|undefined} Tool accelerator label if available
7364 OO
.ui
.Toolbar
.prototype.getToolAccelerator = function () {
7369 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
7370 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
7371 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
7372 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
7374 * Toolgroups can contain individual tools, groups of tools, or all available tools:
7376 * To include an individual tool (or array of individual tools), specify tools by symbolic name:
7378 * include: [ 'tool-name' ] or [ { name: 'tool-name' }]
7380 * To include a group of tools, specify the group name. (The tool's static ‘group’ config is used to assign the tool to a group.)
7382 * include: [ { group: 'group-name' } ]
7384 * To include all tools that are not yet assigned to a toolgroup, use the catch-all selector, an asterisk (*):
7388 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
7389 * please see the [OOjs UI documentation on MediaWiki][1].
7391 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7395 * @extends OO.ui.Widget
7396 * @mixins OO.ui.mixin.GroupElement
7399 * @param {OO.ui.Toolbar} toolbar
7400 * @param {Object} [config] Configuration options
7401 * @cfg {Array|string} [include=[]] List of tools to include in the toolgroup.
7402 * @cfg {Array|string} [exclude=[]] List of tools to exclude from the toolgroup.
7403 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning of the toolgroup.
7404 * @cfg {Array|string} [demote=[]] List of tools to demote to the end of the toolgroup.
7405 * This setting is particularly useful when tools have been added to the toolgroup
7406 * en masse (e.g., via the catch-all selector).
7408 OO
.ui
.ToolGroup
= function OoUiToolGroup( toolbar
, config
) {
7409 // Allow passing positional parameters inside the config object
7410 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
7412 toolbar
= config
.toolbar
;
7415 // Configuration initialization
7416 config
= config
|| {};
7418 // Parent constructor
7419 OO
.ui
.ToolGroup
.super.call( this, config
);
7421 // Mixin constructors
7422 OO
.ui
.mixin
.GroupElement
.call( this, config
);
7425 this.toolbar
= toolbar
;
7427 this.pressed
= null;
7428 this.autoDisabled
= false;
7429 this.include
= config
.include
|| [];
7430 this.exclude
= config
.exclude
|| [];
7431 this.promote
= config
.promote
|| [];
7432 this.demote
= config
.demote
|| [];
7433 this.onCapturedMouseKeyUpHandler
= this.onCapturedMouseKeyUp
.bind( this );
7437 mousedown
: this.onMouseKeyDown
.bind( this ),
7438 mouseup
: this.onMouseKeyUp
.bind( this ),
7439 keydown
: this.onMouseKeyDown
.bind( this ),
7440 keyup
: this.onMouseKeyUp
.bind( this ),
7441 focus
: this.onMouseOverFocus
.bind( this ),
7442 blur
: this.onMouseOutBlur
.bind( this ),
7443 mouseover
: this.onMouseOverFocus
.bind( this ),
7444 mouseout
: this.onMouseOutBlur
.bind( this )
7446 this.toolbar
.getToolFactory().connect( this, { register
: 'onToolFactoryRegister' } );
7447 this.aggregate( { disable
: 'itemDisable' } );
7448 this.connect( this, { itemDisable
: 'updateDisabled' } );
7451 this.$group
.addClass( 'oo-ui-toolGroup-tools' );
7453 .addClass( 'oo-ui-toolGroup' )
7454 .append( this.$group
);
7460 OO
.inheritClass( OO
.ui
.ToolGroup
, OO
.ui
.Widget
);
7461 OO
.mixinClass( OO
.ui
.ToolGroup
, OO
.ui
.mixin
.GroupElement
);
7469 /* Static Properties */
7472 * Show labels in tooltips.
7476 * @property {boolean}
7478 OO
.ui
.ToolGroup
.static.titleTooltips
= false;
7481 * Show acceleration labels in tooltips.
7483 * Note: The OOjs UI library does not include an accelerator system, but does contain
7484 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
7485 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
7486 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
7490 * @property {boolean}
7492 OO
.ui
.ToolGroup
.static.accelTooltips
= false;
7495 * Automatically disable the toolgroup when all tools are disabled
7499 * @property {boolean}
7501 OO
.ui
.ToolGroup
.static.autoDisable
= true;
7508 OO
.ui
.ToolGroup
.prototype.isDisabled = function () {
7509 return this.autoDisabled
|| OO
.ui
.ToolGroup
.super.prototype.isDisabled
.apply( this, arguments
);
7515 OO
.ui
.ToolGroup
.prototype.updateDisabled = function () {
7516 var i
, item
, allDisabled
= true;
7518 if ( this.constructor.static.autoDisable
) {
7519 for ( i
= this.items
.length
- 1; i
>= 0; i
-- ) {
7520 item
= this.items
[ i
];
7521 if ( !item
.isDisabled() ) {
7522 allDisabled
= false;
7526 this.autoDisabled
= allDisabled
;
7528 OO
.ui
.ToolGroup
.super.prototype.updateDisabled
.apply( this, arguments
);
7532 * Handle mouse down and key down events.
7535 * @param {jQuery.Event} e Mouse down or key down event
7537 OO
.ui
.ToolGroup
.prototype.onMouseKeyDown = function ( e
) {
7539 !this.isDisabled() &&
7540 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
7542 this.pressed
= this.getTargetTool( e
);
7543 if ( this.pressed
) {
7544 this.pressed
.setActive( true );
7545 this.getElementDocument().addEventListener( 'mouseup', this.onCapturedMouseKeyUpHandler
, true );
7546 this.getElementDocument().addEventListener( 'keyup', this.onCapturedMouseKeyUpHandler
, true );
7553 * Handle captured mouse up and key up events.
7556 * @param {Event} e Mouse up or key up event
7558 OO
.ui
.ToolGroup
.prototype.onCapturedMouseKeyUp = function ( e
) {
7559 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseKeyUpHandler
, true );
7560 this.getElementDocument().removeEventListener( 'keyup', this.onCapturedMouseKeyUpHandler
, true );
7561 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
7562 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
7563 this.onMouseKeyUp( e
);
7567 * Handle mouse up and key up events.
7570 * @param {jQuery.Event} e Mouse up or key up event
7572 OO
.ui
.ToolGroup
.prototype.onMouseKeyUp = function ( e
) {
7573 var tool
= this.getTargetTool( e
);
7576 !this.isDisabled() && this.pressed
&& this.pressed
=== tool
&&
7577 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
7579 this.pressed
.onSelect();
7580 this.pressed
= null;
7584 this.pressed
= null;
7588 * Handle mouse over and focus events.
7591 * @param {jQuery.Event} e Mouse over or focus event
7593 OO
.ui
.ToolGroup
.prototype.onMouseOverFocus = function ( e
) {
7594 var tool
= this.getTargetTool( e
);
7596 if ( this.pressed
&& this.pressed
=== tool
) {
7597 this.pressed
.setActive( true );
7602 * Handle mouse out and blur events.
7605 * @param {jQuery.Event} e Mouse out or blur event
7607 OO
.ui
.ToolGroup
.prototype.onMouseOutBlur = function ( e
) {
7608 var tool
= this.getTargetTool( e
);
7610 if ( this.pressed
&& this.pressed
=== tool
) {
7611 this.pressed
.setActive( false );
7616 * Get the closest tool to a jQuery.Event.
7618 * Only tool links are considered, which prevents other elements in the tool such as popups from
7619 * triggering tool group interactions.
7622 * @param {jQuery.Event} e
7623 * @return {OO.ui.Tool|null} Tool, `null` if none was found
7625 OO
.ui
.ToolGroup
.prototype.getTargetTool = function ( e
) {
7627 $item
= $( e
.target
).closest( '.oo-ui-tool-link' );
7629 if ( $item
.length
) {
7630 tool
= $item
.parent().data( 'oo-ui-tool' );
7633 return tool
&& !tool
.isDisabled() ? tool
: null;
7637 * Handle tool registry register events.
7639 * If a tool is registered after the group is created, we must repopulate the list to account for:
7641 * - a tool being added that may be included
7642 * - a tool already included being overridden
7645 * @param {string} name Symbolic name of tool
7647 OO
.ui
.ToolGroup
.prototype.onToolFactoryRegister = function () {
7652 * Get the toolbar that contains the toolgroup.
7654 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
7656 OO
.ui
.ToolGroup
.prototype.getToolbar = function () {
7657 return this.toolbar
;
7661 * Add and remove tools based on configuration.
7663 OO
.ui
.ToolGroup
.prototype.populate = function () {
7664 var i
, len
, name
, tool
,
7665 toolFactory
= this.toolbar
.getToolFactory(),
7669 list
= this.toolbar
.getToolFactory().getTools(
7670 this.include
, this.exclude
, this.promote
, this.demote
7673 // Build a list of needed tools
7674 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
7678 toolFactory
.lookup( name
) &&
7679 // Tool is available or is already in this group
7680 ( this.toolbar
.isToolAvailable( name
) || this.tools
[ name
] )
7682 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
7683 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
7684 this.toolbar
.tools
[ name
] = true;
7685 tool
= this.tools
[ name
];
7687 // Auto-initialize tools on first use
7688 this.tools
[ name
] = tool
= toolFactory
.create( name
, this );
7691 this.toolbar
.reserveTool( tool
);
7693 names
[ name
] = true;
7696 // Remove tools that are no longer needed
7697 for ( name
in this.tools
) {
7698 if ( !names
[ name
] ) {
7699 this.tools
[ name
].destroy();
7700 this.toolbar
.releaseTool( this.tools
[ name
] );
7701 remove
.push( this.tools
[ name
] );
7702 delete this.tools
[ name
];
7705 if ( remove
.length
) {
7706 this.removeItems( remove
);
7708 // Update emptiness state
7710 this.$element
.removeClass( 'oo-ui-toolGroup-empty' );
7712 this.$element
.addClass( 'oo-ui-toolGroup-empty' );
7714 // Re-add tools (moving existing ones to new locations)
7715 this.addItems( add
);
7716 // Disabled state may depend on items
7717 this.updateDisabled();
7721 * Destroy toolgroup.
7723 OO
.ui
.ToolGroup
.prototype.destroy = function () {
7727 this.toolbar
.getToolFactory().disconnect( this );
7728 for ( name
in this.tools
) {
7729 this.toolbar
.releaseTool( this.tools
[ name
] );
7730 this.tools
[ name
].disconnect( this ).destroy();
7731 delete this.tools
[ name
];
7733 this.$element
.remove();
7737 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
7738 * consists of a header that contains the dialog title, a body with the message, and a footer that
7739 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
7740 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
7742 * There are two basic types of message dialogs, confirmation and alert:
7744 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
7745 * more details about the consequences.
7746 * - **alert**: the dialog title describes which event occurred and the message provides more information
7747 * about why the event occurred.
7749 * The MessageDialog class specifies two actions: ‘accept’, the primary
7750 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
7751 * passing along the selected action.
7753 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
7756 * // Example: Creating and opening a message dialog window.
7757 * var messageDialog = new OO.ui.MessageDialog();
7759 * // Create and append a window manager.
7760 * var windowManager = new OO.ui.WindowManager();
7761 * $( 'body' ).append( windowManager.$element );
7762 * windowManager.addWindows( [ messageDialog ] );
7763 * // Open the window.
7764 * windowManager.openWindow( messageDialog, {
7765 * title: 'Basic message dialog',
7766 * message: 'This is the message'
7769 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
7772 * @extends OO.ui.Dialog
7775 * @param {Object} [config] Configuration options
7777 OO
.ui
.MessageDialog
= function OoUiMessageDialog( config
) {
7778 // Parent constructor
7779 OO
.ui
.MessageDialog
.super.call( this, config
);
7782 this.verticalActionLayout
= null;
7785 this.$element
.addClass( 'oo-ui-messageDialog' );
7790 OO
.inheritClass( OO
.ui
.MessageDialog
, OO
.ui
.Dialog
);
7792 /* Static Properties */
7794 OO
.ui
.MessageDialog
.static.name
= 'message';
7796 OO
.ui
.MessageDialog
.static.size
= 'small';
7798 OO
.ui
.MessageDialog
.static.verbose
= false;
7803 * The title of a confirmation dialog describes what a progressive action will do. The
7804 * title of an alert dialog describes which event occurred.
7808 * @property {jQuery|string|Function|null}
7810 OO
.ui
.MessageDialog
.static.title
= null;
7813 * The message displayed in the dialog body.
7815 * A confirmation message describes the consequences of a progressive action. An alert
7816 * message describes why an event occurred.
7820 * @property {jQuery|string|Function|null}
7822 OO
.ui
.MessageDialog
.static.message
= null;
7824 OO
.ui
.MessageDialog
.static.actions
= [
7825 { action
: 'accept', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-accept' ), flags
: 'primary' },
7826 { action
: 'reject', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-reject' ), flags
: 'safe' }
7834 OO
.ui
.MessageDialog
.prototype.setManager = function ( manager
) {
7835 OO
.ui
.MessageDialog
.super.prototype.setManager
.call( this, manager
);
7838 this.manager
.connect( this, {
7848 OO
.ui
.MessageDialog
.prototype.onActionResize = function ( action
) {
7850 return OO
.ui
.MessageDialog
.super.prototype.onActionResize
.call( this, action
);
7854 * Handle window resized events.
7858 OO
.ui
.MessageDialog
.prototype.onResize = function () {
7860 dialog
.fitActions();
7861 // Wait for CSS transition to finish and do it again :(
7862 setTimeout( function () {
7863 dialog
.fitActions();
7868 * Toggle action layout between vertical and horizontal.
7872 * @param {boolean} [value] Layout actions vertically, omit to toggle
7875 OO
.ui
.MessageDialog
.prototype.toggleVerticalActionLayout = function ( value
) {
7876 value
= value
=== undefined ? !this.verticalActionLayout
: !!value
;
7878 if ( value
!== this.verticalActionLayout
) {
7879 this.verticalActionLayout
= value
;
7881 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value
)
7882 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value
);
7891 OO
.ui
.MessageDialog
.prototype.getActionProcess = function ( action
) {
7893 return new OO
.ui
.Process( function () {
7894 this.close( { action
: action
} );
7897 return OO
.ui
.MessageDialog
.super.prototype.getActionProcess
.call( this, action
);
7903 * @param {Object} [data] Dialog opening data
7904 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
7905 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
7906 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
7907 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
7910 OO
.ui
.MessageDialog
.prototype.getSetupProcess = function ( data
) {
7914 return OO
.ui
.MessageDialog
.super.prototype.getSetupProcess
.call( this, data
)
7915 .next( function () {
7916 this.title
.setLabel(
7917 data
.title
!== undefined ? data
.title
: this.constructor.static.title
7919 this.message
.setLabel(
7920 data
.message
!== undefined ? data
.message
: this.constructor.static.message
7922 this.message
.$element
.toggleClass(
7923 'oo-ui-messageDialog-message-verbose',
7924 data
.verbose
!== undefined ? data
.verbose
: this.constructor.static.verbose
7932 OO
.ui
.MessageDialog
.prototype.getBodyHeight = function () {
7933 var bodyHeight
, oldOverflow
,
7934 $scrollable
= this.container
.$element
;
7936 oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
7937 $scrollable
[ 0 ].style
.overflow
= 'hidden';
7939 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
7941 bodyHeight
= this.text
.$element
.outerHeight( true );
7942 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
7950 OO
.ui
.MessageDialog
.prototype.setDimensions = function ( dim
) {
7951 var $scrollable
= this.container
.$element
;
7952 OO
.ui
.MessageDialog
.super.prototype.setDimensions
.call( this, dim
);
7954 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
7955 // Need to do it after transition completes (250ms), add 50ms just in case.
7956 setTimeout( function () {
7957 var oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
7958 $scrollable
[ 0 ].style
.overflow
= 'hidden';
7960 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
7962 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
7971 OO
.ui
.MessageDialog
.prototype.initialize = function () {
7973 OO
.ui
.MessageDialog
.super.prototype.initialize
.call( this );
7976 this.$actions
= $( '<div>' );
7977 this.container
= new OO
.ui
.PanelLayout( {
7978 scrollable
: true, classes
: [ 'oo-ui-messageDialog-container' ]
7980 this.text
= new OO
.ui
.PanelLayout( {
7981 padded
: true, expanded
: false, classes
: [ 'oo-ui-messageDialog-text' ]
7983 this.message
= new OO
.ui
.LabelWidget( {
7984 classes
: [ 'oo-ui-messageDialog-message' ]
7988 this.title
.$element
.addClass( 'oo-ui-messageDialog-title' );
7989 this.$content
.addClass( 'oo-ui-messageDialog-content' );
7990 this.container
.$element
.append( this.text
.$element
);
7991 this.text
.$element
.append( this.title
.$element
, this.message
.$element
);
7992 this.$body
.append( this.container
.$element
);
7993 this.$actions
.addClass( 'oo-ui-messageDialog-actions' );
7994 this.$foot
.append( this.$actions
);
8000 OO
.ui
.MessageDialog
.prototype.attachActions = function () {
8001 var i
, len
, other
, special
, others
;
8004 OO
.ui
.MessageDialog
.super.prototype.attachActions
.call( this );
8006 special
= this.actions
.getSpecial();
8007 others
= this.actions
.getOthers();
8008 if ( special
.safe
) {
8009 this.$actions
.append( special
.safe
.$element
);
8010 special
.safe
.toggleFramed( false );
8012 if ( others
.length
) {
8013 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
8014 other
= others
[ i
];
8015 this.$actions
.append( other
.$element
);
8016 other
.toggleFramed( false );
8019 if ( special
.primary
) {
8020 this.$actions
.append( special
.primary
.$element
);
8021 special
.primary
.toggleFramed( false );
8024 if ( !this.isOpening() ) {
8025 // If the dialog is currently opening, this will be called automatically soon.
8026 // This also calls #fitActions.
8032 * Fit action actions into columns or rows.
8034 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8038 OO
.ui
.MessageDialog
.prototype.fitActions = function () {
8040 previous
= this.verticalActionLayout
,
8041 actions
= this.actions
.get();
8044 this.toggleVerticalActionLayout( false );
8045 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
8046 action
= actions
[ i
];
8047 if ( action
.$element
.innerWidth() < action
.$label
.outerWidth( true ) ) {
8048 this.toggleVerticalActionLayout( true );
8053 // Move the body out of the way of the foot
8054 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
8056 if ( this.verticalActionLayout
!== previous
) {
8057 // We changed the layout, window height might need to be updated.
8063 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8064 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8065 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8066 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8067 * required for each process.
8069 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8070 * processes with an animation. The header contains the dialog title as well as
8071 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8072 * a ‘primary’ action on the right (e.g., ‘Done’).
8074 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8075 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8078 * // Example: Creating and opening a process dialog window.
8079 * function MyProcessDialog( config ) {
8080 * MyProcessDialog.super.call( this, config );
8082 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8084 * MyProcessDialog.static.title = 'Process dialog';
8085 * MyProcessDialog.static.actions = [
8086 * { action: 'save', label: 'Done', flags: 'primary' },
8087 * { label: 'Cancel', flags: 'safe' }
8090 * MyProcessDialog.prototype.initialize = function () {
8091 * MyProcessDialog.super.prototype.initialize.apply( this, arguments );
8092 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8093 * this.content.$element.append( '<p>This is a process dialog window. The header contains the title and two buttons: \'Cancel\' (a safe action) on the left and \'Done\' (a primary action) on the right.</p>' );
8094 * this.$body.append( this.content.$element );
8096 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8097 * var dialog = this;
8099 * return new OO.ui.Process( function () {
8100 * dialog.close( { action: action } );
8103 * return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
8106 * var windowManager = new OO.ui.WindowManager();
8107 * $( 'body' ).append( windowManager.$element );
8109 * var dialog = new MyProcessDialog();
8110 * windowManager.addWindows( [ dialog ] );
8111 * windowManager.openWindow( dialog );
8113 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8117 * @extends OO.ui.Dialog
8120 * @param {Object} [config] Configuration options
8122 OO
.ui
.ProcessDialog
= function OoUiProcessDialog( config
) {
8123 // Parent constructor
8124 OO
.ui
.ProcessDialog
.super.call( this, config
);
8127 this.$element
.addClass( 'oo-ui-processDialog' );
8132 OO
.inheritClass( OO
.ui
.ProcessDialog
, OO
.ui
.Dialog
);
8137 * Handle dismiss button click events.
8143 OO
.ui
.ProcessDialog
.prototype.onDismissErrorButtonClick = function () {
8148 * Handle retry button click events.
8150 * Hides errors and then tries again.
8154 OO
.ui
.ProcessDialog
.prototype.onRetryButtonClick = function () {
8156 this.executeAction( this.currentAction
);
8162 OO
.ui
.ProcessDialog
.prototype.onActionResize = function ( action
) {
8163 if ( this.actions
.isSpecial( action
) ) {
8166 return OO
.ui
.ProcessDialog
.super.prototype.onActionResize
.call( this, action
);
8172 OO
.ui
.ProcessDialog
.prototype.initialize = function () {
8174 OO
.ui
.ProcessDialog
.super.prototype.initialize
.call( this );
8177 this.$navigation
= $( '<div>' );
8178 this.$location
= $( '<div>' );
8179 this.$safeActions
= $( '<div>' );
8180 this.$primaryActions
= $( '<div>' );
8181 this.$otherActions
= $( '<div>' );
8182 this.dismissButton
= new OO
.ui
.ButtonWidget( {
8183 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' )
8185 this.retryButton
= new OO
.ui
.ButtonWidget();
8186 this.$errors
= $( '<div>' );
8187 this.$errorsTitle
= $( '<div>' );
8190 this.dismissButton
.connect( this, { click
: 'onDismissErrorButtonClick' } );
8191 this.retryButton
.connect( this, { click
: 'onRetryButtonClick' } );
8194 this.title
.$element
.addClass( 'oo-ui-processDialog-title' );
8196 .append( this.title
.$element
)
8197 .addClass( 'oo-ui-processDialog-location' );
8198 this.$safeActions
.addClass( 'oo-ui-processDialog-actions-safe' );
8199 this.$primaryActions
.addClass( 'oo-ui-processDialog-actions-primary' );
8200 this.$otherActions
.addClass( 'oo-ui-processDialog-actions-other' );
8202 .addClass( 'oo-ui-processDialog-errors-title' )
8203 .text( OO
.ui
.msg( 'ooui-dialog-process-error' ) );
8205 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8206 .append( this.$errorsTitle
, this.dismissButton
.$element
, this.retryButton
.$element
);
8208 .addClass( 'oo-ui-processDialog-content' )
8209 .append( this.$errors
);
8211 .addClass( 'oo-ui-processDialog-navigation' )
8212 .append( this.$safeActions
, this.$location
, this.$primaryActions
);
8213 this.$head
.append( this.$navigation
);
8214 this.$foot
.append( this.$otherActions
);
8220 OO
.ui
.ProcessDialog
.prototype.getActionWidgets = function ( actions
) {
8221 var i
, len
, widgets
= [];
8222 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
8224 new OO
.ui
.ActionWidget( $.extend( { framed
: true }, actions
[ i
] ) )
8233 OO
.ui
.ProcessDialog
.prototype.attachActions = function () {
8234 var i
, len
, other
, special
, others
;
8237 OO
.ui
.ProcessDialog
.super.prototype.attachActions
.call( this );
8239 special
= this.actions
.getSpecial();
8240 others
= this.actions
.getOthers();
8241 if ( special
.primary
) {
8242 this.$primaryActions
.append( special
.primary
.$element
);
8244 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
8245 other
= others
[ i
];
8246 this.$otherActions
.append( other
.$element
);
8248 if ( special
.safe
) {
8249 this.$safeActions
.append( special
.safe
.$element
);
8253 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
8259 OO
.ui
.ProcessDialog
.prototype.executeAction = function ( action
) {
8261 return OO
.ui
.ProcessDialog
.super.prototype.executeAction
.call( this, action
)
8262 .fail( function ( errors
) {
8263 process
.showErrors( errors
|| [] );
8268 * Fit label between actions.
8273 OO
.ui
.ProcessDialog
.prototype.fitLabel = function () {
8274 var safeWidth
, primaryWidth
, biggerWidth
, labelWidth
, navigationWidth
, leftWidth
, rightWidth
;
8276 safeWidth
= this.$safeActions
.is( ':visible' ) ? this.$safeActions
.width() : 0;
8277 primaryWidth
= this.$primaryActions
.is( ':visible' ) ? this.$primaryActions
.width() : 0;
8278 biggerWidth
= Math
.max( safeWidth
, primaryWidth
);
8280 labelWidth
= this.title
.$element
.width();
8281 // Is there a better way to calculate this?
8282 navigationWidth
= OO
.ui
.WindowManager
.static.sizes
[ this.getSize() ].width
- 20;
8284 if ( 2 * biggerWidth
+ labelWidth
< navigationWidth
) {
8285 // We have enough space to center the label
8286 leftWidth
= rightWidth
= biggerWidth
;
8288 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
8289 if ( this.getDir() === 'ltr' ) {
8290 leftWidth
= safeWidth
;
8291 rightWidth
= primaryWidth
;
8293 leftWidth
= primaryWidth
;
8294 rightWidth
= safeWidth
;
8298 this.$location
.css( { paddingLeft
: leftWidth
, paddingRight
: rightWidth
} );
8304 * Handle errors that occurred during accept or reject processes.
8307 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
8309 OO
.ui
.ProcessDialog
.prototype.showErrors = function ( errors
) {
8310 var i
, len
, $item
, actions
,
8316 if ( errors
instanceof OO
.ui
.Error
) {
8317 errors
= [ errors
];
8320 for ( i
= 0, len
= errors
.length
; i
< len
; i
++ ) {
8321 if ( !errors
[ i
].isRecoverable() ) {
8322 recoverable
= false;
8324 if ( errors
[ i
].isWarning() ) {
8327 $item
= $( '<div>' )
8328 .addClass( 'oo-ui-processDialog-error' )
8329 .append( errors
[ i
].getMessage() );
8330 items
.push( $item
[ 0 ] );
8332 this.$errorItems
= $( items
);
8333 if ( recoverable
) {
8334 abilities
[this.currentAction
] = true;
8335 // Copy the flags from the first matching action
8336 actions
= this.actions
.get( { actions
: this.currentAction
} );
8337 if ( actions
.length
) {
8338 this.retryButton
.clearFlags().setFlags( actions
[0].getFlags() );
8341 abilities
[this.currentAction
] = false;
8342 this.actions
.setAbilities( abilities
);
8345 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-continue' ) );
8347 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-retry' ) );
8349 this.retryButton
.toggle( recoverable
);
8350 this.$errorsTitle
.after( this.$errorItems
);
8351 this.$errors
.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
8359 OO
.ui
.ProcessDialog
.prototype.hideErrors = function () {
8360 this.$errors
.addClass( 'oo-ui-element-hidden' );
8361 if ( this.$errorItems
) {
8362 this.$errorItems
.remove();
8363 this.$errorItems
= null;
8370 OO
.ui
.ProcessDialog
.prototype.getTeardownProcess = function ( data
) {
8372 return OO
.ui
.ProcessDialog
.super.prototype.getTeardownProcess
.call( this, data
)
8373 .first( function () {
8374 // Make sure to hide errors
8380 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8381 * which is a widget that is specified by reference before any optional configuration settings.
8383 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8385 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8386 * A left-alignment is used for forms with many fields.
8387 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8388 * A right-alignment is used for long but familiar forms which users tab through,
8389 * verifying the current field with a quick glance at the label.
8390 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8391 * that users fill out from top to bottom.
8392 * - **inline**: The label is placed after the field-widget and aligned to the left.
8393 * An inline-alignment is best used with checkboxes or radio buttons.
8395 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
8396 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
8398 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8400 * @extends OO.ui.Layout
8401 * @mixins OO.ui.mixin.LabelElement
8404 * @param {OO.ui.Widget} fieldWidget Field widget
8405 * @param {Object} [config] Configuration options
8406 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8407 * @cfg {string} [help] Help text. When help text is specified, a help icon will appear
8408 * in the upper-right corner of the rendered field.
8410 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
8411 // Allow passing positional parameters inside the config object
8412 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
8413 config
= fieldWidget
;
8414 fieldWidget
= config
.fieldWidget
;
8417 var hasInputWidget
= fieldWidget
.constructor.static.supportsSimpleLabel
;
8419 // Configuration initialization
8420 config
= $.extend( { align
: 'left' }, config
);
8422 // Parent constructor
8423 OO
.ui
.FieldLayout
.super.call( this, config
);
8425 // Mixin constructors
8426 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8429 this.fieldWidget
= fieldWidget
;
8430 this.$field
= $( '<div>' );
8431 this.$body
= $( '<' + ( hasInputWidget
? 'label' : 'div' ) + '>' );
8433 if ( config
.help
) {
8434 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
8435 classes
: [ 'oo-ui-fieldLayout-help' ],
8440 this.popupButtonWidget
.getPopup().$body
.append(
8442 .text( config
.help
)
8443 .addClass( 'oo-ui-fieldLayout-help-content' )
8445 this.$help
= this.popupButtonWidget
.$element
;
8447 this.$help
= $( [] );
8451 if ( hasInputWidget
) {
8452 this.$label
.on( 'click', this.onLabelClick
.bind( this ) );
8454 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
8458 .addClass( 'oo-ui-fieldLayout' )
8459 .append( this.$help
, this.$body
);
8460 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
8462 .addClass( 'oo-ui-fieldLayout-field' )
8463 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget
.isDisabled() )
8464 .append( this.fieldWidget
.$element
);
8466 this.setAlignment( config
.align
);
8471 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
8472 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
8477 * Handle field disable events.
8480 * @param {boolean} value Field is disabled
8482 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
8483 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
8487 * Handle label mouse click events.
8490 * @param {jQuery.Event} e Mouse click event
8492 OO
.ui
.FieldLayout
.prototype.onLabelClick = function () {
8493 this.fieldWidget
.simulateLabelClick();
8498 * Get the widget contained by the field.
8500 * @return {OO.ui.Widget} Field widget
8502 OO
.ui
.FieldLayout
.prototype.getField = function () {
8503 return this.fieldWidget
;
8507 * Set the field alignment mode.
8510 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
8513 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
8514 if ( value
!== this.align
) {
8515 // Default to 'left'
8516 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
8520 if ( value
=== 'inline' ) {
8521 this.$body
.append( this.$field
, this.$label
);
8523 this.$body
.append( this.$label
, this.$field
);
8525 // Set classes. The following classes can be used here:
8526 // * oo-ui-fieldLayout-align-left
8527 // * oo-ui-fieldLayout-align-right
8528 // * oo-ui-fieldLayout-align-top
8529 // * oo-ui-fieldLayout-align-inline
8531 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
8533 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
8541 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
8542 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
8543 * is required and is specified before any optional configuration settings.
8545 * Labels can be aligned in one of four ways:
8547 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8548 * A left-alignment is used for forms with many fields.
8549 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8550 * A right-alignment is used for long but familiar forms which users tab through,
8551 * verifying the current field with a quick glance at the label.
8552 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8553 * that users fill out from top to bottom.
8554 * - **inline**: The label is placed after the field-widget and aligned to the left.
8555 * An inline-alignment is best used with checkboxes or radio buttons.
8557 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
8558 * text is specified.
8561 * // Example of an ActionFieldLayout
8562 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
8563 * new OO.ui.TextInputWidget( {
8564 * placeholder: 'Field widget'
8566 * new OO.ui.ButtonWidget( {
8570 * label: 'An ActionFieldLayout. This label is aligned top',
8572 * help: 'This is help text'
8576 * $( 'body' ).append( actionFieldLayout.$element );
8580 * @extends OO.ui.FieldLayout
8583 * @param {OO.ui.Widget} fieldWidget Field widget
8584 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
8586 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
8587 // Allow passing positional parameters inside the config object
8588 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
8589 config
= fieldWidget
;
8590 fieldWidget
= config
.fieldWidget
;
8591 buttonWidget
= config
.buttonWidget
;
8594 // Parent constructor
8595 OO
.ui
.ActionFieldLayout
.super.call( this, fieldWidget
, config
);
8598 this.buttonWidget
= buttonWidget
;
8599 this.$button
= $( '<div>' );
8600 this.$input
= $( '<div>' );
8604 .addClass( 'oo-ui-actionFieldLayout' );
8606 .addClass( 'oo-ui-actionFieldLayout-button' )
8607 .append( this.buttonWidget
.$element
);
8609 .addClass( 'oo-ui-actionFieldLayout-input' )
8610 .append( this.fieldWidget
.$element
);
8612 .append( this.$input
, this.$button
);
8617 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
8620 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
8621 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
8622 * configured with a label as well. For more information and examples,
8623 * please see the [OOjs UI documentation on MediaWiki][1].
8626 * // Example of a fieldset layout
8627 * var input1 = new OO.ui.TextInputWidget( {
8628 * placeholder: 'A text input field'
8631 * var input2 = new OO.ui.TextInputWidget( {
8632 * placeholder: 'A text input field'
8635 * var fieldset = new OO.ui.FieldsetLayout( {
8636 * label: 'Example of a fieldset layout'
8639 * fieldset.addItems( [
8640 * new OO.ui.FieldLayout( input1, {
8641 * label: 'Field One'
8643 * new OO.ui.FieldLayout( input2, {
8644 * label: 'Field Two'
8647 * $( 'body' ).append( fieldset.$element );
8649 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8652 * @extends OO.ui.Layout
8653 * @mixins OO.ui.mixin.IconElement
8654 * @mixins OO.ui.mixin.LabelElement
8655 * @mixins OO.ui.mixin.GroupElement
8658 * @param {Object} [config] Configuration options
8659 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
8661 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
8662 // Configuration initialization
8663 config
= config
|| {};
8665 // Parent constructor
8666 OO
.ui
.FieldsetLayout
.super.call( this, config
);
8668 // Mixin constructors
8669 OO
.ui
.mixin
.IconElement
.call( this, config
);
8670 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8671 OO
.ui
.mixin
.GroupElement
.call( this, config
);
8673 if ( config
.help
) {
8674 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
8675 classes
: [ 'oo-ui-fieldsetLayout-help' ],
8680 this.popupButtonWidget
.getPopup().$body
.append(
8682 .text( config
.help
)
8683 .addClass( 'oo-ui-fieldsetLayout-help-content' )
8685 this.$help
= this.popupButtonWidget
.$element
;
8687 this.$help
= $( [] );
8692 .addClass( 'oo-ui-fieldsetLayout' )
8693 .prepend( this.$help
, this.$icon
, this.$label
, this.$group
);
8694 if ( Array
.isArray( config
.items
) ) {
8695 this.addItems( config
.items
);
8701 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
8702 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
8703 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
8704 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
8707 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
8708 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
8709 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
8710 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
8712 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
8713 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
8714 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
8715 * some fancier controls. Some controls have both regular and InputWidget variants, for example
8716 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
8717 * often have simplified APIs to match the capabilities of HTML forms.
8718 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
8720 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
8721 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8724 * // Example of a form layout that wraps a fieldset layout
8725 * var input1 = new OO.ui.TextInputWidget( {
8726 * placeholder: 'Username'
8728 * var input2 = new OO.ui.TextInputWidget( {
8729 * placeholder: 'Password',
8732 * var submit = new OO.ui.ButtonInputWidget( {
8736 * var fieldset = new OO.ui.FieldsetLayout( {
8737 * label: 'A form layout'
8739 * fieldset.addItems( [
8740 * new OO.ui.FieldLayout( input1, {
8741 * label: 'Username',
8744 * new OO.ui.FieldLayout( input2, {
8745 * label: 'Password',
8748 * new OO.ui.FieldLayout( submit )
8750 * var form = new OO.ui.FormLayout( {
8751 * items: [ fieldset ],
8752 * action: '/api/formhandler',
8755 * $( 'body' ).append( form.$element );
8758 * @extends OO.ui.Layout
8759 * @mixins OO.ui.mixin.GroupElement
8762 * @param {Object} [config] Configuration options
8763 * @cfg {string} [method] HTML form `method` attribute
8764 * @cfg {string} [action] HTML form `action` attribute
8765 * @cfg {string} [enctype] HTML form `enctype` attribute
8766 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
8768 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
8769 // Configuration initialization
8770 config
= config
|| {};
8772 // Parent constructor
8773 OO
.ui
.FormLayout
.super.call( this, config
);
8775 // Mixin constructors
8776 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
8779 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
8783 .addClass( 'oo-ui-formLayout' )
8785 method
: config
.method
,
8786 action
: config
.action
,
8787 enctype
: config
.enctype
8789 if ( Array
.isArray( config
.items
) ) {
8790 this.addItems( config
.items
);
8796 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
8797 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
8802 * A 'submit' event is emitted when the form is submitted.
8807 /* Static Properties */
8809 OO
.ui
.FormLayout
.static.tagName
= 'form';
8814 * Handle form submit events.
8817 * @param {jQuery.Event} e Submit event
8820 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
8821 if ( this.emit( 'submit' ) ) {
8827 * MenuLayouts combine a menu and a content {@link OO.ui.PanelLayout panel}. The menu is positioned relative to the content (after, before, top, or bottom)
8828 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
8831 * var menuLayout = new OO.ui.MenuLayout( {
8834 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
8835 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
8836 * select = new OO.ui.SelectWidget( {
8838 * new OO.ui.OptionWidget( {
8842 * new OO.ui.OptionWidget( {
8846 * new OO.ui.OptionWidget( {
8850 * new OO.ui.OptionWidget( {
8855 * } ).on( 'select', function ( item ) {
8856 * menuLayout.setMenuPosition( item.getData() );
8859 * menuLayout.$menu.append(
8860 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
8862 * menuLayout.$content.append(
8863 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
8865 * $( 'body' ).append( menuLayout.$element );
8867 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
8868 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
8869 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
8872 * .oo-ui-menuLayout-menu {
8876 * .oo-ui-menuLayout-content {
8884 * @extends OO.ui.Layout
8887 * @param {Object} [config] Configuration options
8888 * @cfg {boolean} [showMenu=true] Show menu
8889 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
8891 OO
.ui
.MenuLayout
= function OoUiMenuLayout( config
) {
8892 // Configuration initialization
8893 config
= $.extend( {
8895 menuPosition
: 'before'
8898 // Parent constructor
8899 OO
.ui
.MenuLayout
.super.call( this, config
);
8904 * @property {jQuery}
8906 this.$menu
= $( '<div>' );
8910 * @property {jQuery}
8912 this.$content
= $( '<div>' );
8916 .addClass( 'oo-ui-menuLayout-menu' );
8917 this.$content
.addClass( 'oo-ui-menuLayout-content' );
8919 .addClass( 'oo-ui-menuLayout' )
8920 .append( this.$content
, this.$menu
);
8921 this.setMenuPosition( config
.menuPosition
);
8922 this.toggleMenu( config
.showMenu
);
8927 OO
.inheritClass( OO
.ui
.MenuLayout
, OO
.ui
.Layout
);
8934 * @param {boolean} showMenu Show menu, omit to toggle
8937 OO
.ui
.MenuLayout
.prototype.toggleMenu = function ( showMenu
) {
8938 showMenu
= showMenu
=== undefined ? !this.showMenu
: !!showMenu
;
8940 if ( this.showMenu
!== showMenu
) {
8941 this.showMenu
= showMenu
;
8943 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu
)
8944 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu
);
8951 * Check if menu is visible
8953 * @return {boolean} Menu is visible
8955 OO
.ui
.MenuLayout
.prototype.isMenuVisible = function () {
8956 return this.showMenu
;
8960 * Set menu position.
8962 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
8963 * @throws {Error} If position value is not supported
8966 OO
.ui
.MenuLayout
.prototype.setMenuPosition = function ( position
) {
8967 this.$element
.removeClass( 'oo-ui-menuLayout-' + this.menuPosition
);
8968 this.menuPosition
= position
;
8969 this.$element
.addClass( 'oo-ui-menuLayout-' + position
);
8975 * Get menu position.
8977 * @return {string} Menu position
8979 OO
.ui
.MenuLayout
.prototype.getMenuPosition = function () {
8980 return this.menuPosition
;
8984 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
8985 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
8986 * through the pages and select which one to display. By default, only one page is
8987 * displayed at a time and the outline is hidden. When a user navigates to a new page,
8988 * the booklet layout automatically focuses on the first focusable element, unless the
8989 * default setting is changed. Optionally, booklets can be configured to show
8990 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
8993 * // Example of a BookletLayout that contains two PageLayouts.
8995 * function PageOneLayout( name, config ) {
8996 * PageOneLayout.super.call( this, name, config );
8997 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
8999 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9000 * PageOneLayout.prototype.setupOutlineItem = function () {
9001 * this.outlineItem.setLabel( 'Page One' );
9004 * function PageTwoLayout( name, config ) {
9005 * PageTwoLayout.super.call( this, name, config );
9006 * this.$element.append( '<p>Second page</p>' );
9008 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9009 * PageTwoLayout.prototype.setupOutlineItem = function () {
9010 * this.outlineItem.setLabel( 'Page Two' );
9013 * var page1 = new PageOneLayout( 'one' ),
9014 * page2 = new PageTwoLayout( 'two' );
9016 * var booklet = new OO.ui.BookletLayout( {
9020 * booklet.addPages ( [ page1, page2 ] );
9021 * $( 'body' ).append( booklet.$element );
9024 * @extends OO.ui.MenuLayout
9027 * @param {Object} [config] Configuration options
9028 * @cfg {boolean} [continuous=false] Show all pages, one after another
9029 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9030 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9031 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9033 OO
.ui
.BookletLayout
= function OoUiBookletLayout( config
) {
9034 // Configuration initialization
9035 config
= config
|| {};
9037 // Parent constructor
9038 OO
.ui
.BookletLayout
.super.call( this, config
);
9041 this.currentPageName
= null;
9043 this.ignoreFocus
= false;
9044 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
9045 this.$content
.append( this.stackLayout
.$element
);
9046 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
9047 this.outlineVisible
= false;
9048 this.outlined
= !!config
.outlined
;
9049 if ( this.outlined
) {
9050 this.editable
= !!config
.editable
;
9051 this.outlineControlsWidget
= null;
9052 this.outlineSelectWidget
= new OO
.ui
.OutlineSelectWidget();
9053 this.outlinePanel
= new OO
.ui
.PanelLayout( { scrollable
: true } );
9054 this.$menu
.append( this.outlinePanel
.$element
);
9055 this.outlineVisible
= true;
9056 if ( this.editable
) {
9057 this.outlineControlsWidget
= new OO
.ui
.OutlineControlsWidget(
9058 this.outlineSelectWidget
9062 this.toggleMenu( this.outlined
);
9065 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
9066 if ( this.outlined
) {
9067 this.outlineSelectWidget
.connect( this, { select
: 'onOutlineSelectWidgetSelect' } );
9069 if ( this.autoFocus
) {
9070 // Event 'focus' does not bubble, but 'focusin' does
9071 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
9075 this.$element
.addClass( 'oo-ui-bookletLayout' );
9076 this.stackLayout
.$element
.addClass( 'oo-ui-bookletLayout-stackLayout' );
9077 if ( this.outlined
) {
9078 this.outlinePanel
.$element
9079 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
9080 .append( this.outlineSelectWidget
.$element
);
9081 if ( this.editable
) {
9082 this.outlinePanel
.$element
9083 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
9084 .append( this.outlineControlsWidget
.$element
);
9091 OO
.inheritClass( OO
.ui
.BookletLayout
, OO
.ui
.MenuLayout
);
9096 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
9098 * @param {OO.ui.PageLayout} page Current page
9102 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
9105 * @param {OO.ui.PageLayout[]} page Added pages
9106 * @param {number} index Index pages were added at
9110 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
9111 * {@link #removePages removed} from the booklet.
9114 * @param {OO.ui.PageLayout[]} pages Removed pages
9120 * Handle stack layout focus.
9123 * @param {jQuery.Event} e Focusin event
9125 OO
.ui
.BookletLayout
.prototype.onStackLayoutFocus = function ( e
) {
9128 // Find the page that an element was focused within
9129 $target
= $( e
.target
).closest( '.oo-ui-pageLayout' );
9130 for ( name
in this.pages
) {
9131 // Check for page match, exclude current page to find only page changes
9132 if ( this.pages
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentPageName
) {
9133 this.setPage( name
);
9140 * Handle stack layout set events.
9143 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
9145 OO
.ui
.BookletLayout
.prototype.onStackLayoutSet = function ( page
) {
9148 page
.scrollElementIntoView( { complete: function () {
9149 if ( layout
.autoFocus
) {
9157 * Focus the first input in the current page.
9159 * If no page is selected, the first selectable page will be selected.
9160 * If the focus is already in an element on the current page, nothing will happen.
9161 * @param {number} [itemIndex] A specific item to focus on
9163 OO
.ui
.BookletLayout
.prototype.focus = function ( itemIndex
) {
9165 items
= this.stackLayout
.getItems();
9167 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
9168 page
= items
[ itemIndex
];
9170 page
= this.stackLayout
.getCurrentItem();
9173 if ( !page
&& this.outlined
) {
9174 this.selectFirstSelectablePage();
9175 page
= this.stackLayout
.getCurrentItem();
9180 // Only change the focus if is not already in the current page
9181 if ( !page
.$element
.find( ':focus' ).length
) {
9182 $input
= page
.$element
.find( ':input:first' );
9183 if ( $input
.length
) {
9184 $input
[ 0 ].focus();
9190 * Find the first focusable input in the booklet layout and focus
9193 OO
.ui
.BookletLayout
.prototype.focusFirstFocusable = function () {
9196 items
= this.stackLayout
.getItems(),
9197 checkAndFocus = function () {
9198 if ( OO
.ui
.isFocusableElement( $( this ) ) ) {
9205 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
9209 // Find all potentially focusable elements in the item
9210 // and check if they are focusable
9212 .find( 'input, select, textarea, button, object' )
9213 /* jshint loopfunc:true */
9214 .each( checkAndFocus
);
9219 * Handle outline widget select events.
9222 * @param {OO.ui.OptionWidget|null} item Selected item
9224 OO
.ui
.BookletLayout
.prototype.onOutlineSelectWidgetSelect = function ( item
) {
9226 this.setPage( item
.getData() );
9231 * Check if booklet has an outline.
9233 * @return {boolean} Booklet has an outline
9235 OO
.ui
.BookletLayout
.prototype.isOutlined = function () {
9236 return this.outlined
;
9240 * Check if booklet has editing controls.
9242 * @return {boolean} Booklet is editable
9244 OO
.ui
.BookletLayout
.prototype.isEditable = function () {
9245 return this.editable
;
9249 * Check if booklet has a visible outline.
9251 * @return {boolean} Outline is visible
9253 OO
.ui
.BookletLayout
.prototype.isOutlineVisible = function () {
9254 return this.outlined
&& this.outlineVisible
;
9258 * Hide or show the outline.
9260 * @param {boolean} [show] Show outline, omit to invert current state
9263 OO
.ui
.BookletLayout
.prototype.toggleOutline = function ( show
) {
9264 if ( this.outlined
) {
9265 show
= show
=== undefined ? !this.outlineVisible
: !!show
;
9266 this.outlineVisible
= show
;
9267 this.toggleMenu( show
);
9274 * Get the page closest to the specified page.
9276 * @param {OO.ui.PageLayout} page Page to use as a reference point
9277 * @return {OO.ui.PageLayout|null} Page closest to the specified page
9279 OO
.ui
.BookletLayout
.prototype.getClosestPage = function ( page
) {
9280 var next
, prev
, level
,
9281 pages
= this.stackLayout
.getItems(),
9282 index
= $.inArray( page
, pages
);
9284 if ( index
!== -1 ) {
9285 next
= pages
[ index
+ 1 ];
9286 prev
= pages
[ index
- 1 ];
9287 // Prefer adjacent pages at the same level
9288 if ( this.outlined
) {
9289 level
= this.outlineSelectWidget
.getItemFromData( page
.getName() ).getLevel();
9292 level
=== this.outlineSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
9298 level
=== this.outlineSelectWidget
.getItemFromData( next
.getName() ).getLevel()
9304 return prev
|| next
|| null;
9308 * Get the outline widget.
9310 * If the booklet is not outlined, the method will return `null`.
9312 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
9314 OO
.ui
.BookletLayout
.prototype.getOutline = function () {
9315 return this.outlineSelectWidget
;
9319 * Get the outline controls widget.
9321 * If the outline is not editable, the method will return `null`.
9323 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
9325 OO
.ui
.BookletLayout
.prototype.getOutlineControls = function () {
9326 return this.outlineControlsWidget
;
9330 * Get a page by its symbolic name.
9332 * @param {string} name Symbolic name of page
9333 * @return {OO.ui.PageLayout|undefined} Page, if found
9335 OO
.ui
.BookletLayout
.prototype.getPage = function ( name
) {
9336 return this.pages
[ name
];
9340 * Get the current page.
9342 * @return {OO.ui.PageLayout|undefined} Current page, if found
9344 OO
.ui
.BookletLayout
.prototype.getCurrentPage = function () {
9345 var name
= this.getCurrentPageName();
9346 return name
? this.getPage( name
) : undefined;
9350 * Get the symbolic name of the current page.
9352 * @return {string|null} Symbolic name of the current page
9354 OO
.ui
.BookletLayout
.prototype.getCurrentPageName = function () {
9355 return this.currentPageName
;
9359 * Add pages to the booklet layout
9361 * When pages are added with the same names as existing pages, the existing pages will be
9362 * automatically removed before the new pages are added.
9364 * @param {OO.ui.PageLayout[]} pages Pages to add
9365 * @param {number} index Index of the insertion point
9369 OO
.ui
.BookletLayout
.prototype.addPages = function ( pages
, index
) {
9370 var i
, len
, name
, page
, item
, currentIndex
,
9371 stackLayoutPages
= this.stackLayout
.getItems(),
9375 // Remove pages with same names
9376 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9378 name
= page
.getName();
9380 if ( Object
.prototype.hasOwnProperty
.call( this.pages
, name
) ) {
9381 // Correct the insertion index
9382 currentIndex
= $.inArray( this.pages
[ name
], stackLayoutPages
);
9383 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
9386 remove
.push( this.pages
[ name
] );
9389 if ( remove
.length
) {
9390 this.removePages( remove
);
9394 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9396 name
= page
.getName();
9397 this.pages
[ page
.getName() ] = page
;
9398 if ( this.outlined
) {
9399 item
= new OO
.ui
.OutlineOptionWidget( { data
: name
} );
9400 page
.setOutlineItem( item
);
9405 if ( this.outlined
&& items
.length
) {
9406 this.outlineSelectWidget
.addItems( items
, index
);
9407 this.selectFirstSelectablePage();
9409 this.stackLayout
.addItems( pages
, index
);
9410 this.emit( 'add', pages
, index
);
9416 * Remove the specified pages from the booklet layout.
9418 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
9420 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
9424 OO
.ui
.BookletLayout
.prototype.removePages = function ( pages
) {
9425 var i
, len
, name
, page
,
9428 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9430 name
= page
.getName();
9431 delete this.pages
[ name
];
9432 if ( this.outlined
) {
9433 items
.push( this.outlineSelectWidget
.getItemFromData( name
) );
9434 page
.setOutlineItem( null );
9437 if ( this.outlined
&& items
.length
) {
9438 this.outlineSelectWidget
.removeItems( items
);
9439 this.selectFirstSelectablePage();
9441 this.stackLayout
.removeItems( pages
);
9442 this.emit( 'remove', pages
);
9448 * Clear all pages from the booklet layout.
9450 * To remove only a subset of pages from the booklet, use the #removePages method.
9455 OO
.ui
.BookletLayout
.prototype.clearPages = function () {
9457 pages
= this.stackLayout
.getItems();
9460 this.currentPageName
= null;
9461 if ( this.outlined
) {
9462 this.outlineSelectWidget
.clearItems();
9463 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9464 pages
[ i
].setOutlineItem( null );
9467 this.stackLayout
.clearItems();
9469 this.emit( 'remove', pages
);
9475 * Set the current page by symbolic name.
9478 * @param {string} name Symbolic name of page
9480 OO
.ui
.BookletLayout
.prototype.setPage = function ( name
) {
9483 page
= this.pages
[ name
];
9485 if ( name
!== this.currentPageName
) {
9486 if ( this.outlined
) {
9487 selectedItem
= this.outlineSelectWidget
.getSelectedItem();
9488 if ( selectedItem
&& selectedItem
.getData() !== name
) {
9489 this.outlineSelectWidget
.selectItemByData( name
);
9493 if ( this.currentPageName
&& this.pages
[ this.currentPageName
] ) {
9494 this.pages
[ this.currentPageName
].setActive( false );
9495 // Blur anything focused if the next page doesn't have anything focusable - this
9496 // is not needed if the next page has something focusable because once it is focused
9497 // this blur happens automatically
9498 if ( this.autoFocus
&& !page
.$element
.find( ':input' ).length
) {
9499 $focused
= this.pages
[ this.currentPageName
].$element
.find( ':focus' );
9500 if ( $focused
.length
) {
9501 $focused
[ 0 ].blur();
9505 this.currentPageName
= name
;
9506 this.stackLayout
.setItem( page
);
9507 page
.setActive( true );
9508 this.emit( 'set', page
);
9514 * Select the first selectable page.
9518 OO
.ui
.BookletLayout
.prototype.selectFirstSelectablePage = function () {
9519 if ( !this.outlineSelectWidget
.getSelectedItem() ) {
9520 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getFirstSelectableItem() );
9527 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
9528 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
9529 * select which one to display. By default, only one card is displayed at a time. When a user
9530 * navigates to a new card, the index layout automatically focuses on the first focusable element,
9531 * unless the default setting is changed.
9533 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
9536 * // Example of a IndexLayout that contains two CardLayouts.
9538 * function CardOneLayout( name, config ) {
9539 * CardOneLayout.super.call( this, name, config );
9540 * this.$element.append( '<p>First card</p>' );
9542 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
9543 * CardOneLayout.prototype.setupTabItem = function () {
9544 * this.tabItem.setLabel( 'Card One' );
9547 * function CardTwoLayout( name, config ) {
9548 * CardTwoLayout.super.call( this, name, config );
9549 * this.$element.append( '<p>Second card</p>' );
9551 * OO.inheritClass( CardTwoLayout, OO.ui.CardLayout );
9552 * CardTwoLayout.prototype.setupTabItem = function () {
9553 * this.tabItem.setLabel( 'Card Two' );
9556 * var card1 = new CardOneLayout( 'one' ),
9557 * card2 = new CardTwoLayout( 'two' );
9559 * var index = new OO.ui.IndexLayout();
9561 * index.addCards ( [ card1, card2 ] );
9562 * $( 'body' ).append( index.$element );
9565 * @extends OO.ui.MenuLayout
9568 * @param {Object} [config] Configuration options
9569 * @cfg {boolean} [continuous=false] Show all cards, one after another
9570 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
9572 OO
.ui
.IndexLayout
= function OoUiIndexLayout( config
) {
9573 // Configuration initialization
9574 config
= $.extend( {}, config
, { menuPosition
: 'top' } );
9576 // Parent constructor
9577 OO
.ui
.IndexLayout
.super.call( this, config
);
9580 this.currentCardName
= null;
9582 this.ignoreFocus
= false;
9583 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
9584 this.$content
.append( this.stackLayout
.$element
);
9585 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
9587 this.tabSelectWidget
= new OO
.ui
.TabSelectWidget();
9588 this.tabPanel
= new OO
.ui
.PanelLayout();
9589 this.$menu
.append( this.tabPanel
.$element
);
9591 this.toggleMenu( true );
9594 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
9595 this.tabSelectWidget
.connect( this, { select
: 'onTabSelectWidgetSelect' } );
9596 if ( this.autoFocus
) {
9597 // Event 'focus' does not bubble, but 'focusin' does
9598 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
9602 this.$element
.addClass( 'oo-ui-indexLayout' );
9603 this.stackLayout
.$element
.addClass( 'oo-ui-indexLayout-stackLayout' );
9604 this.tabPanel
.$element
9605 .addClass( 'oo-ui-indexLayout-tabPanel' )
9606 .append( this.tabSelectWidget
.$element
);
9611 OO
.inheritClass( OO
.ui
.IndexLayout
, OO
.ui
.MenuLayout
);
9616 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
9618 * @param {OO.ui.CardLayout} card Current card
9622 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
9625 * @param {OO.ui.CardLayout[]} card Added cards
9626 * @param {number} index Index cards were added at
9630 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
9631 * {@link #removeCards removed} from the index.
9634 * @param {OO.ui.CardLayout[]} cards Removed cards
9640 * Handle stack layout focus.
9643 * @param {jQuery.Event} e Focusin event
9645 OO
.ui
.IndexLayout
.prototype.onStackLayoutFocus = function ( e
) {
9648 // Find the card that an element was focused within
9649 $target
= $( e
.target
).closest( '.oo-ui-cardLayout' );
9650 for ( name
in this.cards
) {
9651 // Check for card match, exclude current card to find only card changes
9652 if ( this.cards
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentCardName
) {
9653 this.setCard( name
);
9660 * Handle stack layout set events.
9663 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
9665 OO
.ui
.IndexLayout
.prototype.onStackLayoutSet = function ( card
) {
9668 card
.scrollElementIntoView( { complete: function () {
9669 if ( layout
.autoFocus
) {
9677 * Focus the first input in the current card.
9679 * If no card is selected, the first selectable card will be selected.
9680 * If the focus is already in an element on the current card, nothing will happen.
9681 * @param {number} [itemIndex] A specific item to focus on
9683 OO
.ui
.IndexLayout
.prototype.focus = function ( itemIndex
) {
9685 items
= this.stackLayout
.getItems();
9687 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
9688 card
= items
[ itemIndex
];
9690 card
= this.stackLayout
.getCurrentItem();
9694 this.selectFirstSelectableCard();
9695 card
= this.stackLayout
.getCurrentItem();
9700 // Only change the focus if is not already in the current card
9701 if ( !card
.$element
.find( ':focus' ).length
) {
9702 $input
= card
.$element
.find( ':input:first' );
9703 if ( $input
.length
) {
9704 $input
[ 0 ].focus();
9710 * Find the first focusable input in the index layout and focus
9713 OO
.ui
.IndexLayout
.prototype.focusFirstFocusable = function () {
9716 items
= this.stackLayout
.getItems(),
9717 checkAndFocus = function () {
9718 if ( OO
.ui
.isFocusableElement( $( this ) ) ) {
9725 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
9729 // Find all potentially focusable elements in the item
9730 // and check if they are focusable
9732 .find( 'input, select, textarea, button, object' )
9733 .each( checkAndFocus
);
9738 * Handle tab widget select events.
9741 * @param {OO.ui.OptionWidget|null} item Selected item
9743 OO
.ui
.IndexLayout
.prototype.onTabSelectWidgetSelect = function ( item
) {
9745 this.setCard( item
.getData() );
9750 * Get the card closest to the specified card.
9752 * @param {OO.ui.CardLayout} card Card to use as a reference point
9753 * @return {OO.ui.CardLayout|null} Card closest to the specified card
9755 OO
.ui
.IndexLayout
.prototype.getClosestCard = function ( card
) {
9756 var next
, prev
, level
,
9757 cards
= this.stackLayout
.getItems(),
9758 index
= $.inArray( card
, cards
);
9760 if ( index
!== -1 ) {
9761 next
= cards
[ index
+ 1 ];
9762 prev
= cards
[ index
- 1 ];
9763 // Prefer adjacent cards at the same level
9764 level
= this.tabSelectWidget
.getItemFromData( card
.getName() ).getLevel();
9767 level
=== this.tabSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
9773 level
=== this.tabSelectWidget
.getItemFromData( next
.getName() ).getLevel()
9778 return prev
|| next
|| null;
9782 * Get the tabs widget.
9784 * @return {OO.ui.TabSelectWidget} Tabs widget
9786 OO
.ui
.IndexLayout
.prototype.getTabs = function () {
9787 return this.tabSelectWidget
;
9791 * Get a card by its symbolic name.
9793 * @param {string} name Symbolic name of card
9794 * @return {OO.ui.CardLayout|undefined} Card, if found
9796 OO
.ui
.IndexLayout
.prototype.getCard = function ( name
) {
9797 return this.cards
[ name
];
9801 * Get the current card.
9803 * @return {OO.ui.CardLayout|undefined} Current card, if found
9805 OO
.ui
.IndexLayout
.prototype.getCurrentCard = function () {
9806 var name
= this.getCurrentCardName();
9807 return name
? this.getCard( name
) : undefined;
9811 * Get the symbolic name of the current card.
9813 * @return {string|null} Symbolic name of the current card
9815 OO
.ui
.IndexLayout
.prototype.getCurrentCardName = function () {
9816 return this.currentCardName
;
9820 * Add cards to the index layout
9822 * When cards are added with the same names as existing cards, the existing cards will be
9823 * automatically removed before the new cards are added.
9825 * @param {OO.ui.CardLayout[]} cards Cards to add
9826 * @param {number} index Index of the insertion point
9830 OO
.ui
.IndexLayout
.prototype.addCards = function ( cards
, index
) {
9831 var i
, len
, name
, card
, item
, currentIndex
,
9832 stackLayoutCards
= this.stackLayout
.getItems(),
9836 // Remove cards with same names
9837 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
9839 name
= card
.getName();
9841 if ( Object
.prototype.hasOwnProperty
.call( this.cards
, name
) ) {
9842 // Correct the insertion index
9843 currentIndex
= $.inArray( this.cards
[ name
], stackLayoutCards
);
9844 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
9847 remove
.push( this.cards
[ name
] );
9850 if ( remove
.length
) {
9851 this.removeCards( remove
);
9855 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
9857 name
= card
.getName();
9858 this.cards
[ card
.getName() ] = card
;
9859 item
= new OO
.ui
.TabOptionWidget( { data
: name
} );
9860 card
.setTabItem( item
);
9864 if ( items
.length
) {
9865 this.tabSelectWidget
.addItems( items
, index
);
9866 this.selectFirstSelectableCard();
9868 this.stackLayout
.addItems( cards
, index
);
9869 this.emit( 'add', cards
, index
);
9875 * Remove the specified cards from the index layout.
9877 * To remove all cards from the index, you may wish to use the #clearCards method instead.
9879 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
9883 OO
.ui
.IndexLayout
.prototype.removeCards = function ( cards
) {
9884 var i
, len
, name
, card
,
9887 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
9889 name
= card
.getName();
9890 delete this.cards
[ name
];
9891 items
.push( this.tabSelectWidget
.getItemFromData( name
) );
9892 card
.setTabItem( null );
9894 if ( items
.length
) {
9895 this.tabSelectWidget
.removeItems( items
);
9896 this.selectFirstSelectableCard();
9898 this.stackLayout
.removeItems( cards
);
9899 this.emit( 'remove', cards
);
9905 * Clear all cards from the index layout.
9907 * To remove only a subset of cards from the index, use the #removeCards method.
9912 OO
.ui
.IndexLayout
.prototype.clearCards = function () {
9914 cards
= this.stackLayout
.getItems();
9917 this.currentCardName
= null;
9918 this.tabSelectWidget
.clearItems();
9919 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
9920 cards
[ i
].setTabItem( null );
9922 this.stackLayout
.clearItems();
9924 this.emit( 'remove', cards
);
9930 * Set the current card by symbolic name.
9933 * @param {string} name Symbolic name of card
9935 OO
.ui
.IndexLayout
.prototype.setCard = function ( name
) {
9938 card
= this.cards
[ name
];
9940 if ( name
!== this.currentCardName
) {
9941 selectedItem
= this.tabSelectWidget
.getSelectedItem();
9942 if ( selectedItem
&& selectedItem
.getData() !== name
) {
9943 this.tabSelectWidget
.selectItemByData( name
);
9946 if ( this.currentCardName
&& this.cards
[ this.currentCardName
] ) {
9947 this.cards
[ this.currentCardName
].setActive( false );
9948 // Blur anything focused if the next card doesn't have anything focusable - this
9949 // is not needed if the next card has something focusable because once it is focused
9950 // this blur happens automatically
9951 if ( this.autoFocus
&& !card
.$element
.find( ':input' ).length
) {
9952 $focused
= this.cards
[ this.currentCardName
].$element
.find( ':focus' );
9953 if ( $focused
.length
) {
9954 $focused
[ 0 ].blur();
9958 this.currentCardName
= name
;
9959 this.stackLayout
.setItem( card
);
9960 card
.setActive( true );
9961 this.emit( 'set', card
);
9967 * Select the first selectable card.
9971 OO
.ui
.IndexLayout
.prototype.selectFirstSelectableCard = function () {
9972 if ( !this.tabSelectWidget
.getSelectedItem() ) {
9973 this.tabSelectWidget
.selectItem( this.tabSelectWidget
.getFirstSelectableItem() );
9980 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
9981 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
9984 * // Example of a panel layout
9985 * var panel = new OO.ui.PanelLayout( {
9989 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
9991 * $( 'body' ).append( panel.$element );
9994 * @extends OO.ui.Layout
9997 * @param {Object} [config] Configuration options
9998 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
9999 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10000 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10001 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10003 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
10004 // Configuration initialization
10005 config
= $.extend( {
10012 // Parent constructor
10013 OO
.ui
.PanelLayout
.super.call( this, config
);
10016 this.$element
.addClass( 'oo-ui-panelLayout' );
10017 if ( config
.scrollable
) {
10018 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
10020 if ( config
.padded
) {
10021 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
10023 if ( config
.expanded
) {
10024 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
10026 if ( config
.framed
) {
10027 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
10033 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
10036 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10037 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10038 * rather extended to include the required content and functionality.
10040 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10041 * item is customized (with a label) using the #setupTabItem method. See
10042 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10045 * @extends OO.ui.PanelLayout
10048 * @param {string} name Unique symbolic name of card
10049 * @param {Object} [config] Configuration options
10051 OO
.ui
.CardLayout
= function OoUiCardLayout( name
, config
) {
10052 // Allow passing positional parameters inside the config object
10053 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
10055 name
= config
.name
;
10058 // Configuration initialization
10059 config
= $.extend( { scrollable
: true }, config
);
10061 // Parent constructor
10062 OO
.ui
.CardLayout
.super.call( this, config
);
10066 this.tabItem
= null;
10067 this.active
= false;
10070 this.$element
.addClass( 'oo-ui-cardLayout' );
10075 OO
.inheritClass( OO
.ui
.CardLayout
, OO
.ui
.PanelLayout
);
10080 * An 'active' event is emitted when the card becomes active. Cards become active when they are
10081 * shown in a index layout that is configured to display only one card at a time.
10084 * @param {boolean} active Card is active
10090 * Get the symbolic name of the card.
10092 * @return {string} Symbolic name of card
10094 OO
.ui
.CardLayout
.prototype.getName = function () {
10099 * Check if card is active.
10101 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
10102 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
10104 * @return {boolean} Card is active
10106 OO
.ui
.CardLayout
.prototype.isActive = function () {
10107 return this.active
;
10113 * The tab item allows users to access the card from the index's tab
10114 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
10116 * @return {OO.ui.TabOptionWidget|null} Tab option widget
10118 OO
.ui
.CardLayout
.prototype.getTabItem = function () {
10119 return this.tabItem
;
10123 * Set or unset the tab item.
10125 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
10126 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
10127 * level), use #setupTabItem instead of this method.
10129 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
10132 OO
.ui
.CardLayout
.prototype.setTabItem = function ( tabItem
) {
10133 this.tabItem
= tabItem
|| null;
10135 this.setupTabItem();
10141 * Set up the tab item.
10143 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
10144 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
10145 * the #setTabItem method instead.
10147 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
10150 OO
.ui
.CardLayout
.prototype.setupTabItem = function () {
10155 * Set the card to its 'active' state.
10157 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
10158 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
10159 * context, setting the active state on a card does nothing.
10161 * @param {boolean} value Card is active
10164 OO
.ui
.CardLayout
.prototype.setActive = function ( active
) {
10167 if ( active
!== this.active
) {
10168 this.active
= active
;
10169 this.$element
.toggleClass( 'oo-ui-cardLayout-active', this.active
);
10170 this.emit( 'active', this.active
);
10175 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
10176 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
10177 * rather extended to include the required content and functionality.
10179 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
10180 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
10181 * {@link OO.ui.BookletLayout BookletLayout} for an example.
10184 * @extends OO.ui.PanelLayout
10187 * @param {string} name Unique symbolic name of page
10188 * @param {Object} [config] Configuration options
10190 OO
.ui
.PageLayout
= function OoUiPageLayout( name
, config
) {
10191 // Allow passing positional parameters inside the config object
10192 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
10194 name
= config
.name
;
10197 // Configuration initialization
10198 config
= $.extend( { scrollable
: true }, config
);
10200 // Parent constructor
10201 OO
.ui
.PageLayout
.super.call( this, config
);
10205 this.outlineItem
= null;
10206 this.active
= false;
10209 this.$element
.addClass( 'oo-ui-pageLayout' );
10214 OO
.inheritClass( OO
.ui
.PageLayout
, OO
.ui
.PanelLayout
);
10219 * An 'active' event is emitted when the page becomes active. Pages become active when they are
10220 * shown in a booklet layout that is configured to display only one page at a time.
10223 * @param {boolean} active Page is active
10229 * Get the symbolic name of the page.
10231 * @return {string} Symbolic name of page
10233 OO
.ui
.PageLayout
.prototype.getName = function () {
10238 * Check if page is active.
10240 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
10241 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
10243 * @return {boolean} Page is active
10245 OO
.ui
.PageLayout
.prototype.isActive = function () {
10246 return this.active
;
10250 * Get outline item.
10252 * The outline item allows users to access the page from the booklet's outline
10253 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
10255 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
10257 OO
.ui
.PageLayout
.prototype.getOutlineItem = function () {
10258 return this.outlineItem
;
10262 * Set or unset the outline item.
10264 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
10265 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
10266 * level), use #setupOutlineItem instead of this method.
10268 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
10271 OO
.ui
.PageLayout
.prototype.setOutlineItem = function ( outlineItem
) {
10272 this.outlineItem
= outlineItem
|| null;
10273 if ( outlineItem
) {
10274 this.setupOutlineItem();
10280 * Set up the outline item.
10282 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
10283 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
10284 * the #setOutlineItem method instead.
10286 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
10289 OO
.ui
.PageLayout
.prototype.setupOutlineItem = function () {
10294 * Set the page to its 'active' state.
10296 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
10297 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
10298 * context, setting the active state on a page does nothing.
10300 * @param {boolean} value Page is active
10303 OO
.ui
.PageLayout
.prototype.setActive = function ( active
) {
10306 if ( active
!== this.active
) {
10307 this.active
= active
;
10308 this.$element
.toggleClass( 'oo-ui-pageLayout-active', active
);
10309 this.emit( 'active', this.active
);
10314 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
10315 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
10316 * by setting the #continuous option to 'true'.
10319 * // A stack layout with two panels, configured to be displayed continously
10320 * var myStack = new OO.ui.StackLayout( {
10322 * new OO.ui.PanelLayout( {
10323 * $content: $( '<p>Panel One</p>' ),
10327 * new OO.ui.PanelLayout( {
10328 * $content: $( '<p>Panel Two</p>' ),
10335 * $( 'body' ).append( myStack.$element );
10338 * @extends OO.ui.PanelLayout
10339 * @mixins OO.ui.mixin.GroupElement
10342 * @param {Object} [config] Configuration options
10343 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
10344 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
10346 OO
.ui
.StackLayout
= function OoUiStackLayout( config
) {
10347 // Configuration initialization
10348 config
= $.extend( { scrollable
: true }, config
);
10350 // Parent constructor
10351 OO
.ui
.StackLayout
.super.call( this, config
);
10353 // Mixin constructors
10354 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
10357 this.currentItem
= null;
10358 this.continuous
= !!config
.continuous
;
10361 this.$element
.addClass( 'oo-ui-stackLayout' );
10362 if ( this.continuous
) {
10363 this.$element
.addClass( 'oo-ui-stackLayout-continuous' );
10365 if ( Array
.isArray( config
.items
) ) {
10366 this.addItems( config
.items
);
10372 OO
.inheritClass( OO
.ui
.StackLayout
, OO
.ui
.PanelLayout
);
10373 OO
.mixinClass( OO
.ui
.StackLayout
, OO
.ui
.mixin
.GroupElement
);
10378 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
10379 * {@link #clearItems cleared} or {@link #setItem displayed}.
10382 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
10388 * Get the current panel.
10390 * @return {OO.ui.Layout|null}
10392 OO
.ui
.StackLayout
.prototype.getCurrentItem = function () {
10393 return this.currentItem
;
10397 * Unset the current item.
10400 * @param {OO.ui.StackLayout} layout
10403 OO
.ui
.StackLayout
.prototype.unsetCurrentItem = function () {
10404 var prevItem
= this.currentItem
;
10405 if ( prevItem
=== null ) {
10409 this.currentItem
= null;
10410 this.emit( 'set', null );
10414 * Add panel layouts to the stack layout.
10416 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
10417 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
10420 * @param {OO.ui.Layout[]} items Panels to add
10421 * @param {number} [index] Index of the insertion point
10424 OO
.ui
.StackLayout
.prototype.addItems = function ( items
, index
) {
10425 // Update the visibility
10426 this.updateHiddenState( items
, this.currentItem
);
10429 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
, index
);
10431 if ( !this.currentItem
&& items
.length
) {
10432 this.setItem( items
[ 0 ] );
10439 * Remove the specified panels from the stack layout.
10441 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
10442 * you may wish to use the #clearItems method instead.
10444 * @param {OO.ui.Layout[]} items Panels to remove
10448 OO
.ui
.StackLayout
.prototype.removeItems = function ( items
) {
10450 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
10452 if ( $.inArray( this.currentItem
, items
) !== -1 ) {
10453 if ( this.items
.length
) {
10454 this.setItem( this.items
[ 0 ] );
10456 this.unsetCurrentItem();
10464 * Clear all panels from the stack layout.
10466 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
10467 * a subset of panels, use the #removeItems method.
10472 OO
.ui
.StackLayout
.prototype.clearItems = function () {
10473 this.unsetCurrentItem();
10474 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
10480 * Show the specified panel.
10482 * If another panel is currently displayed, it will be hidden.
10484 * @param {OO.ui.Layout} item Panel to show
10488 OO
.ui
.StackLayout
.prototype.setItem = function ( item
) {
10489 if ( item
!== this.currentItem
) {
10490 this.updateHiddenState( this.items
, item
);
10492 if ( $.inArray( item
, this.items
) !== -1 ) {
10493 this.currentItem
= item
;
10494 this.emit( 'set', item
);
10496 this.unsetCurrentItem();
10504 * Update the visibility of all items in case of non-continuous view.
10506 * Ensure all items are hidden except for the selected one.
10507 * This method does nothing when the stack is continuous.
10510 * @param {OO.ui.Layout[]} items Item list iterate over
10511 * @param {OO.ui.Layout} [selectedItem] Selected item to show
10513 OO
.ui
.StackLayout
.prototype.updateHiddenState = function ( items
, selectedItem
) {
10516 if ( !this.continuous
) {
10517 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
10518 if ( !selectedItem
|| selectedItem
!== items
[ i
] ) {
10519 items
[ i
].$element
.addClass( 'oo-ui-element-hidden' );
10522 if ( selectedItem
) {
10523 selectedItem
.$element
.removeClass( 'oo-ui-element-hidden' );
10529 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
10530 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
10531 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
10532 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
10535 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
10539 * // Example of a BarToolGroup with two tools
10540 * var toolFactory = new OO.ui.ToolFactory();
10541 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
10542 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
10544 * // We will be placing status text in this element when tools are used
10545 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
10547 * // Define the tools that we're going to place in our toolbar
10549 * // Create a class inheriting from OO.ui.Tool
10550 * function PictureTool() {
10551 * PictureTool.super.apply( this, arguments );
10553 * OO.inheritClass( PictureTool, OO.ui.Tool );
10554 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
10555 * // of 'icon' and 'title' (displayed icon and text).
10556 * PictureTool.static.name = 'picture';
10557 * PictureTool.static.icon = 'picture';
10558 * PictureTool.static.title = 'Insert picture';
10559 * // Defines the action that will happen when this tool is selected (clicked).
10560 * PictureTool.prototype.onSelect = function () {
10561 * $area.text( 'Picture tool clicked!' );
10562 * // Never display this tool as "active" (selected).
10563 * this.setActive( false );
10565 * // Make this tool available in our toolFactory and thus our toolbar
10566 * toolFactory.register( PictureTool );
10568 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
10569 * // little popup window (a PopupWidget).
10570 * function HelpTool( toolGroup, config ) {
10571 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
10576 * this.popup.$body.append( '<p>I am helpful!</p>' );
10578 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
10579 * HelpTool.static.name = 'help';
10580 * HelpTool.static.icon = 'help';
10581 * HelpTool.static.title = 'Help';
10582 * toolFactory.register( HelpTool );
10584 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
10585 * // used once (but not all defined tools must be used).
10588 * // 'bar' tool groups display tools by icon only
10590 * include: [ 'picture', 'help' ]
10594 * // Create some UI around the toolbar and place it in the document
10595 * var frame = new OO.ui.PanelLayout( {
10599 * var contentFrame = new OO.ui.PanelLayout( {
10603 * frame.$element.append(
10604 * toolbar.$element,
10605 * contentFrame.$element.append( $area )
10607 * $( 'body' ).append( frame.$element );
10609 * // Here is where the toolbar is actually built. This must be done after inserting it into the
10611 * toolbar.initialize();
10613 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
10614 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
10616 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
10619 * @extends OO.ui.ToolGroup
10622 * @param {OO.ui.Toolbar} toolbar
10623 * @param {Object} [config] Configuration options
10625 OO
.ui
.BarToolGroup
= function OoUiBarToolGroup( toolbar
, config
) {
10626 // Allow passing positional parameters inside the config object
10627 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
10629 toolbar
= config
.toolbar
;
10632 // Parent constructor
10633 OO
.ui
.BarToolGroup
.super.call( this, toolbar
, config
);
10636 this.$element
.addClass( 'oo-ui-barToolGroup' );
10641 OO
.inheritClass( OO
.ui
.BarToolGroup
, OO
.ui
.ToolGroup
);
10643 /* Static Properties */
10645 OO
.ui
.BarToolGroup
.static.titleTooltips
= true;
10647 OO
.ui
.BarToolGroup
.static.accelTooltips
= true;
10649 OO
.ui
.BarToolGroup
.static.name
= 'bar';
10652 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
10653 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
10654 * optional icon and label. This class can be used for other base classes that also use this functionality.
10658 * @extends OO.ui.ToolGroup
10659 * @mixins OO.ui.mixin.IconElement
10660 * @mixins OO.ui.mixin.IndicatorElement
10661 * @mixins OO.ui.mixin.LabelElement
10662 * @mixins OO.ui.mixin.TitledElement
10663 * @mixins OO.ui.mixin.ClippableElement
10664 * @mixins OO.ui.mixin.TabIndexedElement
10667 * @param {OO.ui.Toolbar} toolbar
10668 * @param {Object} [config] Configuration options
10669 * @cfg {string} [header] Text to display at the top of the popup
10671 OO
.ui
.PopupToolGroup
= function OoUiPopupToolGroup( toolbar
, config
) {
10672 // Allow passing positional parameters inside the config object
10673 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
10675 toolbar
= config
.toolbar
;
10678 // Configuration initialization
10679 config
= config
|| {};
10681 // Parent constructor
10682 OO
.ui
.PopupToolGroup
.super.call( this, toolbar
, config
);
10685 this.active
= false;
10686 this.dragging
= false;
10687 this.onBlurHandler
= this.onBlur
.bind( this );
10688 this.$handle
= $( '<span>' );
10690 // Mixin constructors
10691 OO
.ui
.mixin
.IconElement
.call( this, config
);
10692 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
10693 OO
.ui
.mixin
.LabelElement
.call( this, config
);
10694 OO
.ui
.mixin
.TitledElement
.call( this, config
);
10695 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
10696 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
10700 keydown
: this.onHandleMouseKeyDown
.bind( this ),
10701 keyup
: this.onHandleMouseKeyUp
.bind( this ),
10702 mousedown
: this.onHandleMouseKeyDown
.bind( this ),
10703 mouseup
: this.onHandleMouseKeyUp
.bind( this )
10708 .addClass( 'oo-ui-popupToolGroup-handle' )
10709 .append( this.$icon
, this.$label
, this.$indicator
);
10710 // If the pop-up should have a header, add it to the top of the toolGroup.
10711 // Note: If this feature is useful for other widgets, we could abstract it into an
10712 // OO.ui.HeaderedElement mixin constructor.
10713 if ( config
.header
!== undefined ) {
10715 .prepend( $( '<span>' )
10716 .addClass( 'oo-ui-popupToolGroup-header' )
10717 .text( config
.header
)
10721 .addClass( 'oo-ui-popupToolGroup' )
10722 .prepend( this.$handle
);
10727 OO
.inheritClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ToolGroup
);
10728 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.IconElement
);
10729 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.IndicatorElement
);
10730 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.LabelElement
);
10731 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.TitledElement
);
10732 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.ClippableElement
);
10733 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.TabIndexedElement
);
10740 OO
.ui
.PopupToolGroup
.prototype.setDisabled = function () {
10742 OO
.ui
.PopupToolGroup
.super.prototype.setDisabled
.apply( this, arguments
);
10744 if ( this.isDisabled() && this.isElementAttached() ) {
10745 this.setActive( false );
10750 * Handle focus being lost.
10752 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
10755 * @param {jQuery.Event} e Mouse up or key up event
10757 OO
.ui
.PopupToolGroup
.prototype.onBlur = function ( e
) {
10758 // Only deactivate when clicking outside the dropdown element
10759 if ( $( e
.target
).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element
[ 0 ] ) {
10760 this.setActive( false );
10767 OO
.ui
.PopupToolGroup
.prototype.onMouseKeyUp = function ( e
) {
10768 // Only close toolgroup when a tool was actually selected
10770 !this.isDisabled() && this.pressed
&& this.pressed
=== this.getTargetTool( e
) &&
10771 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
10773 this.setActive( false );
10775 return OO
.ui
.PopupToolGroup
.super.prototype.onMouseKeyUp
.call( this, e
);
10779 * Handle mouse up and key up events.
10782 * @param {jQuery.Event} e Mouse up or key up event
10784 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyUp = function ( e
) {
10786 !this.isDisabled() &&
10787 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
10794 * Handle mouse down and key down events.
10797 * @param {jQuery.Event} e Mouse down or key down event
10799 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyDown = function ( e
) {
10801 !this.isDisabled() &&
10802 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
10804 this.setActive( !this.active
);
10810 * Switch into 'active' mode.
10812 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
10815 OO
.ui
.PopupToolGroup
.prototype.setActive = function ( value
) {
10817 if ( this.active
!== value
) {
10818 this.active
= value
;
10820 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler
, true );
10821 this.getElementDocument().addEventListener( 'keyup', this.onBlurHandler
, true );
10823 // Try anchoring the popup to the left first
10824 this.$element
.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
10825 this.toggleClipping( true );
10826 if ( this.isClippedHorizontally() ) {
10827 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
10828 this.toggleClipping( false );
10830 .removeClass( 'oo-ui-popupToolGroup-left' )
10831 .addClass( 'oo-ui-popupToolGroup-right' );
10832 this.toggleClipping( true );
10835 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler
, true );
10836 this.getElementDocument().removeEventListener( 'keyup', this.onBlurHandler
, true );
10837 this.$element
.removeClass(
10838 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
10840 this.toggleClipping( false );
10846 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
10847 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
10848 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
10849 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
10850 * with a label, icon, indicator, header, and title.
10852 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
10853 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
10854 * users to collapse the list again.
10856 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
10857 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
10858 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
10861 * // Example of a ListToolGroup
10862 * var toolFactory = new OO.ui.ToolFactory();
10863 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
10864 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
10866 * // Configure and register two tools
10867 * function SettingsTool() {
10868 * SettingsTool.super.apply( this, arguments );
10870 * OO.inheritClass( SettingsTool, OO.ui.Tool );
10871 * SettingsTool.static.name = 'settings';
10872 * SettingsTool.static.icon = 'settings';
10873 * SettingsTool.static.title = 'Change settings';
10874 * SettingsTool.prototype.onSelect = function () {
10875 * this.setActive( false );
10877 * toolFactory.register( SettingsTool );
10878 * // Register two more tools, nothing interesting here
10879 * function StuffTool() {
10880 * StuffTool.super.apply( this, arguments );
10882 * OO.inheritClass( StuffTool, OO.ui.Tool );
10883 * StuffTool.static.name = 'stuff';
10884 * StuffTool.static.icon = 'ellipsis';
10885 * StuffTool.static.title = 'Change the world';
10886 * StuffTool.prototype.onSelect = function () {
10887 * this.setActive( false );
10889 * toolFactory.register( StuffTool );
10892 * // Configurations for list toolgroup.
10894 * label: 'ListToolGroup',
10895 * indicator: 'down',
10897 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
10898 * header: 'This is the header',
10899 * include: [ 'settings', 'stuff' ],
10900 * allowCollapse: ['stuff']
10904 * // Create some UI around the toolbar and place it in the document
10905 * var frame = new OO.ui.PanelLayout( {
10909 * frame.$element.append(
10912 * $( 'body' ).append( frame.$element );
10913 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
10914 * toolbar.initialize();
10916 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
10918 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
10921 * @extends OO.ui.PopupToolGroup
10924 * @param {OO.ui.Toolbar} toolbar
10925 * @param {Object} [config] Configuration options
10926 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
10927 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
10928 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
10929 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
10930 * To open a collapsible list in its expanded state, set #expanded to 'true'.
10931 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
10932 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
10933 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
10934 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
10935 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
10937 OO
.ui
.ListToolGroup
= function OoUiListToolGroup( toolbar
, config
) {
10938 // Allow passing positional parameters inside the config object
10939 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
10941 toolbar
= config
.toolbar
;
10944 // Configuration initialization
10945 config
= config
|| {};
10947 // Properties (must be set before parent constructor, which calls #populate)
10948 this.allowCollapse
= config
.allowCollapse
;
10949 this.forceExpand
= config
.forceExpand
;
10950 this.expanded
= config
.expanded
!== undefined ? config
.expanded
: false;
10951 this.collapsibleTools
= [];
10953 // Parent constructor
10954 OO
.ui
.ListToolGroup
.super.call( this, toolbar
, config
);
10957 this.$element
.addClass( 'oo-ui-listToolGroup' );
10962 OO
.inheritClass( OO
.ui
.ListToolGroup
, OO
.ui
.PopupToolGroup
);
10964 /* Static Properties */
10966 OO
.ui
.ListToolGroup
.static.name
= 'list';
10973 OO
.ui
.ListToolGroup
.prototype.populate = function () {
10974 var i
, len
, allowCollapse
= [];
10976 OO
.ui
.ListToolGroup
.super.prototype.populate
.call( this );
10978 // Update the list of collapsible tools
10979 if ( this.allowCollapse
!== undefined ) {
10980 allowCollapse
= this.allowCollapse
;
10981 } else if ( this.forceExpand
!== undefined ) {
10982 allowCollapse
= OO
.simpleArrayDifference( Object
.keys( this.tools
), this.forceExpand
);
10985 this.collapsibleTools
= [];
10986 for ( i
= 0, len
= allowCollapse
.length
; i
< len
; i
++ ) {
10987 if ( this.tools
[ allowCollapse
[ i
] ] !== undefined ) {
10988 this.collapsibleTools
.push( this.tools
[ allowCollapse
[ i
] ] );
10992 // Keep at the end, even when tools are added
10993 this.$group
.append( this.getExpandCollapseTool().$element
);
10995 this.getExpandCollapseTool().toggle( this.collapsibleTools
.length
!== 0 );
10996 this.updateCollapsibleState();
10999 OO
.ui
.ListToolGroup
.prototype.getExpandCollapseTool = function () {
11000 if ( this.expandCollapseTool
=== undefined ) {
11001 var ExpandCollapseTool = function () {
11002 ExpandCollapseTool
.super.apply( this, arguments
);
11005 OO
.inheritClass( ExpandCollapseTool
, OO
.ui
.Tool
);
11007 ExpandCollapseTool
.prototype.onSelect = function () {
11008 this.toolGroup
.expanded
= !this.toolGroup
.expanded
;
11009 this.toolGroup
.updateCollapsibleState();
11010 this.setActive( false );
11012 ExpandCollapseTool
.prototype.onUpdateState = function () {
11013 // Do nothing. Tool interface requires an implementation of this function.
11016 ExpandCollapseTool
.static.name
= 'more-fewer';
11018 this.expandCollapseTool
= new ExpandCollapseTool( this );
11020 return this.expandCollapseTool
;
11026 OO
.ui
.ListToolGroup
.prototype.onMouseKeyUp = function ( e
) {
11027 // Do not close the popup when the user wants to show more/fewer tools
11029 $( e
.target
).closest( '.oo-ui-tool-name-more-fewer' ).length
&&
11030 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11032 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
11033 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
11034 return OO
.ui
.ListToolGroup
.super.super.prototype.onMouseKeyUp
.call( this, e
);
11036 return OO
.ui
.ListToolGroup
.super.prototype.onMouseKeyUp
.call( this, e
);
11040 OO
.ui
.ListToolGroup
.prototype.updateCollapsibleState = function () {
11043 this.getExpandCollapseTool()
11044 .setIcon( this.expanded
? 'collapse' : 'expand' )
11045 .setTitle( OO
.ui
.msg( this.expanded
? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
11047 for ( i
= 0, len
= this.collapsibleTools
.length
; i
< len
; i
++ ) {
11048 this.collapsibleTools
[ i
].toggle( this.expanded
);
11053 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11054 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
11055 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
11056 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
11057 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
11058 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
11060 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
11061 * is set up. Note that all tools must define an {@link OO.ui.Tool#onUpdateState onUpdateState} method if
11062 * a MenuToolGroup is used.
11065 * // Example of a MenuToolGroup
11066 * var toolFactory = new OO.ui.ToolFactory();
11067 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11068 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11070 * // We will be placing status text in this element when tools are used
11071 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
11073 * // Define the tools that we're going to place in our toolbar
11075 * function SettingsTool() {
11076 * SettingsTool.super.apply( this, arguments );
11077 * this.reallyActive = false;
11079 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11080 * SettingsTool.static.name = 'settings';
11081 * SettingsTool.static.icon = 'settings';
11082 * SettingsTool.static.title = 'Change settings';
11083 * SettingsTool.prototype.onSelect = function () {
11084 * $area.text( 'Settings tool clicked!' );
11085 * // Toggle the active state on each click
11086 * this.reallyActive = !this.reallyActive;
11087 * this.setActive( this.reallyActive );
11088 * // To update the menu label
11089 * this.toolbar.emit( 'updateState' );
11091 * SettingsTool.prototype.onUpdateState = function () {
11093 * toolFactory.register( SettingsTool );
11095 * function StuffTool() {
11096 * StuffTool.super.apply( this, arguments );
11097 * this.reallyActive = false;
11099 * OO.inheritClass( StuffTool, OO.ui.Tool );
11100 * StuffTool.static.name = 'stuff';
11101 * StuffTool.static.icon = 'ellipsis';
11102 * StuffTool.static.title = 'More stuff';
11103 * StuffTool.prototype.onSelect = function () {
11104 * $area.text( 'More stuff tool clicked!' );
11105 * // Toggle the active state on each click
11106 * this.reallyActive = !this.reallyActive;
11107 * this.setActive( this.reallyActive );
11108 * // To update the menu label
11109 * this.toolbar.emit( 'updateState' );
11111 * StuffTool.prototype.onUpdateState = function () {
11113 * toolFactory.register( StuffTool );
11115 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11116 * // used once (but not all defined tools must be used).
11120 * header: 'This is the (optional) header',
11121 * title: 'This is the (optional) title',
11122 * indicator: 'down',
11123 * include: [ 'settings', 'stuff' ]
11127 * // Create some UI around the toolbar and place it in the document
11128 * var frame = new OO.ui.PanelLayout( {
11132 * var contentFrame = new OO.ui.PanelLayout( {
11136 * frame.$element.append(
11137 * toolbar.$element,
11138 * contentFrame.$element.append( $area )
11140 * $( 'body' ).append( frame.$element );
11142 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11144 * toolbar.initialize();
11145 * toolbar.emit( 'updateState' );
11147 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11148 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
11150 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11153 * @extends OO.ui.PopupToolGroup
11156 * @param {OO.ui.Toolbar} toolbar
11157 * @param {Object} [config] Configuration options
11159 OO
.ui
.MenuToolGroup
= function OoUiMenuToolGroup( toolbar
, config
) {
11160 // Allow passing positional parameters inside the config object
11161 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11163 toolbar
= config
.toolbar
;
11166 // Configuration initialization
11167 config
= config
|| {};
11169 // Parent constructor
11170 OO
.ui
.MenuToolGroup
.super.call( this, toolbar
, config
);
11173 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
11176 this.$element
.addClass( 'oo-ui-menuToolGroup' );
11181 OO
.inheritClass( OO
.ui
.MenuToolGroup
, OO
.ui
.PopupToolGroup
);
11183 /* Static Properties */
11185 OO
.ui
.MenuToolGroup
.static.name
= 'menu';
11190 * Handle the toolbar state being updated.
11192 * When the state changes, the title of each active item in the menu will be joined together and
11193 * used as a label for the group. The label will be empty if none of the items are active.
11197 OO
.ui
.MenuToolGroup
.prototype.onUpdateState = function () {
11201 for ( name
in this.tools
) {
11202 if ( this.tools
[ name
].isActive() ) {
11203 labelTexts
.push( this.tools
[ name
].getTitle() );
11207 this.setLabel( labelTexts
.join( ', ' ) || ' ' );
11211 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
11212 * with a static name, title, and icon, as well with as any popup configurations. Unlike other tools, popup tools do not require that developers specify
11213 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
11215 * // Example of a popup tool. When selected, a popup tool displays
11216 * // a popup window.
11217 * function HelpTool( toolGroup, config ) {
11218 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11223 * this.popup.$body.append( '<p>I am helpful!</p>' );
11225 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11226 * HelpTool.static.name = 'help';
11227 * HelpTool.static.icon = 'help';
11228 * HelpTool.static.title = 'Help';
11229 * toolFactory.register( HelpTool );
11231 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
11232 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
11234 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11238 * @extends OO.ui.Tool
11239 * @mixins OO.ui.mixin.PopupElement
11242 * @param {OO.ui.ToolGroup} toolGroup
11243 * @param {Object} [config] Configuration options
11245 OO
.ui
.PopupTool
= function OoUiPopupTool( toolGroup
, config
) {
11246 // Allow passing positional parameters inside the config object
11247 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
11248 config
= toolGroup
;
11249 toolGroup
= config
.toolGroup
;
11252 // Parent constructor
11253 OO
.ui
.PopupTool
.super.call( this, toolGroup
, config
);
11255 // Mixin constructors
11256 OO
.ui
.mixin
.PopupElement
.call( this, config
);
11260 .addClass( 'oo-ui-popupTool' )
11261 .append( this.popup
.$element
);
11266 OO
.inheritClass( OO
.ui
.PopupTool
, OO
.ui
.Tool
);
11267 OO
.mixinClass( OO
.ui
.PopupTool
, OO
.ui
.mixin
.PopupElement
);
11272 * Handle the tool being selected.
11276 OO
.ui
.PopupTool
.prototype.onSelect = function () {
11277 if ( !this.isDisabled() ) {
11278 this.popup
.toggle();
11280 this.setActive( false );
11285 * Handle the toolbar state being updated.
11289 OO
.ui
.PopupTool
.prototype.onUpdateState = function () {
11290 this.setActive( false );
11294 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
11295 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
11296 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
11297 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
11298 * when the ToolGroupTool is selected.
11300 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
11302 * function SettingsTool() {
11303 * SettingsTool.super.apply( this, arguments );
11305 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
11306 * SettingsTool.static.name = 'settings';
11307 * SettingsTool.static.title = 'Change settings';
11308 * SettingsTool.static.groupConfig = {
11309 * icon: 'settings',
11310 * label: 'ToolGroupTool',
11311 * include: [ 'setting1', 'setting2' ]
11313 * toolFactory.register( SettingsTool );
11315 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
11317 * Please note that this implementation is subject to change per [T74159] [2].
11319 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
11320 * [2]: https://phabricator.wikimedia.org/T74159
11324 * @extends OO.ui.Tool
11327 * @param {OO.ui.ToolGroup} toolGroup
11328 * @param {Object} [config] Configuration options
11330 OO
.ui
.ToolGroupTool
= function OoUiToolGroupTool( toolGroup
, config
) {
11331 // Allow passing positional parameters inside the config object
11332 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
11333 config
= toolGroup
;
11334 toolGroup
= config
.toolGroup
;
11337 // Parent constructor
11338 OO
.ui
.ToolGroupTool
.super.call( this, toolGroup
, config
);
11341 this.innerToolGroup
= this.createGroup( this.constructor.static.groupConfig
);
11344 this.innerToolGroup
.connect( this, { disable
: 'onToolGroupDisable' } );
11347 this.$link
.remove();
11349 .addClass( 'oo-ui-toolGroupTool' )
11350 .append( this.innerToolGroup
.$element
);
11355 OO
.inheritClass( OO
.ui
.ToolGroupTool
, OO
.ui
.Tool
);
11357 /* Static Properties */
11360 * Toolgroup configuration.
11362 * The toolgroup configuration consists of the tools to include, as well as an icon and label
11363 * to use for the bar item. Tools can be included by symbolic name, group, or with the
11364 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
11366 * @property {Object.<string,Array>}
11368 OO
.ui
.ToolGroupTool
.static.groupConfig
= {};
11373 * Handle the tool being selected.
11377 OO
.ui
.ToolGroupTool
.prototype.onSelect = function () {
11378 this.innerToolGroup
.setActive( !this.innerToolGroup
.active
);
11383 * Synchronize disabledness state of the tool with the inner toolgroup.
11386 * @param {boolean} disabled Element is disabled
11388 OO
.ui
.ToolGroupTool
.prototype.onToolGroupDisable = function ( disabled
) {
11389 this.setDisabled( disabled
);
11393 * Handle the toolbar state being updated.
11397 OO
.ui
.ToolGroupTool
.prototype.onUpdateState = function () {
11398 this.setActive( false );
11402 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
11404 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
11405 * more information.
11406 * @return {OO.ui.ListToolGroup}
11408 OO
.ui
.ToolGroupTool
.prototype.createGroup = function ( group
) {
11409 if ( group
.include
=== '*' ) {
11410 // Apply defaults to catch-all groups
11411 if ( group
.label
=== undefined ) {
11412 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
11416 return this.toolbar
.getToolGroupFactory().create( 'list', this.toolbar
, group
);
11420 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
11422 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
11427 * @extends OO.ui.mixin.GroupElement
11430 * @param {Object} [config] Configuration options
11432 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
11433 // Parent constructor
11434 OO
.ui
.mixin
.GroupWidget
.super.call( this, config
);
11439 OO
.inheritClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
11444 * Set the disabled state of the widget.
11446 * This will also update the disabled state of child widgets.
11448 * @param {boolean} disabled Disable widget
11451 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
11455 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
11456 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
11458 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
11459 if ( this.items
) {
11460 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
11461 this.items
[ i
].updateDisabled();
11469 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
11471 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
11472 * allows bidirectional communication.
11474 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
11482 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
11489 * Check if widget is disabled.
11491 * Checks parent if present, making disabled state inheritable.
11493 * @return {boolean} Widget is disabled
11495 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
11496 return this.disabled
||
11497 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
11501 * Set group element is in.
11503 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
11506 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
11508 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
11509 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
11511 // Initialize item disabled states
11512 this.updateDisabled();
11518 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
11519 * Controls include moving items up and down, removing items, and adding different kinds of items.
11520 * ####Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.####
11523 * @extends OO.ui.Widget
11524 * @mixins OO.ui.mixin.GroupElement
11525 * @mixins OO.ui.mixin.IconElement
11528 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
11529 * @param {Object} [config] Configuration options
11530 * @cfg {Object} [abilities] List of abilties
11531 * @cfg {boolean} [abilities.move=true] Allow moving movable items
11532 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
11534 OO
.ui
.OutlineControlsWidget
= function OoUiOutlineControlsWidget( outline
, config
) {
11535 // Allow passing positional parameters inside the config object
11536 if ( OO
.isPlainObject( outline
) && config
=== undefined ) {
11538 outline
= config
.outline
;
11541 // Configuration initialization
11542 config
= $.extend( { icon
: 'add' }, config
);
11544 // Parent constructor
11545 OO
.ui
.OutlineControlsWidget
.super.call( this, config
);
11547 // Mixin constructors
11548 OO
.ui
.mixin
.GroupElement
.call( this, config
);
11549 OO
.ui
.mixin
.IconElement
.call( this, config
);
11552 this.outline
= outline
;
11553 this.$movers
= $( '<div>' );
11554 this.upButton
= new OO
.ui
.ButtonWidget( {
11557 title
: OO
.ui
.msg( 'ooui-outline-control-move-up' )
11559 this.downButton
= new OO
.ui
.ButtonWidget( {
11562 title
: OO
.ui
.msg( 'ooui-outline-control-move-down' )
11564 this.removeButton
= new OO
.ui
.ButtonWidget( {
11567 title
: OO
.ui
.msg( 'ooui-outline-control-remove' )
11569 this.abilities
= { move: true, remove
: true };
11572 outline
.connect( this, {
11573 select
: 'onOutlineChange',
11574 add
: 'onOutlineChange',
11575 remove
: 'onOutlineChange'
11577 this.upButton
.connect( this, { click
: [ 'emit', 'move', -1 ] } );
11578 this.downButton
.connect( this, { click
: [ 'emit', 'move', 1 ] } );
11579 this.removeButton
.connect( this, { click
: [ 'emit', 'remove' ] } );
11582 this.$element
.addClass( 'oo-ui-outlineControlsWidget' );
11583 this.$group
.addClass( 'oo-ui-outlineControlsWidget-items' );
11585 .addClass( 'oo-ui-outlineControlsWidget-movers' )
11586 .append( this.removeButton
.$element
, this.upButton
.$element
, this.downButton
.$element
);
11587 this.$element
.append( this.$icon
, this.$group
, this.$movers
);
11588 this.setAbilities( config
.abilities
|| {} );
11593 OO
.inheritClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.Widget
);
11594 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.GroupElement
);
11595 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.IconElement
);
11601 * @param {number} places Number of places to move
11613 * @param {Object} abilities List of abilties
11614 * @param {boolean} [abilities.move] Allow moving movable items
11615 * @param {boolean} [abilities.remove] Allow removing removable items
11617 OO
.ui
.OutlineControlsWidget
.prototype.setAbilities = function ( abilities
) {
11620 for ( ability
in this.abilities
) {
11621 if ( abilities
[ability
] !== undefined ) {
11622 this.abilities
[ability
] = !!abilities
[ability
];
11626 this.onOutlineChange();
11632 * Handle outline change events.
11634 OO
.ui
.OutlineControlsWidget
.prototype.onOutlineChange = function () {
11635 var i
, len
, firstMovable
, lastMovable
,
11636 items
= this.outline
.getItems(),
11637 selectedItem
= this.outline
.getSelectedItem(),
11638 movable
= this.abilities
.move && selectedItem
&& selectedItem
.isMovable(),
11639 removable
= this.abilities
.remove
&& selectedItem
&& selectedItem
.isRemovable();
11643 len
= items
.length
;
11644 while ( ++i
< len
) {
11645 if ( items
[ i
].isMovable() ) {
11646 firstMovable
= items
[ i
];
11652 if ( items
[ i
].isMovable() ) {
11653 lastMovable
= items
[ i
];
11658 this.upButton
.setDisabled( !movable
|| selectedItem
=== firstMovable
);
11659 this.downButton
.setDisabled( !movable
|| selectedItem
=== lastMovable
);
11660 this.removeButton
.setDisabled( !removable
);
11664 * ToggleWidget implements basic behavior of widgets with an on/off state.
11665 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
11669 * @extends OO.ui.Widget
11672 * @param {Object} [config] Configuration options
11673 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
11674 * By default, the toggle is in the 'off' state.
11676 OO
.ui
.ToggleWidget
= function OoUiToggleWidget( config
) {
11677 // Configuration initialization
11678 config
= config
|| {};
11680 // Parent constructor
11681 OO
.ui
.ToggleWidget
.super.call( this, config
);
11687 this.$element
.addClass( 'oo-ui-toggleWidget' );
11688 this.setValue( !!config
.value
);
11693 OO
.inheritClass( OO
.ui
.ToggleWidget
, OO
.ui
.Widget
);
11700 * A change event is emitted when the on/off state of the toggle changes.
11702 * @param {boolean} value Value representing the new state of the toggle
11708 * Get the value representing the toggle’s state.
11710 * @return {boolean} The on/off state of the toggle
11712 OO
.ui
.ToggleWidget
.prototype.getValue = function () {
11717 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
11719 * @param {boolean} value The state of the toggle
11723 OO
.ui
.ToggleWidget
.prototype.setValue = function ( value
) {
11725 if ( this.value
!== value
) {
11726 this.value
= value
;
11727 this.emit( 'change', value
);
11728 this.$element
.toggleClass( 'oo-ui-toggleWidget-on', value
);
11729 this.$element
.toggleClass( 'oo-ui-toggleWidget-off', !value
);
11730 this.$element
.attr( 'aria-checked', value
.toString() );
11736 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
11737 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
11738 * removed, and cleared from the group.
11741 * // Example: A ButtonGroupWidget with two buttons
11742 * var button1 = new OO.ui.PopupButtonWidget( {
11743 * label: 'Select a category',
11746 * $content: $( '<p>List of categories...</p>' ),
11751 * var button2 = new OO.ui.ButtonWidget( {
11752 * label: 'Add item'
11754 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
11755 * items: [button1, button2]
11757 * $( 'body' ).append( buttonGroup.$element );
11760 * @extends OO.ui.Widget
11761 * @mixins OO.ui.mixin.GroupElement
11764 * @param {Object} [config] Configuration options
11765 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
11767 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
11768 // Configuration initialization
11769 config
= config
|| {};
11771 // Parent constructor
11772 OO
.ui
.ButtonGroupWidget
.super.call( this, config
);
11774 // Mixin constructors
11775 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11778 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
11779 if ( Array
.isArray( config
.items
) ) {
11780 this.addItems( config
.items
);
11786 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
11787 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
11790 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
11791 * feels, and functionality can be customized via the class’s configuration options
11792 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
11795 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
11798 * // A button widget
11799 * var button = new OO.ui.ButtonWidget( {
11800 * label: 'Button with Icon',
11802 * iconTitle: 'Remove'
11804 * $( 'body' ).append( button.$element );
11806 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
11809 * @extends OO.ui.Widget
11810 * @mixins OO.ui.mixin.ButtonElement
11811 * @mixins OO.ui.mixin.IconElement
11812 * @mixins OO.ui.mixin.IndicatorElement
11813 * @mixins OO.ui.mixin.LabelElement
11814 * @mixins OO.ui.mixin.TitledElement
11815 * @mixins OO.ui.mixin.FlaggedElement
11816 * @mixins OO.ui.mixin.TabIndexedElement
11819 * @param {Object} [config] Configuration options
11820 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
11821 * @cfg {string} [target] The frame or window in which to open the hyperlink.
11822 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
11824 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
11825 // Configuration initialization
11826 config
= config
|| {};
11828 // Parent constructor
11829 OO
.ui
.ButtonWidget
.super.call( this, config
);
11831 // Mixin constructors
11832 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
11833 OO
.ui
.mixin
.IconElement
.call( this, config
);
11834 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
11835 OO
.ui
.mixin
.LabelElement
.call( this, config
);
11836 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
11837 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
11838 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
11842 this.target
= null;
11843 this.noFollow
= false;
11846 this.connect( this, { disable
: 'onDisable' } );
11849 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
11851 .addClass( 'oo-ui-buttonWidget' )
11852 .append( this.$button
);
11853 this.setHref( config
.href
);
11854 this.setTarget( config
.target
);
11855 this.setNoFollow( config
.noFollow
);
11860 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
11861 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
11862 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
11863 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
11864 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
11865 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
11866 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
11867 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
11874 OO
.ui
.ButtonWidget
.prototype.onMouseDown = function ( e
) {
11875 if ( !this.isDisabled() ) {
11876 // Remove the tab-index while the button is down to prevent the button from stealing focus
11877 this.$button
.removeAttr( 'tabindex' );
11880 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown
.call( this, e
);
11886 OO
.ui
.ButtonWidget
.prototype.onMouseUp = function ( e
) {
11887 if ( !this.isDisabled() ) {
11888 // Restore the tab-index after the button is up to restore the button's accessibility
11889 this.$button
.attr( 'tabindex', this.tabIndex
);
11892 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp
.call( this, e
);
11896 * Get hyperlink location.
11898 * @return {string} Hyperlink location
11900 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
11905 * Get hyperlink target.
11907 * @return {string} Hyperlink target
11909 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
11910 return this.target
;
11914 * Get search engine traversal hint.
11916 * @return {boolean} Whether search engines should avoid traversing this hyperlink
11918 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
11919 return this.noFollow
;
11923 * Set hyperlink location.
11925 * @param {string|null} href Hyperlink location, null to remove
11927 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
11928 href
= typeof href
=== 'string' ? href
: null;
11930 if ( href
!== this.href
) {
11939 * Update the `href` attribute, in case of changes to href or
11945 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
11946 if ( this.href
!== null && !this.isDisabled() ) {
11947 this.$button
.attr( 'href', this.href
);
11949 this.$button
.removeAttr( 'href' );
11956 * Handle disable events.
11959 * @param {boolean} disabled Element is disabled
11961 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
11966 * Set hyperlink target.
11968 * @param {string|null} target Hyperlink target, null to remove
11970 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
11971 target
= typeof target
=== 'string' ? target
: null;
11973 if ( target
!== this.target
) {
11974 this.target
= target
;
11975 if ( target
!== null ) {
11976 this.$button
.attr( 'target', target
);
11978 this.$button
.removeAttr( 'target' );
11986 * Set search engine traversal hint.
11988 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
11990 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
11991 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
11993 if ( noFollow
!== this.noFollow
) {
11994 this.noFollow
= noFollow
;
11996 this.$button
.attr( 'rel', 'nofollow' );
11998 this.$button
.removeAttr( 'rel' );
12006 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
12007 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
12010 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
12011 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12014 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
12017 * @extends OO.ui.ButtonWidget
12018 * @mixins OO.ui.mixin.PendingElement
12021 * @param {Object} [config] Configuration options
12022 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12023 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
12024 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
12025 * for more information about setting modes.
12026 * @cfg {boolean} [framed=false] Render the action button with a frame
12028 OO
.ui
.ActionWidget
= function OoUiActionWidget( config
) {
12029 // Configuration initialization
12030 config
= $.extend( { framed
: false }, config
);
12032 // Parent constructor
12033 OO
.ui
.ActionWidget
.super.call( this, config
);
12035 // Mixin constructors
12036 OO
.ui
.mixin
.PendingElement
.call( this, config
);
12039 this.action
= config
.action
|| '';
12040 this.modes
= config
.modes
|| [];
12045 this.$element
.addClass( 'oo-ui-actionWidget' );
12050 OO
.inheritClass( OO
.ui
.ActionWidget
, OO
.ui
.ButtonWidget
);
12051 OO
.mixinClass( OO
.ui
.ActionWidget
, OO
.ui
.mixin
.PendingElement
);
12056 * A resize event is emitted when the size of the widget changes.
12064 * Check if the action is configured to be available in the specified `mode`.
12066 * @param {string} mode Name of mode
12067 * @return {boolean} The action is configured with the mode
12069 OO
.ui
.ActionWidget
.prototype.hasMode = function ( mode
) {
12070 return this.modes
.indexOf( mode
) !== -1;
12074 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12078 OO
.ui
.ActionWidget
.prototype.getAction = function () {
12079 return this.action
;
12083 * Get the symbolic name of the mode or modes for which the action is configured to be available.
12085 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
12086 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
12089 * @return {string[]}
12091 OO
.ui
.ActionWidget
.prototype.getModes = function () {
12092 return this.modes
.slice();
12096 * Emit a resize event if the size has changed.
12101 OO
.ui
.ActionWidget
.prototype.propagateResize = function () {
12104 if ( this.isElementAttached() ) {
12105 width
= this.$element
.width();
12106 height
= this.$element
.height();
12108 if ( width
!== this.width
|| height
!== this.height
) {
12109 this.width
= width
;
12110 this.height
= height
;
12111 this.emit( 'resize' );
12121 OO
.ui
.ActionWidget
.prototype.setIcon = function () {
12123 OO
.ui
.mixin
.IconElement
.prototype.setIcon
.apply( this, arguments
);
12124 this.propagateResize();
12132 OO
.ui
.ActionWidget
.prototype.setLabel = function () {
12134 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.apply( this, arguments
);
12135 this.propagateResize();
12143 OO
.ui
.ActionWidget
.prototype.setFlags = function () {
12145 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags
.apply( this, arguments
);
12146 this.propagateResize();
12154 OO
.ui
.ActionWidget
.prototype.clearFlags = function () {
12156 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags
.apply( this, arguments
);
12157 this.propagateResize();
12163 * Toggle the visibility of the action button.
12165 * @param {boolean} [show] Show button, omit to toggle visibility
12168 OO
.ui
.ActionWidget
.prototype.toggle = function () {
12170 OO
.ui
.ActionWidget
.super.prototype.toggle
.apply( this, arguments
);
12171 this.propagateResize();
12177 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
12178 * which is used to display additional information or options.
12181 * // Example of a popup button.
12182 * var popupButton = new OO.ui.PopupButtonWidget( {
12183 * label: 'Popup button with options',
12186 * $content: $( '<p>Additional options here.</p>' ),
12188 * align: 'force-left'
12191 * // Append the button to the DOM.
12192 * $( 'body' ).append( popupButton.$element );
12195 * @extends OO.ui.ButtonWidget
12196 * @mixins OO.ui.mixin.PopupElement
12199 * @param {Object} [config] Configuration options
12201 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
12202 // Parent constructor
12203 OO
.ui
.PopupButtonWidget
.super.call( this, config
);
12205 // Mixin constructors
12206 OO
.ui
.mixin
.PopupElement
.call( this, config
);
12209 this.connect( this, { click
: 'onAction' } );
12213 .addClass( 'oo-ui-popupButtonWidget' )
12214 .attr( 'aria-haspopup', 'true' )
12215 .append( this.popup
.$element
);
12220 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
12221 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
12226 * Handle the button action being triggered.
12230 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
12231 this.popup
.toggle();
12235 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
12236 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
12237 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
12238 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
12239 * and {@link OO.ui.mixin.LabelElement labels}. Please see
12240 * the [OOjs UI documentation][1] on MediaWiki for more information.
12243 * // Toggle buttons in the 'off' and 'on' state.
12244 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
12245 * label: 'Toggle Button off'
12247 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
12248 * label: 'Toggle Button on',
12251 * // Append the buttons to the DOM.
12252 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
12254 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
12257 * @extends OO.ui.ToggleWidget
12258 * @mixins OO.ui.mixin.ButtonElement
12259 * @mixins OO.ui.mixin.IconElement
12260 * @mixins OO.ui.mixin.IndicatorElement
12261 * @mixins OO.ui.mixin.LabelElement
12262 * @mixins OO.ui.mixin.TitledElement
12263 * @mixins OO.ui.mixin.FlaggedElement
12264 * @mixins OO.ui.mixin.TabIndexedElement
12267 * @param {Object} [config] Configuration options
12268 * @cfg {boolean} [value=false] The toggle button’s initial on/off
12269 * state. By default, the button is in the 'off' state.
12271 OO
.ui
.ToggleButtonWidget
= function OoUiToggleButtonWidget( config
) {
12272 // Configuration initialization
12273 config
= config
|| {};
12275 // Parent constructor
12276 OO
.ui
.ToggleButtonWidget
.super.call( this, config
);
12278 // Mixin constructors
12279 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
12280 OO
.ui
.mixin
.IconElement
.call( this, config
);
12281 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12282 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12283 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
12284 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
12285 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
12288 this.connect( this, { click
: 'onAction' } );
12291 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
12293 .addClass( 'oo-ui-toggleButtonWidget' )
12294 .append( this.$button
);
12299 OO
.inheritClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ToggleWidget
);
12300 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
12301 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IconElement
);
12302 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
12303 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.LabelElement
);
12304 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TitledElement
);
12305 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
12306 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
12311 * Handle the button action being triggered.
12315 OO
.ui
.ToggleButtonWidget
.prototype.onAction = function () {
12316 this.setValue( !this.value
);
12322 OO
.ui
.ToggleButtonWidget
.prototype.setValue = function ( value
) {
12324 if ( value
!== this.value
) {
12325 // Might be called from parent constructor before ButtonElement constructor
12326 if ( this.$button
) {
12327 this.$button
.attr( 'aria-pressed', value
.toString() );
12329 this.setActive( value
);
12333 OO
.ui
.ToggleButtonWidget
.super.prototype.setValue
.call( this, value
);
12341 OO
.ui
.ToggleButtonWidget
.prototype.setButtonElement = function ( $button
) {
12342 if ( this.$button
) {
12343 this.$button
.removeAttr( 'aria-pressed' );
12345 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement
.call( this, $button
);
12346 this.$button
.attr( 'aria-pressed', this.value
.toString() );
12350 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
12351 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
12352 * users can interact with it.
12354 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
12355 * OO.ui.DropdownInputWidget instead.
12358 * // Example: A DropdownWidget with a menu that contains three options
12359 * var dropDown = new OO.ui.DropdownWidget( {
12360 * label: 'Dropdown menu: Select a menu option',
12363 * new OO.ui.MenuOptionWidget( {
12367 * new OO.ui.MenuOptionWidget( {
12371 * new OO.ui.MenuOptionWidget( {
12379 * $( 'body' ).append( dropDown.$element );
12381 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
12383 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12386 * @extends OO.ui.Widget
12387 * @mixins OO.ui.mixin.IconElement
12388 * @mixins OO.ui.mixin.IndicatorElement
12389 * @mixins OO.ui.mixin.LabelElement
12390 * @mixins OO.ui.mixin.TitledElement
12391 * @mixins OO.ui.mixin.TabIndexedElement
12394 * @param {Object} [config] Configuration options
12395 * @cfg {Object} [menu] Configuration options to pass to menu widget
12397 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
12398 // Configuration initialization
12399 config
= $.extend( { indicator
: 'down' }, config
);
12401 // Parent constructor
12402 OO
.ui
.DropdownWidget
.super.call( this, config
);
12404 // Properties (must be set before TabIndexedElement constructor call)
12405 this.$handle
= this.$( '<span>' );
12407 // Mixin constructors
12408 OO
.ui
.mixin
.IconElement
.call( this, config
);
12409 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12410 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12411 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
12412 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
12415 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend( { widget
: this }, config
.menu
) );
12419 click
: this.onClick
.bind( this ),
12420 keypress
: this.onKeyPress
.bind( this )
12422 this.menu
.connect( this, { select
: 'onMenuSelect' } );
12426 .addClass( 'oo-ui-dropdownWidget-handle' )
12427 .append( this.$icon
, this.$label
, this.$indicator
);
12429 .addClass( 'oo-ui-dropdownWidget' )
12430 .append( this.$handle
, this.menu
.$element
);
12435 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
12436 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
12437 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
12438 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
12439 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
12440 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
12447 * @return {OO.ui.MenuSelectWidget} Menu of widget
12449 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
12454 * Handles menu select events.
12457 * @param {OO.ui.MenuOptionWidget} item Selected menu item
12459 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
12463 this.setLabel( null );
12467 selectedLabel
= item
.getLabel();
12469 // If the label is a DOM element, clone it, because setLabel will append() it
12470 if ( selectedLabel
instanceof jQuery
) {
12471 selectedLabel
= selectedLabel
.clone();
12474 this.setLabel( selectedLabel
);
12478 * Handle mouse click events.
12481 * @param {jQuery.Event} e Mouse click event
12483 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
12484 if ( !this.isDisabled() && e
.which
=== 1 ) {
12485 this.menu
.toggle();
12491 * Handle key press events.
12494 * @param {jQuery.Event} e Key press event
12496 OO
.ui
.DropdownWidget
.prototype.onKeyPress = function ( e
) {
12497 if ( !this.isDisabled() &&
12498 ( ( e
.which
=== OO
.ui
.Keys
.SPACE
&& !this.menu
.isVisible() ) || e
.which
=== OO
.ui
.Keys
.ENTER
)
12500 this.menu
.toggle();
12506 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
12507 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
12508 * OO.ui.mixin.IndicatorElement indicators}.
12509 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
12512 * // Example of a file select widget
12513 * var selectFile = new OO.ui.SelectFileWidget();
12514 * $( 'body' ).append( selectFile.$element );
12516 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
12519 * @extends OO.ui.Widget
12520 * @mixins OO.ui.mixin.IconElement
12521 * @mixins OO.ui.mixin.IndicatorElement
12522 * @mixins OO.ui.mixin.PendingElement
12523 * @mixins OO.ui.mixin.LabelElement
12524 * @mixins OO.ui.mixin.TabIndexedElement
12527 * @param {Object} [config] Configuration options
12528 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
12529 * @cfg {string} [placeholder] Text to display when no file is selected.
12530 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
12531 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
12533 OO
.ui
.SelectFileWidget
= function OoUiSelectFileWidget( config
) {
12536 // Configuration initialization
12537 config
= $.extend( {
12539 placeholder
: OO
.ui
.msg( 'ooui-selectfile-placeholder' ),
12540 notsupported
: OO
.ui
.msg( 'ooui-selectfile-not-supported' ),
12544 // Parent constructor
12545 OO
.ui
.SelectFileWidget
.super.call( this, config
);
12547 // Properties (must be set before TabIndexedElement constructor call)
12548 this.$handle
= $( '<span>' );
12550 // Mixin constructors
12551 OO
.ui
.mixin
.IconElement
.call( this, config
);
12552 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12553 OO
.ui
.mixin
.PendingElement
.call( this, config
);
12554 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( config
, { autoFitLabel
: true } ) );
12555 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
12558 this.isSupported
= this.constructor.static.isSupported();
12559 this.currentFile
= null;
12560 if ( Array
.isArray( config
.accept
) ) {
12561 this.accept
= config
.accept
;
12563 this.accept
= null;
12565 this.placeholder
= config
.placeholder
;
12566 this.notsupported
= config
.notsupported
;
12567 this.onFileSelectedHandler
= this.onFileSelected
.bind( this );
12569 this.clearButton
= new OO
.ui
.ButtonWidget( {
12570 classes
: [ 'oo-ui-selectFileWidget-clearButton' ],
12573 disabled
: this.disabled
12578 keypress
: this.onKeyPress
.bind( this )
12580 this.clearButton
.connect( this, {
12581 click
: 'onClearClick'
12583 if ( config
.droppable
) {
12584 dragHandler
= this.onDragEnterOrOver
.bind( this );
12586 dragenter
: dragHandler
,
12587 dragover
: dragHandler
,
12588 dragleave
: this.onDragLeave
.bind( this ),
12589 drop
: this.onDrop
.bind( this )
12596 this.$label
.addClass( 'oo-ui-selectFileWidget-label' );
12598 .addClass( 'oo-ui-selectFileWidget-handle' )
12599 .append( this.$icon
, this.$label
, this.clearButton
.$element
, this.$indicator
);
12601 .addClass( 'oo-ui-selectFileWidget' )
12602 .append( this.$handle
);
12603 if ( config
.droppable
) {
12604 this.$element
.addClass( 'oo-ui-selectFileWidget-droppable' );
12610 OO
.inheritClass( OO
.ui
.SelectFileWidget
, OO
.ui
.Widget
);
12611 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IconElement
);
12612 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IndicatorElement
);
12613 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.PendingElement
);
12614 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.LabelElement
);
12615 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.TabIndexedElement
);
12617 /* Static properties */
12620 * Check if this widget is supported
12623 * @return {boolean}
12625 OO
.ui
.SelectFileWidget
.static.isSupported = function () {
12627 if ( OO
.ui
.SelectFileWidget
.static.isSupportedCache
=== null ) {
12628 $input
= $( '<input type="file">' );
12629 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= $input
[0].files
!== undefined;
12631 return OO
.ui
.SelectFileWidget
.static.isSupportedCache
;
12634 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= null;
12641 * A change event is emitted when the on/off state of the toggle changes.
12643 * @param {File|null} value New value
12649 * Get the current value of the field
12651 * @return {File|null}
12653 OO
.ui
.SelectFileWidget
.prototype.getValue = function () {
12654 return this.currentFile
;
12658 * Set the current value of the field
12660 * @param {File|null} file File to select
12662 OO
.ui
.SelectFileWidget
.prototype.setValue = function ( file
) {
12663 if ( this.currentFile
!== file
) {
12664 this.currentFile
= file
;
12666 this.emit( 'change', this.currentFile
);
12671 * Update the user interface when a file is selected or unselected
12675 OO
.ui
.SelectFileWidget
.prototype.updateUI = function () {
12676 if ( !this.isSupported
) {
12677 this.$element
.addClass( 'oo-ui-selectFileWidget-notsupported' );
12678 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
12679 this.setLabel( this.notsupported
);
12680 } else if ( this.currentFile
) {
12681 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
12682 this.setLabel( this.currentFile
.name
+
12683 ( this.currentFile
.type
!== '' ? OO
.ui
.msg( 'ooui-semicolon-separator' ) + this.currentFile
.type
: '' )
12686 this.$element
.addClass( 'oo-ui-selectFileWidget-empty' );
12687 this.setLabel( this.placeholder
);
12690 if ( this.$input
) {
12691 this.$input
.attr( 'title', this.getLabel() );
12696 * Add the input to the handle
12700 OO
.ui
.SelectFileWidget
.prototype.addInput = function () {
12701 if ( this.$input
) {
12702 this.$input
.remove();
12705 if ( !this.isSupported
) {
12706 this.$input
= null;
12710 this.$input
= $( '<input type="file">' );
12711 this.$input
.on( 'change', this.onFileSelectedHandler
);
12712 this.$input
.attr( {
12714 title
: this.getLabel()
12716 if ( this.accept
) {
12717 this.$input
.attr( 'accept', this.accept
.join( ', ' ) );
12719 this.$handle
.append( this.$input
);
12723 * Determine if we should accept this file
12726 * @param {File} file
12727 * @return {boolean}
12729 OO
.ui
.SelectFileWidget
.prototype.isFileAcceptable = function ( file
) {
12730 var i
, mime
, mimeTest
;
12732 if ( !this.accept
|| file
.type
=== '' ) {
12737 for ( i
= 0; i
< this.accept
.length
; i
++ ) {
12738 mimeTest
= this.accept
[i
];
12739 if ( mimeTest
=== mime
) {
12741 } else if ( mimeTest
.substr( -2 ) === '/*' ) {
12742 mimeTest
= mimeTest
.substr( 0, mimeTest
.length
- 1 );
12743 if ( mime
.substr( 0, mimeTest
.length
) === mimeTest
) {
12753 * Handle file selection from the input
12756 * @param {jQuery.Event} e
12758 OO
.ui
.SelectFileWidget
.prototype.onFileSelected = function ( e
) {
12761 if ( e
.target
.files
&& e
.target
.files
[0] ) {
12762 file
= e
.target
.files
[0];
12763 if ( !this.isFileAcceptable( file
) ) {
12768 this.setValue( file
);
12773 * Handle clear button click events.
12777 OO
.ui
.SelectFileWidget
.prototype.onClearClick = function () {
12778 this.setValue( null );
12783 * Handle key press events.
12786 * @param {jQuery.Event} e Key press event
12788 OO
.ui
.SelectFileWidget
.prototype.onKeyPress = function ( e
) {
12789 if ( this.isSupported
&& !this.isDisabled() && this.$input
&&
12790 ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
12792 this.$input
.click();
12798 * Handle drag enter and over events
12801 * @param {jQuery.Event} e Drag event
12803 OO
.ui
.SelectFileWidget
.prototype.onDragEnterOrOver = function ( e
) {
12805 dt
= e
.originalEvent
.dataTransfer
;
12807 e
.preventDefault();
12808 e
.stopPropagation();
12810 if ( this.isDisabled() || !this.isSupported
) {
12811 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
12812 dt
.dropEffect
= 'none';
12816 if ( dt
&& dt
.files
&& dt
.files
[0] ) {
12817 file
= dt
.files
[0];
12818 if ( !this.isFileAcceptable( file
) ) {
12821 } else if ( dt
&& dt
.types
&& $.inArray( 'Files', dt
.types
) ) {
12822 // We know we have files so set 'file' to something truthy, we just
12823 // can't know any details about them.
12824 // * https://bugzilla.mozilla.org/show_bug.cgi?id=640534
12825 file
= 'Files exist, but details are unknown';
12828 this.$element
.addClass( 'oo-ui-selectFileWidget-canDrop' );
12830 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
12831 dt
.dropEffect
= 'none';
12838 * Handle drag leave events
12841 * @param {jQuery.Event} e Drag event
12843 OO
.ui
.SelectFileWidget
.prototype.onDragLeave = function () {
12844 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
12848 * Handle drop events
12851 * @param {jQuery.Event} e Drop event
12853 OO
.ui
.SelectFileWidget
.prototype.onDrop = function ( e
) {
12855 dt
= e
.originalEvent
.dataTransfer
;
12857 e
.preventDefault();
12858 e
.stopPropagation();
12859 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
12861 if ( this.isDisabled() || !this.isSupported
) {
12865 if ( dt
&& dt
.files
&& dt
.files
[0] ) {
12866 file
= dt
.files
[0];
12867 if ( !this.isFileAcceptable( file
) ) {
12872 this.setValue( file
);
12881 OO
.ui
.SelectFileWidget
.prototype.setDisabled = function ( state
) {
12882 OO
.ui
.SelectFileWidget
.super.prototype.setDisabled
.call( this, state
);
12883 if ( this.clearButton
) {
12884 this.clearButton
.setDisabled( state
);
12890 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
12891 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
12892 * for a list of icons included in the library.
12895 * // An icon widget with a label
12896 * var myIcon = new OO.ui.IconWidget( {
12898 * iconTitle: 'Help'
12900 * // Create a label.
12901 * var iconLabel = new OO.ui.LabelWidget( {
12904 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
12906 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
12909 * @extends OO.ui.Widget
12910 * @mixins OO.ui.mixin.IconElement
12911 * @mixins OO.ui.mixin.TitledElement
12912 * @mixins OO.ui.mixin.FlaggedElement
12915 * @param {Object} [config] Configuration options
12917 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
12918 // Configuration initialization
12919 config
= config
|| {};
12921 // Parent constructor
12922 OO
.ui
.IconWidget
.super.call( this, config
);
12924 // Mixin constructors
12925 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
12926 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
12927 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
12930 this.$element
.addClass( 'oo-ui-iconWidget' );
12935 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
12936 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
12937 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
12938 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
12940 /* Static Properties */
12942 OO
.ui
.IconWidget
.static.tagName
= 'span';
12945 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
12946 * attention to the status of an item or to clarify the function of a control. For a list of
12947 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
12950 * // Example of an indicator widget
12951 * var indicator1 = new OO.ui.IndicatorWidget( {
12952 * indicator: 'alert'
12955 * // Create a fieldset layout to add a label
12956 * var fieldset = new OO.ui.FieldsetLayout();
12957 * fieldset.addItems( [
12958 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
12960 * $( 'body' ).append( fieldset.$element );
12962 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
12965 * @extends OO.ui.Widget
12966 * @mixins OO.ui.mixin.IndicatorElement
12967 * @mixins OO.ui.mixin.TitledElement
12970 * @param {Object} [config] Configuration options
12972 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
12973 // Configuration initialization
12974 config
= config
|| {};
12976 // Parent constructor
12977 OO
.ui
.IndicatorWidget
.super.call( this, config
);
12979 // Mixin constructors
12980 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
12981 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
12984 this.$element
.addClass( 'oo-ui-indicatorWidget' );
12989 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
12990 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
12991 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
12993 /* Static Properties */
12995 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
12998 * InputWidget is the base class for all input widgets, which
12999 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
13000 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
13001 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
13003 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
13007 * @extends OO.ui.Widget
13008 * @mixins OO.ui.mixin.FlaggedElement
13009 * @mixins OO.ui.mixin.TabIndexedElement
13012 * @param {Object} [config] Configuration options
13013 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
13014 * @cfg {string} [value=''] The value of the input.
13015 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
13016 * before it is accepted.
13018 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
13019 // Configuration initialization
13020 config
= config
|| {};
13022 // Parent constructor
13023 OO
.ui
.InputWidget
.super.call( this, config
);
13026 this.$input
= this.getInputElement( config
);
13028 this.inputFilter
= config
.inputFilter
;
13030 // Mixin constructors
13031 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
13032 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
13035 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
13039 .attr( 'name', config
.name
)
13040 .prop( 'disabled', this.isDisabled() );
13041 this.$element
.addClass( 'oo-ui-inputWidget' ).append( this.$input
, $( '<span>' ) );
13042 this.setValue( config
.value
);
13047 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
13048 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
13049 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13051 /* Static Properties */
13053 OO
.ui
.InputWidget
.static.supportsSimpleLabel
= true;
13060 * A change event is emitted when the value of the input changes.
13062 * @param {string} value
13068 * Get input element.
13070 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
13071 * different circumstances. The element must have a `value` property (like form elements).
13074 * @param {Object} config Configuration options
13075 * @return {jQuery} Input element
13077 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
13078 return $( '<input>' );
13082 * Handle potentially value-changing events.
13085 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
13087 OO
.ui
.InputWidget
.prototype.onEdit = function () {
13089 if ( !this.isDisabled() ) {
13090 // Allow the stack to clear so the value will be updated
13091 setTimeout( function () {
13092 widget
.setValue( widget
.$input
.val() );
13098 * Get the value of the input.
13100 * @return {string} Input value
13102 OO
.ui
.InputWidget
.prototype.getValue = function () {
13103 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
13104 // it, and we won't know unless they're kind enough to trigger a 'change' event.
13105 var value
= this.$input
.val();
13106 if ( this.value
!== value
) {
13107 this.setValue( value
);
13113 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
13115 * @param {boolean} isRTL
13116 * Direction is right-to-left
13118 OO
.ui
.InputWidget
.prototype.setRTL = function ( isRTL
) {
13119 this.$input
.prop( 'dir', isRTL
? 'rtl' : 'ltr' );
13123 * Set the value of the input.
13125 * @param {string} value New value
13129 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
13130 value
= this.cleanUpValue( value
);
13131 // Update the DOM if it has changed. Note that with cleanUpValue, it
13132 // is possible for the DOM value to change without this.value changing.
13133 if ( this.$input
.val() !== value
) {
13134 this.$input
.val( value
);
13136 if ( this.value
!== value
) {
13137 this.value
= value
;
13138 this.emit( 'change', this.value
);
13144 * Clean up incoming value.
13146 * Ensures value is a string, and converts undefined and null to empty string.
13149 * @param {string} value Original value
13150 * @return {string} Cleaned up value
13152 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
13153 if ( value
=== undefined || value
=== null ) {
13155 } else if ( this.inputFilter
) {
13156 return this.inputFilter( String( value
) );
13158 return String( value
);
13163 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
13164 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
13167 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
13168 if ( !this.isDisabled() ) {
13169 if ( this.$input
.is( ':checkbox, :radio' ) ) {
13170 this.$input
.click();
13172 if ( this.$input
.is( ':input' ) ) {
13173 this.$input
[ 0 ].focus();
13181 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
13182 OO
.ui
.InputWidget
.super.prototype.setDisabled
.call( this, state
);
13183 if ( this.$input
) {
13184 this.$input
.prop( 'disabled', this.isDisabled() );
13194 OO
.ui
.InputWidget
.prototype.focus = function () {
13195 this.$input
[ 0 ].focus();
13204 OO
.ui
.InputWidget
.prototype.blur = function () {
13205 this.$input
[ 0 ].blur();
13210 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
13211 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
13212 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
13213 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
13214 * [OOjs UI documentation on MediaWiki] [1] for more information.
13217 * // A ButtonInputWidget rendered as an HTML button, the default.
13218 * var button = new OO.ui.ButtonInputWidget( {
13219 * label: 'Input button',
13223 * $( 'body' ).append( button.$element );
13225 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
13228 * @extends OO.ui.InputWidget
13229 * @mixins OO.ui.mixin.ButtonElement
13230 * @mixins OO.ui.mixin.IconElement
13231 * @mixins OO.ui.mixin.IndicatorElement
13232 * @mixins OO.ui.mixin.LabelElement
13233 * @mixins OO.ui.mixin.TitledElement
13236 * @param {Object} [config] Configuration options
13237 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
13238 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
13239 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
13240 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
13241 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
13243 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
13244 // Configuration initialization
13245 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
13247 // Properties (must be set before parent constructor, which calls #setValue)
13248 this.useInputTag
= config
.useInputTag
;
13250 // Parent constructor
13251 OO
.ui
.ButtonInputWidget
.super.call( this, config
);
13253 // Mixin constructors
13254 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
13255 OO
.ui
.mixin
.IconElement
.call( this, config
);
13256 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13257 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13258 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
13261 if ( !config
.useInputTag
) {
13262 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
13264 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
13269 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
13270 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
13271 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
13272 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
13273 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
13274 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
13282 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
13283 var type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ?
13286 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
13292 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
13294 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
13295 * text, or `null` for no label
13298 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
13299 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
13301 if ( this.useInputTag
) {
13302 if ( typeof label
=== 'function' ) {
13303 label
= OO
.ui
.resolveMsg( label
);
13305 if ( label
instanceof jQuery
) {
13306 label
= label
.text();
13311 this.$input
.val( label
);
13318 * Set the value of the input.
13320 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
13321 * they do not support {@link #value values}.
13323 * @param {string} value New value
13326 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
13327 if ( !this.useInputTag
) {
13328 OO
.ui
.ButtonInputWidget
.super.prototype.setValue
.call( this, value
);
13334 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
13335 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
13336 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
13337 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
13339 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
13342 * // An example of selected, unselected, and disabled checkbox inputs
13343 * var checkbox1=new OO.ui.CheckboxInputWidget( {
13347 * var checkbox2=new OO.ui.CheckboxInputWidget( {
13350 * var checkbox3=new OO.ui.CheckboxInputWidget( {
13354 * // Create a fieldset layout with fields for each checkbox.
13355 * var fieldset = new OO.ui.FieldsetLayout( {
13356 * label: 'Checkboxes'
13358 * fieldset.addItems( [
13359 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
13360 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
13361 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
13363 * $( 'body' ).append( fieldset.$element );
13365 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
13368 * @extends OO.ui.InputWidget
13371 * @param {Object} [config] Configuration options
13372 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
13374 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
13375 // Configuration initialization
13376 config
= config
|| {};
13378 // Parent constructor
13379 OO
.ui
.CheckboxInputWidget
.super.call( this, config
);
13382 this.$element
.addClass( 'oo-ui-checkboxInputWidget' );
13383 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
13388 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
13396 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
13397 return $( '<input type="checkbox" />' );
13403 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
13405 if ( !this.isDisabled() ) {
13406 // Allow the stack to clear so the value will be updated
13407 setTimeout( function () {
13408 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
13414 * Set selection state of this checkbox.
13416 * @param {boolean} state `true` for selected
13419 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
13421 if ( this.selected
!== state
) {
13422 this.selected
= state
;
13423 this.$input
.prop( 'checked', this.selected
);
13424 this.emit( 'change', this.selected
);
13430 * Check if this checkbox is selected.
13432 * @return {boolean} Checkbox is selected
13434 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
13435 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
13436 // it, and we won't know unless they're kind enough to trigger a 'change' event.
13437 var selected
= this.$input
.prop( 'checked' );
13438 if ( this.selected
!== selected
) {
13439 this.setSelected( selected
);
13441 return this.selected
;
13445 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
13446 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
13447 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
13448 * more information about input widgets.
13450 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
13451 * are no options. If no `value` configuration option is provided, the first option is selected.
13452 * If you need a state representing no value (no option being selected), use a DropdownWidget.
13454 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
13457 * // Example: A DropdownInputWidget with three options
13458 * var dropdownInput = new OO.ui.DropdownInputWidget( {
13460 * { data: 'a', label: 'First' },
13461 * { data: 'b', label: 'Second'},
13462 * { data: 'c', label: 'Third' }
13465 * $( 'body' ).append( dropdownInput.$element );
13467 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
13470 * @extends OO.ui.InputWidget
13473 * @param {Object} [config] Configuration options
13474 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
13476 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
13477 // Configuration initialization
13478 config
= config
|| {};
13480 // Properties (must be done before parent constructor which calls #setDisabled)
13481 this.dropdownWidget
= new OO
.ui
.DropdownWidget();
13483 // Parent constructor
13484 OO
.ui
.DropdownInputWidget
.super.call( this, config
);
13487 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
13490 this.setOptions( config
.options
|| [] );
13492 .addClass( 'oo-ui-dropdownInputWidget' )
13493 .append( this.dropdownWidget
.$element
);
13498 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
13506 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
13507 return $( '<input type="hidden">' );
13511 * Handles menu select events.
13514 * @param {OO.ui.MenuOptionWidget} item Selected menu item
13516 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
13517 this.setValue( item
.getData() );
13523 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
13524 this.dropdownWidget
.getMenu().selectItemByData( value
);
13525 OO
.ui
.DropdownInputWidget
.super.prototype.setValue
.call( this, value
);
13532 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
13533 this.dropdownWidget
.setDisabled( state
);
13534 OO
.ui
.DropdownInputWidget
.super.prototype.setDisabled
.call( this, state
);
13539 * Set the options available for this input.
13541 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
13544 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
13545 var value
= this.getValue();
13547 // Rebuild the dropdown menu
13548 this.dropdownWidget
.getMenu()
13550 .addItems( options
.map( function ( opt
) {
13551 return new OO
.ui
.MenuOptionWidget( {
13553 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
13557 // Restore the previous value, or reset to something sensible
13558 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
13559 // Previous value is still available, ensure consistency with the dropdown
13560 this.setValue( value
);
13562 // No longer valid, reset
13563 if ( options
.length
) {
13564 this.setValue( options
[ 0 ].data
);
13574 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
13575 this.dropdownWidget
.getMenu().toggle( true );
13582 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
13583 this.dropdownWidget
.getMenu().toggle( false );
13588 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
13589 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
13590 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
13591 * please see the [OOjs UI documentation on MediaWiki][1].
13593 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
13596 * // An example of selected, unselected, and disabled radio inputs
13597 * var radio1 = new OO.ui.RadioInputWidget( {
13601 * var radio2 = new OO.ui.RadioInputWidget( {
13604 * var radio3 = new OO.ui.RadioInputWidget( {
13608 * // Create a fieldset layout with fields for each radio button.
13609 * var fieldset = new OO.ui.FieldsetLayout( {
13610 * label: 'Radio inputs'
13612 * fieldset.addItems( [
13613 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
13614 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
13615 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
13617 * $( 'body' ).append( fieldset.$element );
13619 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
13622 * @extends OO.ui.InputWidget
13625 * @param {Object} [config] Configuration options
13626 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
13628 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
13629 // Configuration initialization
13630 config
= config
|| {};
13632 // Parent constructor
13633 OO
.ui
.RadioInputWidget
.super.call( this, config
);
13636 this.$element
.addClass( 'oo-ui-radioInputWidget' );
13637 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
13642 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
13650 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
13651 return $( '<input type="radio" />' );
13657 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
13658 // RadioInputWidget doesn't track its state.
13662 * Set selection state of this radio button.
13664 * @param {boolean} state `true` for selected
13667 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
13668 // RadioInputWidget doesn't track its state.
13669 this.$input
.prop( 'checked', state
);
13674 * Check if this radio button is selected.
13676 * @return {boolean} Radio is selected
13678 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
13679 return this.$input
.prop( 'checked' );
13683 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
13684 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
13685 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
13686 * more information about input widgets.
13688 * This and OO.ui.DropdownInputWidget support the same configuration options.
13691 * // Example: A RadioSelectInputWidget with three options
13692 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
13694 * { data: 'a', label: 'First' },
13695 * { data: 'b', label: 'Second'},
13696 * { data: 'c', label: 'Third' }
13699 * $( 'body' ).append( radioSelectInput.$element );
13701 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
13704 * @extends OO.ui.InputWidget
13707 * @param {Object} [config] Configuration options
13708 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
13710 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
13711 // Configuration initialization
13712 config
= config
|| {};
13714 // Properties (must be done before parent constructor which calls #setDisabled)
13715 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
13717 // Parent constructor
13718 OO
.ui
.RadioSelectInputWidget
.super.call( this, config
);
13721 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
13724 this.setOptions( config
.options
|| [] );
13726 .addClass( 'oo-ui-radioSelectInputWidget' )
13727 .append( this.radioSelectWidget
.$element
);
13732 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
13734 /* Static Properties */
13736 OO
.ui
.RadioSelectInputWidget
.static.supportsSimpleLabel
= false;
13744 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
13745 return $( '<input type="hidden">' );
13749 * Handles menu select events.
13752 * @param {OO.ui.RadioOptionWidget} item Selected menu item
13754 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
13755 this.setValue( item
.getData() );
13761 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
13762 this.radioSelectWidget
.selectItemByData( value
);
13763 OO
.ui
.RadioSelectInputWidget
.super.prototype.setValue
.call( this, value
);
13770 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
13771 this.radioSelectWidget
.setDisabled( state
);
13772 OO
.ui
.RadioSelectInputWidget
.super.prototype.setDisabled
.call( this, state
);
13777 * Set the options available for this input.
13779 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
13782 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
13783 var value
= this.getValue();
13785 // Rebuild the radioSelect menu
13786 this.radioSelectWidget
13788 .addItems( options
.map( function ( opt
) {
13789 return new OO
.ui
.RadioOptionWidget( {
13791 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
13795 // Restore the previous value, or reset to something sensible
13796 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
13797 // Previous value is still available, ensure consistency with the radioSelect
13798 this.setValue( value
);
13800 // No longer valid, reset
13801 if ( options
.length
) {
13802 this.setValue( options
[ 0 ].data
);
13810 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
13811 * size of the field as well as its presentation. In addition, these widgets can be configured
13812 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
13813 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
13814 * which modifies incoming values rather than validating them.
13815 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
13817 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
13820 * // Example of a text input widget
13821 * var textInput = new OO.ui.TextInputWidget( {
13822 * value: 'Text input'
13824 * $( 'body' ).append( textInput.$element );
13826 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
13829 * @extends OO.ui.InputWidget
13830 * @mixins OO.ui.mixin.IconElement
13831 * @mixins OO.ui.mixin.IndicatorElement
13832 * @mixins OO.ui.mixin.PendingElement
13833 * @mixins OO.ui.mixin.LabelElement
13836 * @param {Object} [config] Configuration options
13837 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
13838 * 'email' or 'url'. Ignored if `multiline` is true.
13839 * @cfg {string} [placeholder] Placeholder text
13840 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
13841 * instruct the browser to focus this widget.
13842 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
13843 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
13844 * @cfg {boolean} [multiline=false] Allow multiple lines of text
13845 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
13846 * Use the #maxRows config to specify a maximum number of displayed rows.
13847 * @cfg {boolean} [maxRows=10] Maximum number of rows to display when #autosize is set to true.
13848 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
13849 * the value or placeholder text: `'before'` or `'after'`
13850 * @cfg {boolean} [required=false] Mark the field as required
13851 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
13852 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
13853 * (the value must contain only numbers); when RegExp, a regular expression that must match the
13854 * value for it to be considered valid; when Function, a function receiving the value as parameter
13855 * that must return true, or promise resolving to true, for it to be considered valid.
13857 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
13858 // Configuration initialization
13859 config
= $.extend( {
13861 labelPosition
: 'after',
13865 // Parent constructor
13866 OO
.ui
.TextInputWidget
.super.call( this, config
);
13868 // Mixin constructors
13869 OO
.ui
.mixin
.IconElement
.call( this, config
);
13870 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13871 OO
.ui
.mixin
.PendingElement
.call( this, config
);
13872 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13875 this.readOnly
= false;
13876 this.multiline
= !!config
.multiline
;
13877 this.autosize
= !!config
.autosize
;
13878 this.maxRows
= config
.maxRows
;
13879 this.validate
= null;
13881 // Clone for resizing
13882 if ( this.autosize
) {
13883 this.$clone
= this.$input
13885 .insertAfter( this.$input
)
13886 .attr( 'aria-hidden', 'true' )
13887 .addClass( 'oo-ui-element-hidden' );
13890 this.setValidation( config
.validate
);
13891 this.setLabelPosition( config
.labelPosition
);
13895 keypress
: this.onKeyPress
.bind( this ),
13896 blur
: this.onBlur
.bind( this )
13899 focus
: this.onElementAttach
.bind( this )
13901 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
13902 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
13903 this.on( 'labelChange', this.updatePosition
.bind( this ) );
13904 this.connect( this, { change
: 'onChange' } );
13908 .addClass( 'oo-ui-textInputWidget' )
13909 .append( this.$icon
, this.$indicator
);
13910 this.setReadOnly( !!config
.readOnly
);
13911 if ( config
.placeholder
) {
13912 this.$input
.attr( 'placeholder', config
.placeholder
);
13914 if ( config
.maxLength
!== undefined ) {
13915 this.$input
.attr( 'maxlength', config
.maxLength
);
13917 if ( config
.autofocus
) {
13918 this.$input
.attr( 'autofocus', 'autofocus' );
13920 if ( config
.required
) {
13921 this.$input
.attr( 'required', 'required' );
13922 this.$input
.attr( 'aria-required', 'true' );
13924 if ( this.label
|| config
.autosize
) {
13925 this.installParentChangeDetector();
13931 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
13932 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
13933 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
13934 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
13935 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
13937 /* Static properties */
13939 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
13947 * An `enter` event is emitted when the user presses 'enter' inside the text box.
13949 * Not emitted if the input is multiline.
13957 * Handle icon mouse down events.
13960 * @param {jQuery.Event} e Mouse down event
13963 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
13964 if ( e
.which
=== 1 ) {
13965 this.$input
[ 0 ].focus();
13971 * Handle indicator mouse down events.
13974 * @param {jQuery.Event} e Mouse down event
13977 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
13978 if ( e
.which
=== 1 ) {
13979 this.$input
[ 0 ].focus();
13985 * Handle key press events.
13988 * @param {jQuery.Event} e Key press event
13989 * @fires enter If enter key is pressed and input is not multiline
13991 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
13992 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
13993 this.emit( 'enter', e
);
13998 * Handle blur events.
14001 * @param {jQuery.Event} e Blur event
14003 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
14004 this.setValidityFlag();
14008 * Handle element attach events.
14011 * @param {jQuery.Event} e Element attach event
14013 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
14014 // Any previously calculated size is now probably invalid if we reattached elsewhere
14015 this.valCache
= null;
14017 this.positionLabel();
14021 * Handle change events.
14023 * @param {string} value
14026 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
14027 this.setValidityFlag();
14032 * Check if the input is {@link #readOnly read-only}.
14034 * @return {boolean}
14036 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
14037 return this.readOnly
;
14041 * Set the {@link #readOnly read-only} state of the input.
14043 * @param {boolean} state Make input read-only
14046 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
14047 this.readOnly
= !!state
;
14048 this.$input
.prop( 'readOnly', this.readOnly
);
14053 * Support function for making #onElementAttach work across browsers.
14055 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
14056 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
14058 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
14059 * first time that the element gets attached to the documented.
14061 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
14062 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
14063 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
14066 if ( MutationObserver
) {
14067 // The new way. If only it wasn't so ugly.
14069 if ( this.$element
.closest( 'html' ).length
) {
14070 // Widget is attached already, do nothing. This breaks the functionality of this function when
14071 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
14072 // would require observation of the whole document, which would hurt performance of other,
14073 // more important code.
14077 // Find topmost node in the tree
14078 topmostNode
= this.$element
[0];
14079 while ( topmostNode
.parentNode
) {
14080 topmostNode
= topmostNode
.parentNode
;
14083 // We have no way to detect the $element being attached somewhere without observing the entire
14084 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
14085 // parent node of $element, and instead detect when $element is removed from it (and thus
14086 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
14087 // doesn't get attached, we end up back here and create the parent.
14089 mutationObserver
= new MutationObserver( function ( mutations
) {
14090 var i
, j
, removedNodes
;
14091 for ( i
= 0; i
< mutations
.length
; i
++ ) {
14092 removedNodes
= mutations
[ i
].removedNodes
;
14093 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
14094 if ( removedNodes
[ j
] === topmostNode
) {
14095 setTimeout( onRemove
, 0 );
14102 onRemove = function () {
14103 // If the node was attached somewhere else, report it
14104 if ( widget
.$element
.closest( 'html' ).length
) {
14105 widget
.onElementAttach();
14107 mutationObserver
.disconnect();
14108 widget
.installParentChangeDetector();
14111 // Create a fake parent and observe it
14112 fakeParentNode
= $( '<div>' ).append( this.$element
)[0];
14113 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
14115 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
14116 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
14117 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
14122 * Automatically adjust the size of the text input.
14124 * This only affects #multiline inputs that are {@link #autosize autosized}.
14128 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
14129 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
, idealHeight
;
14131 if ( this.multiline
&& this.autosize
&& this.$input
.val() !== this.valCache
) {
14133 .val( this.$input
.val() )
14134 .attr( 'rows', '' )
14135 // Set inline height property to 0 to measure scroll height
14136 .css( 'height', 0 );
14138 this.$clone
.removeClass( 'oo-ui-element-hidden' );
14140 this.valCache
= this.$input
.val();
14142 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
14144 // Remove inline height property to measure natural heights
14145 this.$clone
.css( 'height', '' );
14146 innerHeight
= this.$clone
.innerHeight();
14147 outerHeight
= this.$clone
.outerHeight();
14149 // Measure max rows height
14151 .attr( 'rows', this.maxRows
)
14152 .css( 'height', 'auto' )
14154 maxInnerHeight
= this.$clone
.innerHeight();
14156 // Difference between reported innerHeight and scrollHeight with no scrollbars present
14157 // Equals 1 on Blink-based browsers and 0 everywhere else
14158 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
14159 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
14161 this.$clone
.addClass( 'oo-ui-element-hidden' );
14163 // Only apply inline height when expansion beyond natural height is needed
14164 if ( idealHeight
> innerHeight
) {
14165 // Use the difference between the inner and outer height as a buffer
14166 this.$input
.css( 'height', idealHeight
+ ( outerHeight
- innerHeight
) );
14168 this.$input
.css( 'height', '' );
14178 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
14179 var type
= [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config
.type
) !== -1 ?
14182 return config
.multiline
? $( '<textarea>' ) : $( '<input type="' + type
+ '" />' );
14186 * Check if the input supports multiple lines.
14188 * @return {boolean}
14190 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
14191 return !!this.multiline
;
14195 * Check if the input automatically adjusts its size.
14197 * @return {boolean}
14199 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
14200 return !!this.autosize
;
14204 * Select the entire text of the input.
14208 OO
.ui
.TextInputWidget
.prototype.select = function () {
14209 this.$input
.select();
14214 * Set the validation pattern.
14216 * The validation pattern is either a regular expression, a function, or the symbolic name of a
14217 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
14218 * value must contain only numbers).
14220 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
14221 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
14223 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
14224 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
14225 this.validate
= validate
;
14227 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
14232 * Sets the 'invalid' flag appropriately.
14234 * @param {boolean} [isValid] Optionally override validation result
14236 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
14238 setFlag = function ( valid
) {
14240 widget
.$input
.attr( 'aria-invalid', 'true' );
14242 widget
.$input
.removeAttr( 'aria-invalid' );
14244 widget
.setFlags( { invalid
: !valid
} );
14247 if ( isValid
!== undefined ) {
14248 setFlag( isValid
);
14250 this.isValid().done( setFlag
);
14255 * Check if a value is valid.
14257 * This method returns a promise that resolves with a boolean `true` if the current value is
14258 * considered valid according to the supplied {@link #validate validation pattern}.
14260 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
14262 OO
.ui
.TextInputWidget
.prototype.isValid = function () {
14263 if ( this.validate
instanceof Function
) {
14264 var result
= this.validate( this.getValue() );
14265 if ( $.isFunction( result
.promise
) ) {
14266 return result
.promise();
14268 return $.Deferred().resolve( !!result
).promise();
14271 return $.Deferred().resolve( !!this.getValue().match( this.validate
) ).promise();
14276 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
14278 * @param {string} labelPosition Label position, 'before' or 'after'
14281 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
14282 this.labelPosition
= labelPosition
;
14283 this.updatePosition();
14288 * Deprecated alias of #setLabelPosition
14290 * @deprecated Use setLabelPosition instead.
14292 OO
.ui
.TextInputWidget
.prototype.setPosition
=
14293 OO
.ui
.TextInputWidget
.prototype.setLabelPosition
;
14296 * Update the position of the inline label.
14298 * This method is called by #setLabelPosition, and can also be called on its own if
14299 * something causes the label to be mispositioned.
14304 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
14305 var after
= this.labelPosition
=== 'after';
14308 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
14309 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
14311 if ( this.label
) {
14312 this.positionLabel();
14319 * Position the label by setting the correct padding on the input.
14324 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
14325 // Clear old values
14327 // Clear old values if present
14329 'padding-right': '',
14333 if ( this.label
) {
14334 this.$element
.append( this.$label
);
14336 this.$label
.detach();
14340 var after
= this.labelPosition
=== 'after',
14341 rtl
= this.$element
.css( 'direction' ) === 'rtl',
14342 property
= after
=== rtl
? 'padding-left' : 'padding-right';
14344 this.$input
.css( property
, this.$label
.outerWidth( true ) );
14350 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
14351 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
14352 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
14354 * - by typing a value in the text input field. If the value exactly matches the value of a menu
14355 * option, that option will appear to be selected.
14356 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
14359 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
14362 * // Example: A ComboBoxWidget.
14363 * var comboBox = new OO.ui.ComboBoxWidget( {
14364 * label: 'ComboBoxWidget',
14365 * input: { value: 'Option One' },
14368 * new OO.ui.MenuOptionWidget( {
14369 * data: 'Option 1',
14370 * label: 'Option One'
14372 * new OO.ui.MenuOptionWidget( {
14373 * data: 'Option 2',
14374 * label: 'Option Two'
14376 * new OO.ui.MenuOptionWidget( {
14377 * data: 'Option 3',
14378 * label: 'Option Three'
14380 * new OO.ui.MenuOptionWidget( {
14381 * data: 'Option 4',
14382 * label: 'Option Four'
14384 * new OO.ui.MenuOptionWidget( {
14385 * data: 'Option 5',
14386 * label: 'Option Five'
14391 * $( 'body' ).append( comboBox.$element );
14393 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
14396 * @extends OO.ui.Widget
14397 * @mixins OO.ui.mixin.TabIndexedElement
14400 * @param {Object} [config] Configuration options
14401 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
14402 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
14403 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
14404 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
14405 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
14407 OO
.ui
.ComboBoxWidget
= function OoUiComboBoxWidget( config
) {
14408 // Configuration initialization
14409 config
= config
|| {};
14411 // Parent constructor
14412 OO
.ui
.ComboBoxWidget
.super.call( this, config
);
14414 // Properties (must be set before TabIndexedElement constructor call)
14415 this.$indicator
= this.$( '<span>' );
14417 // Mixin constructors
14418 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
14421 this.$overlay
= config
.$overlay
|| this.$element
;
14422 this.input
= new OO
.ui
.TextInputWidget( $.extend(
14425 $indicator
: this.$indicator
,
14426 disabled
: this.isDisabled()
14430 this.input
.$input
.eq( 0 ).attr( {
14432 'aria-autocomplete': 'list'
14434 this.menu
= new OO
.ui
.TextInputMenuSelectWidget( this.input
, $.extend(
14438 disabled
: this.isDisabled()
14444 this.$indicator
.on( {
14445 click
: this.onClick
.bind( this ),
14446 keypress
: this.onKeyPress
.bind( this )
14448 this.input
.connect( this, {
14449 change
: 'onInputChange',
14450 enter
: 'onInputEnter'
14452 this.menu
.connect( this, {
14453 choose
: 'onMenuChoose',
14454 add
: 'onMenuItemsChange',
14455 remove
: 'onMenuItemsChange'
14459 this.$element
.addClass( 'oo-ui-comboBoxWidget' ).append( this.input
.$element
);
14460 this.$overlay
.append( this.menu
.$element
);
14461 this.onMenuItemsChange();
14466 OO
.inheritClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.Widget
);
14467 OO
.mixinClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.mixin
.TabIndexedElement
);
14472 * Get the combobox's menu.
14473 * @return {OO.ui.TextInputMenuSelectWidget} Menu widget
14475 OO
.ui
.ComboBoxWidget
.prototype.getMenu = function () {
14480 * Get the combobox's text input widget.
14481 * @return {OO.ui.TextInputWidget} Text input widget
14483 OO
.ui
.ComboBoxWidget
.prototype.getInput = function () {
14488 * Handle input change events.
14491 * @param {string} value New value
14493 OO
.ui
.ComboBoxWidget
.prototype.onInputChange = function ( value
) {
14494 var match
= this.menu
.getItemFromData( value
);
14496 this.menu
.selectItem( match
);
14497 if ( this.menu
.getHighlightedItem() ) {
14498 this.menu
.highlightItem( match
);
14501 if ( !this.isDisabled() ) {
14502 this.menu
.toggle( true );
14507 * Handle mouse click events.
14511 * @param {jQuery.Event} e Mouse click event
14513 OO
.ui
.ComboBoxWidget
.prototype.onClick = function ( e
) {
14514 if ( !this.isDisabled() && e
.which
=== 1 ) {
14515 this.menu
.toggle();
14516 this.input
.$input
[ 0 ].focus();
14522 * Handle key press events.
14526 * @param {jQuery.Event} e Key press event
14528 OO
.ui
.ComboBoxWidget
.prototype.onKeyPress = function ( e
) {
14529 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
14530 this.menu
.toggle();
14531 this.input
.$input
[ 0 ].focus();
14537 * Handle input enter events.
14541 OO
.ui
.ComboBoxWidget
.prototype.onInputEnter = function () {
14542 if ( !this.isDisabled() ) {
14543 this.menu
.toggle( false );
14548 * Handle menu choose events.
14551 * @param {OO.ui.OptionWidget} item Chosen item
14553 OO
.ui
.ComboBoxWidget
.prototype.onMenuChoose = function ( item
) {
14554 this.input
.setValue( item
.getData() );
14558 * Handle menu item change events.
14562 OO
.ui
.ComboBoxWidget
.prototype.onMenuItemsChange = function () {
14563 var match
= this.menu
.getItemFromData( this.input
.getValue() );
14564 this.menu
.selectItem( match
);
14565 if ( this.menu
.getHighlightedItem() ) {
14566 this.menu
.highlightItem( match
);
14568 this.$element
.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu
.isEmpty() );
14574 OO
.ui
.ComboBoxWidget
.prototype.setDisabled = function ( disabled
) {
14576 OO
.ui
.ComboBoxWidget
.super.prototype.setDisabled
.call( this, disabled
);
14578 if ( this.input
) {
14579 this.input
.setDisabled( this.isDisabled() );
14582 this.menu
.setDisabled( this.isDisabled() );
14589 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
14590 * be configured with a `label` option that is set to a string, a label node, or a function:
14592 * - String: a plaintext string
14593 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
14594 * label that includes a link or special styling, such as a gray color or additional graphical elements.
14595 * - Function: a function that will produce a string in the future. Functions are used
14596 * in cases where the value of the label is not currently defined.
14598 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
14599 * will come into focus when the label is clicked.
14602 * // Examples of LabelWidgets
14603 * var label1 = new OO.ui.LabelWidget( {
14604 * label: 'plaintext label'
14606 * var label2 = new OO.ui.LabelWidget( {
14607 * label: $( '<a href="default.html">jQuery label</a>' )
14609 * // Create a fieldset layout with fields for each example
14610 * var fieldset = new OO.ui.FieldsetLayout();
14611 * fieldset.addItems( [
14612 * new OO.ui.FieldLayout( label1 ),
14613 * new OO.ui.FieldLayout( label2 )
14615 * $( 'body' ).append( fieldset.$element );
14619 * @extends OO.ui.Widget
14620 * @mixins OO.ui.mixin.LabelElement
14623 * @param {Object} [config] Configuration options
14624 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
14625 * Clicking the label will focus the specified input field.
14627 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
14628 // Configuration initialization
14629 config
= config
|| {};
14631 // Parent constructor
14632 OO
.ui
.LabelWidget
.super.call( this, config
);
14634 // Mixin constructors
14635 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
14636 OO
.ui
.mixin
.TitledElement
.call( this, config
);
14639 this.input
= config
.input
;
14642 if ( this.input
instanceof OO
.ui
.InputWidget
) {
14643 this.$element
.on( 'click', this.onClick
.bind( this ) );
14647 this.$element
.addClass( 'oo-ui-labelWidget' );
14652 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
14653 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
14654 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
14656 /* Static Properties */
14658 OO
.ui
.LabelWidget
.static.tagName
= 'span';
14663 * Handles label mouse click events.
14666 * @param {jQuery.Event} e Mouse click event
14668 OO
.ui
.LabelWidget
.prototype.onClick = function () {
14669 this.input
.simulateLabelClick();
14674 * OptionWidgets are special elements that can be selected and configured with data. The
14675 * data is often unique for each option, but it does not have to be. OptionWidgets are used
14676 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
14677 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
14679 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14682 * @extends OO.ui.Widget
14683 * @mixins OO.ui.mixin.LabelElement
14684 * @mixins OO.ui.mixin.FlaggedElement
14687 * @param {Object} [config] Configuration options
14689 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
14690 // Configuration initialization
14691 config
= config
|| {};
14693 // Parent constructor
14694 OO
.ui
.OptionWidget
.super.call( this, config
);
14696 // Mixin constructors
14697 OO
.ui
.mixin
.ItemWidget
.call( this );
14698 OO
.ui
.mixin
.LabelElement
.call( this, config
);
14699 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
14702 this.selected
= false;
14703 this.highlighted
= false;
14704 this.pressed
= false;
14708 .data( 'oo-ui-optionWidget', this )
14709 .attr( 'role', 'option' )
14710 .addClass( 'oo-ui-optionWidget' )
14711 .append( this.$label
);
14716 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
14717 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
14718 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
14719 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
14721 /* Static Properties */
14723 OO
.ui
.OptionWidget
.static.selectable
= true;
14725 OO
.ui
.OptionWidget
.static.highlightable
= true;
14727 OO
.ui
.OptionWidget
.static.pressable
= true;
14729 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
14734 * Check if the option can be selected.
14736 * @return {boolean} Item is selectable
14738 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
14739 return this.constructor.static.selectable
&& !this.isDisabled();
14743 * Check if the option can be highlighted. A highlight indicates that the option
14744 * may be selected when a user presses enter or clicks. Disabled items cannot
14747 * @return {boolean} Item is highlightable
14749 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
14750 return this.constructor.static.highlightable
&& !this.isDisabled();
14754 * Check if the option can be pressed. The pressed state occurs when a user mouses
14755 * down on an item, but has not yet let go of the mouse.
14757 * @return {boolean} Item is pressable
14759 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
14760 return this.constructor.static.pressable
&& !this.isDisabled();
14764 * Check if the option is selected.
14766 * @return {boolean} Item is selected
14768 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
14769 return this.selected
;
14773 * Check if the option is highlighted. A highlight indicates that the
14774 * item may be selected when a user presses enter or clicks.
14776 * @return {boolean} Item is highlighted
14778 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
14779 return this.highlighted
;
14783 * Check if the option is pressed. The pressed state occurs when a user mouses
14784 * down on an item, but has not yet let go of the mouse. The item may appear
14785 * selected, but it will not be selected until the user releases the mouse.
14787 * @return {boolean} Item is pressed
14789 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
14790 return this.pressed
;
14794 * Set the option’s selected state. In general, all modifications to the selection
14795 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
14796 * method instead of this method.
14798 * @param {boolean} [state=false] Select option
14801 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
14802 if ( this.constructor.static.selectable
) {
14803 this.selected
= !!state
;
14805 .toggleClass( 'oo-ui-optionWidget-selected', state
)
14806 .attr( 'aria-selected', state
.toString() );
14807 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
14808 this.scrollElementIntoView();
14810 this.updateThemeClasses();
14816 * Set the option’s highlighted state. In general, all programmatic
14817 * modifications to the highlight should be handled by the
14818 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
14819 * method instead of this method.
14821 * @param {boolean} [state=false] Highlight option
14824 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
14825 if ( this.constructor.static.highlightable
) {
14826 this.highlighted
= !!state
;
14827 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
14828 this.updateThemeClasses();
14834 * Set the option’s pressed state. In general, all
14835 * programmatic modifications to the pressed state should be handled by the
14836 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
14837 * method instead of this method.
14839 * @param {boolean} [state=false] Press option
14842 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
14843 if ( this.constructor.static.pressable
) {
14844 this.pressed
= !!state
;
14845 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
14846 this.updateThemeClasses();
14852 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
14853 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
14854 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
14855 * options. For more information about options and selects, please see the
14856 * [OOjs UI documentation on MediaWiki][1].
14859 * // Decorated options in a select widget
14860 * var select = new OO.ui.SelectWidget( {
14862 * new OO.ui.DecoratedOptionWidget( {
14864 * label: 'Option with icon',
14867 * new OO.ui.DecoratedOptionWidget( {
14869 * label: 'Option with indicator',
14870 * indicator: 'next'
14874 * $( 'body' ).append( select.$element );
14876 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14879 * @extends OO.ui.OptionWidget
14880 * @mixins OO.ui.mixin.IconElement
14881 * @mixins OO.ui.mixin.IndicatorElement
14884 * @param {Object} [config] Configuration options
14886 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
14887 // Parent constructor
14888 OO
.ui
.DecoratedOptionWidget
.super.call( this, config
);
14890 // Mixin constructors
14891 OO
.ui
.mixin
.IconElement
.call( this, config
);
14892 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
14896 .addClass( 'oo-ui-decoratedOptionWidget' )
14897 .prepend( this.$icon
)
14898 .append( this.$indicator
);
14903 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
14904 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
14905 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
14908 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
14909 * can be selected and configured with data. The class is
14910 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
14911 * [OOjs UI documentation on MediaWiki] [1] for more information.
14913 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
14916 * @extends OO.ui.DecoratedOptionWidget
14917 * @mixins OO.ui.mixin.ButtonElement
14918 * @mixins OO.ui.mixin.TabIndexedElement
14921 * @param {Object} [config] Configuration options
14923 OO
.ui
.ButtonOptionWidget
= function OoUiButtonOptionWidget( config
) {
14924 // Configuration initialization
14925 config
= $.extend( { tabIndex
: -1 }, config
);
14927 // Parent constructor
14928 OO
.ui
.ButtonOptionWidget
.super.call( this, config
);
14930 // Mixin constructors
14931 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
14932 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
14935 this.$element
.addClass( 'oo-ui-buttonOptionWidget' );
14936 this.$button
.append( this.$element
.contents() );
14937 this.$element
.append( this.$button
);
14942 OO
.inheritClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
14943 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.ButtonElement
);
14944 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.TabIndexedElement
);
14946 /* Static Properties */
14948 // Allow button mouse down events to pass through so they can be handled by the parent select widget
14949 OO
.ui
.ButtonOptionWidget
.static.cancelButtonMouseDownEvents
= false;
14951 OO
.ui
.ButtonOptionWidget
.static.highlightable
= false;
14958 OO
.ui
.ButtonOptionWidget
.prototype.setSelected = function ( state
) {
14959 OO
.ui
.ButtonOptionWidget
.super.prototype.setSelected
.call( this, state
);
14961 if ( this.constructor.static.selectable
) {
14962 this.setActive( state
);
14969 * RadioOptionWidget is an option widget that looks like a radio button.
14970 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
14971 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
14973 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
14976 * @extends OO.ui.OptionWidget
14979 * @param {Object} [config] Configuration options
14981 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
14982 // Configuration initialization
14983 config
= config
|| {};
14985 // Properties (must be done before parent constructor which calls #setDisabled)
14986 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
14988 // Parent constructor
14989 OO
.ui
.RadioOptionWidget
.super.call( this, config
);
14992 this.radio
.$input
.on( 'focus', this.onInputFocus
.bind( this ) );
14996 .addClass( 'oo-ui-radioOptionWidget' )
14997 .prepend( this.radio
.$element
);
15002 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
15004 /* Static Properties */
15006 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
15008 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
15010 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
15012 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
15017 * @param {jQuery.Event} e Focus event
15020 OO
.ui
.RadioOptionWidget
.prototype.onInputFocus = function () {
15021 this.radio
.$input
.blur();
15022 this.$element
.parent().focus();
15028 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
15029 OO
.ui
.RadioOptionWidget
.super.prototype.setSelected
.call( this, state
);
15031 this.radio
.setSelected( state
);
15039 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
15040 OO
.ui
.RadioOptionWidget
.super.prototype.setDisabled
.call( this, disabled
);
15042 this.radio
.setDisabled( this.isDisabled() );
15048 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
15049 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
15050 * the [OOjs UI documentation on MediaWiki] [1] for more information.
15052 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
15055 * @extends OO.ui.DecoratedOptionWidget
15058 * @param {Object} [config] Configuration options
15060 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
15061 // Configuration initialization
15062 config
= $.extend( { icon
: 'check' }, config
);
15064 // Parent constructor
15065 OO
.ui
.MenuOptionWidget
.super.call( this, config
);
15069 .attr( 'role', 'menuitem' )
15070 .addClass( 'oo-ui-menuOptionWidget' );
15075 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
15077 /* Static Properties */
15079 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
15082 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
15083 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
15086 * var myDropdown = new OO.ui.DropdownWidget( {
15089 * new OO.ui.MenuSectionOptionWidget( {
15092 * new OO.ui.MenuOptionWidget( {
15094 * label: 'Welsh Corgi'
15096 * new OO.ui.MenuOptionWidget( {
15098 * label: 'Standard Poodle'
15100 * new OO.ui.MenuSectionOptionWidget( {
15103 * new OO.ui.MenuOptionWidget( {
15110 * $( 'body' ).append( myDropdown.$element );
15114 * @extends OO.ui.DecoratedOptionWidget
15117 * @param {Object} [config] Configuration options
15119 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
15120 // Parent constructor
15121 OO
.ui
.MenuSectionOptionWidget
.super.call( this, config
);
15124 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
15129 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
15131 /* Static Properties */
15133 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
15135 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
15138 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
15140 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
15141 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
15145 * @extends OO.ui.DecoratedOptionWidget
15148 * @param {Object} [config] Configuration options
15149 * @cfg {number} [level] Indentation level
15150 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
15152 OO
.ui
.OutlineOptionWidget
= function OoUiOutlineOptionWidget( config
) {
15153 // Configuration initialization
15154 config
= config
|| {};
15156 // Parent constructor
15157 OO
.ui
.OutlineOptionWidget
.super.call( this, config
);
15161 this.movable
= !!config
.movable
;
15162 this.removable
= !!config
.removable
;
15165 this.$element
.addClass( 'oo-ui-outlineOptionWidget' );
15166 this.setLevel( config
.level
);
15171 OO
.inheritClass( OO
.ui
.OutlineOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
15173 /* Static Properties */
15175 OO
.ui
.OutlineOptionWidget
.static.highlightable
= false;
15177 OO
.ui
.OutlineOptionWidget
.static.scrollIntoViewOnSelect
= true;
15179 OO
.ui
.OutlineOptionWidget
.static.levelClass
= 'oo-ui-outlineOptionWidget-level-';
15181 OO
.ui
.OutlineOptionWidget
.static.levels
= 3;
15186 * Check if item is movable.
15188 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
15190 * @return {boolean} Item is movable
15192 OO
.ui
.OutlineOptionWidget
.prototype.isMovable = function () {
15193 return this.movable
;
15197 * Check if item is removable.
15199 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
15201 * @return {boolean} Item is removable
15203 OO
.ui
.OutlineOptionWidget
.prototype.isRemovable = function () {
15204 return this.removable
;
15208 * Get indentation level.
15210 * @return {number} Indentation level
15212 OO
.ui
.OutlineOptionWidget
.prototype.getLevel = function () {
15219 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
15221 * @param {boolean} movable Item is movable
15224 OO
.ui
.OutlineOptionWidget
.prototype.setMovable = function ( movable
) {
15225 this.movable
= !!movable
;
15226 this.updateThemeClasses();
15231 * Set removability.
15233 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
15235 * @param {boolean} movable Item is removable
15238 OO
.ui
.OutlineOptionWidget
.prototype.setRemovable = function ( removable
) {
15239 this.removable
= !!removable
;
15240 this.updateThemeClasses();
15245 * Set indentation level.
15247 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
15250 OO
.ui
.OutlineOptionWidget
.prototype.setLevel = function ( level
) {
15251 var levels
= this.constructor.static.levels
,
15252 levelClass
= this.constructor.static.levelClass
,
15255 this.level
= level
? Math
.max( 0, Math
.min( levels
- 1, level
) ) : 0;
15257 if ( this.level
=== i
) {
15258 this.$element
.addClass( levelClass
+ i
);
15260 this.$element
.removeClass( levelClass
+ i
);
15263 this.updateThemeClasses();
15269 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
15271 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
15272 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
15276 * @extends OO.ui.OptionWidget
15279 * @param {Object} [config] Configuration options
15281 OO
.ui
.TabOptionWidget
= function OoUiTabOptionWidget( config
) {
15282 // Configuration initialization
15283 config
= config
|| {};
15285 // Parent constructor
15286 OO
.ui
.TabOptionWidget
.super.call( this, config
);
15289 this.$element
.addClass( 'oo-ui-tabOptionWidget' );
15294 OO
.inheritClass( OO
.ui
.TabOptionWidget
, OO
.ui
.OptionWidget
);
15296 /* Static Properties */
15298 OO
.ui
.TabOptionWidget
.static.highlightable
= false;
15301 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
15302 * By default, each popup has an anchor that points toward its origin.
15303 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
15306 * // A popup widget.
15307 * var popup = new OO.ui.PopupWidget( {
15308 * $content: $( '<p>Hi there!</p>' ),
15313 * $( 'body' ).append( popup.$element );
15314 * // To display the popup, toggle the visibility to 'true'.
15315 * popup.toggle( true );
15317 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
15320 * @extends OO.ui.Widget
15321 * @mixins OO.ui.mixin.LabelElement
15324 * @param {Object} [config] Configuration options
15325 * @cfg {number} [width=320] Width of popup in pixels
15326 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
15327 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
15328 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
15329 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
15330 * popup is leaning towards the right of the screen.
15331 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
15332 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
15333 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
15334 * sentence in the given language.
15335 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
15336 * See the [OOjs UI docs on MediaWiki][3] for an example.
15337 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
15338 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
15339 * @cfg {jQuery} [$content] Content to append to the popup's body
15340 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
15341 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
15342 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
15344 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
15345 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
15347 * @cfg {boolean} [padded] Add padding to the popup's body
15349 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
15350 // Configuration initialization
15351 config
= config
|| {};
15353 // Parent constructor
15354 OO
.ui
.PopupWidget
.super.call( this, config
);
15356 // Properties (must be set before ClippableElement constructor call)
15357 this.$body
= $( '<div>' );
15359 // Mixin constructors
15360 OO
.ui
.mixin
.LabelElement
.call( this, config
);
15361 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$body
} ) );
15364 this.$popup
= $( '<div>' );
15365 this.$head
= $( '<div>' );
15366 this.$anchor
= $( '<div>' );
15367 // If undefined, will be computed lazily in updateDimensions()
15368 this.$container
= config
.$container
;
15369 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
15370 this.autoClose
= !!config
.autoClose
;
15371 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
15372 this.transitionTimeout
= null;
15373 this.anchor
= null;
15374 this.width
= config
.width
!== undefined ? config
.width
: 320;
15375 this.height
= config
.height
!== undefined ? config
.height
: null;
15376 this.setAlignment( config
.align
);
15377 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
15378 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
15379 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
15382 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
15385 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
15386 this.$body
.addClass( 'oo-ui-popupWidget-body' );
15387 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
15389 .addClass( 'oo-ui-popupWidget-head' )
15390 .append( this.$label
, this.closeButton
.$element
);
15391 if ( !config
.head
) {
15392 this.$head
.addClass( 'oo-ui-element-hidden' );
15395 .addClass( 'oo-ui-popupWidget-popup' )
15396 .append( this.$head
, this.$body
);
15398 .addClass( 'oo-ui-popupWidget' )
15399 .append( this.$popup
, this.$anchor
);
15400 // Move content, which was added to #$element by OO.ui.Widget, to the body
15401 if ( config
.$content
instanceof jQuery
) {
15402 this.$body
.append( config
.$content
);
15404 if ( config
.padded
) {
15405 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
15408 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
15409 // that reference properties not initialized at that time of parent class construction
15410 // TODO: Find a better way to handle post-constructor setup
15411 this.visible
= false;
15412 this.$element
.addClass( 'oo-ui-element-hidden' );
15417 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
15418 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
15419 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
15424 * Handles mouse down events.
15427 * @param {MouseEvent} e Mouse down event
15429 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
15431 this.isVisible() &&
15432 !$.contains( this.$element
[ 0 ], e
.target
) &&
15433 ( !this.$autoCloseIgnore
|| !this.$autoCloseIgnore
.has( e
.target
).length
)
15435 this.toggle( false );
15440 * Bind mouse down listener.
15444 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
15445 // Capture clicks outside popup
15446 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler
, true );
15450 * Handles close button click events.
15454 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
15455 if ( this.isVisible() ) {
15456 this.toggle( false );
15461 * Unbind mouse down listener.
15465 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
15466 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler
, true );
15470 * Handles key down events.
15473 * @param {KeyboardEvent} e Key down event
15475 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
15477 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
15480 this.toggle( false );
15481 e
.preventDefault();
15482 e
.stopPropagation();
15487 * Bind key down listener.
15491 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
15492 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
15496 * Unbind key down listener.
15500 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
15501 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
15505 * Show, hide, or toggle the visibility of the anchor.
15507 * @param {boolean} [show] Show anchor, omit to toggle
15509 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
15510 show
= show
=== undefined ? !this.anchored
: !!show
;
15512 if ( this.anchored
!== show
) {
15514 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
15516 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
15518 this.anchored
= show
;
15523 * Check if the anchor is visible.
15525 * @return {boolean} Anchor is visible
15527 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
15528 return this.anchor
;
15534 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
15535 show
= show
=== undefined ? !this.isVisible() : !!show
;
15537 var change
= show
!== this.isVisible();
15540 OO
.ui
.PopupWidget
.super.prototype.toggle
.call( this, show
);
15544 if ( this.autoClose
) {
15545 this.bindMouseDownListener();
15546 this.bindKeyDownListener();
15548 this.updateDimensions();
15549 this.toggleClipping( true );
15551 this.toggleClipping( false );
15552 if ( this.autoClose
) {
15553 this.unbindMouseDownListener();
15554 this.unbindKeyDownListener();
15563 * Set the size of the popup.
15565 * Changing the size may also change the popup's position depending on the alignment.
15567 * @param {number} width Width in pixels
15568 * @param {number} height Height in pixels
15569 * @param {boolean} [transition=false] Use a smooth transition
15572 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
15573 this.width
= width
;
15574 this.height
= height
!== undefined ? height
: null;
15575 if ( this.isVisible() ) {
15576 this.updateDimensions( transition
);
15581 * Update the size and position.
15583 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
15584 * be called automatically.
15586 * @param {boolean} [transition=false] Use a smooth transition
15589 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
15590 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
15591 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
15592 align
= this.align
,
15595 if ( !this.$container
) {
15596 // Lazy-initialize $container if not specified in constructor
15597 this.$container
= $( this.getClosestScrollableElementContainer() );
15600 // Set height and width before measuring things, since it might cause our measurements
15601 // to change (e.g. due to scrollbars appearing or disappearing)
15604 height
: this.height
!== null ? this.height
: 'auto'
15607 // If we are in RTL, we need to flip the alignment, unless it is center
15608 if ( align
=== 'forwards' || align
=== 'backwards' ) {
15609 if ( this.$container
.css( 'direction' ) === 'rtl' ) {
15610 align
= ( { forwards
: 'force-left', backwards
: 'force-right' } )[ this.align
];
15612 align
= ( { forwards
: 'force-right', backwards
: 'force-left' } )[ this.align
];
15617 // Compute initial popupOffset based on alignment
15618 popupOffset
= this.width
* ( { 'force-left': -1, center
: -0.5, 'force-right': 0 } )[ align
];
15620 // Figure out if this will cause the popup to go beyond the edge of the container
15621 originOffset
= this.$element
.offset().left
;
15622 containerLeft
= this.$container
.offset().left
;
15623 containerWidth
= this.$container
.innerWidth();
15624 containerRight
= containerLeft
+ containerWidth
;
15625 popupLeft
= popupOffset
- this.containerPadding
;
15626 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
15627 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
15628 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
15630 // Adjust offset to make the popup not go beyond the edge, if needed
15631 if ( overlapRight
< 0 ) {
15632 popupOffset
+= overlapRight
;
15633 } else if ( overlapLeft
< 0 ) {
15634 popupOffset
-= overlapLeft
;
15637 // Adjust offset to avoid anchor being rendered too close to the edge
15638 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
15639 // TODO: Find a measurement that works for CSS anchors and image anchors
15640 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
15641 if ( popupOffset
+ this.width
< anchorWidth
) {
15642 popupOffset
= anchorWidth
- this.width
;
15643 } else if ( -popupOffset
< anchorWidth
) {
15644 popupOffset
= -anchorWidth
;
15647 // Prevent transition from being interrupted
15648 clearTimeout( this.transitionTimeout
);
15649 if ( transition
) {
15650 // Enable transition
15651 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
15654 // Position body relative to anchor
15655 this.$popup
.css( 'margin-left', popupOffset
);
15657 if ( transition
) {
15658 // Prevent transitioning after transition is complete
15659 this.transitionTimeout
= setTimeout( function () {
15660 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
15663 // Prevent transitioning immediately
15664 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
15667 // Reevaluate clipping state since we've relocated and resized the popup
15674 * Set popup alignment
15675 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
15676 * `backwards` or `forwards`.
15678 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
15679 // Validate alignment and transform deprecated values
15680 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
15681 this.align
= { left
: 'force-right', right
: 'force-left' }[ align
] || align
;
15683 this.align
= 'center';
15688 * Get popup alignment
15689 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
15690 * `backwards` or `forwards`.
15692 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
15697 * Progress bars visually display the status of an operation, such as a download,
15698 * and can be either determinate or indeterminate:
15700 * - **determinate** process bars show the percent of an operation that is complete.
15702 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
15703 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
15704 * not use percentages.
15706 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
15709 * // Examples of determinate and indeterminate progress bars.
15710 * var progressBar1 = new OO.ui.ProgressBarWidget( {
15713 * var progressBar2 = new OO.ui.ProgressBarWidget();
15715 * // Create a FieldsetLayout to layout progress bars
15716 * var fieldset = new OO.ui.FieldsetLayout;
15717 * fieldset.addItems( [
15718 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
15719 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
15721 * $( 'body' ).append( fieldset.$element );
15724 * @extends OO.ui.Widget
15727 * @param {Object} [config] Configuration options
15728 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
15729 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
15730 * By default, the progress bar is indeterminate.
15732 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
15733 // Configuration initialization
15734 config
= config
|| {};
15736 // Parent constructor
15737 OO
.ui
.ProgressBarWidget
.super.call( this, config
);
15740 this.$bar
= $( '<div>' );
15741 this.progress
= null;
15744 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
15745 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
15748 role
: 'progressbar',
15749 'aria-valuemin': 0,
15750 'aria-valuemax': 100
15752 .addClass( 'oo-ui-progressBarWidget' )
15753 .append( this.$bar
);
15758 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
15760 /* Static Properties */
15762 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
15767 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
15769 * @return {number|boolean} Progress percent
15771 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
15772 return this.progress
;
15776 * Set the percent of the process completed or `false` for an indeterminate process.
15778 * @param {number|boolean} progress Progress percent or `false` for indeterminate
15780 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
15781 this.progress
= progress
;
15783 if ( progress
!== false ) {
15784 this.$bar
.css( 'width', this.progress
+ '%' );
15785 this.$element
.attr( 'aria-valuenow', this.progress
);
15787 this.$bar
.css( 'width', '' );
15788 this.$element
.removeAttr( 'aria-valuenow' );
15790 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress
);
15794 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
15795 * and a {@link OO.ui.TextInputMenuSelectWidget menu} of search results, which is displayed beneath the query
15796 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
15797 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
15798 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
15800 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
15801 * the [OOjs UI demos][1] for an example.
15803 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
15806 * @extends OO.ui.Widget
15809 * @param {Object} [config] Configuration options
15810 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
15811 * @cfg {string} [value] Initial query value
15813 OO
.ui
.SearchWidget
= function OoUiSearchWidget( config
) {
15814 // Configuration initialization
15815 config
= config
|| {};
15817 // Parent constructor
15818 OO
.ui
.SearchWidget
.super.call( this, config
);
15821 this.query
= new OO
.ui
.TextInputWidget( {
15823 placeholder
: config
.placeholder
,
15824 value
: config
.value
15826 this.results
= new OO
.ui
.SelectWidget();
15827 this.$query
= $( '<div>' );
15828 this.$results
= $( '<div>' );
15831 this.query
.connect( this, {
15832 change
: 'onQueryChange',
15833 enter
: 'onQueryEnter'
15835 this.results
.connect( this, {
15836 highlight
: 'onResultsHighlight',
15837 select
: 'onResultsSelect'
15839 this.query
.$input
.on( 'keydown', this.onQueryKeydown
.bind( this ) );
15843 .addClass( 'oo-ui-searchWidget-query' )
15844 .append( this.query
.$element
);
15846 .addClass( 'oo-ui-searchWidget-results' )
15847 .append( this.results
.$element
);
15849 .addClass( 'oo-ui-searchWidget' )
15850 .append( this.$results
, this.$query
);
15855 OO
.inheritClass( OO
.ui
.SearchWidget
, OO
.ui
.Widget
);
15860 * A 'highlight' event is emitted when an item is highlighted. The highlight indicates which
15861 * item will be selected. When a user mouses over a menu item, it is highlighted. If a search
15862 * string is typed into the query field instead, the first menu item that matches the query
15863 * will be highlighted.
15866 * @deprecated Connect straight to getResults() events instead
15867 * @param {Object|null} item Item data or null if no item is highlighted
15871 * A 'select' event is emitted when an item is selected. A menu item is selected when it is clicked,
15872 * or when a user types a search query, a menu result is highlighted, and the user presses enter.
15875 * @deprecated Connect straight to getResults() events instead
15876 * @param {Object|null} item Item data or null if no item is selected
15882 * Handle query key down events.
15885 * @param {jQuery.Event} e Key down event
15887 OO
.ui
.SearchWidget
.prototype.onQueryKeydown = function ( e
) {
15888 var highlightedItem
, nextItem
,
15889 dir
= e
.which
=== OO
.ui
.Keys
.DOWN
? 1 : ( e
.which
=== OO
.ui
.Keys
.UP
? -1 : 0 );
15892 highlightedItem
= this.results
.getHighlightedItem();
15893 if ( !highlightedItem
) {
15894 highlightedItem
= this.results
.getSelectedItem();
15896 nextItem
= this.results
.getRelativeSelectableItem( highlightedItem
, dir
);
15897 this.results
.highlightItem( nextItem
);
15898 nextItem
.scrollElementIntoView();
15903 * Handle select widget select events.
15905 * Clears existing results. Subclasses should repopulate items according to new query.
15908 * @param {string} value New value
15910 OO
.ui
.SearchWidget
.prototype.onQueryChange = function () {
15912 this.results
.clearItems();
15916 * Handle select widget enter key events.
15918 * Selects highlighted item.
15921 * @param {string} value New value
15923 OO
.ui
.SearchWidget
.prototype.onQueryEnter = function () {
15925 this.results
.selectItem( this.results
.getHighlightedItem() );
15929 * Handle select widget highlight events.
15932 * @deprecated Connect straight to getResults() events instead
15933 * @param {OO.ui.OptionWidget} item Highlighted item
15936 OO
.ui
.SearchWidget
.prototype.onResultsHighlight = function ( item
) {
15937 this.emit( 'highlight', item
? item
.getData() : null );
15941 * Handle select widget select events.
15944 * @deprecated Connect straight to getResults() events instead
15945 * @param {OO.ui.OptionWidget} item Selected item
15948 OO
.ui
.SearchWidget
.prototype.onResultsSelect = function ( item
) {
15949 this.emit( 'select', item
? item
.getData() : null );
15953 * Get the query input.
15955 * @return {OO.ui.TextInputWidget} Query input
15957 OO
.ui
.SearchWidget
.prototype.getQuery = function () {
15962 * Get the search results menu.
15964 * @return {OO.ui.SelectWidget} Menu of search results
15966 OO
.ui
.SearchWidget
.prototype.getResults = function () {
15967 return this.results
;
15971 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
15972 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
15973 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
15976 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
15977 * information, please see the [OOjs UI documentation on MediaWiki][1].
15980 * // Example of a select widget with three options
15981 * var select = new OO.ui.SelectWidget( {
15983 * new OO.ui.OptionWidget( {
15985 * label: 'Option One',
15987 * new OO.ui.OptionWidget( {
15989 * label: 'Option Two',
15991 * new OO.ui.OptionWidget( {
15993 * label: 'Option Three',
15997 * $( 'body' ).append( select.$element );
15999 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16003 * @extends OO.ui.Widget
16004 * @mixins OO.ui.mixin.GroupElement
16007 * @param {Object} [config] Configuration options
16008 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
16009 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
16010 * the [OOjs UI documentation on MediaWiki] [2] for examples.
16011 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16013 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
16014 // Configuration initialization
16015 config
= config
|| {};
16017 // Parent constructor
16018 OO
.ui
.SelectWidget
.super.call( this, config
);
16020 // Mixin constructors
16021 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
16024 this.pressed
= false;
16025 this.selecting
= null;
16026 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
16027 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
16028 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
16029 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
16030 this.keyPressBuffer
= '';
16031 this.keyPressBufferTimer
= null;
16034 this.connect( this, {
16037 this.$element
.on( {
16038 mousedown
: this.onMouseDown
.bind( this ),
16039 mouseover
: this.onMouseOver
.bind( this ),
16040 mouseleave
: this.onMouseLeave
.bind( this )
16045 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
16046 .attr( 'role', 'listbox' );
16047 if ( Array
.isArray( config
.items
) ) {
16048 this.addItems( config
.items
);
16054 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
16056 // Need to mixin base class as well
16057 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupElement
);
16058 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
16061 OO
.ui
.SelectWidget
.static.passAllFilter = function () {
16070 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
16072 * @param {OO.ui.OptionWidget|null} item Highlighted item
16078 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
16079 * pressed state of an option.
16081 * @param {OO.ui.OptionWidget|null} item Pressed item
16087 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
16089 * @param {OO.ui.OptionWidget|null} item Selected item
16094 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
16095 * @param {OO.ui.OptionWidget} item Chosen item
16101 * An `add` event is emitted when options are added to the select with the #addItems method.
16103 * @param {OO.ui.OptionWidget[]} items Added items
16104 * @param {number} index Index of insertion point
16110 * A `remove` event is emitted when options are removed from the select with the #clearItems
16111 * or #removeItems methods.
16113 * @param {OO.ui.OptionWidget[]} items Removed items
16119 * Handle mouse down events.
16122 * @param {jQuery.Event} e Mouse down event
16124 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
16127 if ( !this.isDisabled() && e
.which
=== 1 ) {
16128 this.togglePressed( true );
16129 item
= this.getTargetItem( e
);
16130 if ( item
&& item
.isSelectable() ) {
16131 this.pressItem( item
);
16132 this.selecting
= item
;
16133 this.getElementDocument().addEventListener(
16135 this.onMouseUpHandler
,
16138 this.getElementDocument().addEventListener(
16140 this.onMouseMoveHandler
,
16149 * Handle mouse up events.
16152 * @param {jQuery.Event} e Mouse up event
16154 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
16157 this.togglePressed( false );
16158 if ( !this.selecting
) {
16159 item
= this.getTargetItem( e
);
16160 if ( item
&& item
.isSelectable() ) {
16161 this.selecting
= item
;
16164 if ( !this.isDisabled() && e
.which
=== 1 && this.selecting
) {
16165 this.pressItem( null );
16166 this.chooseItem( this.selecting
);
16167 this.selecting
= null;
16170 this.getElementDocument().removeEventListener(
16172 this.onMouseUpHandler
,
16175 this.getElementDocument().removeEventListener(
16177 this.onMouseMoveHandler
,
16185 * Handle mouse move events.
16188 * @param {jQuery.Event} e Mouse move event
16190 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
16193 if ( !this.isDisabled() && this.pressed
) {
16194 item
= this.getTargetItem( e
);
16195 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
16196 this.pressItem( item
);
16197 this.selecting
= item
;
16204 * Handle mouse over events.
16207 * @param {jQuery.Event} e Mouse over event
16209 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
16212 if ( !this.isDisabled() ) {
16213 item
= this.getTargetItem( e
);
16214 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
16220 * Handle mouse leave events.
16223 * @param {jQuery.Event} e Mouse over event
16225 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
16226 if ( !this.isDisabled() ) {
16227 this.highlightItem( null );
16233 * Handle key down events.
16236 * @param {jQuery.Event} e Key down event
16238 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
16241 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
16243 if ( !this.isDisabled() && this.isVisible() ) {
16244 switch ( e
.keyCode
) {
16245 case OO
.ui
.Keys
.ENTER
:
16246 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
16247 // Was only highlighted, now let's select it. No-op if already selected.
16248 this.chooseItem( currentItem
);
16252 case OO
.ui
.Keys
.UP
:
16253 case OO
.ui
.Keys
.LEFT
:
16254 this.clearKeyPressBuffer();
16255 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
16258 case OO
.ui
.Keys
.DOWN
:
16259 case OO
.ui
.Keys
.RIGHT
:
16260 this.clearKeyPressBuffer();
16261 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
16264 case OO
.ui
.Keys
.ESCAPE
:
16265 case OO
.ui
.Keys
.TAB
:
16266 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
16267 currentItem
.setHighlighted( false );
16269 this.unbindKeyDownListener();
16270 this.unbindKeyPressListener();
16271 // Don't prevent tabbing away / defocusing
16277 if ( nextItem
.constructor.static.highlightable
) {
16278 this.highlightItem( nextItem
);
16280 this.chooseItem( nextItem
);
16282 nextItem
.scrollElementIntoView();
16286 // Can't just return false, because e is not always a jQuery event
16287 e
.preventDefault();
16288 e
.stopPropagation();
16294 * Bind key down listener.
16298 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
16299 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler
, true );
16303 * Unbind key down listener.
16307 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
16308 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler
, true );
16312 * Clear the key-press buffer
16316 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
16317 if ( this.keyPressBufferTimer
) {
16318 clearTimeout( this.keyPressBufferTimer
);
16319 this.keyPressBufferTimer
= null;
16321 this.keyPressBuffer
= '';
16325 * Handle key press events.
16328 * @param {jQuery.Event} e Key press event
16330 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
16331 var c
, filter
, item
;
16333 if ( !e
.charCode
) {
16334 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
16335 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
16340 if ( String
.fromCodePoint
) {
16341 c
= String
.fromCodePoint( e
.charCode
);
16343 c
= String
.fromCharCode( e
.charCode
);
16346 if ( this.keyPressBufferTimer
) {
16347 clearTimeout( this.keyPressBufferTimer
);
16349 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
16351 item
= this.getHighlightedItem() || this.getSelectedItem();
16353 if ( this.keyPressBuffer
=== c
) {
16354 // Common (if weird) special case: typing "xxxx" will cycle through all
16355 // the items beginning with "x".
16357 item
= this.getRelativeSelectableItem( item
, 1 );
16360 this.keyPressBuffer
+= c
;
16363 filter
= this.getItemMatcher( this.keyPressBuffer
);
16364 if ( !item
|| !filter( item
) ) {
16365 item
= this.getRelativeSelectableItem( item
, 1, filter
);
16368 if ( item
.constructor.static.highlightable
) {
16369 this.highlightItem( item
);
16371 this.chooseItem( item
);
16373 item
.scrollElementIntoView();
16380 * Get a matcher for the specific string
16383 * @param {string} s String to match against items
16384 * @return {Function} function ( OO.ui.OptionItem ) => boolean
16386 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
) {
16389 if ( s
.normalize
) {
16392 re
= new RegExp( '^\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' ), 'i' );
16393 return function ( item
) {
16394 var l
= item
.getLabel();
16395 if ( typeof l
!== 'string' ) {
16396 l
= item
.$label
.text();
16398 if ( l
.normalize
) {
16401 return re
.test( l
);
16406 * Bind key press listener.
16410 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
16411 this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler
, true );
16415 * Unbind key down listener.
16417 * If you override this, be sure to call this.clearKeyPressBuffer() from your
16422 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
16423 this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler
, true );
16424 this.clearKeyPressBuffer();
16428 * Visibility change handler
16431 * @param {boolean} visible
16433 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
16435 this.clearKeyPressBuffer();
16440 * Get the closest item to a jQuery.Event.
16443 * @param {jQuery.Event} e
16444 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
16446 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
16447 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
16451 * Get selected item.
16453 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
16455 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
16458 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
16459 if ( this.items
[ i
].isSelected() ) {
16460 return this.items
[ i
];
16467 * Get highlighted item.
16469 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
16471 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
16474 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
16475 if ( this.items
[ i
].isHighlighted() ) {
16476 return this.items
[ i
];
16483 * Toggle pressed state.
16485 * Press is a state that occurs when a user mouses down on an item, but
16486 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
16487 * until the user releases the mouse.
16489 * @param {boolean} pressed An option is being pressed
16491 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
16492 if ( pressed
=== undefined ) {
16493 pressed
= !this.pressed
;
16495 if ( pressed
!== this.pressed
) {
16497 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
16498 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
16499 this.pressed
= pressed
;
16504 * Highlight an option. If the `item` param is omitted, no options will be highlighted
16505 * and any existing highlight will be removed. The highlight is mutually exclusive.
16507 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
16511 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
16512 var i
, len
, highlighted
,
16515 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
16516 highlighted
= this.items
[ i
] === item
;
16517 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
16518 this.items
[ i
].setHighlighted( highlighted
);
16523 this.emit( 'highlight', item
);
16530 * Programmatically select an option by its data. If the `data` parameter is omitted,
16531 * or if the item does not exist, all options will be deselected.
16533 * @param {Object|string} [data] Value of the item to select, omit to deselect all
16537 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
16538 var itemFromData
= this.getItemFromData( data
);
16539 if ( data
=== undefined || !itemFromData
) {
16540 return this.selectItem();
16542 return this.selectItem( itemFromData
);
16546 * Programmatically select an option by its reference. If the `item` parameter is omitted,
16547 * all options will be deselected.
16549 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
16553 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
16554 var i
, len
, selected
,
16557 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
16558 selected
= this.items
[ i
] === item
;
16559 if ( this.items
[ i
].isSelected() !== selected
) {
16560 this.items
[ i
].setSelected( selected
);
16565 this.emit( 'select', item
);
16574 * Press is a state that occurs when a user mouses down on an item, but has not
16575 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
16576 * releases the mouse.
16578 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
16582 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
16583 var i
, len
, pressed
,
16586 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
16587 pressed
= this.items
[ i
] === item
;
16588 if ( this.items
[ i
].isPressed() !== pressed
) {
16589 this.items
[ i
].setPressed( pressed
);
16594 this.emit( 'press', item
);
16603 * Note that ‘choose’ should never be modified programmatically. A user can choose
16604 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
16605 * use the #selectItem method.
16607 * This method is identical to #selectItem, but may vary in subclasses that take additional action
16608 * when users choose an item with the keyboard or mouse.
16610 * @param {OO.ui.OptionWidget} item Item to choose
16614 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
16615 this.selectItem( item
);
16616 this.emit( 'choose', item
);
16622 * Get an option by its position relative to the specified item (or to the start of the option array,
16623 * if item is `null`). The direction in which to search through the option array is specified with a
16624 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
16625 * `null` if there are no options in the array.
16627 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
16628 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
16629 * @param {Function} filter Only consider items for which this function returns
16630 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
16631 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
16633 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
16634 var currentIndex
, nextIndex
, i
,
16635 increase
= direction
> 0 ? 1 : -1,
16636 len
= this.items
.length
;
16638 if ( !$.isFunction( filter
) ) {
16639 filter
= OO
.ui
.SelectWidget
.static.passAllFilter
;
16642 if ( item
instanceof OO
.ui
.OptionWidget
) {
16643 currentIndex
= $.inArray( item
, this.items
);
16644 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
16646 // If no item is selected and moving forward, start at the beginning.
16647 // If moving backward, start at the end.
16648 nextIndex
= direction
> 0 ? 0 : len
- 1;
16651 for ( i
= 0; i
< len
; i
++ ) {
16652 item
= this.items
[ nextIndex
];
16653 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
16656 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
16662 * Get the next selectable item or `null` if there are no selectable items.
16663 * Disabled options and menu-section markers and breaks are not selectable.
16665 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
16667 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
16670 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
16671 item
= this.items
[ i
];
16672 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
16681 * Add an array of options to the select. Optionally, an index number can be used to
16682 * specify an insertion point.
16684 * @param {OO.ui.OptionWidget[]} items Items to add
16685 * @param {number} [index] Index to insert items after
16689 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
16691 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
16693 // Always provide an index, even if it was omitted
16694 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
16700 * Remove the specified array of options from the select. Options will be detached
16701 * from the DOM, not removed, so they can be reused later. To remove all options from
16702 * the select, you may wish to use the #clearItems method instead.
16704 * @param {OO.ui.OptionWidget[]} items Items to remove
16708 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
16711 // Deselect items being removed
16712 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
16714 if ( item
.isSelected() ) {
16715 this.selectItem( null );
16720 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
16722 this.emit( 'remove', items
);
16728 * Clear all options from the select. Options will be detached from the DOM, not removed,
16729 * so that they can be reused later. To remove a subset of options from the select, use
16730 * the #removeItems method.
16735 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
16736 var items
= this.items
.slice();
16739 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
16742 this.selectItem( null );
16744 this.emit( 'remove', items
);
16750 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
16751 * button options and is used together with
16752 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
16753 * highlighting, choosing, and selecting mutually exclusive options. Please see
16754 * the [OOjs UI documentation on MediaWiki] [1] for more information.
16757 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
16758 * var option1 = new OO.ui.ButtonOptionWidget( {
16760 * label: 'Option 1',
16761 * title: 'Button option 1'
16764 * var option2 = new OO.ui.ButtonOptionWidget( {
16766 * label: 'Option 2',
16767 * title: 'Button option 2'
16770 * var option3 = new OO.ui.ButtonOptionWidget( {
16772 * label: 'Option 3',
16773 * title: 'Button option 3'
16776 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
16777 * items: [ option1, option2, option3 ]
16779 * $( 'body' ).append( buttonSelect.$element );
16781 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16784 * @extends OO.ui.SelectWidget
16785 * @mixins OO.ui.mixin.TabIndexedElement
16788 * @param {Object} [config] Configuration options
16790 OO
.ui
.ButtonSelectWidget
= function OoUiButtonSelectWidget( config
) {
16791 // Parent constructor
16792 OO
.ui
.ButtonSelectWidget
.super.call( this, config
);
16794 // Mixin constructors
16795 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
16798 this.$element
.on( {
16799 focus
: this.bindKeyDownListener
.bind( this ),
16800 blur
: this.unbindKeyDownListener
.bind( this )
16804 this.$element
.addClass( 'oo-ui-buttonSelectWidget' );
16809 OO
.inheritClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.SelectWidget
);
16810 OO
.mixinClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
16813 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
16814 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
16815 * an interface for adding, removing and selecting options.
16816 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
16818 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
16819 * OO.ui.RadioSelectInputWidget instead.
16822 * // A RadioSelectWidget with RadioOptions.
16823 * var option1 = new OO.ui.RadioOptionWidget( {
16825 * label: 'Selected radio option'
16828 * var option2 = new OO.ui.RadioOptionWidget( {
16830 * label: 'Unselected radio option'
16833 * var radioSelect=new OO.ui.RadioSelectWidget( {
16834 * items: [ option1, option2 ]
16837 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
16838 * radioSelect.selectItem( option1 );
16840 * $( 'body' ).append( radioSelect.$element );
16842 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16846 * @extends OO.ui.SelectWidget
16847 * @mixins OO.ui.mixin.TabIndexedElement
16850 * @param {Object} [config] Configuration options
16852 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
16853 // Parent constructor
16854 OO
.ui
.RadioSelectWidget
.super.call( this, config
);
16856 // Mixin constructors
16857 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
16860 this.$element
.on( {
16861 focus
: this.bindKeyDownListener
.bind( this ),
16862 blur
: this.unbindKeyDownListener
.bind( this )
16866 this.$element
.addClass( 'oo-ui-radioSelectWidget' );
16871 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
16872 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
16875 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
16876 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
16877 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
16878 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
16879 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
16880 * and customized to be opened, closed, and displayed as needed.
16882 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
16883 * mouse outside the menu.
16885 * Menus also have support for keyboard interaction:
16887 * - Enter/Return key: choose and select a menu option
16888 * - Up-arrow key: highlight the previous menu option
16889 * - Down-arrow key: highlight the next menu option
16890 * - Esc key: hide the menu
16892 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
16893 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16896 * @extends OO.ui.SelectWidget
16897 * @mixins OO.ui.mixin.ClippableElement
16900 * @param {Object} [config] Configuration options
16901 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
16902 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
16903 * and {@link OO.ui.mixin.LookupElement LookupElement}
16904 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
16905 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
16906 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
16907 * that button, unless the button (or its parent widget) is passed in here.
16908 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
16910 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
16911 // Configuration initialization
16912 config
= config
|| {};
16914 // Parent constructor
16915 OO
.ui
.MenuSelectWidget
.super.call( this, config
);
16917 // Mixin constructors
16918 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
16921 this.newItems
= null;
16922 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
16923 this.$input
= config
.input
? config
.input
.$input
: null;
16924 this.$widget
= config
.widget
? config
.widget
.$element
: null;
16925 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
16929 .addClass( 'oo-ui-menuSelectWidget' )
16930 .attr( 'role', 'menu' );
16932 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
16933 // that reference properties not initialized at that time of parent class construction
16934 // TODO: Find a better way to handle post-constructor setup
16935 this.visible
= false;
16936 this.$element
.addClass( 'oo-ui-element-hidden' );
16941 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
16942 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
16947 * Handles document mouse down events.
16950 * @param {jQuery.Event} e Key down event
16952 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
16954 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
16955 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
16957 this.toggle( false );
16964 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
16965 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
16967 if ( !this.isDisabled() && this.isVisible() ) {
16968 switch ( e
.keyCode
) {
16969 case OO
.ui
.Keys
.LEFT
:
16970 case OO
.ui
.Keys
.RIGHT
:
16971 // Do nothing if a text field is associated, arrow keys will be handled natively
16972 if ( !this.$input
) {
16973 OO
.ui
.MenuSelectWidget
.super.prototype.onKeyDown
.call( this, e
);
16976 case OO
.ui
.Keys
.ESCAPE
:
16977 case OO
.ui
.Keys
.TAB
:
16978 if ( currentItem
) {
16979 currentItem
.setHighlighted( false );
16981 this.toggle( false );
16982 // Don't prevent tabbing away, prevent defocusing
16983 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
16984 e
.preventDefault();
16985 e
.stopPropagation();
16989 OO
.ui
.MenuSelectWidget
.super.prototype.onKeyDown
.call( this, e
);
16998 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
16999 if ( this.$input
) {
17000 this.$input
.on( 'keydown', this.onKeyDownHandler
);
17002 OO
.ui
.MenuSelectWidget
.super.prototype.bindKeyDownListener
.call( this );
17009 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
17010 if ( this.$input
) {
17011 this.$input
.off( 'keydown', this.onKeyDownHandler
);
17013 OO
.ui
.MenuSelectWidget
.super.prototype.unbindKeyDownListener
.call( this );
17020 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
17021 if ( !this.$input
) {
17022 OO
.ui
.MenuSelectWidget
.super.prototype.bindKeyPressListener
.call( this );
17029 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
17030 if ( this.$input
) {
17031 this.clearKeyPressBuffer();
17033 OO
.ui
.MenuSelectWidget
.super.prototype.unbindKeyPressListener
.call( this );
17040 * When a user chooses an item, the menu is closed.
17042 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
17043 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
17044 * @param {OO.ui.OptionWidget} item Item to choose
17047 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
17048 OO
.ui
.MenuSelectWidget
.super.prototype.chooseItem
.call( this, item
);
17049 this.toggle( false );
17056 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
17060 OO
.ui
.MenuSelectWidget
.super.prototype.addItems
.call( this, items
, index
);
17063 if ( !this.newItems
) {
17064 this.newItems
= [];
17067 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
17069 if ( this.isVisible() ) {
17070 // Defer fitting label until item has been attached
17073 this.newItems
.push( item
);
17077 // Reevaluate clipping
17086 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
17088 OO
.ui
.MenuSelectWidget
.super.prototype.removeItems
.call( this, items
);
17090 // Reevaluate clipping
17099 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
17101 OO
.ui
.MenuSelectWidget
.super.prototype.clearItems
.call( this );
17103 // Reevaluate clipping
17112 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
17113 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
17116 change
= visible
!== this.isVisible();
17119 OO
.ui
.MenuSelectWidget
.super.prototype.toggle
.call( this, visible
);
17123 this.bindKeyDownListener();
17124 this.bindKeyPressListener();
17126 if ( this.newItems
&& this.newItems
.length
) {
17127 for ( i
= 0, len
= this.newItems
.length
; i
< len
; i
++ ) {
17128 this.newItems
[ i
].fitLabel();
17130 this.newItems
= null;
17132 this.toggleClipping( true );
17135 if ( this.autoHide
) {
17136 this.getElementDocument().addEventListener(
17137 'mousedown', this.onDocumentMouseDownHandler
, true
17141 this.unbindKeyDownListener();
17142 this.unbindKeyPressListener();
17143 this.getElementDocument().removeEventListener(
17144 'mousedown', this.onDocumentMouseDownHandler
, true
17146 this.toggleClipping( false );
17154 * TextInputMenuSelectWidget is a menu that is specially designed to be positioned beneath
17155 * a {@link OO.ui.TextInputWidget text input} field. The menu's position is automatically
17156 * calculated and maintained when the menu is toggled or the window is resized.
17157 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
17160 * @extends OO.ui.MenuSelectWidget
17163 * @param {OO.ui.TextInputWidget} inputWidget Text input widget to provide menu for
17164 * @param {Object} [config] Configuration options
17165 * @cfg {jQuery} [$container=input.$element] Element to render menu under
17167 OO
.ui
.TextInputMenuSelectWidget
= function OoUiTextInputMenuSelectWidget( inputWidget
, config
) {
17168 // Allow passing positional parameters inside the config object
17169 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
17170 config
= inputWidget
;
17171 inputWidget
= config
.inputWidget
;
17174 // Configuration initialization
17175 config
= config
|| {};
17177 // Parent constructor
17178 OO
.ui
.TextInputMenuSelectWidget
.super.call( this, config
);
17181 this.inputWidget
= inputWidget
;
17182 this.$container
= config
.$container
|| this.inputWidget
.$element
;
17183 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
17186 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
17191 OO
.inheritClass( OO
.ui
.TextInputMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
17196 * Handle window resize event.
17199 * @param {jQuery.Event} e Window resize event
17201 OO
.ui
.TextInputMenuSelectWidget
.prototype.onWindowResize = function () {
17208 OO
.ui
.TextInputMenuSelectWidget
.prototype.toggle = function ( visible
) {
17209 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
17211 var change
= visible
!== this.isVisible();
17213 if ( change
&& visible
) {
17214 // Make sure the width is set before the parent method runs.
17215 // After this we have to call this.position(); again to actually
17216 // position ourselves correctly.
17221 OO
.ui
.TextInputMenuSelectWidget
.super.prototype.toggle
.call( this, visible
);
17224 if ( this.isVisible() ) {
17226 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
17228 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
17236 * Position the menu.
17241 OO
.ui
.TextInputMenuSelectWidget
.prototype.position = function () {
17242 var $container
= this.$container
,
17243 pos
= OO
.ui
.Element
.static.getRelativePosition( $container
, this.$element
.offsetParent() );
17245 // Position under input
17246 pos
.top
+= $container
.height();
17247 this.$element
.css( pos
);
17250 this.setIdealSize( $container
.width() );
17251 // We updated the position, so re-evaluate the clipping state
17258 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
17259 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
17261 * ####Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.####
17264 * @extends OO.ui.SelectWidget
17265 * @mixins OO.ui.mixin.TabIndexedElement
17268 * @param {Object} [config] Configuration options
17270 OO
.ui
.OutlineSelectWidget
= function OoUiOutlineSelectWidget( config
) {
17271 // Parent constructor
17272 OO
.ui
.OutlineSelectWidget
.super.call( this, config
);
17274 // Mixin constructors
17275 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
17278 this.$element
.on( {
17279 focus
: this.bindKeyDownListener
.bind( this ),
17280 blur
: this.unbindKeyDownListener
.bind( this )
17284 this.$element
.addClass( 'oo-ui-outlineSelectWidget' );
17289 OO
.inheritClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.SelectWidget
);
17290 OO
.mixinClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
17293 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
17295 * ####Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.####
17298 * @extends OO.ui.SelectWidget
17299 * @mixins OO.ui.mixin.TabIndexedElement
17302 * @param {Object} [config] Configuration options
17304 OO
.ui
.TabSelectWidget
= function OoUiTabSelectWidget( config
) {
17305 // Parent constructor
17306 OO
.ui
.TabSelectWidget
.super.call( this, config
);
17308 // Mixin constructors
17309 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
17312 this.$element
.on( {
17313 focus
: this.bindKeyDownListener
.bind( this ),
17314 blur
: this.unbindKeyDownListener
.bind( this )
17318 this.$element
.addClass( 'oo-ui-tabSelectWidget' );
17323 OO
.inheritClass( OO
.ui
.TabSelectWidget
, OO
.ui
.SelectWidget
);
17324 OO
.mixinClass( OO
.ui
.TabSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
17327 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
17328 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
17329 * (to adjust the value in increments) to allow the user to enter a number.
17332 * // Example: A NumberInputWidget.
17333 * var numberInput = new OO.ui.NumberInputWidget( {
17334 * label: 'NumberInputWidget',
17335 * input: { value: 5, min: 1, max: 10 }
17337 * $( 'body' ).append( numberInput.$element );
17340 * @extends OO.ui.Widget
17343 * @param {Object} [config] Configuration options
17344 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
17345 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
17346 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
17347 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
17348 * @cfg {number} [min=-Infinity] Minimum allowed value
17349 * @cfg {number} [max=Infinity] Maximum allowed value
17350 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
17351 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
17353 OO
.ui
.NumberInputWidget
= function OoUiNumberInputWidget( config
) {
17354 // Configuration initialization
17355 config
= $.extend( {
17363 // Parent constructor
17364 OO
.ui
.NumberInputWidget
.super.call( this, config
);
17367 this.input
= new OO
.ui
.TextInputWidget( $.extend(
17369 disabled
: this.isDisabled()
17373 this.minusButton
= new OO
.ui
.ButtonWidget( $.extend(
17375 disabled
: this.isDisabled(),
17378 config
.minusButton
,
17380 classes
: [ 'oo-ui-numberInputWidget-minusButton' ],
17384 this.plusButton
= new OO
.ui
.ButtonWidget( $.extend(
17386 disabled
: this.isDisabled(),
17391 classes
: [ 'oo-ui-numberInputWidget-plusButton' ],
17397 this.input
.connect( this, {
17398 change
: this.emit
.bind( this, 'change' ),
17399 enter
: this.emit
.bind( this, 'enter' )
17401 this.input
.$input
.on( {
17402 keydown
: this.onKeyDown
.bind( this ),
17403 'wheel mousewheel DOMMouseScroll': this.onWheel
.bind( this )
17405 this.plusButton
.connect( this, {
17406 click
: [ 'onButtonClick', +1 ]
17408 this.minusButton
.connect( this, {
17409 click
: [ 'onButtonClick', -1 ]
17413 this.setIsInteger( !!config
.isInteger
);
17414 this.setRange( config
.min
, config
.max
);
17415 this.setStep( config
.step
, config
.pageStep
);
17417 this.$field
= $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
17419 this.minusButton
.$element
,
17420 this.input
.$element
,
17421 this.plusButton
.$element
17423 this.$element
.addClass( 'oo-ui-numberInputWidget' ).append( this.$field
);
17424 this.input
.setValidation( this.validateNumber
.bind( this ) );
17429 OO
.inheritClass( OO
.ui
.NumberInputWidget
, OO
.ui
.Widget
);
17434 * A `change` event is emitted when the value of the input changes.
17440 * An `enter` event is emitted when the user presses 'enter' inside the text box.
17448 * Set whether only integers are allowed
17449 * @param {boolean} flag
17451 OO
.ui
.NumberInputWidget
.prototype.setIsInteger = function ( flag
) {
17452 this.isInteger
= !!flag
;
17453 this.input
.setValidityFlag();
17457 * Get whether only integers are allowed
17458 * @return {boolean} Flag value
17460 OO
.ui
.NumberInputWidget
.prototype.getIsInteger = function () {
17461 return this.isInteger
;
17465 * Set the range of allowed values
17466 * @param {number} min Minimum allowed value
17467 * @param {number} max Maximum allowed value
17469 OO
.ui
.NumberInputWidget
.prototype.setRange = function ( min
, max
) {
17471 throw new Error( 'Minimum (' + min
+ ') must not be greater than maximum (' + max
+ ')' );
17475 this.input
.setValidityFlag();
17479 * Get the current range
17480 * @return {number[]} Minimum and maximum values
17482 OO
.ui
.NumberInputWidget
.prototype.getRange = function () {
17483 return [ this.min
, this.max
];
17487 * Set the stepping deltas
17488 * @param {number} step Normal step
17489 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
17491 OO
.ui
.NumberInputWidget
.prototype.setStep = function ( step
, pageStep
) {
17493 throw new Error( 'Step value must be positive' );
17495 if ( pageStep
=== null ) {
17496 pageStep
= step
* 10;
17497 } else if ( pageStep
<= 0 ) {
17498 throw new Error( 'Page step value must be positive' );
17501 this.pageStep
= pageStep
;
17505 * Get the current stepping values
17506 * @return {number[]} Step and page step
17508 OO
.ui
.NumberInputWidget
.prototype.getStep = function () {
17509 return [ this.step
, this.pageStep
];
17513 * Get the current value of the widget
17516 OO
.ui
.NumberInputWidget
.prototype.getValue = function () {
17517 return this.input
.getValue();
17521 * Get the current value of the widget as a number
17522 * @return {number} May be NaN, or an invalid number
17524 OO
.ui
.NumberInputWidget
.prototype.getNumericValue = function () {
17525 return +this.input
.getValue();
17529 * Set the value of the widget
17530 * @param {string} value Invalid values are allowed
17532 OO
.ui
.NumberInputWidget
.prototype.setValue = function ( value
) {
17533 this.input
.setValue( value
);
17537 * Adjust the value of the widget
17538 * @param {number} delta Adjustment amount
17540 OO
.ui
.NumberInputWidget
.prototype.adjustValue = function ( delta
) {
17541 var n
, v
= this.getNumericValue();
17544 if ( isNaN( delta
) || !isFinite( delta
) ) {
17545 throw new Error( 'Delta must be a finite number' );
17548 if ( isNaN( v
) ) {
17552 n
= Math
.max( Math
.min( n
, this.max
), this.min
);
17553 if ( this.isInteger
) {
17554 n
= Math
.round( n
);
17559 this.setValue( n
);
17566 * @param {string} value Field value
17567 * @return {boolean}
17569 OO
.ui
.NumberInputWidget
.prototype.validateNumber = function ( value
) {
17571 if ( isNaN( n
) || !isFinite( n
) ) {
17575 /*jshint bitwise: false */
17576 if ( this.isInteger
&& ( n
| 0 ) !== n
) {
17579 /*jshint bitwise: true */
17581 if ( n
< this.min
|| n
> this.max
) {
17589 * Handle mouse click events.
17592 * @param {number} dir +1 or -1
17594 OO
.ui
.NumberInputWidget
.prototype.onButtonClick = function ( dir
) {
17595 this.adjustValue( dir
* this.step
);
17599 * Handle mouse wheel events.
17602 * @param {jQuery.Event} event
17604 OO
.ui
.NumberInputWidget
.prototype.onWheel = function ( event
) {
17607 // Standard 'wheel' event
17608 if ( event
.originalEvent
.deltaMode
!== undefined ) {
17609 this.sawWheelEvent
= true;
17611 if ( event
.originalEvent
.deltaY
) {
17612 delta
= -event
.originalEvent
.deltaY
;
17613 } else if ( event
.originalEvent
.deltaX
) {
17614 delta
= event
.originalEvent
.deltaX
;
17617 // Non-standard events
17618 if ( !this.sawWheelEvent
) {
17619 if ( event
.originalEvent
.wheelDeltaX
) {
17620 delta
= -event
.originalEvent
.wheelDeltaX
;
17621 } else if ( event
.originalEvent
.wheelDeltaY
) {
17622 delta
= event
.originalEvent
.wheelDeltaY
;
17623 } else if ( event
.originalEvent
.wheelDelta
) {
17624 delta
= event
.originalEvent
.wheelDelta
;
17625 } else if ( event
.originalEvent
.detail
) {
17626 delta
= -event
.originalEvent
.detail
;
17631 this.adjustValue( Math
.sign( delta
) * this.step
);
17638 * Handle key down events.
17642 * @param {jQuery.Event} e Key down event
17644 OO
.ui
.NumberInputWidget
.prototype.onKeyDown = function ( e
) {
17645 if ( !this.isDisabled() ) {
17646 switch ( e
.which
) {
17647 case OO
.ui
.Keys
.UP
:
17648 this.adjustValue( this.step
);
17650 case OO
.ui
.Keys
.DOWN
:
17651 this.adjustValue( -this.step
);
17653 case OO
.ui
.Keys
.PAGEUP
:
17654 this.adjustValue( this.pageStep
);
17656 case OO
.ui
.Keys
.PAGEDOWN
:
17657 this.adjustValue( -this.pageStep
);
17666 OO
.ui
.NumberInputWidget
.prototype.setDisabled = function ( disabled
) {
17668 OO
.ui
.NumberInputWidget
.super.prototype.setDisabled
.call( this, disabled
);
17670 if ( this.input
) {
17671 this.input
.setDisabled( this.isDisabled() );
17673 if ( this.minusButton
) {
17674 this.minusButton
.setDisabled( this.isDisabled() );
17676 if ( this.plusButton
) {
17677 this.plusButton
.setDisabled( this.isDisabled() );
17684 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
17685 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
17686 * visually by a slider in the leftmost position.
17689 * // Toggle switches in the 'off' and 'on' position.
17690 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
17691 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
17695 * // Create a FieldsetLayout to layout and label switches
17696 * var fieldset = new OO.ui.FieldsetLayout( {
17697 * label: 'Toggle switches'
17699 * fieldset.addItems( [
17700 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
17701 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
17703 * $( 'body' ).append( fieldset.$element );
17706 * @extends OO.ui.ToggleWidget
17707 * @mixins OO.ui.mixin.TabIndexedElement
17710 * @param {Object} [config] Configuration options
17711 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
17712 * By default, the toggle switch is in the 'off' position.
17714 OO
.ui
.ToggleSwitchWidget
= function OoUiToggleSwitchWidget( config
) {
17715 // Parent constructor
17716 OO
.ui
.ToggleSwitchWidget
.super.call( this, config
);
17718 // Mixin constructors
17719 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
17722 this.dragging
= false;
17723 this.dragStart
= null;
17724 this.sliding
= false;
17725 this.$glow
= $( '<span>' );
17726 this.$grip
= $( '<span>' );
17729 this.$element
.on( {
17730 click
: this.onClick
.bind( this ),
17731 keypress
: this.onKeyPress
.bind( this )
17735 this.$glow
.addClass( 'oo-ui-toggleSwitchWidget-glow' );
17736 this.$grip
.addClass( 'oo-ui-toggleSwitchWidget-grip' );
17738 .addClass( 'oo-ui-toggleSwitchWidget' )
17739 .attr( 'role', 'checkbox' )
17740 .append( this.$glow
, this.$grip
);
17745 OO
.inheritClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.ToggleWidget
);
17746 OO
.mixinClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.mixin
.TabIndexedElement
);
17751 * Handle mouse click events.
17754 * @param {jQuery.Event} e Mouse click event
17756 OO
.ui
.ToggleSwitchWidget
.prototype.onClick = function ( e
) {
17757 if ( !this.isDisabled() && e
.which
=== 1 ) {
17758 this.setValue( !this.value
);
17764 * Handle key press events.
17767 * @param {jQuery.Event} e Key press event
17769 OO
.ui
.ToggleSwitchWidget
.prototype.onKeyPress = function ( e
) {
17770 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
17771 this.setValue( !this.value
);
17777 * Deprecated aliases for classes in the `OO.ui.mixin` namespace.
17781 * @inheritdoc OO.ui.mixin.ButtonElement
17782 * @deprecated Use {@link OO.ui.mixin.ButtonElement} instead.
17784 OO
.ui
.ButtonElement
= OO
.ui
.mixin
.ButtonElement
;
17787 * @inheritdoc OO.ui.mixin.ClippableElement
17788 * @deprecated Use {@link OO.ui.mixin.ClippableElement} instead.
17790 OO
.ui
.ClippableElement
= OO
.ui
.mixin
.ClippableElement
;
17793 * @inheritdoc OO.ui.mixin.DraggableElement
17794 * @deprecated Use {@link OO.ui.mixin.DraggableElement} instead.
17796 OO
.ui
.DraggableElement
= OO
.ui
.mixin
.DraggableElement
;
17799 * @inheritdoc OO.ui.mixin.DraggableGroupElement
17800 * @deprecated Use {@link OO.ui.mixin.DraggableGroupElement} instead.
17802 OO
.ui
.DraggableGroupElement
= OO
.ui
.mixin
.DraggableGroupElement
;
17805 * @inheritdoc OO.ui.mixin.FlaggedElement
17806 * @deprecated Use {@link OO.ui.mixin.FlaggedElement} instead.
17808 OO
.ui
.FlaggedElement
= OO
.ui
.mixin
.FlaggedElement
;
17811 * @inheritdoc OO.ui.mixin.GroupElement
17812 * @deprecated Use {@link OO.ui.mixin.GroupElement} instead.
17814 OO
.ui
.GroupElement
= OO
.ui
.mixin
.GroupElement
;
17817 * @inheritdoc OO.ui.mixin.GroupWidget
17818 * @deprecated Use {@link OO.ui.mixin.GroupWidget} instead.
17820 OO
.ui
.GroupWidget
= OO
.ui
.mixin
.GroupWidget
;
17823 * @inheritdoc OO.ui.mixin.IconElement
17824 * @deprecated Use {@link OO.ui.mixin.IconElement} instead.
17826 OO
.ui
.IconElement
= OO
.ui
.mixin
.IconElement
;
17829 * @inheritdoc OO.ui.mixin.IndicatorElement
17830 * @deprecated Use {@link OO.ui.mixin.IndicatorElement} instead.
17832 OO
.ui
.IndicatorElement
= OO
.ui
.mixin
.IndicatorElement
;
17835 * @inheritdoc OO.ui.mixin.ItemWidget
17836 * @deprecated Use {@link OO.ui.mixin.ItemWidget} instead.
17838 OO
.ui
.ItemWidget
= OO
.ui
.mixin
.ItemWidget
;
17841 * @inheritdoc OO.ui.mixin.LabelElement
17842 * @deprecated Use {@link OO.ui.mixin.LabelElement} instead.
17844 OO
.ui
.LabelElement
= OO
.ui
.mixin
.LabelElement
;
17847 * @inheritdoc OO.ui.mixin.LookupElement
17848 * @deprecated Use {@link OO.ui.mixin.LookupElement} instead.
17850 OO
.ui
.LookupElement
= OO
.ui
.mixin
.LookupElement
;
17853 * @inheritdoc OO.ui.mixin.PendingElement
17854 * @deprecated Use {@link OO.ui.mixin.PendingElement} instead.
17856 OO
.ui
.PendingElement
= OO
.ui
.mixin
.PendingElement
;
17859 * @inheritdoc OO.ui.mixin.PopupElement
17860 * @deprecated Use {@link OO.ui.mixin.PopupElement} instead.
17862 OO
.ui
.PopupElement
= OO
.ui
.mixin
.PopupElement
;
17865 * @inheritdoc OO.ui.mixin.TabIndexedElement
17866 * @deprecated Use {@link OO.ui.mixin.TabIndexedElement} instead.
17868 OO
.ui
.TabIndexedElement
= OO
.ui
.mixin
.TabIndexedElement
;
17871 * @inheritdoc OO.ui.mixin.TitledElement
17872 * @deprecated Use {@link OO.ui.mixin.TitledElement} instead.
17874 OO
.ui
.TitledElement
= OO
.ui
.mixin
.TitledElement
;