3 * https://www.mediawiki.org/wiki/OOjs_UI
5 * Copyright 2011–2015 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2015-07-22T19:37:07Z
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.parent.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.parent.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.parent.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.parent.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.parent.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.parent.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.parent.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
, parts
, parent
, 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 parts
= data
._
.split( '.' );
1136 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
1137 if ( cls
=== undefined ) {
1138 // The PHP output might be old and not including the "OO.ui" prefix
1139 // TODO: Remove this back-compat after next major release
1140 cls
= OO
.getProp
.apply( OO
, [ OO
.ui
].concat( parts
) );
1141 if ( cls
=== undefined ) {
1142 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
1146 // Verify that we're creating an OO.ui.Element instance
1147 parent
= cls
.parent
;
1149 while ( parent
!== undefined ) {
1150 if ( parent
=== OO
.ui
.Element
) {
1155 parent
= parent
.parent
;
1158 if ( parent
!== OO
.ui
.Element
) {
1159 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
1162 $elem
.data( 'ooui-infused', true ); // prevent loops
1163 data
.id
= id
; // implicit
1164 data
= OO
.copy( data
, null, function deserialize( value
) {
1165 if ( OO
.isPlainObject( value
) ) {
1167 return OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, false );
1170 return new OO
.ui
.HtmlSnippet( value
.html
);
1174 // jscs:disable requireCapitalizedConstructors
1175 obj
= new cls( data
); // rebuild widget
1176 // now replace old DOM with this new DOM.
1178 $elem
.replaceWith( obj
.$element
);
1180 obj
.$element
.data( 'ooui-infused', obj
);
1181 // set the 'data-ooui' attribute so we can identify infused widgets
1182 obj
.$element
.attr( 'data-ooui', '' );
1187 * Get a jQuery function within a specific document.
1190 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1191 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1193 * @return {Function} Bound jQuery function
1195 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
1196 function wrapper( selector
) {
1197 return $( selector
, wrapper
.context
);
1200 wrapper
.context
= this.getDocument( context
);
1203 wrapper
.$iframe
= $iframe
;
1210 * Get the document of an element.
1213 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1214 * @return {HTMLDocument|null} Document object
1216 OO
.ui
.Element
.static.getDocument = function ( obj
) {
1217 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1218 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
1219 // Empty jQuery selections might have a context
1222 obj
.ownerDocument
||
1226 ( obj
.nodeType
=== 9 && obj
) ||
1231 * Get the window of an element or document.
1234 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1235 * @return {Window} Window object
1237 OO
.ui
.Element
.static.getWindow = function ( obj
) {
1238 var doc
= this.getDocument( obj
);
1239 return doc
.parentWindow
|| doc
.defaultView
;
1243 * Get the direction of an element or document.
1246 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1247 * @return {string} Text direction, either 'ltr' or 'rtl'
1249 OO
.ui
.Element
.static.getDir = function ( obj
) {
1252 if ( obj
instanceof jQuery
) {
1255 isDoc
= obj
.nodeType
=== 9;
1256 isWin
= obj
.document
!== undefined;
1257 if ( isDoc
|| isWin
) {
1263 return $( obj
).css( 'direction' );
1267 * Get the offset between two frames.
1269 * TODO: Make this function not use recursion.
1272 * @param {Window} from Window of the child frame
1273 * @param {Window} [to=window] Window of the parent frame
1274 * @param {Object} [offset] Offset to start with, used internally
1275 * @return {Object} Offset object, containing left and top properties
1277 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
1278 var i
, len
, frames
, frame
, rect
;
1284 offset
= { top
: 0, left
: 0 };
1286 if ( from.parent
=== from ) {
1290 // Get iframe element
1291 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
1292 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
1293 if ( frames
[ i
].contentWindow
=== from ) {
1294 frame
= frames
[ i
];
1299 // Recursively accumulate offset values
1301 rect
= frame
.getBoundingClientRect();
1302 offset
.left
+= rect
.left
;
1303 offset
.top
+= rect
.top
;
1304 if ( from !== to
) {
1305 this.getFrameOffset( from.parent
, offset
);
1312 * Get the offset between two elements.
1314 * The two elements may be in a different frame, but in that case the frame $element is in must
1315 * be contained in the frame $anchor is in.
1318 * @param {jQuery} $element Element whose position to get
1319 * @param {jQuery} $anchor Element to get $element's position relative to
1320 * @return {Object} Translated position coordinates, containing top and left properties
1322 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
1323 var iframe
, iframePos
,
1324 pos
= $element
.offset(),
1325 anchorPos
= $anchor
.offset(),
1326 elementDocument
= this.getDocument( $element
),
1327 anchorDocument
= this.getDocument( $anchor
);
1329 // If $element isn't in the same document as $anchor, traverse up
1330 while ( elementDocument
!== anchorDocument
) {
1331 iframe
= elementDocument
.defaultView
.frameElement
;
1333 throw new Error( '$element frame is not contained in $anchor frame' );
1335 iframePos
= $( iframe
).offset();
1336 pos
.left
+= iframePos
.left
;
1337 pos
.top
+= iframePos
.top
;
1338 elementDocument
= iframe
.ownerDocument
;
1340 pos
.left
-= anchorPos
.left
;
1341 pos
.top
-= anchorPos
.top
;
1346 * Get element border sizes.
1349 * @param {HTMLElement} el Element to measure
1350 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1352 OO
.ui
.Element
.static.getBorders = function ( el
) {
1353 var doc
= el
.ownerDocument
,
1354 win
= doc
.parentWindow
|| doc
.defaultView
,
1355 style
= win
&& win
.getComputedStyle
?
1356 win
.getComputedStyle( el
, null ) :
1359 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1360 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1361 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1362 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1373 * Get dimensions of an element or window.
1376 * @param {HTMLElement|Window} el Element to measure
1377 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1379 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1381 doc
= el
.ownerDocument
|| el
.document
,
1382 win
= doc
.parentWindow
|| doc
.defaultView
;
1384 if ( win
=== el
|| el
=== doc
.documentElement
) {
1387 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1389 top
: $win
.scrollTop(),
1390 left
: $win
.scrollLeft()
1392 scrollbar
: { right
: 0, bottom
: 0 },
1396 bottom
: $win
.innerHeight(),
1397 right
: $win
.innerWidth()
1403 borders
: this.getBorders( el
),
1405 top
: $el
.scrollTop(),
1406 left
: $el
.scrollLeft()
1409 right
: $el
.innerWidth() - el
.clientWidth
,
1410 bottom
: $el
.innerHeight() - el
.clientHeight
1412 rect
: el
.getBoundingClientRect()
1418 * Get scrollable object parent
1420 * documentElement can't be used to get or set the scrollTop
1421 * property on Blink. Changing and testing its value lets us
1422 * use 'body' or 'documentElement' based on what is working.
1424 * https://code.google.com/p/chromium/issues/detail?id=303131
1427 * @param {HTMLElement} el Element to find scrollable parent for
1428 * @return {HTMLElement} Scrollable parent
1430 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1431 var scrollTop
, body
;
1433 if ( OO
.ui
.scrollableElement
=== undefined ) {
1434 body
= el
.ownerDocument
.body
;
1435 scrollTop
= body
.scrollTop
;
1438 if ( body
.scrollTop
=== 1 ) {
1439 body
.scrollTop
= scrollTop
;
1440 OO
.ui
.scrollableElement
= 'body';
1442 OO
.ui
.scrollableElement
= 'documentElement';
1446 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1450 * Get closest scrollable container.
1452 * Traverses up until either a scrollable element or the root is reached, in which case the window
1456 * @param {HTMLElement} el Element to find scrollable container for
1457 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1458 * @return {HTMLElement} Closest scrollable container
1460 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1462 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1463 props
= [ 'overflow-x', 'overflow-y' ],
1464 $parent
= $( el
).parent();
1466 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1467 props
= [ 'overflow-' + dimension
];
1470 while ( $parent
.length
) {
1471 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1472 return $parent
[ 0 ];
1476 val
= $parent
.css( props
[ i
] );
1477 if ( val
=== 'auto' || val
=== 'scroll' ) {
1478 return $parent
[ 0 ];
1481 $parent
= $parent
.parent();
1483 return this.getDocument( el
).body
;
1487 * Scroll element into view.
1490 * @param {HTMLElement} el Element to scroll into view
1491 * @param {Object} [config] Configuration options
1492 * @param {string} [config.duration] jQuery animation duration value
1493 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1494 * to scroll in both directions
1495 * @param {Function} [config.complete] Function to call when scrolling completes
1497 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1498 // Configuration initialization
1499 config
= config
|| {};
1502 callback
= typeof config
.complete
=== 'function' && config
.complete
,
1503 sc
= this.getClosestScrollableContainer( el
, config
.direction
),
1505 eld
= this.getDimensions( el
),
1506 scd
= this.getDimensions( sc
),
1507 $win
= $( this.getWindow( el
) );
1509 // Compute the distances between the edges of el and the edges of the scroll viewport
1510 if ( $sc
.is( 'html, body' ) ) {
1511 // If the scrollable container is the root, this is easy
1514 bottom
: $win
.innerHeight() - eld
.rect
.bottom
,
1515 left
: eld
.rect
.left
,
1516 right
: $win
.innerWidth() - eld
.rect
.right
1519 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1521 top
: eld
.rect
.top
- ( scd
.rect
.top
+ scd
.borders
.top
),
1522 bottom
: scd
.rect
.bottom
- scd
.borders
.bottom
- scd
.scrollbar
.bottom
- eld
.rect
.bottom
,
1523 left
: eld
.rect
.left
- ( scd
.rect
.left
+ scd
.borders
.left
),
1524 right
: scd
.rect
.right
- scd
.borders
.right
- scd
.scrollbar
.right
- eld
.rect
.right
1528 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1529 if ( rel
.top
< 0 ) {
1530 anim
.scrollTop
= scd
.scroll
.top
+ rel
.top
;
1531 } else if ( rel
.top
> 0 && rel
.bottom
< 0 ) {
1532 anim
.scrollTop
= scd
.scroll
.top
+ Math
.min( rel
.top
, -rel
.bottom
);
1535 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1536 if ( rel
.left
< 0 ) {
1537 anim
.scrollLeft
= scd
.scroll
.left
+ rel
.left
;
1538 } else if ( rel
.left
> 0 && rel
.right
< 0 ) {
1539 anim
.scrollLeft
= scd
.scroll
.left
+ Math
.min( rel
.left
, -rel
.right
);
1542 if ( !$.isEmptyObject( anim
) ) {
1543 $sc
.stop( true ).animate( anim
, config
.duration
|| 'fast' );
1545 $sc
.queue( function ( next
) {
1558 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1559 * and reserve space for them, because it probably doesn't.
1561 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1562 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1563 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1564 * and then reattach (or show) them back.
1567 * @param {HTMLElement} el Element to reconsider the scrollbars on
1569 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1570 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1571 // Save scroll position
1572 scrollLeft
= el
.scrollLeft
;
1573 scrollTop
= el
.scrollTop
;
1574 // Detach all children
1575 while ( el
.firstChild
) {
1576 nodes
.push( el
.firstChild
);
1577 el
.removeChild( el
.firstChild
);
1580 void el
.offsetHeight
;
1581 // Reattach all children
1582 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1583 el
.appendChild( nodes
[ i
] );
1585 // Restore scroll position (no-op if scrollbars disappeared)
1586 el
.scrollLeft
= scrollLeft
;
1587 el
.scrollTop
= scrollTop
;
1593 * Toggle visibility of an element.
1595 * @param {boolean} [show] Make element visible, omit to toggle visibility
1599 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1600 show
= show
=== undefined ? !this.visible
: !!show
;
1602 if ( show
!== this.isVisible() ) {
1603 this.visible
= show
;
1604 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1605 this.emit( 'toggle', show
);
1612 * Check if element is visible.
1614 * @return {boolean} element is visible
1616 OO
.ui
.Element
.prototype.isVisible = function () {
1617 return this.visible
;
1623 * @return {Mixed} Element data
1625 OO
.ui
.Element
.prototype.getData = function () {
1632 * @param {Mixed} Element data
1635 OO
.ui
.Element
.prototype.setData = function ( data
) {
1641 * Check if element supports one or more methods.
1643 * @param {string|string[]} methods Method or list of methods to check
1644 * @return {boolean} All methods are supported
1646 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1650 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1651 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1652 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1657 return methods
.length
=== support
;
1661 * Update the theme-provided classes.
1663 * @localdoc This is called in element mixins and widget classes any time state changes.
1664 * Updating is debounced, minimizing overhead of changing multiple attributes and
1665 * guaranteeing that theme updates do not occur within an element's constructor
1667 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1668 if ( !this.updateThemeClassesPending
) {
1669 this.updateThemeClassesPending
= true;
1670 setTimeout( this.debouncedUpdateThemeClassesHandler
);
1677 OO
.ui
.Element
.prototype.debouncedUpdateThemeClasses = function () {
1678 OO
.ui
.theme
.updateElementClasses( this );
1679 this.updateThemeClassesPending
= false;
1683 * Get the HTML tag name.
1685 * Override this method to base the result on instance information.
1687 * @return {string} HTML tag name
1689 OO
.ui
.Element
.prototype.getTagName = function () {
1690 return this.constructor.static.tagName
;
1694 * Check if the element is attached to the DOM
1695 * @return {boolean} The element is attached to the DOM
1697 OO
.ui
.Element
.prototype.isElementAttached = function () {
1698 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1702 * Get the DOM document.
1704 * @return {HTMLDocument} Document object
1706 OO
.ui
.Element
.prototype.getElementDocument = function () {
1707 // Don't cache this in other ways either because subclasses could can change this.$element
1708 return OO
.ui
.Element
.static.getDocument( this.$element
);
1712 * Get the DOM window.
1714 * @return {Window} Window object
1716 OO
.ui
.Element
.prototype.getElementWindow = function () {
1717 return OO
.ui
.Element
.static.getWindow( this.$element
);
1721 * Get closest scrollable container.
1723 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1724 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1728 * Get group element is in.
1730 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1732 OO
.ui
.Element
.prototype.getElementGroup = function () {
1733 return this.elementGroup
;
1737 * Set group element is in.
1739 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1742 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1743 this.elementGroup
= group
;
1748 * Scroll element into view.
1750 * @param {Object} [config] Configuration options
1752 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1753 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1757 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1758 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1759 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1760 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1761 * and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1765 * @extends OO.ui.Element
1766 * @mixins OO.EventEmitter
1769 * @param {Object} [config] Configuration options
1771 OO
.ui
.Layout
= function OoUiLayout( config
) {
1772 // Configuration initialization
1773 config
= config
|| {};
1775 // Parent constructor
1776 OO
.ui
.Layout
.parent
.call( this, config
);
1778 // Mixin constructors
1779 OO
.EventEmitter
.call( this );
1782 this.$element
.addClass( 'oo-ui-layout' );
1787 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1788 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1791 * Widgets are compositions of one or more OOjs UI elements that users can both view
1792 * and interact with. All widgets can be configured and modified via a standard API,
1793 * and their state can change dynamically according to a model.
1797 * @extends OO.ui.Element
1798 * @mixins OO.EventEmitter
1801 * @param {Object} [config] Configuration options
1802 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1803 * appearance reflects this state.
1805 OO
.ui
.Widget
= function OoUiWidget( config
) {
1806 // Initialize config
1807 config
= $.extend( { disabled
: false }, config
);
1809 // Parent constructor
1810 OO
.ui
.Widget
.parent
.call( this, config
);
1812 // Mixin constructors
1813 OO
.EventEmitter
.call( this );
1816 this.disabled
= null;
1817 this.wasDisabled
= null;
1820 this.$element
.addClass( 'oo-ui-widget' );
1821 this.setDisabled( !!config
.disabled
);
1826 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1827 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1829 /* Static Properties */
1832 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
1833 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
1838 * @property {boolean}
1840 OO
.ui
.Widget
.static.supportsSimpleLabel
= false;
1847 * A 'disable' event is emitted when a widget is disabled.
1849 * @param {boolean} disabled Widget is disabled
1855 * A 'toggle' event is emitted when the visibility of the widget changes.
1857 * @param {boolean} visible Widget is visible
1863 * Check if the widget is disabled.
1865 * @return {boolean} Widget is disabled
1867 OO
.ui
.Widget
.prototype.isDisabled = function () {
1868 return this.disabled
;
1872 * Set the 'disabled' state of the widget.
1874 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1876 * @param {boolean} disabled Disable widget
1879 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1882 this.disabled
= !!disabled
;
1883 isDisabled
= this.isDisabled();
1884 if ( isDisabled
!== this.wasDisabled
) {
1885 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1886 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1887 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1888 this.emit( 'disable', isDisabled
);
1889 this.updateThemeClasses();
1891 this.wasDisabled
= isDisabled
;
1897 * Update the disabled state, in case of changes in parent widget.
1901 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1902 this.setDisabled( this.disabled
);
1907 * A window is a container for elements that are in a child frame. They are used with
1908 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
1909 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
1910 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
1911 * the window manager will choose a sensible fallback.
1913 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
1914 * different processes are executed:
1916 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
1917 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
1920 * - {@link #getSetupProcess} method is called and its result executed
1921 * - {@link #getReadyProcess} method is called and its result executed
1923 * **opened**: The window is now open
1925 * **closing**: The closing stage begins when the window manager's
1926 * {@link OO.ui.WindowManager#closeWindow closeWindow}
1927 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
1929 * - {@link #getHoldProcess} method is called and its result executed
1930 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
1932 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
1933 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
1934 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
1935 * processing can complete. Always assume window processes are executed asynchronously.
1937 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
1939 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
1943 * @extends OO.ui.Element
1944 * @mixins OO.EventEmitter
1947 * @param {Object} [config] Configuration options
1948 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
1949 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
1951 OO
.ui
.Window
= function OoUiWindow( config
) {
1952 // Configuration initialization
1953 config
= config
|| {};
1955 // Parent constructor
1956 OO
.ui
.Window
.parent
.call( this, config
);
1958 // Mixin constructors
1959 OO
.EventEmitter
.call( this );
1962 this.manager
= null;
1963 this.size
= config
.size
|| this.constructor.static.size
;
1964 this.$frame
= $( '<div>' );
1965 this.$overlay
= $( '<div>' );
1966 this.$content
= $( '<div>' );
1969 this.$overlay
.addClass( 'oo-ui-window-overlay' );
1971 .addClass( 'oo-ui-window-content' )
1972 .attr( 'tabindex', 0 );
1974 .addClass( 'oo-ui-window-frame' )
1975 .append( this.$content
);
1978 .addClass( 'oo-ui-window' )
1979 .append( this.$frame
, this.$overlay
);
1981 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
1982 // that reference properties not initialized at that time of parent class construction
1983 // TODO: Find a better way to handle post-constructor setup
1984 this.visible
= false;
1985 this.$element
.addClass( 'oo-ui-element-hidden' );
1990 OO
.inheritClass( OO
.ui
.Window
, OO
.ui
.Element
);
1991 OO
.mixinClass( OO
.ui
.Window
, OO
.EventEmitter
);
1993 /* Static Properties */
1996 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
1998 * The static size is used if no #size is configured during construction.
2002 * @property {string}
2004 OO
.ui
.Window
.static.size
= 'medium';
2009 * Handle mouse down events.
2012 * @param {jQuery.Event} e Mouse down event
2014 OO
.ui
.Window
.prototype.onMouseDown = function ( e
) {
2015 // Prevent clicking on the click-block from stealing focus
2016 if ( e
.target
=== this.$element
[ 0 ] ) {
2022 * Check if the window has been initialized.
2024 * Initialization occurs when a window is added to a manager.
2026 * @return {boolean} Window has been initialized
2028 OO
.ui
.Window
.prototype.isInitialized = function () {
2029 return !!this.manager
;
2033 * Check if the window is visible.
2035 * @return {boolean} Window is visible
2037 OO
.ui
.Window
.prototype.isVisible = function () {
2038 return this.visible
;
2042 * Check if the window is opening.
2044 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2047 * @return {boolean} Window is opening
2049 OO
.ui
.Window
.prototype.isOpening = function () {
2050 return this.manager
.isOpening( this );
2054 * Check if the window is closing.
2056 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2058 * @return {boolean} Window is closing
2060 OO
.ui
.Window
.prototype.isClosing = function () {
2061 return this.manager
.isClosing( this );
2065 * Check if the window is opened.
2067 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2069 * @return {boolean} Window is opened
2071 OO
.ui
.Window
.prototype.isOpened = function () {
2072 return this.manager
.isOpened( this );
2076 * Get the window manager.
2078 * All windows must be attached to a window manager, which is used to open
2079 * and close the window and control its presentation.
2081 * @return {OO.ui.WindowManager} Manager of window
2083 OO
.ui
.Window
.prototype.getManager = function () {
2084 return this.manager
;
2088 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2090 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2092 OO
.ui
.Window
.prototype.getSize = function () {
2097 * Disable transitions on window's frame for the duration of the callback function, then enable them
2101 * @param {Function} callback Function to call while transitions are disabled
2103 OO
.ui
.Window
.prototype.withoutSizeTransitions = function ( callback
) {
2104 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2105 // Disable transitions first, otherwise we'll get values from when the window was animating.
2107 styleObj
= this.$frame
[ 0 ].style
;
2108 oldTransition
= styleObj
.transition
|| styleObj
.OTransition
|| styleObj
.MsTransition
||
2109 styleObj
.MozTransition
|| styleObj
.WebkitTransition
;
2110 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
2111 styleObj
.MozTransition
= styleObj
.WebkitTransition
= 'none';
2113 // Force reflow to make sure the style changes done inside callback really are not transitioned
2114 this.$frame
.height();
2115 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
2116 styleObj
.MozTransition
= styleObj
.WebkitTransition
= oldTransition
;
2120 * Get the height of the full window contents (i.e., the window head, body and foot together).
2122 * What consistitutes the head, body, and foot varies depending on the window type.
2123 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2124 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2125 * and special actions in the head, and dialog content in the body.
2127 * To get just the height of the dialog body, use the #getBodyHeight method.
2129 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2131 OO
.ui
.Window
.prototype.getContentHeight = function () {
2134 bodyStyleObj
= this.$body
[ 0 ].style
,
2135 frameStyleObj
= this.$frame
[ 0 ].style
;
2137 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2138 // Disable transitions first, otherwise we'll get values from when the window was animating.
2139 this.withoutSizeTransitions( function () {
2140 var oldHeight
= frameStyleObj
.height
,
2141 oldPosition
= bodyStyleObj
.position
;
2142 frameStyleObj
.height
= '1px';
2143 // Force body to resize to new width
2144 bodyStyleObj
.position
= 'relative';
2145 bodyHeight
= win
.getBodyHeight();
2146 frameStyleObj
.height
= oldHeight
;
2147 bodyStyleObj
.position
= oldPosition
;
2151 // Add buffer for border
2152 ( this.$frame
.outerHeight() - this.$frame
.innerHeight() ) +
2153 // Use combined heights of children
2154 ( this.$head
.outerHeight( true ) + bodyHeight
+ this.$foot
.outerHeight( true ) )
2159 * Get the height of the window body.
2161 * To get the height of the full window contents (the window body, head, and foot together),
2162 * use #getContentHeight.
2164 * When this function is called, the window will temporarily have been resized
2165 * to height=1px, so .scrollHeight measurements can be taken accurately.
2167 * @return {number} Height of the window body in pixels
2169 OO
.ui
.Window
.prototype.getBodyHeight = function () {
2170 return this.$body
[ 0 ].scrollHeight
;
2174 * Get the directionality of the frame (right-to-left or left-to-right).
2176 * @return {string} Directionality: `'ltr'` or `'rtl'`
2178 OO
.ui
.Window
.prototype.getDir = function () {
2179 return OO
.ui
.Element
.static.getDir( this.$content
) || 'ltr';
2183 * Get the 'setup' process.
2185 * The setup process is used to set up a window for use in a particular context,
2186 * based on the `data` argument. This method is called during the opening phase of the window’s
2189 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2190 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2193 * To add window content that persists between openings, you may wish to use the #initialize method
2197 * @param {Object} [data] Window opening data
2198 * @return {OO.ui.Process} Setup process
2200 OO
.ui
.Window
.prototype.getSetupProcess = function () {
2201 return new OO
.ui
.Process();
2205 * Get the ‘ready’ process.
2207 * The ready process is used to ready a window for use in a particular
2208 * context, based on the `data` argument. This method is called during the opening phase of
2209 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2211 * Override this method to add additional steps to the ‘ready’ process the parent method
2212 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2213 * methods of OO.ui.Process.
2216 * @param {Object} [data] Window opening data
2217 * @return {OO.ui.Process} Ready process
2219 OO
.ui
.Window
.prototype.getReadyProcess = function () {
2220 return new OO
.ui
.Process();
2224 * Get the 'hold' process.
2226 * The hold proccess is used to keep a window from being used in a particular context,
2227 * based on the `data` argument. This method is called during the closing phase of the window’s
2230 * Override this method to add additional steps to the 'hold' process the parent method provides
2231 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2235 * @param {Object} [data] Window closing data
2236 * @return {OO.ui.Process} Hold process
2238 OO
.ui
.Window
.prototype.getHoldProcess = function () {
2239 return new OO
.ui
.Process();
2243 * Get the ‘teardown’ process.
2245 * The teardown process is used to teardown a window after use. During teardown,
2246 * user interactions within the window are conveyed and the window is closed, based on the `data`
2247 * argument. This method is called during the closing phase of the window’s lifecycle.
2249 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2250 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2254 * @param {Object} [data] Window closing data
2255 * @return {OO.ui.Process} Teardown process
2257 OO
.ui
.Window
.prototype.getTeardownProcess = function () {
2258 return new OO
.ui
.Process();
2262 * Set the window manager.
2264 * This will cause the window to initialize. Calling it more than once will cause an error.
2266 * @param {OO.ui.WindowManager} manager Manager for this window
2267 * @throws {Error} An error is thrown if the method is called more than once
2270 OO
.ui
.Window
.prototype.setManager = function ( manager
) {
2271 if ( this.manager
) {
2272 throw new Error( 'Cannot set window manager, window already has a manager' );
2275 this.manager
= manager
;
2282 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2284 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2288 OO
.ui
.Window
.prototype.setSize = function ( size
) {
2295 * Update the window size.
2297 * @throws {Error} An error is thrown if the window is not attached to a window manager
2300 OO
.ui
.Window
.prototype.updateSize = function () {
2301 if ( !this.manager
) {
2302 throw new Error( 'Cannot update window size, must be attached to a manager' );
2305 this.manager
.updateWindowSize( this );
2311 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2312 * when the window is opening. In general, setDimensions should not be called directly.
2314 * To set the size of the window, use the #setSize method.
2316 * @param {Object} dim CSS dimension properties
2317 * @param {string|number} [dim.width] Width
2318 * @param {string|number} [dim.minWidth] Minimum width
2319 * @param {string|number} [dim.maxWidth] Maximum width
2320 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2321 * @param {string|number} [dim.minWidth] Minimum height
2322 * @param {string|number} [dim.maxWidth] Maximum height
2325 OO
.ui
.Window
.prototype.setDimensions = function ( dim
) {
2328 styleObj
= this.$frame
[ 0 ].style
;
2330 // Calculate the height we need to set using the correct width
2331 if ( dim
.height
=== undefined ) {
2332 this.withoutSizeTransitions( function () {
2333 var oldWidth
= styleObj
.width
;
2334 win
.$frame
.css( 'width', dim
.width
|| '' );
2335 height
= win
.getContentHeight();
2336 styleObj
.width
= oldWidth
;
2339 height
= dim
.height
;
2343 width
: dim
.width
|| '',
2344 minWidth
: dim
.minWidth
|| '',
2345 maxWidth
: dim
.maxWidth
|| '',
2346 height
: height
|| '',
2347 minHeight
: dim
.minHeight
|| '',
2348 maxHeight
: dim
.maxHeight
|| ''
2355 * Initialize window contents.
2357 * Before the window is opened for the first time, #initialize is called so that content that
2358 * persists between openings can be added to the window.
2360 * To set up a window with new content each time the window opens, use #getSetupProcess.
2362 * @throws {Error} An error is thrown if the window is not attached to a window manager
2365 OO
.ui
.Window
.prototype.initialize = function () {
2366 if ( !this.manager
) {
2367 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2371 this.$head
= $( '<div>' );
2372 this.$body
= $( '<div>' );
2373 this.$foot
= $( '<div>' );
2374 this.$document
= $( this.getElementDocument() );
2377 this.$element
.on( 'mousedown', this.onMouseDown
.bind( this ) );
2380 this.$head
.addClass( 'oo-ui-window-head' );
2381 this.$body
.addClass( 'oo-ui-window-body' );
2382 this.$foot
.addClass( 'oo-ui-window-foot' );
2383 this.$content
.append( this.$head
, this.$body
, this.$foot
);
2391 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2392 * method, which returns a promise resolved when the window is done opening.
2394 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2396 * @param {Object} [data] Window opening data
2397 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2398 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2399 * value is a new promise, which is resolved when the window begins closing.
2400 * @throws {Error} An error is thrown if the window is not attached to a window manager
2402 OO
.ui
.Window
.prototype.open = function ( data
) {
2403 if ( !this.manager
) {
2404 throw new Error( 'Cannot open window, must be attached to a manager' );
2407 return this.manager
.openWindow( this, data
);
2413 * This method is a wrapper around a call to the window
2414 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2415 * which returns a closing promise resolved when the window is done closing.
2417 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2418 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2419 * the window closes.
2421 * @param {Object} [data] Window closing data
2422 * @return {jQuery.Promise} Promise resolved when window is closed
2423 * @throws {Error} An error is thrown if the window is not attached to a window manager
2425 OO
.ui
.Window
.prototype.close = function ( data
) {
2426 if ( !this.manager
) {
2427 throw new Error( 'Cannot close window, must be attached to a manager' );
2430 return this.manager
.closeWindow( this, data
);
2436 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2439 * @param {Object} [data] Window opening data
2440 * @return {jQuery.Promise} Promise resolved when window is setup
2442 OO
.ui
.Window
.prototype.setup = function ( data
) {
2444 deferred
= $.Deferred();
2446 this.toggle( true );
2448 this.getSetupProcess( data
).execute().done( function () {
2449 // Force redraw by asking the browser to measure the elements' widths
2450 win
.$element
.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2451 win
.$content
.addClass( 'oo-ui-window-content-setup' ).width();
2455 return deferred
.promise();
2461 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2464 * @param {Object} [data] Window opening data
2465 * @return {jQuery.Promise} Promise resolved when window is ready
2467 OO
.ui
.Window
.prototype.ready = function ( data
) {
2469 deferred
= $.Deferred();
2471 this.$content
.focus();
2472 this.getReadyProcess( data
).execute().done( function () {
2473 // Force redraw by asking the browser to measure the elements' widths
2474 win
.$element
.addClass( 'oo-ui-window-ready' ).width();
2475 win
.$content
.addClass( 'oo-ui-window-content-ready' ).width();
2479 return deferred
.promise();
2485 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2488 * @param {Object} [data] Window closing data
2489 * @return {jQuery.Promise} Promise resolved when window is held
2491 OO
.ui
.Window
.prototype.hold = function ( data
) {
2493 deferred
= $.Deferred();
2495 this.getHoldProcess( data
).execute().done( function () {
2496 // Get the focused element within the window's content
2497 var $focus
= win
.$content
.find( OO
.ui
.Element
.static.getDocument( win
.$content
).activeElement
);
2499 // Blur the focused element
2500 if ( $focus
.length
) {
2504 // Force redraw by asking the browser to measure the elements' widths
2505 win
.$element
.removeClass( 'oo-ui-window-ready' ).width();
2506 win
.$content
.removeClass( 'oo-ui-window-content-ready' ).width();
2510 return deferred
.promise();
2516 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2519 * @param {Object} [data] Window closing data
2520 * @return {jQuery.Promise} Promise resolved when window is torn down
2522 OO
.ui
.Window
.prototype.teardown = function ( data
) {
2525 return this.getTeardownProcess( data
).execute()
2526 .done( function () {
2527 // Force redraw by asking the browser to measure the elements' widths
2528 win
.$element
.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2529 win
.$content
.removeClass( 'oo-ui-window-content-setup' ).width();
2530 win
.toggle( false );
2535 * The Dialog class serves as the base class for the other types of dialogs.
2536 * Unless extended to include controls, the rendered dialog box is a simple window
2537 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2538 * which opens, closes, and controls the presentation of the window. See the
2539 * [OOjs UI documentation on MediaWiki] [1] for more information.
2542 * // A simple dialog window.
2543 * function MyDialog( config ) {
2544 * MyDialog.parent.call( this, config );
2546 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2547 * MyDialog.prototype.initialize = function () {
2548 * MyDialog.parent.prototype.initialize.call( this );
2549 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2550 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2551 * this.$body.append( this.content.$element );
2553 * MyDialog.prototype.getBodyHeight = function () {
2554 * return this.content.$element.outerHeight( true );
2556 * var myDialog = new MyDialog( {
2559 * // Create and append a window manager, which opens and closes the window.
2560 * var windowManager = new OO.ui.WindowManager();
2561 * $( 'body' ).append( windowManager.$element );
2562 * windowManager.addWindows( [ myDialog ] );
2563 * // Open the window!
2564 * windowManager.openWindow( myDialog );
2566 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2570 * @extends OO.ui.Window
2571 * @mixins OO.ui.mixin.PendingElement
2574 * @param {Object} [config] Configuration options
2576 OO
.ui
.Dialog
= function OoUiDialog( config
) {
2577 // Parent constructor
2578 OO
.ui
.Dialog
.parent
.call( this, config
);
2580 // Mixin constructors
2581 OO
.ui
.mixin
.PendingElement
.call( this );
2584 this.actions
= new OO
.ui
.ActionSet();
2585 this.attachedActions
= [];
2586 this.currentAction
= null;
2587 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
2590 this.actions
.connect( this, {
2591 click
: 'onActionClick',
2592 resize
: 'onActionResize',
2593 change
: 'onActionsChange'
2598 .addClass( 'oo-ui-dialog' )
2599 .attr( 'role', 'dialog' );
2604 OO
.inheritClass( OO
.ui
.Dialog
, OO
.ui
.Window
);
2605 OO
.mixinClass( OO
.ui
.Dialog
, OO
.ui
.mixin
.PendingElement
);
2607 /* Static Properties */
2610 * Symbolic name of dialog.
2612 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2613 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2615 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2620 * @property {string}
2622 OO
.ui
.Dialog
.static.name
= '';
2627 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2628 * that will produce a Label node or string. The title can also be specified with data passed to the
2629 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2634 * @property {jQuery|string|Function}
2636 OO
.ui
.Dialog
.static.title
= '';
2639 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2641 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2642 * value will be overriden.
2644 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2648 * @property {Object[]}
2650 OO
.ui
.Dialog
.static.actions
= [];
2653 * Close the dialog when the 'Esc' key is pressed.
2658 * @property {boolean}
2660 OO
.ui
.Dialog
.static.escapable
= true;
2665 * Handle frame document key down events.
2668 * @param {jQuery.Event} e Key down event
2670 OO
.ui
.Dialog
.prototype.onDocumentKeyDown = function ( e
) {
2671 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
2674 e
.stopPropagation();
2679 * Handle action resized events.
2682 * @param {OO.ui.ActionWidget} action Action that was resized
2684 OO
.ui
.Dialog
.prototype.onActionResize = function () {
2685 // Override in subclass
2689 * Handle action click events.
2692 * @param {OO.ui.ActionWidget} action Action that was clicked
2694 OO
.ui
.Dialog
.prototype.onActionClick = function ( action
) {
2695 if ( !this.isPending() ) {
2696 this.executeAction( action
.getAction() );
2701 * Handle actions change event.
2705 OO
.ui
.Dialog
.prototype.onActionsChange = function () {
2706 this.detachActions();
2707 if ( !this.isClosing() ) {
2708 this.attachActions();
2713 * Get the set of actions used by the dialog.
2715 * @return {OO.ui.ActionSet}
2717 OO
.ui
.Dialog
.prototype.getActions = function () {
2718 return this.actions
;
2722 * Get a process for taking action.
2724 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2725 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2726 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2729 * @param {string} [action] Symbolic name of action
2730 * @return {OO.ui.Process} Action process
2732 OO
.ui
.Dialog
.prototype.getActionProcess = function ( action
) {
2733 return new OO
.ui
.Process()
2734 .next( function () {
2736 // An empty action always closes the dialog without data, which should always be
2737 // safe and make no changes
2746 * @param {Object} [data] Dialog opening data
2747 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2748 * the {@link #static-title static title}
2749 * @param {Object[]} [data.actions] List of configuration options for each
2750 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2752 OO
.ui
.Dialog
.prototype.getSetupProcess = function ( data
) {
2756 return OO
.ui
.Dialog
.parent
.prototype.getSetupProcess
.call( this, data
)
2757 .next( function () {
2758 var config
= this.constructor.static,
2759 actions
= data
.actions
!== undefined ? data
.actions
: config
.actions
;
2761 this.title
.setLabel(
2762 data
.title
!== undefined ? data
.title
: this.constructor.static.title
2764 this.actions
.add( this.getActionWidgets( actions
) );
2766 if ( this.constructor.static.escapable
) {
2767 this.$document
.on( 'keydown', this.onDocumentKeyDownHandler
);
2775 OO
.ui
.Dialog
.prototype.getTeardownProcess = function ( data
) {
2777 return OO
.ui
.Dialog
.parent
.prototype.getTeardownProcess
.call( this, data
)
2778 .first( function () {
2779 if ( this.constructor.static.escapable
) {
2780 this.$document
.off( 'keydown', this.onDocumentKeyDownHandler
);
2783 this.actions
.clear();
2784 this.currentAction
= null;
2791 OO
.ui
.Dialog
.prototype.initialize = function () {
2793 OO
.ui
.Dialog
.parent
.prototype.initialize
.call( this );
2795 var titleId
= OO
.ui
.generateElementId();
2798 this.title
= new OO
.ui
.LabelWidget( {
2803 this.$content
.addClass( 'oo-ui-dialog-content' );
2804 this.$element
.attr( 'aria-labelledby', titleId
);
2805 this.setPendingElement( this.$head
);
2809 * Get action widgets from a list of configs
2811 * @param {Object[]} actions Action widget configs
2812 * @return {OO.ui.ActionWidget[]} Action widgets
2814 OO
.ui
.Dialog
.prototype.getActionWidgets = function ( actions
) {
2815 var i
, len
, widgets
= [];
2816 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
2818 new OO
.ui
.ActionWidget( actions
[ i
] )
2825 * Attach action actions.
2829 OO
.ui
.Dialog
.prototype.attachActions = function () {
2830 // Remember the list of potentially attached actions
2831 this.attachedActions
= this.actions
.get();
2835 * Detach action actions.
2840 OO
.ui
.Dialog
.prototype.detachActions = function () {
2843 // Detach all actions that may have been previously attached
2844 for ( i
= 0, len
= this.attachedActions
.length
; i
< len
; i
++ ) {
2845 this.attachedActions
[ i
].$element
.detach();
2847 this.attachedActions
= [];
2851 * Execute an action.
2853 * @param {string} action Symbolic name of action to execute
2854 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2856 OO
.ui
.Dialog
.prototype.executeAction = function ( action
) {
2858 this.currentAction
= action
;
2859 return this.getActionProcess( action
).execute()
2860 .always( this.popPending
.bind( this ) );
2864 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
2865 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
2866 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
2867 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
2868 * pertinent data and reused.
2870 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
2871 * `opened`, and `closing`, which represent the primary stages of the cycle:
2873 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
2874 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
2876 * - an `opening` event is emitted with an `opening` promise
2877 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
2878 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
2879 * window and its result executed
2880 * - a `setup` progress notification is emitted from the `opening` promise
2881 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
2882 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
2883 * window and its result executed
2884 * - a `ready` progress notification is emitted from the `opening` promise
2885 * - the `opening` promise is resolved with an `opened` promise
2887 * **Opened**: the window is now open.
2889 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
2890 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
2891 * to close the window.
2893 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
2894 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
2895 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
2896 * window and its result executed
2897 * - a `hold` progress notification is emitted from the `closing` promise
2898 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
2899 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
2900 * window and its result executed
2901 * - a `teardown` progress notification is emitted from the `closing` promise
2902 * - the `closing` promise is resolved. The window is now closed
2904 * See the [OOjs UI documentation on MediaWiki][1] for more information.
2906 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2909 * @extends OO.ui.Element
2910 * @mixins OO.EventEmitter
2913 * @param {Object} [config] Configuration options
2914 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
2915 * Note that window classes that are instantiated with a factory must have
2916 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
2917 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
2919 OO
.ui
.WindowManager
= function OoUiWindowManager( config
) {
2920 // Configuration initialization
2921 config
= config
|| {};
2923 // Parent constructor
2924 OO
.ui
.WindowManager
.parent
.call( this, config
);
2926 // Mixin constructors
2927 OO
.EventEmitter
.call( this );
2930 this.factory
= config
.factory
;
2931 this.modal
= config
.modal
=== undefined || !!config
.modal
;
2933 this.opening
= null;
2935 this.closing
= null;
2936 this.preparingToOpen
= null;
2937 this.preparingToClose
= null;
2938 this.currentWindow
= null;
2939 this.globalEvents
= false;
2940 this.$ariaHidden
= null;
2941 this.onWindowResizeTimeout
= null;
2942 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
2943 this.afterWindowResizeHandler
= this.afterWindowResize
.bind( this );
2947 .addClass( 'oo-ui-windowManager' )
2948 .toggleClass( 'oo-ui-windowManager-modal', this.modal
);
2953 OO
.inheritClass( OO
.ui
.WindowManager
, OO
.ui
.Element
);
2954 OO
.mixinClass( OO
.ui
.WindowManager
, OO
.EventEmitter
);
2959 * An 'opening' event is emitted when the window begins to be opened.
2962 * @param {OO.ui.Window} win Window that's being opened
2963 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
2964 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
2965 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
2966 * @param {Object} data Window opening data
2970 * A 'closing' event is emitted when the window begins to be closed.
2973 * @param {OO.ui.Window} win Window that's being closed
2974 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
2975 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
2976 * processes are complete. When the `closing` promise is resolved, the first argument of its value
2977 * is the closing data.
2978 * @param {Object} data Window closing data
2982 * A 'resize' event is emitted when a window is resized.
2985 * @param {OO.ui.Window} win Window that was resized
2988 /* Static Properties */
2991 * Map of the symbolic name of each window size and its CSS properties.
2995 * @property {Object}
2997 OO
.ui
.WindowManager
.static.sizes
= {
3011 // These can be non-numeric because they are never used in calculations
3018 * Symbolic name of the default window size.
3020 * The default size is used if the window's requested size is not recognized.
3024 * @property {string}
3026 OO
.ui
.WindowManager
.static.defaultSize
= 'medium';
3031 * Handle window resize events.
3034 * @param {jQuery.Event} e Window resize event
3036 OO
.ui
.WindowManager
.prototype.onWindowResize = function () {
3037 clearTimeout( this.onWindowResizeTimeout
);
3038 this.onWindowResizeTimeout
= setTimeout( this.afterWindowResizeHandler
, 200 );
3042 * Handle window resize events.
3045 * @param {jQuery.Event} e Window resize event
3047 OO
.ui
.WindowManager
.prototype.afterWindowResize = function () {
3048 if ( this.currentWindow
) {
3049 this.updateWindowSize( this.currentWindow
);
3054 * Check if window is opening.
3056 * @return {boolean} Window is opening
3058 OO
.ui
.WindowManager
.prototype.isOpening = function ( win
) {
3059 return win
=== this.currentWindow
&& !!this.opening
&& this.opening
.state() === 'pending';
3063 * Check if window is closing.
3065 * @return {boolean} Window is closing
3067 OO
.ui
.WindowManager
.prototype.isClosing = function ( win
) {
3068 return win
=== this.currentWindow
&& !!this.closing
&& this.closing
.state() === 'pending';
3072 * Check if window is opened.
3074 * @return {boolean} Window is opened
3076 OO
.ui
.WindowManager
.prototype.isOpened = function ( win
) {
3077 return win
=== this.currentWindow
&& !!this.opened
&& this.opened
.state() === 'pending';
3081 * Check if a window is being managed.
3083 * @param {OO.ui.Window} win Window to check
3084 * @return {boolean} Window is being managed
3086 OO
.ui
.WindowManager
.prototype.hasWindow = function ( win
) {
3089 for ( name
in this.windows
) {
3090 if ( this.windows
[ name
] === win
) {
3099 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
3101 * @param {OO.ui.Window} win Window being opened
3102 * @param {Object} [data] Window opening data
3103 * @return {number} Milliseconds to wait
3105 OO
.ui
.WindowManager
.prototype.getSetupDelay = function () {
3110 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3112 * @param {OO.ui.Window} win Window being opened
3113 * @param {Object} [data] Window opening data
3114 * @return {number} Milliseconds to wait
3116 OO
.ui
.WindowManager
.prototype.getReadyDelay = function () {
3121 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3123 * @param {OO.ui.Window} win Window being closed
3124 * @param {Object} [data] Window closing data
3125 * @return {number} Milliseconds to wait
3127 OO
.ui
.WindowManager
.prototype.getHoldDelay = function () {
3132 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3133 * executing the ‘teardown’ process.
3135 * @param {OO.ui.Window} win Window being closed
3136 * @param {Object} [data] Window closing data
3137 * @return {number} Milliseconds to wait
3139 OO
.ui
.WindowManager
.prototype.getTeardownDelay = function () {
3140 return this.modal
? 250 : 0;
3144 * Get a window by its symbolic name.
3146 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3147 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3148 * for more information about using factories.
3149 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3151 * @param {string} name Symbolic name of the window
3152 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3153 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3154 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3156 OO
.ui
.WindowManager
.prototype.getWindow = function ( name
) {
3157 var deferred
= $.Deferred(),
3158 win
= this.windows
[ name
];
3160 if ( !( win
instanceof OO
.ui
.Window
) ) {
3161 if ( this.factory
) {
3162 if ( !this.factory
.lookup( name
) ) {
3163 deferred
.reject( new OO
.ui
.Error(
3164 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3167 win
= this.factory
.create( name
);
3168 this.addWindows( [ win
] );
3169 deferred
.resolve( win
);
3172 deferred
.reject( new OO
.ui
.Error(
3173 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3177 deferred
.resolve( win
);
3180 return deferred
.promise();
3184 * Get current window.
3186 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3188 OO
.ui
.WindowManager
.prototype.getCurrentWindow = function () {
3189 return this.currentWindow
;
3195 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3196 * @param {Object} [data] Window opening data
3197 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3198 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3201 OO
.ui
.WindowManager
.prototype.openWindow = function ( win
, data
) {
3203 opening
= $.Deferred();
3205 // Argument handling
3206 if ( typeof win
=== 'string' ) {
3207 return this.getWindow( win
).then( function ( win
) {
3208 return manager
.openWindow( win
, data
);
3213 if ( !this.hasWindow( win
) ) {
3214 opening
.reject( new OO
.ui
.Error(
3215 'Cannot open window: window is not attached to manager'
3217 } else if ( this.preparingToOpen
|| this.opening
|| this.opened
) {
3218 opening
.reject( new OO
.ui
.Error(
3219 'Cannot open window: another window is opening or open'
3224 if ( opening
.state() !== 'rejected' ) {
3225 // If a window is currently closing, wait for it to complete
3226 this.preparingToOpen
= $.when( this.closing
);
3227 // Ensure handlers get called after preparingToOpen is set
3228 this.preparingToOpen
.done( function () {
3229 if ( manager
.modal
) {
3230 manager
.toggleGlobalEvents( true );
3231 manager
.toggleAriaIsolation( true );
3233 manager
.currentWindow
= win
;
3234 manager
.opening
= opening
;
3235 manager
.preparingToOpen
= null;
3236 manager
.emit( 'opening', win
, opening
, data
);
3237 setTimeout( function () {
3238 win
.setup( data
).then( function () {
3239 manager
.updateWindowSize( win
);
3240 manager
.opening
.notify( { state
: 'setup' } );
3241 setTimeout( function () {
3242 win
.ready( data
).then( function () {
3243 manager
.opening
.notify( { state
: 'ready' } );
3244 manager
.opening
= null;
3245 manager
.opened
= $.Deferred();
3246 opening
.resolve( manager
.opened
.promise(), data
);
3248 }, manager
.getReadyDelay() );
3250 }, manager
.getSetupDelay() );
3254 return opening
.promise();
3260 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3261 * @param {Object} [data] Window closing data
3262 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3263 * See {@link #event-closing 'closing' event} for more information about closing promises.
3264 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3267 OO
.ui
.WindowManager
.prototype.closeWindow = function ( win
, data
) {
3269 closing
= $.Deferred(),
3272 // Argument handling
3273 if ( typeof win
=== 'string' ) {
3274 win
= this.windows
[ win
];
3275 } else if ( !this.hasWindow( win
) ) {
3281 closing
.reject( new OO
.ui
.Error(
3282 'Cannot close window: window is not attached to manager'
3284 } else if ( win
!== this.currentWindow
) {
3285 closing
.reject( new OO
.ui
.Error(
3286 'Cannot close window: window already closed with different data'
3288 } else if ( this.preparingToClose
|| this.closing
) {
3289 closing
.reject( new OO
.ui
.Error(
3290 'Cannot close window: window already closing with different data'
3295 if ( closing
.state() !== 'rejected' ) {
3296 // If the window is currently opening, close it when it's done
3297 this.preparingToClose
= $.when( this.opening
);
3298 // Ensure handlers get called after preparingToClose is set
3299 this.preparingToClose
.done( function () {
3300 manager
.closing
= closing
;
3301 manager
.preparingToClose
= null;
3302 manager
.emit( 'closing', win
, closing
, data
);
3303 opened
= manager
.opened
;
3304 manager
.opened
= null;
3305 opened
.resolve( closing
.promise(), data
);
3306 setTimeout( function () {
3307 win
.hold( data
).then( function () {
3308 closing
.notify( { state
: 'hold' } );
3309 setTimeout( function () {
3310 win
.teardown( data
).then( function () {
3311 closing
.notify( { state
: 'teardown' } );
3312 if ( manager
.modal
) {
3313 manager
.toggleGlobalEvents( false );
3314 manager
.toggleAriaIsolation( false );
3316 manager
.closing
= null;
3317 manager
.currentWindow
= null;
3318 closing
.resolve( data
);
3320 }, manager
.getTeardownDelay() );
3322 }, manager
.getHoldDelay() );
3326 return closing
.promise();
3330 * Add windows to the window manager.
3332 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3333 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3334 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3336 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3337 * by reference, symbolic name, or explicitly defined symbolic names.
3338 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3339 * explicit nor a statically configured symbolic name.
3341 OO
.ui
.WindowManager
.prototype.addWindows = function ( windows
) {
3342 var i
, len
, win
, name
, list
;
3344 if ( Array
.isArray( windows
) ) {
3345 // Convert to map of windows by looking up symbolic names from static configuration
3347 for ( i
= 0, len
= windows
.length
; i
< len
; i
++ ) {
3348 name
= windows
[ i
].constructor.static.name
;
3349 if ( typeof name
!== 'string' ) {
3350 throw new Error( 'Cannot add window' );
3352 list
[ name
] = windows
[ i
];
3354 } else if ( OO
.isPlainObject( windows
) ) {
3359 for ( name
in list
) {
3361 this.windows
[ name
] = win
.toggle( false );
3362 this.$element
.append( win
.$element
);
3363 win
.setManager( this );
3368 * Remove the specified windows from the windows manager.
3370 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3371 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3372 * longer listens to events, use the #destroy method.
3374 * @param {string[]} names Symbolic names of windows to remove
3375 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3376 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3378 OO
.ui
.WindowManager
.prototype.removeWindows = function ( names
) {
3379 var i
, len
, win
, name
, cleanupWindow
,
3382 cleanup = function ( name
, win
) {
3383 delete manager
.windows
[ name
];
3384 win
.$element
.detach();
3387 for ( i
= 0, len
= names
.length
; i
< len
; i
++ ) {
3389 win
= this.windows
[ name
];
3391 throw new Error( 'Cannot remove window' );
3393 cleanupWindow
= cleanup
.bind( null, name
, win
);
3394 promises
.push( this.closeWindow( name
).then( cleanupWindow
, cleanupWindow
) );
3397 return $.when
.apply( $, promises
);
3401 * Remove all windows from the window manager.
3403 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3404 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3405 * To remove just a subset of windows, use the #removeWindows method.
3407 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3409 OO
.ui
.WindowManager
.prototype.clearWindows = function () {
3410 return this.removeWindows( Object
.keys( this.windows
) );
3414 * Set dialog size. In general, this method should not be called directly.
3416 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3420 OO
.ui
.WindowManager
.prototype.updateWindowSize = function ( win
) {
3421 // Bypass for non-current, and thus invisible, windows
3422 if ( win
!== this.currentWindow
) {
3426 var viewport
= OO
.ui
.Element
.static.getDimensions( win
.getElementWindow() ),
3427 sizes
= this.constructor.static.sizes
,
3428 size
= win
.getSize();
3430 if ( !sizes
[ size
] ) {
3431 size
= this.constructor.static.defaultSize
;
3433 if ( size
!== 'full' && viewport
.rect
.right
- viewport
.rect
.left
< sizes
[ size
].width
) {
3437 this.$element
.toggleClass( 'oo-ui-windowManager-fullscreen', size
=== 'full' );
3438 this.$element
.toggleClass( 'oo-ui-windowManager-floating', size
!== 'full' );
3439 win
.setDimensions( sizes
[ size
] );
3441 this.emit( 'resize', win
);
3447 * Bind or unbind global events for scrolling.
3450 * @param {boolean} [on] Bind global events
3453 OO
.ui
.WindowManager
.prototype.toggleGlobalEvents = function ( on
) {
3454 on
= on
=== undefined ? !!this.globalEvents
: !!on
;
3456 var scrollWidth
, bodyMargin
,
3457 $body
= $( this.getElementDocument().body
),
3458 // We could have multiple window managers open so only modify
3459 // the body css at the bottom of the stack
3460 stackDepth
= $body
.data( 'windowManagerGlobalEvents' ) || 0 ;
3463 if ( !this.globalEvents
) {
3464 $( this.getElementWindow() ).on( {
3465 // Start listening for top-level window dimension changes
3466 'orientationchange resize': this.onWindowResizeHandler
3468 if ( stackDepth
=== 0 ) {
3469 scrollWidth
= window
.innerWidth
- document
.documentElement
.clientWidth
;
3470 bodyMargin
= parseFloat( $body
.css( 'margin-right' ) ) || 0;
3473 'margin-right': bodyMargin
+ scrollWidth
3477 this.globalEvents
= true;
3479 } else if ( this.globalEvents
) {
3480 $( this.getElementWindow() ).off( {
3481 // Stop listening for top-level window dimension changes
3482 'orientationchange resize': this.onWindowResizeHandler
3485 if ( stackDepth
=== 0 ) {
3491 this.globalEvents
= false;
3493 $body
.data( 'windowManagerGlobalEvents', stackDepth
);
3499 * Toggle screen reader visibility of content other than the window manager.
3502 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3505 OO
.ui
.WindowManager
.prototype.toggleAriaIsolation = function ( isolate
) {
3506 isolate
= isolate
=== undefined ? !this.$ariaHidden
: !!isolate
;
3509 if ( !this.$ariaHidden
) {
3510 // Hide everything other than the window manager from screen readers
3511 this.$ariaHidden
= $( 'body' )
3513 .not( this.$element
.parentsUntil( 'body' ).last() )
3514 .attr( 'aria-hidden', '' );
3516 } else if ( this.$ariaHidden
) {
3517 // Restore screen reader visibility
3518 this.$ariaHidden
.removeAttr( 'aria-hidden' );
3519 this.$ariaHidden
= null;
3526 * Destroy the window manager.
3528 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3529 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3532 OO
.ui
.WindowManager
.prototype.destroy = function () {
3533 this.toggleGlobalEvents( false );
3534 this.toggleAriaIsolation( false );
3535 this.clearWindows();
3536 this.$element
.remove();
3540 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3541 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3542 * appearance and functionality of the error interface.
3544 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3545 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3546 * that initiated the failed process will be disabled.
3548 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3551 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3553 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3558 * @param {string|jQuery} message Description of error
3559 * @param {Object} [config] Configuration options
3560 * @cfg {boolean} [recoverable=true] Error is recoverable.
3561 * By default, errors are recoverable, and users can try the process again.
3562 * @cfg {boolean} [warning=false] Error is a warning.
3563 * If the error is a warning, the error interface will include a
3564 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3565 * is not triggered a second time if the user chooses to continue.
3567 OO
.ui
.Error
= function OoUiError( message
, config
) {
3568 // Allow passing positional parameters inside the config object
3569 if ( OO
.isPlainObject( message
) && config
=== undefined ) {
3571 message
= config
.message
;
3574 // Configuration initialization
3575 config
= config
|| {};
3578 this.message
= message
instanceof jQuery
? message
: String( message
);
3579 this.recoverable
= config
.recoverable
=== undefined || !!config
.recoverable
;
3580 this.warning
= !!config
.warning
;
3585 OO
.initClass( OO
.ui
.Error
);
3590 * Check if the error is recoverable.
3592 * If the error is recoverable, users are able to try the process again.
3594 * @return {boolean} Error is recoverable
3596 OO
.ui
.Error
.prototype.isRecoverable = function () {
3597 return this.recoverable
;
3601 * Check if the error is a warning.
3603 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3605 * @return {boolean} Error is warning
3607 OO
.ui
.Error
.prototype.isWarning = function () {
3608 return this.warning
;
3612 * Get error message as DOM nodes.
3614 * @return {jQuery} Error message in DOM nodes
3616 OO
.ui
.Error
.prototype.getMessage = function () {
3617 return this.message
instanceof jQuery
?
3618 this.message
.clone() :
3619 $( '<div>' ).text( this.message
).contents();
3623 * Get the error message text.
3625 * @return {string} Error message
3627 OO
.ui
.Error
.prototype.getMessageText = function () {
3628 return this.message
instanceof jQuery
? this.message
.text() : this.message
;
3632 * Wraps an HTML snippet for use with configuration values which default
3633 * to strings. This bypasses the default html-escaping done to string
3639 * @param {string} [content] HTML content
3641 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
3643 this.content
= content
;
3648 OO
.initClass( OO
.ui
.HtmlSnippet
);
3655 * @return {string} Unchanged HTML snippet.
3657 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
3658 return this.content
;
3662 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3665 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3666 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3667 * or stop if the promise is rejected.
3668 * - **function**: the process will execute the function. The process will stop if the function returns
3669 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3670 * will wait for that number of milliseconds before proceeding.
3672 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3673 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3674 * its remaining steps will not be performed.
3679 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3680 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3681 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3682 * a number or promise.
3683 * @return {Object} Step object, with `callback` and `context` properties
3685 OO
.ui
.Process = function ( step
, context
) {
3690 if ( step
!== undefined ) {
3691 this.next( step
, context
);
3697 OO
.initClass( OO
.ui
.Process
);
3702 * Start the process.
3704 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3705 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3706 * and any remaining steps are not performed.
3708 OO
.ui
.Process
.prototype.execute = function () {
3709 var i
, len
, promise
;
3712 * Continue execution.
3715 * @param {Array} step A function and the context it should be called in
3716 * @return {Function} Function that continues the process
3718 function proceed( step
) {
3719 return function () {
3720 // Execute step in the correct context
3722 result
= step
.callback
.call( step
.context
);
3724 if ( result
=== false ) {
3725 // Use rejected promise for boolean false results
3726 return $.Deferred().reject( [] ).promise();
3728 if ( typeof result
=== 'number' ) {
3730 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3732 // Use a delayed promise for numbers, expecting them to be in milliseconds
3733 deferred
= $.Deferred();
3734 setTimeout( deferred
.resolve
, result
);
3735 return deferred
.promise();
3737 if ( result
instanceof OO
.ui
.Error
) {
3738 // Use rejected promise for error
3739 return $.Deferred().reject( [ result
] ).promise();
3741 if ( Array
.isArray( result
) && result
.length
&& result
[ 0 ] instanceof OO
.ui
.Error
) {
3742 // Use rejected promise for list of errors
3743 return $.Deferred().reject( result
).promise();
3745 // Duck-type the object to see if it can produce a promise
3746 if ( result
&& $.isFunction( result
.promise
) ) {
3747 // Use a promise generated from the result
3748 return result
.promise();
3750 // Use resolved promise for other results
3751 return $.Deferred().resolve().promise();
3755 if ( this.steps
.length
) {
3756 // Generate a chain reaction of promises
3757 promise
= proceed( this.steps
[ 0 ] )();
3758 for ( i
= 1, len
= this.steps
.length
; i
< len
; i
++ ) {
3759 promise
= promise
.then( proceed( this.steps
[ i
] ) );
3762 promise
= $.Deferred().resolve().promise();
3769 * Create a process step.
3772 * @param {number|jQuery.Promise|Function} step
3774 * - Number of milliseconds to wait before proceeding
3775 * - Promise that must be resolved before proceeding
3776 * - Function to execute
3777 * - If the function returns a boolean false the process will stop
3778 * - If the function returns a promise, the process will continue to the next
3779 * step when the promise is resolved or stop if the promise is rejected
3780 * - If the function returns a number, the process will wait for that number of
3781 * milliseconds before proceeding
3782 * @param {Object} [context=null] Execution context of the function. The context is
3783 * ignored if the step is a number or promise.
3784 * @return {Object} Step object, with `callback` and `context` properties
3786 OO
.ui
.Process
.prototype.createStep = function ( step
, context
) {
3787 if ( typeof step
=== 'number' || $.isFunction( step
.promise
) ) {
3789 callback: function () {
3795 if ( $.isFunction( step
) ) {
3801 throw new Error( 'Cannot create process step: number, promise or function expected' );
3805 * Add step to the beginning of the process.
3807 * @inheritdoc #createStep
3808 * @return {OO.ui.Process} this
3811 OO
.ui
.Process
.prototype.first = function ( step
, context
) {
3812 this.steps
.unshift( this.createStep( step
, context
) );
3817 * Add step to the end of the process.
3819 * @inheritdoc #createStep
3820 * @return {OO.ui.Process} this
3823 OO
.ui
.Process
.prototype.next = function ( step
, context
) {
3824 this.steps
.push( this.createStep( step
, context
) );
3829 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
3830 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
3831 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
3833 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
3835 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
3838 * @extends OO.Factory
3841 OO
.ui
.ToolFactory
= function OoUiToolFactory() {
3842 // Parent constructor
3843 OO
.ui
.ToolFactory
.parent
.call( this );
3848 OO
.inheritClass( OO
.ui
.ToolFactory
, OO
.Factory
);
3853 * Get tools from the factory
3855 * @param {Array} include Included tools
3856 * @param {Array} exclude Excluded tools
3857 * @param {Array} promote Promoted tools
3858 * @param {Array} demote Demoted tools
3859 * @return {string[]} List of tools
3861 OO
.ui
.ToolFactory
.prototype.getTools = function ( include
, exclude
, promote
, demote
) {
3862 var i
, len
, included
, promoted
, demoted
,
3866 // Collect included and not excluded tools
3867 included
= OO
.simpleArrayDifference( this.extract( include
), this.extract( exclude
) );
3870 promoted
= this.extract( promote
, used
);
3871 demoted
= this.extract( demote
, used
);
3874 for ( i
= 0, len
= included
.length
; i
< len
; i
++ ) {
3875 if ( !used
[ included
[ i
] ] ) {
3876 auto
.push( included
[ i
] );
3880 return promoted
.concat( auto
).concat( demoted
);
3884 * Get a flat list of names from a list of names or groups.
3886 * Tools can be specified in the following ways:
3888 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
3889 * - All tools in a group: `{ group: 'group-name' }`
3890 * - All tools: `'*'`
3893 * @param {Array|string} collection List of tools
3894 * @param {Object} [used] Object with names that should be skipped as properties; extracted
3895 * names will be added as properties
3896 * @return {string[]} List of extracted names
3898 OO
.ui
.ToolFactory
.prototype.extract = function ( collection
, used
) {
3899 var i
, len
, item
, name
, tool
,
3902 if ( collection
=== '*' ) {
3903 for ( name
in this.registry
) {
3904 tool
= this.registry
[ name
];
3906 // Only add tools by group name when auto-add is enabled
3907 tool
.static.autoAddToCatchall
&&
3908 // Exclude already used tools
3909 ( !used
|| !used
[ name
] )
3913 used
[ name
] = true;
3917 } else if ( Array
.isArray( collection
) ) {
3918 for ( i
= 0, len
= collection
.length
; i
< len
; i
++ ) {
3919 item
= collection
[ i
];
3920 // Allow plain strings as shorthand for named tools
3921 if ( typeof item
=== 'string' ) {
3922 item
= { name
: item
};
3924 if ( OO
.isPlainObject( item
) ) {
3926 for ( name
in this.registry
) {
3927 tool
= this.registry
[ name
];
3929 // Include tools with matching group
3930 tool
.static.group
=== item
.group
&&
3931 // Only add tools by group name when auto-add is enabled
3932 tool
.static.autoAddToGroup
&&
3933 // Exclude already used tools
3934 ( !used
|| !used
[ name
] )
3938 used
[ name
] = true;
3942 // Include tools with matching name and exclude already used tools
3943 } else if ( item
.name
&& ( !used
|| !used
[ item
.name
] ) ) {
3944 names
.push( item
.name
);
3946 used
[ item
.name
] = true;
3956 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
3957 * specify a symbolic name and be registered with the factory. The following classes are registered by
3960 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
3961 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
3962 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
3964 * See {@link OO.ui.Toolbar toolbars} for an example.
3966 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
3968 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
3970 * @extends OO.Factory
3973 OO
.ui
.ToolGroupFactory
= function OoUiToolGroupFactory() {
3974 // Parent constructor
3975 OO
.Factory
.call( this );
3978 defaultClasses
= this.constructor.static.getDefaultClasses();
3980 // Register default toolgroups
3981 for ( i
= 0, l
= defaultClasses
.length
; i
< l
; i
++ ) {
3982 this.register( defaultClasses
[ i
] );
3988 OO
.inheritClass( OO
.ui
.ToolGroupFactory
, OO
.Factory
);
3990 /* Static Methods */
3993 * Get a default set of classes to be registered on construction.
3995 * @return {Function[]} Default classes
3997 OO
.ui
.ToolGroupFactory
.static.getDefaultClasses = function () {
4000 OO
.ui
.ListToolGroup
,
4012 * @param {Object} [config] Configuration options
4014 OO
.ui
.Theme
= function OoUiTheme( config
) {
4015 // Configuration initialization
4016 config
= config
|| {};
4021 OO
.initClass( OO
.ui
.Theme
);
4026 * Get a list of classes to be applied to a widget.
4028 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4029 * otherwise state transitions will not work properly.
4031 * @param {OO.ui.Element} element Element for which to get classes
4032 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4034 OO
.ui
.Theme
.prototype.getElementClasses = function ( /* element */ ) {
4035 return { on
: [], off
: [] };
4039 * Update CSS classes provided by the theme.
4041 * For elements with theme logic hooks, this should be called any time there's a state change.
4043 * @param {OO.ui.Element} element Element for which to update classes
4044 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4046 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
4047 var classes
= this.getElementClasses( element
);
4050 .removeClass( classes
.off
.join( ' ' ) )
4051 .addClass( classes
.on
.join( ' ' ) );
4055 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4056 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4057 * order in which users will navigate through the focusable elements via the "tab" key.
4060 * // TabIndexedElement is mixed into the ButtonWidget class
4061 * // to provide a tabIndex property.
4062 * var button1 = new OO.ui.ButtonWidget( {
4066 * var button2 = new OO.ui.ButtonWidget( {
4070 * var button3 = new OO.ui.ButtonWidget( {
4074 * var button4 = new OO.ui.ButtonWidget( {
4078 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4084 * @param {Object} [config] Configuration options
4085 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4086 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4087 * functionality will be applied to it instead.
4088 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4089 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4090 * to remove the element from the tab-navigation flow.
4092 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
4093 // Configuration initialization
4094 config
= $.extend( { tabIndex
: 0 }, config
);
4097 this.$tabIndexed
= null;
4098 this.tabIndex
= null;
4101 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
4104 this.setTabIndex( config
.tabIndex
);
4105 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
4110 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
4115 * Set the element that should use the tabindex functionality.
4117 * This method is used to retarget a tabindex mixin so that its functionality applies
4118 * to the specified element. If an element is currently using the functionality, the mixin’s
4119 * effect on that element is removed before the new element is set up.
4121 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4124 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
4125 var tabIndex
= this.tabIndex
;
4126 // Remove attributes from old $tabIndexed
4127 this.setTabIndex( null );
4128 // Force update of new $tabIndexed
4129 this.$tabIndexed
= $tabIndexed
;
4130 this.tabIndex
= tabIndex
;
4131 return this.updateTabIndex();
4135 * Set the value of the tabindex.
4137 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4140 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
4141 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
4143 if ( this.tabIndex
!== tabIndex
) {
4144 this.tabIndex
= tabIndex
;
4145 this.updateTabIndex();
4152 * Update the `tabindex` attribute, in case of changes to tab index or
4158 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
4159 if ( this.$tabIndexed
) {
4160 if ( this.tabIndex
!== null ) {
4161 // Do not index over disabled elements
4162 this.$tabIndexed
.attr( {
4163 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
4164 // ChromeVox and NVDA do not seem to inherit this from parent elements
4165 'aria-disabled': this.isDisabled().toString()
4168 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
4175 * Handle disable events.
4178 * @param {boolean} disabled Element is disabled
4180 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
4181 this.updateTabIndex();
4185 * Get the value of the tabindex.
4187 * @return {number|null} Tabindex value
4189 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
4190 return this.tabIndex
;
4194 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4195 * interface element that can be configured with access keys for accessibility.
4196 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4198 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4203 * @param {Object} [config] Configuration options
4204 * @cfg {jQuery} [$button] The button element created by the class.
4205 * If this configuration is omitted, the button element will use a generated `<a>`.
4206 * @cfg {boolean} [framed=true] Render the button with a frame
4207 * @cfg {string} [accessKey] Button's access key
4209 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
4210 // Configuration initialization
4211 config
= config
|| {};
4214 this.$button
= null;
4216 this.accessKey
= null;
4217 this.active
= false;
4218 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
4219 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4220 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
4221 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
4222 this.onClickHandler
= this.onClick
.bind( this );
4223 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
4226 this.$element
.addClass( 'oo-ui-buttonElement' );
4227 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
4228 this.setAccessKey( config
.accessKey
);
4229 this.setButtonElement( config
.$button
|| $( '<a>' ) );
4234 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
4236 /* Static Properties */
4239 * Cancel mouse down events.
4241 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4242 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4243 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4248 * @property {boolean}
4250 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
4255 * A 'click' event is emitted when the button element is clicked.
4263 * Set the button element.
4265 * This method is used to retarget a button mixin so that its functionality applies to
4266 * the specified button element instead of the one created by the class. If a button element
4267 * is already set, the method will remove the mixin’s effect on that element.
4269 * @param {jQuery} $button Element to use as button
4271 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
4272 if ( this.$button
) {
4274 .removeClass( 'oo-ui-buttonElement-button' )
4275 .removeAttr( 'role accesskey' )
4277 mousedown
: this.onMouseDownHandler
,
4278 keydown
: this.onKeyDownHandler
,
4279 click
: this.onClickHandler
,
4280 keypress
: this.onKeyPressHandler
4284 this.$button
= $button
4285 .addClass( 'oo-ui-buttonElement-button' )
4286 .attr( { role
: 'button', accesskey
: this.accessKey
} )
4288 mousedown
: this.onMouseDownHandler
,
4289 keydown
: this.onKeyDownHandler
,
4290 click
: this.onClickHandler
,
4291 keypress
: this.onKeyPressHandler
4296 * Handles mouse down events.
4299 * @param {jQuery.Event} e Mouse down event
4301 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
4302 if ( this.isDisabled() || e
.which
!== 1 ) {
4305 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4306 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4307 // reliably remove the pressed class
4308 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
4309 // Prevent change of focus unless specifically configured otherwise
4310 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
4316 * Handles mouse up events.
4319 * @param {jQuery.Event} e Mouse up event
4321 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
4322 if ( this.isDisabled() || e
.which
!== 1 ) {
4325 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4326 // Stop listening for mouseup, since we only needed this once
4327 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
4331 * Handles mouse click events.
4334 * @param {jQuery.Event} e Mouse click event
4337 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
4338 if ( !this.isDisabled() && e
.which
=== 1 ) {
4339 if ( this.emit( 'click' ) ) {
4346 * Handles key down events.
4349 * @param {jQuery.Event} e Key down event
4351 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
4352 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4355 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4356 // Run the keyup handler no matter where the key is when the button is let go, so we can
4357 // reliably remove the pressed class
4358 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler
, true );
4362 * Handles key up events.
4365 * @param {jQuery.Event} e Key up event
4367 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
4368 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4371 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4372 // Stop listening for keyup, since we only needed this once
4373 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler
, true );
4377 * Handles key press events.
4380 * @param {jQuery.Event} e Key press event
4383 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
4384 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
4385 if ( this.emit( 'click' ) ) {
4392 * Check if button has a frame.
4394 * @return {boolean} Button is framed
4396 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
4401 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4403 * @param {boolean} [framed] Make button framed, omit to toggle
4406 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
4407 framed
= framed
=== undefined ? !this.framed
: !!framed
;
4408 if ( framed
!== this.framed
) {
4409 this.framed
= framed
;
4411 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
4412 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
4413 this.updateThemeClasses();
4420 * Set the button's access key.
4422 * @param {string} accessKey Button's access key, use empty string to remove
4425 OO
.ui
.mixin
.ButtonElement
.prototype.setAccessKey = function ( accessKey
) {
4426 accessKey
= typeof accessKey
=== 'string' && accessKey
.length
? accessKey
: null;
4428 if ( this.accessKey
!== accessKey
) {
4429 if ( this.$button
) {
4430 if ( accessKey
!== null ) {
4431 this.$button
.attr( 'accesskey', accessKey
);
4433 this.$button
.removeAttr( 'accesskey' );
4436 this.accessKey
= accessKey
;
4443 * Set the button to its 'active' state.
4445 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4446 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4447 * for other button types.
4449 * @param {boolean} [value] Make button active
4452 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
4453 this.$element
.toggleClass( 'oo-ui-buttonElement-active', !!value
);
4458 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4459 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4460 * items from the group is done through the interface the class provides.
4461 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4463 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4469 * @param {Object} [config] Configuration options
4470 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4471 * is omitted, the group element will use a generated `<div>`.
4473 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
4474 // Configuration initialization
4475 config
= config
|| {};
4480 this.aggregateItemEvents
= {};
4483 this.setGroupElement( config
.$group
|| $( '<div>' ) );
4489 * Set the group element.
4491 * If an element is already set, items will be moved to the new element.
4493 * @param {jQuery} $group Element to use as group
4495 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
4498 this.$group
= $group
;
4499 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4500 this.$group
.append( this.items
[ i
].$element
);
4505 * Check if a group contains no items.
4507 * @return {boolean} Group is empty
4509 OO
.ui
.mixin
.GroupElement
.prototype.isEmpty = function () {
4510 return !this.items
.length
;
4514 * Get all items in the group.
4516 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4517 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4520 * @return {OO.ui.Element[]} An array of items.
4522 OO
.ui
.mixin
.GroupElement
.prototype.getItems = function () {
4523 return this.items
.slice( 0 );
4527 * Get an item by its data.
4529 * Only the first item with matching data will be returned. To return all matching items,
4530 * use the #getItemsFromData method.
4532 * @param {Object} data Item data to search for
4533 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4535 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
4537 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 * Get items by their data.
4552 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4554 * @param {Object} data Item data to search for
4555 * @return {OO.ui.Element[]} Items with equivalent data
4557 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
4559 hash
= OO
.getHash( data
),
4562 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4563 item
= this.items
[ i
];
4564 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4573 * Aggregate the events emitted by the group.
4575 * When events are aggregated, the group will listen to all contained items for the event,
4576 * and then emit the event under a new name. The new event will contain an additional leading
4577 * parameter containing the item that emitted the original event. Other arguments emitted from
4578 * the original event are passed through.
4580 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4581 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4582 * A `null` value will remove aggregated events.
4584 * @throws {Error} An error is thrown if aggregation already exists.
4586 OO
.ui
.mixin
.GroupElement
.prototype.aggregate = function ( events
) {
4587 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
4589 for ( itemEvent
in events
) {
4590 groupEvent
= events
[ itemEvent
];
4592 // Remove existing aggregated event
4593 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4594 // Don't allow duplicate aggregations
4596 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
4598 // Remove event aggregation from existing items
4599 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4600 item
= this.items
[ i
];
4601 if ( item
.connect
&& item
.disconnect
) {
4603 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[itemEvent
], item
];
4604 item
.disconnect( this, remove
);
4607 // Prevent future items from aggregating event
4608 delete this.aggregateItemEvents
[ itemEvent
];
4611 // Add new aggregate event
4613 // Make future items aggregate event
4614 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
4615 // Add event aggregation to existing items
4616 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4617 item
= this.items
[ i
];
4618 if ( item
.connect
&& item
.disconnect
) {
4620 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
4621 item
.connect( this, add
);
4629 * Add items to the group.
4631 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4632 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4634 * @param {OO.ui.Element[]} items An array of items to add to the group
4635 * @param {number} [index] Index of the insertion point
4638 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
4639 var i
, len
, item
, event
, events
, currentIndex
,
4642 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4645 // Check if item exists then remove it first, effectively "moving" it
4646 currentIndex
= $.inArray( item
, this.items
);
4647 if ( currentIndex
>= 0 ) {
4648 this.removeItems( [ item
] );
4649 // Adjust index to compensate for removal
4650 if ( currentIndex
< index
) {
4655 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
4657 for ( event
in this.aggregateItemEvents
) {
4658 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
4660 item
.connect( this, events
);
4662 item
.setElementGroup( this );
4663 itemElements
.push( item
.$element
.get( 0 ) );
4666 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
4667 this.$group
.append( itemElements
);
4668 this.items
.push
.apply( this.items
, items
);
4669 } else if ( index
=== 0 ) {
4670 this.$group
.prepend( itemElements
);
4671 this.items
.unshift
.apply( this.items
, items
);
4673 this.items
[ index
].$element
.before( itemElements
);
4674 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
4681 * Remove the specified items from a group.
4683 * Removed items are detached (not removed) from the DOM so that they may be reused.
4684 * To remove all items from a group, you may wish to use the #clearItems method instead.
4686 * @param {OO.ui.Element[]} items An array of items to remove
4689 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
4690 var i
, len
, item
, index
, remove
, itemEvent
;
4692 // Remove specific items
4693 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4695 index
= $.inArray( item
, this.items
);
4696 if ( index
!== -1 ) {
4698 item
.connect
&& item
.disconnect
&&
4699 !$.isEmptyObject( this.aggregateItemEvents
)
4702 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4703 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4705 item
.disconnect( this, remove
);
4707 item
.setElementGroup( null );
4708 this.items
.splice( index
, 1 );
4709 item
.$element
.detach();
4717 * Clear all items from the group.
4719 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4720 * To remove only a subset of items from a group, use the #removeItems method.
4724 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
4725 var i
, len
, item
, remove
, itemEvent
;
4728 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4729 item
= this.items
[ i
];
4731 item
.connect
&& item
.disconnect
&&
4732 !$.isEmptyObject( this.aggregateItemEvents
)
4735 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4736 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4738 item
.disconnect( this, remove
);
4740 item
.setElementGroup( null );
4741 item
.$element
.detach();
4749 * DraggableElement is a mixin class used to create elements that can be clicked
4750 * and dragged by a mouse to a new position within a group. This class must be used
4751 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
4752 * the draggable elements.
4759 OO
.ui
.mixin
.DraggableElement
= function OoUiMixinDraggableElement() {
4763 // Initialize and events
4765 .attr( 'draggable', true )
4766 .addClass( 'oo-ui-draggableElement' )
4768 dragstart
: this.onDragStart
.bind( this ),
4769 dragover
: this.onDragOver
.bind( this ),
4770 dragend
: this.onDragEnd
.bind( this ),
4771 drop
: this.onDrop
.bind( this )
4775 OO
.initClass( OO
.ui
.mixin
.DraggableElement
);
4782 * A dragstart event is emitted when the user clicks and begins dragging an item.
4783 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4788 * A dragend event is emitted when the user drags an item and releases the mouse,
4789 * thus terminating the drag operation.
4794 * A drop event is emitted when the user drags an item and then releases the mouse button
4795 * over a valid target.
4798 /* Static Properties */
4801 * @inheritdoc OO.ui.mixin.ButtonElement
4803 OO
.ui
.mixin
.DraggableElement
.static.cancelButtonMouseDownEvents
= false;
4808 * Respond to dragstart event.
4811 * @param {jQuery.Event} event jQuery event
4814 OO
.ui
.mixin
.DraggableElement
.prototype.onDragStart = function ( e
) {
4815 var dataTransfer
= e
.originalEvent
.dataTransfer
;
4816 // Define drop effect
4817 dataTransfer
.dropEffect
= 'none';
4818 dataTransfer
.effectAllowed
= 'move';
4819 // We must set up a dataTransfer data property or Firefox seems to
4820 // ignore the fact the element is draggable.
4822 dataTransfer
.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4824 // The above is only for firefox. No need to set a catch clause
4825 // if it fails, move on.
4827 // Add dragging class
4828 this.$element
.addClass( 'oo-ui-draggableElement-dragging' );
4830 this.emit( 'dragstart', this );
4835 * Respond to dragend event.
4840 OO
.ui
.mixin
.DraggableElement
.prototype.onDragEnd = function () {
4841 this.$element
.removeClass( 'oo-ui-draggableElement-dragging' );
4842 this.emit( 'dragend' );
4846 * Handle drop event.
4849 * @param {jQuery.Event} event jQuery event
4852 OO
.ui
.mixin
.DraggableElement
.prototype.onDrop = function ( e
) {
4854 this.emit( 'drop', e
);
4858 * In order for drag/drop to work, the dragover event must
4859 * return false and stop propogation.
4863 OO
.ui
.mixin
.DraggableElement
.prototype.onDragOver = function ( e
) {
4869 * Store it in the DOM so we can access from the widget drag event
4872 * @param {number} Item index
4874 OO
.ui
.mixin
.DraggableElement
.prototype.setIndex = function ( index
) {
4875 if ( this.index
!== index
) {
4877 this.$element
.data( 'index', index
);
4885 * @return {number} Item index
4887 OO
.ui
.mixin
.DraggableElement
.prototype.getIndex = function () {
4892 * DraggableGroupElement is a mixin class used to create a group element to
4893 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
4894 * The class is used with OO.ui.mixin.DraggableElement.
4898 * @mixins OO.ui.mixin.GroupElement
4901 * @param {Object} [config] Configuration options
4902 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
4903 * should match the layout of the items. Items displayed in a single row
4904 * or in several rows should use horizontal orientation. The vertical orientation should only be
4905 * used when the items are displayed in a single column. Defaults to 'vertical'
4907 OO
.ui
.mixin
.DraggableGroupElement
= function OoUiMixinDraggableGroupElement( config
) {
4908 // Configuration initialization
4909 config
= config
|| {};
4911 // Parent constructor
4912 OO
.ui
.mixin
.GroupElement
.call( this, config
);
4915 this.orientation
= config
.orientation
|| 'vertical';
4916 this.dragItem
= null;
4917 this.itemDragOver
= null;
4919 this.sideInsertion
= '';
4923 dragstart
: 'itemDragStart',
4924 dragend
: 'itemDragEnd',
4927 this.connect( this, {
4928 itemDragStart
: 'onItemDragStart',
4929 itemDrop
: 'onItemDrop',
4930 itemDragEnd
: 'onItemDragEnd'
4933 dragover
: $.proxy( this.onDragOver
, this ),
4934 dragleave
: $.proxy( this.onDragLeave
, this )
4938 if ( Array
.isArray( config
.items
) ) {
4939 this.addItems( config
.items
);
4941 this.$placeholder
= $( '<div>' )
4942 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
4944 .addClass( 'oo-ui-draggableGroupElement' )
4945 .append( this.$status
)
4946 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation
=== 'horizontal' )
4947 .prepend( this.$placeholder
);
4951 OO
.mixinClass( OO
.ui
.mixin
.DraggableGroupElement
, OO
.ui
.mixin
.GroupElement
);
4956 * A 'reorder' event is emitted when the order of items in the group changes.
4959 * @param {OO.ui.mixin.DraggableElement} item Reordered item
4960 * @param {number} [newIndex] New index for the item
4966 * Respond to item drag start event
4969 * @param {OO.ui.mixin.DraggableElement} item Dragged item
4971 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDragStart = function ( item
) {
4974 // Map the index of each object
4975 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4976 this.items
[ i
].setIndex( i
);
4979 if ( this.orientation
=== 'horizontal' ) {
4980 // Set the height of the indicator
4981 this.$placeholder
.css( {
4982 height
: item
.$element
.outerHeight(),
4986 // Set the width of the indicator
4987 this.$placeholder
.css( {
4989 width
: item
.$element
.outerWidth()
4992 this.setDragItem( item
);
4996 * Respond to item drag end event
5000 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDragEnd = function () {
5001 this.unsetDragItem();
5006 * Handle drop event and switch the order of the items accordingly
5009 * @param {OO.ui.mixin.DraggableElement} item Dropped item
5012 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDrop = function ( item
) {
5013 var toIndex
= item
.getIndex();
5014 // Check if the dropped item is from the current group
5015 // TODO: Figure out a way to configure a list of legally droppable
5016 // elements even if they are not yet in the list
5017 if ( this.getDragItem() ) {
5018 // If the insertion point is 'after', the insertion index
5019 // is shifted to the right (or to the left in RTL, hence 'after')
5020 if ( this.sideInsertion
=== 'after' ) {
5023 // Emit change event
5024 this.emit( 'reorder', this.getDragItem(), toIndex
);
5026 this.unsetDragItem();
5027 // Return false to prevent propogation
5032 * Handle dragleave event.
5036 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onDragLeave = function () {
5037 // This means the item was dragged outside the widget
5040 .addClass( 'oo-ui-element-hidden' );
5044 * Respond to dragover event
5047 * @param {jQuery.Event} event Event details
5049 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onDragOver = function ( e
) {
5050 var dragOverObj
, $optionWidget
, itemOffset
, itemMidpoint
, itemBoundingRect
,
5051 itemSize
, cssOutput
, dragPosition
, itemIndex
, itemPosition
,
5052 clientX
= e
.originalEvent
.clientX
,
5053 clientY
= e
.originalEvent
.clientY
;
5055 // Get the OptionWidget item we are dragging over
5056 dragOverObj
= this.getElementDocument().elementFromPoint( clientX
, clientY
);
5057 $optionWidget
= $( dragOverObj
).closest( '.oo-ui-draggableElement' );
5058 if ( $optionWidget
[ 0 ] ) {
5059 itemOffset
= $optionWidget
.offset();
5060 itemBoundingRect
= $optionWidget
[ 0 ].getBoundingClientRect();
5061 itemPosition
= $optionWidget
.position();
5062 itemIndex
= $optionWidget
.data( 'index' );
5067 this.isDragging() &&
5068 itemIndex
!== this.getDragItem().getIndex()
5070 if ( this.orientation
=== 'horizontal' ) {
5071 // Calculate where the mouse is relative to the item width
5072 itemSize
= itemBoundingRect
.width
;
5073 itemMidpoint
= itemBoundingRect
.left
+ itemSize
/ 2;
5074 dragPosition
= clientX
;
5075 // Which side of the item we hover over will dictate
5076 // where the placeholder will appear, on the left or
5079 left
: dragPosition
< itemMidpoint
? itemPosition
.left
: itemPosition
.left
+ itemSize
,
5080 top
: itemPosition
.top
5083 // Calculate where the mouse is relative to the item height
5084 itemSize
= itemBoundingRect
.height
;
5085 itemMidpoint
= itemBoundingRect
.top
+ itemSize
/ 2;
5086 dragPosition
= clientY
;
5087 // Which side of the item we hover over will dictate
5088 // where the placeholder will appear, on the top or
5091 top
: dragPosition
< itemMidpoint
? itemPosition
.top
: itemPosition
.top
+ itemSize
,
5092 left
: itemPosition
.left
5095 // Store whether we are before or after an item to rearrange
5096 // For horizontal layout, we need to account for RTL, as this is flipped
5097 if ( this.orientation
=== 'horizontal' && this.$element
.css( 'direction' ) === 'rtl' ) {
5098 this.sideInsertion
= dragPosition
< itemMidpoint
? 'after' : 'before';
5100 this.sideInsertion
= dragPosition
< itemMidpoint
? 'before' : 'after';
5102 // Add drop indicator between objects
5105 .removeClass( 'oo-ui-element-hidden' );
5107 // This means the item was dragged outside the widget
5110 .addClass( 'oo-ui-element-hidden' );
5117 * Set a dragged item
5119 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5121 OO
.ui
.mixin
.DraggableGroupElement
.prototype.setDragItem = function ( item
) {
5122 this.dragItem
= item
;
5126 * Unset the current dragged item
5128 OO
.ui
.mixin
.DraggableGroupElement
.prototype.unsetDragItem = function () {
5129 this.dragItem
= null;
5130 this.itemDragOver
= null;
5131 this.$placeholder
.addClass( 'oo-ui-element-hidden' );
5132 this.sideInsertion
= '';
5136 * Get the item that is currently being dragged.
5138 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5140 OO
.ui
.mixin
.DraggableGroupElement
.prototype.getDragItem = function () {
5141 return this.dragItem
;
5145 * Check if an item in the group is currently being dragged.
5147 * @return {Boolean} Item is being dragged
5149 OO
.ui
.mixin
.DraggableGroupElement
.prototype.isDragging = function () {
5150 return this.getDragItem() !== null;
5154 * IconElement is often mixed into other classes to generate an icon.
5155 * Icons are graphics, about the size of normal text. They are used to aid the user
5156 * in locating a control or to convey information in a space-efficient way. See the
5157 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5158 * included in the library.
5160 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5166 * @param {Object} [config] Configuration options
5167 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5168 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5169 * the icon element be set to an existing icon instead of the one generated by this class, set a
5170 * value using a jQuery selection. For example:
5172 * // Use a <div> tag instead of a <span>
5174 * // Use an existing icon element instead of the one generated by the class
5175 * $icon: this.$element
5176 * // Use an icon element from a child widget
5177 * $icon: this.childwidget.$element
5178 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5179 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5180 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5181 * by the user's language.
5183 * Example of an i18n map:
5185 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5186 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5187 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5188 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5189 * text. The icon title is displayed when users move the mouse over the icon.
5191 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
5192 // Configuration initialization
5193 config
= config
|| {};
5198 this.iconTitle
= null;
5201 this.setIcon( config
.icon
|| this.constructor.static.icon
);
5202 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
5203 this.setIconElement( config
.$icon
|| $( '<span>' ) );
5208 OO
.initClass( OO
.ui
.mixin
.IconElement
);
5210 /* Static Properties */
5213 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5214 * for i18n purposes and contains a `default` icon name and additional names keyed by
5215 * language code. The `default` name is used when no icon is keyed by the user's language.
5217 * Example of an i18n map:
5219 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5221 * Note: the static property will be overridden if the #icon configuration is used.
5225 * @property {Object|string}
5227 OO
.ui
.mixin
.IconElement
.static.icon
= null;
5230 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5231 * function that returns title text, or `null` for no title.
5233 * The static property will be overridden if the #iconTitle configuration is used.
5237 * @property {string|Function|null}
5239 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
5244 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5245 * applies to the specified icon element instead of the one created by the class. If an icon
5246 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5247 * and mixin methods will no longer affect the element.
5249 * @param {jQuery} $icon Element to use as icon
5251 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
5254 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
5255 .removeAttr( 'title' );
5259 .addClass( 'oo-ui-iconElement-icon' )
5260 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
5261 if ( this.iconTitle
!== null ) {
5262 this.$icon
.attr( 'title', this.iconTitle
);
5267 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5268 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5271 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5272 * by language code, or `null` to remove the icon.
5275 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
5276 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
5277 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
5279 if ( this.icon
!== icon
) {
5281 if ( this.icon
!== null ) {
5282 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
5284 if ( icon
!== null ) {
5285 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
5291 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
5292 this.updateThemeClasses();
5298 * Set the icon title. Use `null` to remove the title.
5300 * @param {string|Function|null} iconTitle A text string used as the icon title,
5301 * a function that returns title text, or `null` for no title.
5304 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
5305 iconTitle
= typeof iconTitle
=== 'function' ||
5306 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
5307 OO
.ui
.resolveMsg( iconTitle
) : null;
5309 if ( this.iconTitle
!== iconTitle
) {
5310 this.iconTitle
= iconTitle
;
5312 if ( this.iconTitle
!== null ) {
5313 this.$icon
.attr( 'title', iconTitle
);
5315 this.$icon
.removeAttr( 'title' );
5324 * Get the symbolic name of the icon.
5326 * @return {string} Icon name
5328 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
5333 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5335 * @return {string} Icon title text
5337 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
5338 return this.iconTitle
;
5342 * IndicatorElement is often mixed into other classes to generate an indicator.
5343 * Indicators are small graphics that are generally used in two ways:
5345 * - To draw attention to the status of an item. For example, an indicator might be
5346 * used to show that an item in a list has errors that need to be resolved.
5347 * - To clarify the function of a control that acts in an exceptional way (a button
5348 * that opens a menu instead of performing an action directly, for example).
5350 * For a list of indicators included in the library, please see the
5351 * [OOjs UI documentation on MediaWiki] [1].
5353 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5359 * @param {Object} [config] Configuration options
5360 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5361 * configuration is omitted, the indicator element will use a generated `<span>`.
5362 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5363 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5365 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5366 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5367 * or a function that returns title text. The indicator title is displayed when users move
5368 * the mouse over the indicator.
5370 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
5371 // Configuration initialization
5372 config
= config
|| {};
5375 this.$indicator
= null;
5376 this.indicator
= null;
5377 this.indicatorTitle
= null;
5380 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
5381 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
5382 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
5387 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
5389 /* Static Properties */
5392 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5393 * The static property will be overridden if the #indicator configuration is used.
5397 * @property {string|null}
5399 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
5402 * A text string used as the indicator title, a function that returns title text, or `null`
5403 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5407 * @property {string|Function|null}
5409 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
5414 * Set the indicator element.
5416 * If an element is already set, it will be cleaned up before setting up the new element.
5418 * @param {jQuery} $indicator Element to use as indicator
5420 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
5421 if ( this.$indicator
) {
5423 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
5424 .removeAttr( 'title' );
5427 this.$indicator
= $indicator
5428 .addClass( 'oo-ui-indicatorElement-indicator' )
5429 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
5430 if ( this.indicatorTitle
!== null ) {
5431 this.$indicator
.attr( 'title', this.indicatorTitle
);
5436 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5438 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5441 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
5442 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
5444 if ( this.indicator
!== indicator
) {
5445 if ( this.$indicator
) {
5446 if ( this.indicator
!== null ) {
5447 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
5449 if ( indicator
!== null ) {
5450 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
5453 this.indicator
= indicator
;
5456 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
5457 this.updateThemeClasses();
5463 * Set the indicator title.
5465 * The title is displayed when a user moves the mouse over the indicator.
5467 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5468 * `null` for no indicator title
5471 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
5472 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
5473 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
5474 OO
.ui
.resolveMsg( indicatorTitle
) : null;
5476 if ( this.indicatorTitle
!== indicatorTitle
) {
5477 this.indicatorTitle
= indicatorTitle
;
5478 if ( this.$indicator
) {
5479 if ( this.indicatorTitle
!== null ) {
5480 this.$indicator
.attr( 'title', indicatorTitle
);
5482 this.$indicator
.removeAttr( 'title' );
5491 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5493 * @return {string} Symbolic name of indicator
5495 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
5496 return this.indicator
;
5500 * Get the indicator title.
5502 * The title is displayed when a user moves the mouse over the indicator.
5504 * @return {string} Indicator title text
5506 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
5507 return this.indicatorTitle
;
5511 * LabelElement is often mixed into other classes to generate a label, which
5512 * helps identify the function of an interface element.
5513 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5515 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5521 * @param {Object} [config] Configuration options
5522 * @cfg {jQuery} [$label] The label element created by the class. If this
5523 * configuration is omitted, the label element will use a generated `<span>`.
5524 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5525 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5526 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5527 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5528 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5529 * The label will be truncated to fit if necessary.
5531 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
5532 // Configuration initialization
5533 config
= config
|| {};
5538 this.autoFitLabel
= config
.autoFitLabel
=== undefined || !!config
.autoFitLabel
;
5541 this.setLabel( config
.label
|| this.constructor.static.label
);
5542 this.setLabelElement( config
.$label
|| $( '<span>' ) );
5547 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
5552 * @event labelChange
5553 * @param {string} value
5556 /* Static Properties */
5559 * The label text. The label can be specified as a plaintext string, a function that will
5560 * produce a string in the future, or `null` for no label. The static value will
5561 * be overridden if a label is specified with the #label config option.
5565 * @property {string|Function|null}
5567 OO
.ui
.mixin
.LabelElement
.static.label
= null;
5572 * Set the label element.
5574 * If an element is already set, it will be cleaned up before setting up the new element.
5576 * @param {jQuery} $label Element to use as label
5578 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
5579 if ( this.$label
) {
5580 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
5583 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
5584 this.setLabelContent( this.label
);
5590 * An empty string will result in the label being hidden. A string containing only whitespace will
5591 * be converted to a single ` `.
5593 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5594 * text; or null for no label
5597 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
5598 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
5599 label
= ( ( typeof label
=== 'string' && label
.length
) || label
instanceof jQuery
|| label
instanceof OO
.ui
.HtmlSnippet
) ? label
: null;
5601 this.$element
.toggleClass( 'oo-ui-labelElement', !!label
);
5603 if ( this.label
!== label
) {
5604 if ( this.$label
) {
5605 this.setLabelContent( label
);
5608 this.emit( 'labelChange' );
5617 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5618 * text; or null for no label
5620 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
5629 OO
.ui
.mixin
.LabelElement
.prototype.fitLabel = function () {
5630 if ( this.$label
&& this.$label
.autoEllipsis
&& this.autoFitLabel
) {
5631 this.$label
.autoEllipsis( { hasSpan
: false, tooltip
: true } );
5638 * Set the content of the label.
5640 * Do not call this method until after the label element has been set by #setLabelElement.
5643 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5644 * text; or null for no label
5646 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
5647 if ( typeof label
=== 'string' ) {
5648 if ( label
.match( /^\s*$/ ) ) {
5649 // Convert whitespace only string to a single non-breaking space
5650 this.$label
.html( ' ' );
5652 this.$label
.text( label
);
5654 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
5655 this.$label
.html( label
.toString() );
5656 } else if ( label
instanceof jQuery
) {
5657 this.$label
.empty().append( label
);
5659 this.$label
.empty();
5664 * LookupElement is a mixin that creates a {@link OO.ui.TextInputMenuSelectWidget menu} of suggested values for
5665 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5666 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5667 * from the lookup menu, that value becomes the value of the input field.
5669 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5670 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5671 * re-enable lookups.
5673 * See the [OOjs UI demos][1] for an example.
5675 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5681 * @param {Object} [config] Configuration options
5682 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5683 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5684 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5685 * By default, the lookup menu is not generated and displayed until the user begins to type.
5687 OO
.ui
.mixin
.LookupElement
= function OoUiMixinLookupElement( config
) {
5688 // Configuration initialization
5689 config
= config
|| {};
5692 this.$overlay
= config
.$overlay
|| this.$element
;
5693 this.lookupMenu
= new OO
.ui
.TextInputMenuSelectWidget( this, {
5696 $container
: config
.$container
5699 this.allowSuggestionsWhenEmpty
= config
.allowSuggestionsWhenEmpty
|| false;
5701 this.lookupCache
= {};
5702 this.lookupQuery
= null;
5703 this.lookupRequest
= null;
5704 this.lookupsDisabled
= false;
5705 this.lookupInputFocused
= false;
5709 focus
: this.onLookupInputFocus
.bind( this ),
5710 blur
: this.onLookupInputBlur
.bind( this ),
5711 mousedown
: this.onLookupInputMouseDown
.bind( this )
5713 this.connect( this, { change
: 'onLookupInputChange' } );
5714 this.lookupMenu
.connect( this, {
5715 toggle
: 'onLookupMenuToggle',
5716 choose
: 'onLookupMenuItemChoose'
5720 this.$element
.addClass( 'oo-ui-lookupElement' );
5721 this.lookupMenu
.$element
.addClass( 'oo-ui-lookupElement-menu' );
5722 this.$overlay
.append( this.lookupMenu
.$element
);
5728 * Handle input focus event.
5731 * @param {jQuery.Event} e Input focus event
5733 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputFocus = function () {
5734 this.lookupInputFocused
= true;
5735 this.populateLookupMenu();
5739 * Handle input blur event.
5742 * @param {jQuery.Event} e Input blur event
5744 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputBlur = function () {
5745 this.closeLookupMenu();
5746 this.lookupInputFocused
= false;
5750 * Handle input mouse down event.
5753 * @param {jQuery.Event} e Input mouse down event
5755 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputMouseDown = function () {
5756 // Only open the menu if the input was already focused.
5757 // This way we allow the user to open the menu again after closing it with Esc
5758 // by clicking in the input. Opening (and populating) the menu when initially
5759 // clicking into the input is handled by the focus handler.
5760 if ( this.lookupInputFocused
&& !this.lookupMenu
.isVisible() ) {
5761 this.populateLookupMenu();
5766 * Handle input change event.
5769 * @param {string} value New input value
5771 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputChange = function () {
5772 if ( this.lookupInputFocused
) {
5773 this.populateLookupMenu();
5778 * Handle the lookup menu being shown/hidden.
5781 * @param {boolean} visible Whether the lookup menu is now visible.
5783 OO
.ui
.mixin
.LookupElement
.prototype.onLookupMenuToggle = function ( visible
) {
5785 // When the menu is hidden, abort any active request and clear the menu.
5786 // This has to be done here in addition to closeLookupMenu(), because
5787 // MenuSelectWidget will close itself when the user presses Esc.
5788 this.abortLookupRequest();
5789 this.lookupMenu
.clearItems();
5794 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5797 * @param {OO.ui.MenuOptionWidget} item Selected item
5799 OO
.ui
.mixin
.LookupElement
.prototype.onLookupMenuItemChoose = function ( item
) {
5800 this.setValue( item
.getData() );
5807 * @return {OO.ui.TextInputMenuSelectWidget}
5809 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenu = function () {
5810 return this.lookupMenu
;
5814 * Disable or re-enable lookups.
5816 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
5818 * @param {boolean} disabled Disable lookups
5820 OO
.ui
.mixin
.LookupElement
.prototype.setLookupsDisabled = function ( disabled
) {
5821 this.lookupsDisabled
= !!disabled
;
5825 * Open the menu. If there are no entries in the menu, this does nothing.
5830 OO
.ui
.mixin
.LookupElement
.prototype.openLookupMenu = function () {
5831 if ( !this.lookupMenu
.isEmpty() ) {
5832 this.lookupMenu
.toggle( true );
5838 * Close the menu, empty it, and abort any pending request.
5843 OO
.ui
.mixin
.LookupElement
.prototype.closeLookupMenu = function () {
5844 this.lookupMenu
.toggle( false );
5845 this.abortLookupRequest();
5846 this.lookupMenu
.clearItems();
5851 * Request menu items based on the input's current value, and when they arrive,
5852 * populate the menu with these items and show the menu.
5854 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
5859 OO
.ui
.mixin
.LookupElement
.prototype.populateLookupMenu = function () {
5861 value
= this.getValue();
5863 if ( this.lookupsDisabled
) {
5867 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
5868 if ( !this.allowSuggestionsWhenEmpty
&& value
=== '' ) {
5869 this.closeLookupMenu();
5870 // Skip population if there is already a request pending for the current value
5871 } else if ( value
!== this.lookupQuery
) {
5872 this.getLookupMenuItems()
5873 .done( function ( items
) {
5874 widget
.lookupMenu
.clearItems();
5875 if ( items
.length
) {
5879 widget
.initializeLookupMenuSelection();
5881 widget
.lookupMenu
.toggle( false );
5884 .fail( function () {
5885 widget
.lookupMenu
.clearItems();
5893 * Highlight the first selectable item in the menu.
5898 OO
.ui
.mixin
.LookupElement
.prototype.initializeLookupMenuSelection = function () {
5899 if ( !this.lookupMenu
.getSelectedItem() ) {
5900 this.lookupMenu
.highlightItem( this.lookupMenu
.getFirstSelectableItem() );
5905 * Get lookup menu items for the current query.
5908 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
5909 * the done event. If the request was aborted to make way for a subsequent request, this promise
5910 * will not be rejected: it will remain pending forever.
5912 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenuItems = function () {
5914 value
= this.getValue(),
5915 deferred
= $.Deferred(),
5918 this.abortLookupRequest();
5919 if ( Object
.prototype.hasOwnProperty
.call( this.lookupCache
, value
) ) {
5920 deferred
.resolve( this.getLookupMenuOptionsFromData( this.lookupCache
[ value
] ) );
5923 this.lookupQuery
= value
;
5924 ourRequest
= this.lookupRequest
= this.getLookupRequest();
5926 .always( function () {
5927 // We need to pop pending even if this is an old request, otherwise
5928 // the widget will remain pending forever.
5929 // TODO: this assumes that an aborted request will fail or succeed soon after
5930 // being aborted, or at least eventually. It would be nice if we could popPending()
5931 // at abort time, but only if we knew that we hadn't already called popPending()
5932 // for that request.
5933 widget
.popPending();
5935 .done( function ( response
) {
5936 // If this is an old request (and aborting it somehow caused it to still succeed),
5937 // ignore its success completely
5938 if ( ourRequest
=== widget
.lookupRequest
) {
5939 widget
.lookupQuery
= null;
5940 widget
.lookupRequest
= null;
5941 widget
.lookupCache
[ value
] = widget
.getLookupCacheDataFromResponse( response
);
5942 deferred
.resolve( widget
.getLookupMenuOptionsFromData( widget
.lookupCache
[ value
] ) );
5945 .fail( function () {
5946 // If this is an old request (or a request failing because it's being aborted),
5947 // ignore its failure completely
5948 if ( ourRequest
=== widget
.lookupRequest
) {
5949 widget
.lookupQuery
= null;
5950 widget
.lookupRequest
= null;
5955 return deferred
.promise();
5959 * Abort the currently pending lookup request, if any.
5963 OO
.ui
.mixin
.LookupElement
.prototype.abortLookupRequest = function () {
5964 var oldRequest
= this.lookupRequest
;
5966 // First unset this.lookupRequest to the fail handler will notice
5967 // that the request is no longer current
5968 this.lookupRequest
= null;
5969 this.lookupQuery
= null;
5975 * Get a new request object of the current lookup query value.
5979 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
5981 OO
.ui
.mixin
.LookupElement
.prototype.getLookupRequest = function () {
5982 // Stub, implemented in subclass
5987 * Pre-process data returned by the request from #getLookupRequest.
5989 * The return value of this function will be cached, and any further queries for the given value
5990 * will use the cache rather than doing API requests.
5994 * @param {Mixed} response Response from server
5995 * @return {Mixed} Cached result data
5997 OO
.ui
.mixin
.LookupElement
.prototype.getLookupCacheDataFromResponse = function () {
5998 // Stub, implemented in subclass
6003 * Get a list of menu option widgets from the (possibly cached) data returned by
6004 * #getLookupCacheDataFromResponse.
6008 * @param {Mixed} data Cached result data, usually an array
6009 * @return {OO.ui.MenuOptionWidget[]} Menu items
6011 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenuOptionsFromData = function () {
6012 // Stub, implemented in subclass
6017 * Set the read-only state of the widget.
6019 * This will also disable/enable the lookups functionality.
6021 * @param {boolean} readOnly Make input read-only
6024 OO
.ui
.mixin
.LookupElement
.prototype.setReadOnly = function ( readOnly
) {
6026 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
6027 OO
.ui
.TextInputWidget
.prototype.setReadOnly
.call( this, readOnly
);
6029 this.setLookupsDisabled( readOnly
);
6030 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
6031 if ( readOnly
&& this.lookupMenu
) {
6032 this.closeLookupMenu();
6039 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
6040 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
6041 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
6042 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
6048 * @param {Object} [config] Configuration options
6049 * @cfg {Object} [popup] Configuration to pass to popup
6050 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
6052 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
6053 // Configuration initialization
6054 config
= config
|| {};
6057 this.popup
= new OO
.ui
.PopupWidget( $.extend(
6058 { autoClose
: true },
6060 { $autoCloseIgnore
: this.$element
}
6069 * @return {OO.ui.PopupWidget} Popup widget
6071 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
6076 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
6077 * additional functionality to an element created by another class. The class provides
6078 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
6079 * which are used to customize the look and feel of a widget to better describe its
6080 * importance and functionality.
6082 * The library currently contains the following styling flags for general use:
6084 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
6085 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
6086 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
6088 * The flags affect the appearance of the buttons:
6091 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
6092 * var button1 = new OO.ui.ButtonWidget( {
6093 * label: 'Constructive',
6094 * flags: 'constructive'
6096 * var button2 = new OO.ui.ButtonWidget( {
6097 * label: 'Destructive',
6098 * flags: 'destructive'
6100 * var button3 = new OO.ui.ButtonWidget( {
6101 * label: 'Progressive',
6102 * flags: 'progressive'
6104 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
6106 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
6107 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6109 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6115 * @param {Object} [config] Configuration options
6116 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
6117 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
6118 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6119 * @cfg {jQuery} [$flagged] The flagged element. By default,
6120 * the flagged functionality is applied to the element created by the class ($element).
6121 * If a different element is specified, the flagged functionality will be applied to it instead.
6123 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
6124 // Configuration initialization
6125 config
= config
|| {};
6129 this.$flagged
= null;
6132 this.setFlags( config
.flags
);
6133 this.setFlaggedElement( config
.$flagged
|| this.$element
);
6140 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
6141 * parameter contains the name of each modified flag and indicates whether it was
6144 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
6145 * that the flag was added, `false` that the flag was removed.
6151 * Set the flagged element.
6153 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
6154 * If an element is already set, the method will remove the mixin’s effect on that element.
6156 * @param {jQuery} $flagged Element that should be flagged
6158 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
6159 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
6160 return 'oo-ui-flaggedElement-' + flag
;
6163 if ( this.$flagged
) {
6164 this.$flagged
.removeClass( classNames
);
6167 this.$flagged
= $flagged
.addClass( classNames
);
6171 * Check if the specified flag is set.
6173 * @param {string} flag Name of flag
6174 * @return {boolean} The flag is set
6176 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
6177 return flag
in this.flags
;
6181 * Get the names of all flags set.
6183 * @return {string[]} Flag names
6185 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
6186 return Object
.keys( this.flags
);
6195 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
6196 var flag
, className
,
6199 classPrefix
= 'oo-ui-flaggedElement-';
6201 for ( flag
in this.flags
) {
6202 className
= classPrefix
+ flag
;
6203 changes
[ flag
] = false;
6204 delete this.flags
[ flag
];
6205 remove
.push( className
);
6208 if ( this.$flagged
) {
6209 this.$flagged
.removeClass( remove
.join( ' ' ) );
6212 this.updateThemeClasses();
6213 this.emit( 'flag', changes
);
6219 * Add one or more flags.
6221 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6222 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6223 * be added (`true`) or removed (`false`).
6227 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
6228 var i
, len
, flag
, className
,
6232 classPrefix
= 'oo-ui-flaggedElement-';
6234 if ( typeof flags
=== 'string' ) {
6235 className
= classPrefix
+ flags
;
6237 if ( !this.flags
[ flags
] ) {
6238 this.flags
[ flags
] = true;
6239 add
.push( className
);
6241 } else if ( Array
.isArray( flags
) ) {
6242 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
6244 className
= classPrefix
+ flag
;
6246 if ( !this.flags
[ flag
] ) {
6247 changes
[ flag
] = true;
6248 this.flags
[ flag
] = true;
6249 add
.push( className
);
6252 } else if ( OO
.isPlainObject( flags
) ) {
6253 for ( flag
in flags
) {
6254 className
= classPrefix
+ flag
;
6255 if ( flags
[ flag
] ) {
6257 if ( !this.flags
[ flag
] ) {
6258 changes
[ flag
] = true;
6259 this.flags
[ flag
] = true;
6260 add
.push( className
);
6264 if ( this.flags
[ flag
] ) {
6265 changes
[ flag
] = false;
6266 delete this.flags
[ flag
];
6267 remove
.push( className
);
6273 if ( this.$flagged
) {
6275 .addClass( add
.join( ' ' ) )
6276 .removeClass( remove
.join( ' ' ) );
6279 this.updateThemeClasses();
6280 this.emit( 'flag', changes
);
6286 * TitledElement is mixed into other classes to provide a `title` attribute.
6287 * Titles are rendered by the browser and are made visible when the user moves
6288 * the mouse over the element. Titles are not visible on touch devices.
6291 * // TitledElement provides a 'title' attribute to the
6292 * // ButtonWidget class
6293 * var button = new OO.ui.ButtonWidget( {
6294 * label: 'Button with Title',
6295 * title: 'I am a button'
6297 * $( 'body' ).append( button.$element );
6303 * @param {Object} [config] Configuration options
6304 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6305 * If this config is omitted, the title functionality is applied to $element, the
6306 * element created by the class.
6307 * @cfg {string|Function} [title] The title text or a function that returns text. If
6308 * this config is omitted, the value of the {@link #static-title static title} property is used.
6310 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
6311 // Configuration initialization
6312 config
= config
|| {};
6315 this.$titled
= null;
6319 this.setTitle( config
.title
|| this.constructor.static.title
);
6320 this.setTitledElement( config
.$titled
|| this.$element
);
6325 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
6327 /* Static Properties */
6330 * The title text, a function that returns text, or `null` for no title. The value of the static property
6331 * is overridden if the #title config option is used.
6335 * @property {string|Function|null}
6337 OO
.ui
.mixin
.TitledElement
.static.title
= null;
6342 * Set the titled element.
6344 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6345 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6347 * @param {jQuery} $titled Element that should use the 'titled' functionality
6349 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
6350 if ( this.$titled
) {
6351 this.$titled
.removeAttr( 'title' );
6354 this.$titled
= $titled
;
6356 this.$titled
.attr( 'title', this.title
);
6363 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6366 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
6367 title
= typeof title
=== 'string' ? OO
.ui
.resolveMsg( title
) : null;
6369 if ( this.title
!== title
) {
6370 if ( this.$titled
) {
6371 if ( title
!== null ) {
6372 this.$titled
.attr( 'title', title
);
6374 this.$titled
.removeAttr( 'title' );
6386 * @return {string} Title string
6388 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
6393 * Element that can be automatically clipped to visible boundaries.
6395 * Whenever the element's natural height changes, you have to call
6396 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
6397 * clipping correctly.
6403 * @param {Object} [config] Configuration options
6404 * @cfg {jQuery} [$clippable] Nodes to clip, assigned to #$clippable, omit to use #$element
6406 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
6407 // Configuration initialization
6408 config
= config
|| {};
6411 this.$clippable
= null;
6412 this.clipping
= false;
6413 this.clippedHorizontally
= false;
6414 this.clippedVertically
= false;
6415 this.$clippableContainer
= null;
6416 this.$clippableScroller
= null;
6417 this.$clippableWindow
= null;
6418 this.idealWidth
= null;
6419 this.idealHeight
= null;
6420 this.onClippableContainerScrollHandler
= this.clip
.bind( this );
6421 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
6424 this.setClippableElement( config
.$clippable
|| this.$element
);
6430 * Set clippable element.
6432 * If an element is already set, it will be cleaned up before setting up the new element.
6434 * @param {jQuery} $clippable Element to make clippable
6436 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
6437 if ( this.$clippable
) {
6438 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
6439 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6440 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6443 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
6450 * Do not turn clipping on until after the element is attached to the DOM and visible.
6452 * @param {boolean} [clipping] Enable clipping, omit to toggle
6455 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
6456 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
6458 if ( this.clipping
!== clipping
) {
6459 this.clipping
= clipping
;
6461 this.$clippableContainer
= $( this.getClosestScrollableElementContainer() );
6462 // If the clippable container is the root, we have to listen to scroll events and check
6463 // jQuery.scrollTop on the window because of browser inconsistencies
6464 this.$clippableScroller
= this.$clippableContainer
.is( 'html, body' ) ?
6465 $( OO
.ui
.Element
.static.getWindow( this.$clippableContainer
) ) :
6466 this.$clippableContainer
;
6467 this.$clippableScroller
.on( 'scroll', this.onClippableContainerScrollHandler
);
6468 this.$clippableWindow
= $( this.getElementWindow() )
6469 .on( 'resize', this.onClippableWindowResizeHandler
);
6470 // Initial clip after visible
6473 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6474 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6476 this.$clippableContainer
= null;
6477 this.$clippableScroller
.off( 'scroll', this.onClippableContainerScrollHandler
);
6478 this.$clippableScroller
= null;
6479 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
6480 this.$clippableWindow
= null;
6488 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6490 * @return {boolean} Element will be clipped to the visible area
6492 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
6493 return this.clipping
;
6497 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6499 * @return {boolean} Part of the element is being clipped
6501 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
6502 return this.clippedHorizontally
|| this.clippedVertically
;
6506 * Check if the right of the element is being clipped by the nearest scrollable container.
6508 * @return {boolean} Part of the element is being clipped
6510 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
6511 return this.clippedHorizontally
;
6515 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6517 * @return {boolean} Part of the element is being clipped
6519 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
6520 return this.clippedVertically
;
6524 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6526 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6527 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6529 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
6530 this.idealWidth
= width
;
6531 this.idealHeight
= height
;
6533 if ( !this.clipping
) {
6534 // Update dimensions
6535 this.$clippable
.css( { width
: width
, height
: height
} );
6537 // While clipping, idealWidth and idealHeight are not considered
6541 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6542 * the element's natural height changes.
6544 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6545 * overlapped by, the visible area of the nearest scrollable container.
6549 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
6550 if ( !this.clipping
) {
6551 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
6555 var buffer
= 7, // Chosen by fair dice roll
6556 cOffset
= this.$clippable
.offset(),
6557 $container
= this.$clippableContainer
.is( 'html, body' ) ?
6558 this.$clippableWindow
: this.$clippableContainer
,
6559 ccOffset
= $container
.offset() || { top
: 0, left
: 0 },
6560 ccHeight
= $container
.innerHeight() - buffer
,
6561 ccWidth
= $container
.innerWidth() - buffer
,
6562 cWidth
= this.$clippable
.outerWidth() + buffer
,
6563 scrollerIsWindow
= this.$clippableScroller
[0] === this.$clippableWindow
[0],
6564 scrollTop
= scrollerIsWindow
? this.$clippableScroller
.scrollTop() : 0,
6565 scrollLeft
= scrollerIsWindow
? this.$clippableScroller
.scrollLeft() : 0,
6566 desiredWidth
= cOffset
.left
< 0 ?
6567 cWidth
+ cOffset
.left
:
6568 ( ccOffset
.left
+ scrollLeft
+ ccWidth
) - cOffset
.left
,
6569 desiredHeight
= ( ccOffset
.top
+ scrollTop
+ ccHeight
) - cOffset
.top
,
6570 naturalWidth
= this.$clippable
.prop( 'scrollWidth' ),
6571 naturalHeight
= this.$clippable
.prop( 'scrollHeight' ),
6572 clipWidth
= desiredWidth
< naturalWidth
,
6573 clipHeight
= desiredHeight
< naturalHeight
;
6576 this.$clippable
.css( { overflowX
: 'scroll', width
: desiredWidth
} );
6578 this.$clippable
.css( { width
: this.idealWidth
|| '', overflowX
: '' } );
6581 this.$clippable
.css( { overflowY
: 'scroll', height
: desiredHeight
} );
6583 this.$clippable
.css( { height
: this.idealHeight
|| '', overflowY
: '' } );
6586 // If we stopped clipping in at least one of the dimensions
6587 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
6588 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6591 this.clippedHorizontally
= clipWidth
;
6592 this.clippedVertically
= clipHeight
;
6598 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
6599 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
6600 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
6601 * which creates the tools on demand.
6603 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
6604 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
6605 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
6607 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
6608 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
6612 * @extends OO.ui.Widget
6613 * @mixins OO.ui.mixin.IconElement
6614 * @mixins OO.ui.mixin.FlaggedElement
6615 * @mixins OO.ui.mixin.TabIndexedElement
6618 * @param {OO.ui.ToolGroup} toolGroup
6619 * @param {Object} [config] Configuration options
6620 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
6621 * the {@link #static-title static title} property is used.
6623 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
6624 * 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
6625 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
6627 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
6628 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
6629 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
6631 OO
.ui
.Tool
= function OoUiTool( toolGroup
, config
) {
6632 // Allow passing positional parameters inside the config object
6633 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
6635 toolGroup
= config
.toolGroup
;
6638 // Configuration initialization
6639 config
= config
|| {};
6641 // Parent constructor
6642 OO
.ui
.Tool
.parent
.call( this, config
);
6645 this.toolGroup
= toolGroup
;
6646 this.toolbar
= this.toolGroup
.getToolbar();
6647 this.active
= false;
6648 this.$title
= $( '<span>' );
6649 this.$accel
= $( '<span>' );
6650 this.$link
= $( '<a>' );
6653 // Mixin constructors
6654 OO
.ui
.mixin
.IconElement
.call( this, config
);
6655 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
6656 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$link
} ) );
6659 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
6662 this.$title
.addClass( 'oo-ui-tool-title' );
6664 .addClass( 'oo-ui-tool-accel' )
6666 // This may need to be changed if the key names are ever localized,
6667 // but for now they are essentially written in English
6672 .addClass( 'oo-ui-tool-link' )
6673 .append( this.$icon
, this.$title
, this.$accel
)
6674 .attr( 'role', 'button' );
6676 .data( 'oo-ui-tool', this )
6678 'oo-ui-tool ' + 'oo-ui-tool-name-' +
6679 this.constructor.static.name
.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
6681 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel
)
6682 .append( this.$link
);
6683 this.setTitle( config
.title
|| this.constructor.static.title
);
6688 OO
.inheritClass( OO
.ui
.Tool
, OO
.ui
.Widget
);
6689 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.IconElement
);
6690 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.FlaggedElement
);
6691 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.TabIndexedElement
);
6693 /* Static Properties */
6699 OO
.ui
.Tool
.static.tagName
= 'span';
6702 * Symbolic name of tool.
6704 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
6705 * also be used when adding tools to toolgroups.
6710 * @property {string}
6712 OO
.ui
.Tool
.static.name
= '';
6715 * Symbolic name of the group.
6717 * The group name is used to associate tools with each other so that they can be selected later by
6718 * a {@link OO.ui.ToolGroup toolgroup}.
6723 * @property {string}
6725 OO
.ui
.Tool
.static.group
= '';
6728 * 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.
6733 * @property {string|Function}
6735 OO
.ui
.Tool
.static.title
= '';
6738 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
6739 * Normally only the icon is displayed, or only the label if no icon is given.
6743 * @property {boolean}
6745 OO
.ui
.Tool
.static.displayBothIconAndLabel
= false;
6748 * Add tool to catch-all groups automatically.
6750 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
6751 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
6755 * @property {boolean}
6757 OO
.ui
.Tool
.static.autoAddToCatchall
= true;
6760 * Add tool to named groups automatically.
6762 * By default, tools that are configured with a static ‘group’ property are added
6763 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
6764 * toolgroups include tools by group name).
6767 * @property {boolean}
6770 OO
.ui
.Tool
.static.autoAddToGroup
= true;
6773 * Check if this tool is compatible with given data.
6775 * This is a stub that can be overriden to provide support for filtering tools based on an
6776 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
6777 * must also call this method so that the compatibility check can be performed.
6781 * @param {Mixed} data Data to check
6782 * @return {boolean} Tool can be used with data
6784 OO
.ui
.Tool
.static.isCompatibleWith = function () {
6791 * Handle the toolbar state being updated.
6793 * This is an abstract method that must be overridden in a concrete subclass.
6798 OO
.ui
.Tool
.prototype.onUpdateState = function () {
6800 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
6805 * Handle the tool being selected.
6807 * This is an abstract method that must be overridden in a concrete subclass.
6812 OO
.ui
.Tool
.prototype.onSelect = function () {
6814 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
6819 * Check if the tool is active.
6821 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
6822 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
6824 * @return {boolean} Tool is active
6826 OO
.ui
.Tool
.prototype.isActive = function () {
6831 * Make the tool appear active or inactive.
6833 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
6834 * appear pressed or not.
6836 * @param {boolean} state Make tool appear active
6838 OO
.ui
.Tool
.prototype.setActive = function ( state
) {
6839 this.active
= !!state
;
6840 if ( this.active
) {
6841 this.$element
.addClass( 'oo-ui-tool-active' );
6843 this.$element
.removeClass( 'oo-ui-tool-active' );
6848 * Set the tool #title.
6850 * @param {string|Function} title Title text or a function that returns text
6853 OO
.ui
.Tool
.prototype.setTitle = function ( title
) {
6854 this.title
= OO
.ui
.resolveMsg( title
);
6860 * Get the tool #title.
6862 * @return {string} Title text
6864 OO
.ui
.Tool
.prototype.getTitle = function () {
6869 * Get the tool's symbolic name.
6871 * @return {string} Symbolic name of tool
6873 OO
.ui
.Tool
.prototype.getName = function () {
6874 return this.constructor.static.name
;
6880 OO
.ui
.Tool
.prototype.updateTitle = function () {
6881 var titleTooltips
= this.toolGroup
.constructor.static.titleTooltips
,
6882 accelTooltips
= this.toolGroup
.constructor.static.accelTooltips
,
6883 accel
= this.toolbar
.getToolAccelerator( this.constructor.static.name
),
6886 this.$title
.text( this.title
);
6887 this.$accel
.text( accel
);
6889 if ( titleTooltips
&& typeof this.title
=== 'string' && this.title
.length
) {
6890 tooltipParts
.push( this.title
);
6892 if ( accelTooltips
&& typeof accel
=== 'string' && accel
.length
) {
6893 tooltipParts
.push( accel
);
6895 if ( tooltipParts
.length
) {
6896 this.$link
.attr( 'title', tooltipParts
.join( ' ' ) );
6898 this.$link
.removeAttr( 'title' );
6905 * Destroying the tool removes all event handlers and the tool’s DOM elements.
6906 * Call this method whenever you are done using a tool.
6908 OO
.ui
.Tool
.prototype.destroy = function () {
6909 this.toolbar
.disconnect( this );
6910 this.$element
.remove();
6914 * Toolbars are complex interface components that permit users to easily access a variety
6915 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
6916 * part of the toolbar, but not configured as tools.
6918 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
6919 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
6920 * picture’), and an icon.
6922 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
6923 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
6924 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
6925 * any order, but each can only appear once in the toolbar.
6927 * The following is an example of a basic toolbar.
6930 * // Example of a toolbar
6931 * // Create the toolbar
6932 * var toolFactory = new OO.ui.ToolFactory();
6933 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
6934 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
6936 * // We will be placing status text in this element when tools are used
6937 * var $area = $( '<p>' ).text( 'Toolbar example' );
6939 * // Define the tools that we're going to place in our toolbar
6941 * // Create a class inheriting from OO.ui.Tool
6942 * function PictureTool() {
6943 * PictureTool.parent.apply( this, arguments );
6945 * OO.inheritClass( PictureTool, OO.ui.Tool );
6946 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
6947 * // of 'icon' and 'title' (displayed icon and text).
6948 * PictureTool.static.name = 'picture';
6949 * PictureTool.static.icon = 'picture';
6950 * PictureTool.static.title = 'Insert picture';
6951 * // Defines the action that will happen when this tool is selected (clicked).
6952 * PictureTool.prototype.onSelect = function () {
6953 * $area.text( 'Picture tool clicked!' );
6954 * // Never display this tool as "active" (selected).
6955 * this.setActive( false );
6957 * // Make this tool available in our toolFactory and thus our toolbar
6958 * toolFactory.register( PictureTool );
6960 * // Register two more tools, nothing interesting here
6961 * function SettingsTool() {
6962 * SettingsTool.parent.apply( this, arguments );
6964 * OO.inheritClass( SettingsTool, OO.ui.Tool );
6965 * SettingsTool.static.name = 'settings';
6966 * SettingsTool.static.icon = 'settings';
6967 * SettingsTool.static.title = 'Change settings';
6968 * SettingsTool.prototype.onSelect = function () {
6969 * $area.text( 'Settings tool clicked!' );
6970 * this.setActive( false );
6972 * toolFactory.register( SettingsTool );
6974 * // Register two more tools, nothing interesting here
6975 * function StuffTool() {
6976 * StuffTool.parent.apply( this, arguments );
6978 * OO.inheritClass( StuffTool, OO.ui.Tool );
6979 * StuffTool.static.name = 'stuff';
6980 * StuffTool.static.icon = 'ellipsis';
6981 * StuffTool.static.title = 'More stuff';
6982 * StuffTool.prototype.onSelect = function () {
6983 * $area.text( 'More stuff tool clicked!' );
6984 * this.setActive( false );
6986 * toolFactory.register( StuffTool );
6988 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
6989 * // little popup window (a PopupWidget).
6990 * function HelpTool( toolGroup, config ) {
6991 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
6996 * this.popup.$body.append( '<p>I am helpful!</p>' );
6998 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
6999 * HelpTool.static.name = 'help';
7000 * HelpTool.static.icon = 'help';
7001 * HelpTool.static.title = 'Help';
7002 * toolFactory.register( HelpTool );
7004 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7005 * // used once (but not all defined tools must be used).
7008 * // 'bar' tool groups display tools' icons only, side-by-side.
7010 * include: [ 'picture', 'help' ]
7013 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7015 * indicator: 'down',
7017 * include: [ 'settings', 'stuff' ]
7019 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7020 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7021 * // since it's more complicated to use. (See the next example snippet on this page.)
7024 * // Create some UI around the toolbar and place it in the document
7025 * var frame = new OO.ui.PanelLayout( {
7029 * var contentFrame = new OO.ui.PanelLayout( {
7033 * frame.$element.append(
7035 * contentFrame.$element.append( $area )
7037 * $( 'body' ).append( frame.$element );
7039 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7041 * toolbar.initialize();
7043 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7044 * 'updateState' event.
7047 * // Create the toolbar
7048 * var toolFactory = new OO.ui.ToolFactory();
7049 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7050 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7052 * // We will be placing status text in this element when tools are used
7053 * var $area = $( '<p>' ).text( 'Toolbar example' );
7055 * // Define the tools that we're going to place in our toolbar
7057 * // Create a class inheriting from OO.ui.Tool
7058 * function PictureTool() {
7059 * PictureTool.parent.apply( this, arguments );
7061 * OO.inheritClass( PictureTool, OO.ui.Tool );
7062 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7063 * // of 'icon' and 'title' (displayed icon and text).
7064 * PictureTool.static.name = 'picture';
7065 * PictureTool.static.icon = 'picture';
7066 * PictureTool.static.title = 'Insert picture';
7067 * // Defines the action that will happen when this tool is selected (clicked).
7068 * PictureTool.prototype.onSelect = function () {
7069 * $area.text( 'Picture tool clicked!' );
7070 * // Never display this tool as "active" (selected).
7071 * this.setActive( false );
7073 * // The toolbar can be synchronized with the state of some external stuff, like a text
7074 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
7075 * // when the text cursor was inside bolded text). Here we simply disable this feature.
7076 * PictureTool.prototype.onUpdateState = function () {
7078 * // Make this tool available in our toolFactory and thus our toolbar
7079 * toolFactory.register( PictureTool );
7081 * // Register two more tools, nothing interesting here
7082 * function SettingsTool() {
7083 * SettingsTool.parent.apply( this, arguments );
7084 * this.reallyActive = false;
7086 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7087 * SettingsTool.static.name = 'settings';
7088 * SettingsTool.static.icon = 'settings';
7089 * SettingsTool.static.title = 'Change settings';
7090 * SettingsTool.prototype.onSelect = function () {
7091 * $area.text( 'Settings tool clicked!' );
7092 * // Toggle the active state on each click
7093 * this.reallyActive = !this.reallyActive;
7094 * this.setActive( this.reallyActive );
7095 * // To update the menu label
7096 * this.toolbar.emit( 'updateState' );
7098 * SettingsTool.prototype.onUpdateState = function () {
7100 * toolFactory.register( SettingsTool );
7102 * // Register two more tools, nothing interesting here
7103 * function StuffTool() {
7104 * StuffTool.parent.apply( this, arguments );
7105 * this.reallyActive = false;
7107 * OO.inheritClass( StuffTool, OO.ui.Tool );
7108 * StuffTool.static.name = 'stuff';
7109 * StuffTool.static.icon = 'ellipsis';
7110 * StuffTool.static.title = 'More stuff';
7111 * StuffTool.prototype.onSelect = function () {
7112 * $area.text( 'More stuff tool clicked!' );
7113 * // Toggle the active state on each click
7114 * this.reallyActive = !this.reallyActive;
7115 * this.setActive( this.reallyActive );
7116 * // To update the menu label
7117 * this.toolbar.emit( 'updateState' );
7119 * StuffTool.prototype.onUpdateState = function () {
7121 * toolFactory.register( StuffTool );
7123 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7124 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7125 * function HelpTool( toolGroup, config ) {
7126 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7131 * this.popup.$body.append( '<p>I am helpful!</p>' );
7133 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7134 * HelpTool.static.name = 'help';
7135 * HelpTool.static.icon = 'help';
7136 * HelpTool.static.title = 'Help';
7137 * toolFactory.register( HelpTool );
7139 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7140 * // used once (but not all defined tools must be used).
7143 * // 'bar' tool groups display tools' icons only, side-by-side.
7145 * include: [ 'picture', 'help' ]
7148 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7149 * // Menu label indicates which items are selected.
7151 * indicator: 'down',
7152 * include: [ 'settings', 'stuff' ]
7156 * // Create some UI around the toolbar and place it in the document
7157 * var frame = new OO.ui.PanelLayout( {
7161 * var contentFrame = new OO.ui.PanelLayout( {
7165 * frame.$element.append(
7167 * contentFrame.$element.append( $area )
7169 * $( 'body' ).append( frame.$element );
7171 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7173 * toolbar.initialize();
7174 * toolbar.emit( 'updateState' );
7177 * @extends OO.ui.Element
7178 * @mixins OO.EventEmitter
7179 * @mixins OO.ui.mixin.GroupElement
7182 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7183 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7184 * @param {Object} [config] Configuration options
7185 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7186 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7188 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7190 OO
.ui
.Toolbar
= function OoUiToolbar( toolFactory
, toolGroupFactory
, config
) {
7191 // Allow passing positional parameters inside the config object
7192 if ( OO
.isPlainObject( toolFactory
) && config
=== undefined ) {
7193 config
= toolFactory
;
7194 toolFactory
= config
.toolFactory
;
7195 toolGroupFactory
= config
.toolGroupFactory
;
7198 // Configuration initialization
7199 config
= config
|| {};
7201 // Parent constructor
7202 OO
.ui
.Toolbar
.parent
.call( this, config
);
7204 // Mixin constructors
7205 OO
.EventEmitter
.call( this );
7206 OO
.ui
.mixin
.GroupElement
.call( this, config
);
7209 this.toolFactory
= toolFactory
;
7210 this.toolGroupFactory
= toolGroupFactory
;
7213 this.$bar
= $( '<div>' );
7214 this.$actions
= $( '<div>' );
7215 this.initialized
= false;
7216 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
7220 .add( this.$bar
).add( this.$group
).add( this.$actions
)
7221 .on( 'mousedown keydown', this.onPointerDown
.bind( this ) );
7224 this.$group
.addClass( 'oo-ui-toolbar-tools' );
7225 if ( config
.actions
) {
7226 this.$bar
.append( this.$actions
.addClass( 'oo-ui-toolbar-actions' ) );
7229 .addClass( 'oo-ui-toolbar-bar' )
7230 .append( this.$group
, '<div style="clear:both"></div>' );
7231 if ( config
.shadow
) {
7232 this.$bar
.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7234 this.$element
.addClass( 'oo-ui-toolbar' ).append( this.$bar
);
7239 OO
.inheritClass( OO
.ui
.Toolbar
, OO
.ui
.Element
);
7240 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.EventEmitter
);
7241 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.ui
.mixin
.GroupElement
);
7246 * Get the tool factory.
7248 * @return {OO.ui.ToolFactory} Tool factory
7250 OO
.ui
.Toolbar
.prototype.getToolFactory = function () {
7251 return this.toolFactory
;
7255 * Get the toolgroup factory.
7257 * @return {OO.Factory} Toolgroup factory
7259 OO
.ui
.Toolbar
.prototype.getToolGroupFactory = function () {
7260 return this.toolGroupFactory
;
7264 * Handles mouse down events.
7267 * @param {jQuery.Event} e Mouse down event
7269 OO
.ui
.Toolbar
.prototype.onPointerDown = function ( e
) {
7270 var $closestWidgetToEvent
= $( e
.target
).closest( '.oo-ui-widget' ),
7271 $closestWidgetToToolbar
= this.$element
.closest( '.oo-ui-widget' );
7272 if ( !$closestWidgetToEvent
.length
|| $closestWidgetToEvent
[ 0 ] === $closestWidgetToToolbar
[ 0 ] ) {
7278 * Handle window resize event.
7281 * @param {jQuery.Event} e Window resize event
7283 OO
.ui
.Toolbar
.prototype.onWindowResize = function () {
7284 this.$element
.toggleClass(
7285 'oo-ui-toolbar-narrow',
7286 this.$bar
.width() <= this.narrowThreshold
7291 * Sets up handles and preloads required information for the toolbar to work.
7292 * This must be called after it is attached to a visible document and before doing anything else.
7294 OO
.ui
.Toolbar
.prototype.initialize = function () {
7295 this.initialized
= true;
7296 this.narrowThreshold
= this.$group
.width() + this.$actions
.width();
7297 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
7298 this.onWindowResize();
7302 * Set up the toolbar.
7304 * The toolbar is set up with a list of toolgroup configurations that specify the type of
7305 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
7306 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
7307 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
7309 * @param {Object.<string,Array>} groups List of toolgroup configurations
7310 * @param {Array|string} [groups.include] Tools to include in the toolgroup
7311 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
7312 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
7313 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
7315 OO
.ui
.Toolbar
.prototype.setup = function ( groups
) {
7316 var i
, len
, type
, group
,
7318 defaultType
= 'bar';
7320 // Cleanup previous groups
7323 // Build out new groups
7324 for ( i
= 0, len
= groups
.length
; i
< len
; i
++ ) {
7325 group
= groups
[ i
];
7326 if ( group
.include
=== '*' ) {
7327 // Apply defaults to catch-all groups
7328 if ( group
.type
=== undefined ) {
7329 group
.type
= 'list';
7331 if ( group
.label
=== undefined ) {
7332 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
7335 // Check type has been registered
7336 type
= this.getToolGroupFactory().lookup( group
.type
) ? group
.type
: defaultType
;
7338 this.getToolGroupFactory().create( type
, this, group
)
7341 this.addItems( items
);
7345 * Remove all tools and toolgroups from the toolbar.
7347 OO
.ui
.Toolbar
.prototype.reset = function () {
7352 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7353 this.items
[ i
].destroy();
7359 * Destroy the toolbar.
7361 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
7362 * this method whenever you are done using a toolbar.
7364 OO
.ui
.Toolbar
.prototype.destroy = function () {
7365 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
7367 this.$element
.remove();
7371 * Check if the tool is available.
7373 * Available tools are ones that have not yet been added to the toolbar.
7375 * @param {string} name Symbolic name of tool
7376 * @return {boolean} Tool is available
7378 OO
.ui
.Toolbar
.prototype.isToolAvailable = function ( name
) {
7379 return !this.tools
[ name
];
7383 * Prevent tool from being used again.
7385 * @param {OO.ui.Tool} tool Tool to reserve
7387 OO
.ui
.Toolbar
.prototype.reserveTool = function ( tool
) {
7388 this.tools
[ tool
.getName() ] = tool
;
7392 * Allow tool to be used again.
7394 * @param {OO.ui.Tool} tool Tool to release
7396 OO
.ui
.Toolbar
.prototype.releaseTool = function ( tool
) {
7397 delete this.tools
[ tool
.getName() ];
7401 * Get accelerator label for tool.
7403 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
7404 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
7405 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
7407 * @param {string} name Symbolic name of tool
7408 * @return {string|undefined} Tool accelerator label if available
7410 OO
.ui
.Toolbar
.prototype.getToolAccelerator = function () {
7415 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
7416 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
7417 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
7418 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
7420 * Toolgroups can contain individual tools, groups of tools, or all available tools:
7422 * To include an individual tool (or array of individual tools), specify tools by symbolic name:
7424 * include: [ 'tool-name' ] or [ { name: 'tool-name' }]
7426 * 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.)
7428 * include: [ { group: 'group-name' } ]
7430 * To include all tools that are not yet assigned to a toolgroup, use the catch-all selector, an asterisk (*):
7434 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
7435 * please see the [OOjs UI documentation on MediaWiki][1].
7437 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7441 * @extends OO.ui.Widget
7442 * @mixins OO.ui.mixin.GroupElement
7445 * @param {OO.ui.Toolbar} toolbar
7446 * @param {Object} [config] Configuration options
7447 * @cfg {Array|string} [include=[]] List of tools to include in the toolgroup.
7448 * @cfg {Array|string} [exclude=[]] List of tools to exclude from the toolgroup.
7449 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning of the toolgroup.
7450 * @cfg {Array|string} [demote=[]] List of tools to demote to the end of the toolgroup.
7451 * This setting is particularly useful when tools have been added to the toolgroup
7452 * en masse (e.g., via the catch-all selector).
7454 OO
.ui
.ToolGroup
= function OoUiToolGroup( toolbar
, config
) {
7455 // Allow passing positional parameters inside the config object
7456 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
7458 toolbar
= config
.toolbar
;
7461 // Configuration initialization
7462 config
= config
|| {};
7464 // Parent constructor
7465 OO
.ui
.ToolGroup
.parent
.call( this, config
);
7467 // Mixin constructors
7468 OO
.ui
.mixin
.GroupElement
.call( this, config
);
7471 this.toolbar
= toolbar
;
7473 this.pressed
= null;
7474 this.autoDisabled
= false;
7475 this.include
= config
.include
|| [];
7476 this.exclude
= config
.exclude
|| [];
7477 this.promote
= config
.promote
|| [];
7478 this.demote
= config
.demote
|| [];
7479 this.onCapturedMouseKeyUpHandler
= this.onCapturedMouseKeyUp
.bind( this );
7483 mousedown
: this.onMouseKeyDown
.bind( this ),
7484 mouseup
: this.onMouseKeyUp
.bind( this ),
7485 keydown
: this.onMouseKeyDown
.bind( this ),
7486 keyup
: this.onMouseKeyUp
.bind( this ),
7487 focus
: this.onMouseOverFocus
.bind( this ),
7488 blur
: this.onMouseOutBlur
.bind( this ),
7489 mouseover
: this.onMouseOverFocus
.bind( this ),
7490 mouseout
: this.onMouseOutBlur
.bind( this )
7492 this.toolbar
.getToolFactory().connect( this, { register
: 'onToolFactoryRegister' } );
7493 this.aggregate( { disable
: 'itemDisable' } );
7494 this.connect( this, { itemDisable
: 'updateDisabled' } );
7497 this.$group
.addClass( 'oo-ui-toolGroup-tools' );
7499 .addClass( 'oo-ui-toolGroup' )
7500 .append( this.$group
);
7506 OO
.inheritClass( OO
.ui
.ToolGroup
, OO
.ui
.Widget
);
7507 OO
.mixinClass( OO
.ui
.ToolGroup
, OO
.ui
.mixin
.GroupElement
);
7515 /* Static Properties */
7518 * Show labels in tooltips.
7522 * @property {boolean}
7524 OO
.ui
.ToolGroup
.static.titleTooltips
= false;
7527 * Show acceleration labels in tooltips.
7529 * Note: The OOjs UI library does not include an accelerator system, but does contain
7530 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
7531 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
7532 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
7536 * @property {boolean}
7538 OO
.ui
.ToolGroup
.static.accelTooltips
= false;
7541 * Automatically disable the toolgroup when all tools are disabled
7545 * @property {boolean}
7547 OO
.ui
.ToolGroup
.static.autoDisable
= true;
7554 OO
.ui
.ToolGroup
.prototype.isDisabled = function () {
7555 return this.autoDisabled
|| OO
.ui
.ToolGroup
.parent
.prototype.isDisabled
.apply( this, arguments
);
7561 OO
.ui
.ToolGroup
.prototype.updateDisabled = function () {
7562 var i
, item
, allDisabled
= true;
7564 if ( this.constructor.static.autoDisable
) {
7565 for ( i
= this.items
.length
- 1; i
>= 0; i
-- ) {
7566 item
= this.items
[ i
];
7567 if ( !item
.isDisabled() ) {
7568 allDisabled
= false;
7572 this.autoDisabled
= allDisabled
;
7574 OO
.ui
.ToolGroup
.parent
.prototype.updateDisabled
.apply( this, arguments
);
7578 * Handle mouse down and key down events.
7581 * @param {jQuery.Event} e Mouse down or key down event
7583 OO
.ui
.ToolGroup
.prototype.onMouseKeyDown = function ( e
) {
7585 !this.isDisabled() &&
7586 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
7588 this.pressed
= this.getTargetTool( e
);
7589 if ( this.pressed
) {
7590 this.pressed
.setActive( true );
7591 this.getElementDocument().addEventListener( 'mouseup', this.onCapturedMouseKeyUpHandler
, true );
7592 this.getElementDocument().addEventListener( 'keyup', this.onCapturedMouseKeyUpHandler
, true );
7599 * Handle captured mouse up and key up events.
7602 * @param {Event} e Mouse up or key up event
7604 OO
.ui
.ToolGroup
.prototype.onCapturedMouseKeyUp = function ( e
) {
7605 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseKeyUpHandler
, true );
7606 this.getElementDocument().removeEventListener( 'keyup', this.onCapturedMouseKeyUpHandler
, true );
7607 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
7608 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
7609 this.onMouseKeyUp( e
);
7613 * Handle mouse up and key up events.
7616 * @param {jQuery.Event} e Mouse up or key up event
7618 OO
.ui
.ToolGroup
.prototype.onMouseKeyUp = function ( e
) {
7619 var tool
= this.getTargetTool( e
);
7622 !this.isDisabled() && this.pressed
&& this.pressed
=== tool
&&
7623 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
7625 this.pressed
.onSelect();
7626 this.pressed
= null;
7630 this.pressed
= null;
7634 * Handle mouse over and focus events.
7637 * @param {jQuery.Event} e Mouse over or focus event
7639 OO
.ui
.ToolGroup
.prototype.onMouseOverFocus = function ( e
) {
7640 var tool
= this.getTargetTool( e
);
7642 if ( this.pressed
&& this.pressed
=== tool
) {
7643 this.pressed
.setActive( true );
7648 * Handle mouse out and blur events.
7651 * @param {jQuery.Event} e Mouse out or blur event
7653 OO
.ui
.ToolGroup
.prototype.onMouseOutBlur = function ( e
) {
7654 var tool
= this.getTargetTool( e
);
7656 if ( this.pressed
&& this.pressed
=== tool
) {
7657 this.pressed
.setActive( false );
7662 * Get the closest tool to a jQuery.Event.
7664 * Only tool links are considered, which prevents other elements in the tool such as popups from
7665 * triggering tool group interactions.
7668 * @param {jQuery.Event} e
7669 * @return {OO.ui.Tool|null} Tool, `null` if none was found
7671 OO
.ui
.ToolGroup
.prototype.getTargetTool = function ( e
) {
7673 $item
= $( e
.target
).closest( '.oo-ui-tool-link' );
7675 if ( $item
.length
) {
7676 tool
= $item
.parent().data( 'oo-ui-tool' );
7679 return tool
&& !tool
.isDisabled() ? tool
: null;
7683 * Handle tool registry register events.
7685 * If a tool is registered after the group is created, we must repopulate the list to account for:
7687 * - a tool being added that may be included
7688 * - a tool already included being overridden
7691 * @param {string} name Symbolic name of tool
7693 OO
.ui
.ToolGroup
.prototype.onToolFactoryRegister = function () {
7698 * Get the toolbar that contains the toolgroup.
7700 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
7702 OO
.ui
.ToolGroup
.prototype.getToolbar = function () {
7703 return this.toolbar
;
7707 * Add and remove tools based on configuration.
7709 OO
.ui
.ToolGroup
.prototype.populate = function () {
7710 var i
, len
, name
, tool
,
7711 toolFactory
= this.toolbar
.getToolFactory(),
7715 list
= this.toolbar
.getToolFactory().getTools(
7716 this.include
, this.exclude
, this.promote
, this.demote
7719 // Build a list of needed tools
7720 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
7724 toolFactory
.lookup( name
) &&
7725 // Tool is available or is already in this group
7726 ( this.toolbar
.isToolAvailable( name
) || this.tools
[ name
] )
7728 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
7729 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
7730 this.toolbar
.tools
[ name
] = true;
7731 tool
= this.tools
[ name
];
7733 // Auto-initialize tools on first use
7734 this.tools
[ name
] = tool
= toolFactory
.create( name
, this );
7737 this.toolbar
.reserveTool( tool
);
7739 names
[ name
] = true;
7742 // Remove tools that are no longer needed
7743 for ( name
in this.tools
) {
7744 if ( !names
[ name
] ) {
7745 this.tools
[ name
].destroy();
7746 this.toolbar
.releaseTool( this.tools
[ name
] );
7747 remove
.push( this.tools
[ name
] );
7748 delete this.tools
[ name
];
7751 if ( remove
.length
) {
7752 this.removeItems( remove
);
7754 // Update emptiness state
7756 this.$element
.removeClass( 'oo-ui-toolGroup-empty' );
7758 this.$element
.addClass( 'oo-ui-toolGroup-empty' );
7760 // Re-add tools (moving existing ones to new locations)
7761 this.addItems( add
);
7762 // Disabled state may depend on items
7763 this.updateDisabled();
7767 * Destroy toolgroup.
7769 OO
.ui
.ToolGroup
.prototype.destroy = function () {
7773 this.toolbar
.getToolFactory().disconnect( this );
7774 for ( name
in this.tools
) {
7775 this.toolbar
.releaseTool( this.tools
[ name
] );
7776 this.tools
[ name
].disconnect( this ).destroy();
7777 delete this.tools
[ name
];
7779 this.$element
.remove();
7783 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
7784 * consists of a header that contains the dialog title, a body with the message, and a footer that
7785 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
7786 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
7788 * There are two basic types of message dialogs, confirmation and alert:
7790 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
7791 * more details about the consequences.
7792 * - **alert**: the dialog title describes which event occurred and the message provides more information
7793 * about why the event occurred.
7795 * The MessageDialog class specifies two actions: ‘accept’, the primary
7796 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
7797 * passing along the selected action.
7799 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
7802 * // Example: Creating and opening a message dialog window.
7803 * var messageDialog = new OO.ui.MessageDialog();
7805 * // Create and append a window manager.
7806 * var windowManager = new OO.ui.WindowManager();
7807 * $( 'body' ).append( windowManager.$element );
7808 * windowManager.addWindows( [ messageDialog ] );
7809 * // Open the window.
7810 * windowManager.openWindow( messageDialog, {
7811 * title: 'Basic message dialog',
7812 * message: 'This is the message'
7815 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
7818 * @extends OO.ui.Dialog
7821 * @param {Object} [config] Configuration options
7823 OO
.ui
.MessageDialog
= function OoUiMessageDialog( config
) {
7824 // Parent constructor
7825 OO
.ui
.MessageDialog
.parent
.call( this, config
);
7828 this.verticalActionLayout
= null;
7831 this.$element
.addClass( 'oo-ui-messageDialog' );
7836 OO
.inheritClass( OO
.ui
.MessageDialog
, OO
.ui
.Dialog
);
7838 /* Static Properties */
7840 OO
.ui
.MessageDialog
.static.name
= 'message';
7842 OO
.ui
.MessageDialog
.static.size
= 'small';
7844 OO
.ui
.MessageDialog
.static.verbose
= false;
7849 * The title of a confirmation dialog describes what a progressive action will do. The
7850 * title of an alert dialog describes which event occurred.
7854 * @property {jQuery|string|Function|null}
7856 OO
.ui
.MessageDialog
.static.title
= null;
7859 * The message displayed in the dialog body.
7861 * A confirmation message describes the consequences of a progressive action. An alert
7862 * message describes why an event occurred.
7866 * @property {jQuery|string|Function|null}
7868 OO
.ui
.MessageDialog
.static.message
= null;
7870 OO
.ui
.MessageDialog
.static.actions
= [
7871 { action
: 'accept', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-accept' ), flags
: 'primary' },
7872 { action
: 'reject', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-reject' ), flags
: 'safe' }
7880 OO
.ui
.MessageDialog
.prototype.setManager = function ( manager
) {
7881 OO
.ui
.MessageDialog
.parent
.prototype.setManager
.call( this, manager
);
7884 this.manager
.connect( this, {
7894 OO
.ui
.MessageDialog
.prototype.onActionResize = function ( action
) {
7896 return OO
.ui
.MessageDialog
.parent
.prototype.onActionResize
.call( this, action
);
7900 * Handle window resized events.
7904 OO
.ui
.MessageDialog
.prototype.onResize = function () {
7906 dialog
.fitActions();
7907 // Wait for CSS transition to finish and do it again :(
7908 setTimeout( function () {
7909 dialog
.fitActions();
7914 * Toggle action layout between vertical and horizontal.
7918 * @param {boolean} [value] Layout actions vertically, omit to toggle
7921 OO
.ui
.MessageDialog
.prototype.toggleVerticalActionLayout = function ( value
) {
7922 value
= value
=== undefined ? !this.verticalActionLayout
: !!value
;
7924 if ( value
!== this.verticalActionLayout
) {
7925 this.verticalActionLayout
= value
;
7927 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value
)
7928 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value
);
7937 OO
.ui
.MessageDialog
.prototype.getActionProcess = function ( action
) {
7939 return new OO
.ui
.Process( function () {
7940 this.close( { action
: action
} );
7943 return OO
.ui
.MessageDialog
.parent
.prototype.getActionProcess
.call( this, action
);
7949 * @param {Object} [data] Dialog opening data
7950 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
7951 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
7952 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
7953 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
7956 OO
.ui
.MessageDialog
.prototype.getSetupProcess = function ( data
) {
7960 return OO
.ui
.MessageDialog
.parent
.prototype.getSetupProcess
.call( this, data
)
7961 .next( function () {
7962 this.title
.setLabel(
7963 data
.title
!== undefined ? data
.title
: this.constructor.static.title
7965 this.message
.setLabel(
7966 data
.message
!== undefined ? data
.message
: this.constructor.static.message
7968 this.message
.$element
.toggleClass(
7969 'oo-ui-messageDialog-message-verbose',
7970 data
.verbose
!== undefined ? data
.verbose
: this.constructor.static.verbose
7978 OO
.ui
.MessageDialog
.prototype.getBodyHeight = function () {
7979 var bodyHeight
, oldOverflow
,
7980 $scrollable
= this.container
.$element
;
7982 oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
7983 $scrollable
[ 0 ].style
.overflow
= 'hidden';
7985 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
7987 bodyHeight
= this.text
.$element
.outerHeight( true );
7988 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
7996 OO
.ui
.MessageDialog
.prototype.setDimensions = function ( dim
) {
7997 var $scrollable
= this.container
.$element
;
7998 OO
.ui
.MessageDialog
.parent
.prototype.setDimensions
.call( this, dim
);
8000 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8001 // Need to do it after transition completes (250ms), add 50ms just in case.
8002 setTimeout( function () {
8003 var oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
8004 $scrollable
[ 0 ].style
.overflow
= 'hidden';
8006 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
8008 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
8017 OO
.ui
.MessageDialog
.prototype.initialize = function () {
8019 OO
.ui
.MessageDialog
.parent
.prototype.initialize
.call( this );
8022 this.$actions
= $( '<div>' );
8023 this.container
= new OO
.ui
.PanelLayout( {
8024 scrollable
: true, classes
: [ 'oo-ui-messageDialog-container' ]
8026 this.text
= new OO
.ui
.PanelLayout( {
8027 padded
: true, expanded
: false, classes
: [ 'oo-ui-messageDialog-text' ]
8029 this.message
= new OO
.ui
.LabelWidget( {
8030 classes
: [ 'oo-ui-messageDialog-message' ]
8034 this.title
.$element
.addClass( 'oo-ui-messageDialog-title' );
8035 this.$content
.addClass( 'oo-ui-messageDialog-content' );
8036 this.container
.$element
.append( this.text
.$element
);
8037 this.text
.$element
.append( this.title
.$element
, this.message
.$element
);
8038 this.$body
.append( this.container
.$element
);
8039 this.$actions
.addClass( 'oo-ui-messageDialog-actions' );
8040 this.$foot
.append( this.$actions
);
8046 OO
.ui
.MessageDialog
.prototype.attachActions = function () {
8047 var i
, len
, other
, special
, others
;
8050 OO
.ui
.MessageDialog
.parent
.prototype.attachActions
.call( this );
8052 special
= this.actions
.getSpecial();
8053 others
= this.actions
.getOthers();
8054 if ( special
.safe
) {
8055 this.$actions
.append( special
.safe
.$element
);
8056 special
.safe
.toggleFramed( false );
8058 if ( others
.length
) {
8059 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
8060 other
= others
[ i
];
8061 this.$actions
.append( other
.$element
);
8062 other
.toggleFramed( false );
8065 if ( special
.primary
) {
8066 this.$actions
.append( special
.primary
.$element
);
8067 special
.primary
.toggleFramed( false );
8070 if ( !this.isOpening() ) {
8071 // If the dialog is currently opening, this will be called automatically soon.
8072 // This also calls #fitActions.
8078 * Fit action actions into columns or rows.
8080 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8084 OO
.ui
.MessageDialog
.prototype.fitActions = function () {
8086 previous
= this.verticalActionLayout
,
8087 actions
= this.actions
.get();
8090 this.toggleVerticalActionLayout( false );
8091 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
8092 action
= actions
[ i
];
8093 if ( action
.$element
.innerWidth() < action
.$label
.outerWidth( true ) ) {
8094 this.toggleVerticalActionLayout( true );
8099 // Move the body out of the way of the foot
8100 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
8102 if ( this.verticalActionLayout
!== previous
) {
8103 // We changed the layout, window height might need to be updated.
8109 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8110 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8111 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8112 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8113 * required for each process.
8115 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8116 * processes with an animation. The header contains the dialog title as well as
8117 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8118 * a ‘primary’ action on the right (e.g., ‘Done’).
8120 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8121 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8124 * // Example: Creating and opening a process dialog window.
8125 * function MyProcessDialog( config ) {
8126 * MyProcessDialog.parent.call( this, config );
8128 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8130 * MyProcessDialog.static.title = 'Process dialog';
8131 * MyProcessDialog.static.actions = [
8132 * { action: 'save', label: 'Done', flags: 'primary' },
8133 * { label: 'Cancel', flags: 'safe' }
8136 * MyProcessDialog.prototype.initialize = function () {
8137 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8138 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8139 * 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>' );
8140 * this.$body.append( this.content.$element );
8142 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8143 * var dialog = this;
8145 * return new OO.ui.Process( function () {
8146 * dialog.close( { action: action } );
8149 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8152 * var windowManager = new OO.ui.WindowManager();
8153 * $( 'body' ).append( windowManager.$element );
8155 * var dialog = new MyProcessDialog();
8156 * windowManager.addWindows( [ dialog ] );
8157 * windowManager.openWindow( dialog );
8159 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8163 * @extends OO.ui.Dialog
8166 * @param {Object} [config] Configuration options
8168 OO
.ui
.ProcessDialog
= function OoUiProcessDialog( config
) {
8169 // Parent constructor
8170 OO
.ui
.ProcessDialog
.parent
.call( this, config
);
8173 this.$element
.addClass( 'oo-ui-processDialog' );
8178 OO
.inheritClass( OO
.ui
.ProcessDialog
, OO
.ui
.Dialog
);
8183 * Handle dismiss button click events.
8189 OO
.ui
.ProcessDialog
.prototype.onDismissErrorButtonClick = function () {
8194 * Handle retry button click events.
8196 * Hides errors and then tries again.
8200 OO
.ui
.ProcessDialog
.prototype.onRetryButtonClick = function () {
8202 this.executeAction( this.currentAction
);
8208 OO
.ui
.ProcessDialog
.prototype.onActionResize = function ( action
) {
8209 if ( this.actions
.isSpecial( action
) ) {
8212 return OO
.ui
.ProcessDialog
.parent
.prototype.onActionResize
.call( this, action
);
8218 OO
.ui
.ProcessDialog
.prototype.initialize = function () {
8220 OO
.ui
.ProcessDialog
.parent
.prototype.initialize
.call( this );
8223 this.$navigation
= $( '<div>' );
8224 this.$location
= $( '<div>' );
8225 this.$safeActions
= $( '<div>' );
8226 this.$primaryActions
= $( '<div>' );
8227 this.$otherActions
= $( '<div>' );
8228 this.dismissButton
= new OO
.ui
.ButtonWidget( {
8229 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' )
8231 this.retryButton
= new OO
.ui
.ButtonWidget();
8232 this.$errors
= $( '<div>' );
8233 this.$errorsTitle
= $( '<div>' );
8236 this.dismissButton
.connect( this, { click
: 'onDismissErrorButtonClick' } );
8237 this.retryButton
.connect( this, { click
: 'onRetryButtonClick' } );
8240 this.title
.$element
.addClass( 'oo-ui-processDialog-title' );
8242 .append( this.title
.$element
)
8243 .addClass( 'oo-ui-processDialog-location' );
8244 this.$safeActions
.addClass( 'oo-ui-processDialog-actions-safe' );
8245 this.$primaryActions
.addClass( 'oo-ui-processDialog-actions-primary' );
8246 this.$otherActions
.addClass( 'oo-ui-processDialog-actions-other' );
8248 .addClass( 'oo-ui-processDialog-errors-title' )
8249 .text( OO
.ui
.msg( 'ooui-dialog-process-error' ) );
8251 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8252 .append( this.$errorsTitle
, this.dismissButton
.$element
, this.retryButton
.$element
);
8254 .addClass( 'oo-ui-processDialog-content' )
8255 .append( this.$errors
);
8257 .addClass( 'oo-ui-processDialog-navigation' )
8258 .append( this.$safeActions
, this.$location
, this.$primaryActions
);
8259 this.$head
.append( this.$navigation
);
8260 this.$foot
.append( this.$otherActions
);
8266 OO
.ui
.ProcessDialog
.prototype.getActionWidgets = function ( actions
) {
8267 var i
, len
, widgets
= [];
8268 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
8270 new OO
.ui
.ActionWidget( $.extend( { framed
: true }, actions
[ i
] ) )
8279 OO
.ui
.ProcessDialog
.prototype.attachActions = function () {
8280 var i
, len
, other
, special
, others
;
8283 OO
.ui
.ProcessDialog
.parent
.prototype.attachActions
.call( this );
8285 special
= this.actions
.getSpecial();
8286 others
= this.actions
.getOthers();
8287 if ( special
.primary
) {
8288 this.$primaryActions
.append( special
.primary
.$element
);
8290 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
8291 other
= others
[ i
];
8292 this.$otherActions
.append( other
.$element
);
8294 if ( special
.safe
) {
8295 this.$safeActions
.append( special
.safe
.$element
);
8299 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
8305 OO
.ui
.ProcessDialog
.prototype.executeAction = function ( action
) {
8307 return OO
.ui
.ProcessDialog
.parent
.prototype.executeAction
.call( this, action
)
8308 .fail( function ( errors
) {
8309 process
.showErrors( errors
|| [] );
8314 * Fit label between actions.
8319 OO
.ui
.ProcessDialog
.prototype.fitLabel = function () {
8320 var safeWidth
, primaryWidth
, biggerWidth
, labelWidth
, navigationWidth
, leftWidth
, rightWidth
;
8322 safeWidth
= this.$safeActions
.is( ':visible' ) ? this.$safeActions
.width() : 0;
8323 primaryWidth
= this.$primaryActions
.is( ':visible' ) ? this.$primaryActions
.width() : 0;
8324 biggerWidth
= Math
.max( safeWidth
, primaryWidth
);
8326 labelWidth
= this.title
.$element
.width();
8327 // Is there a better way to calculate this?
8328 navigationWidth
= OO
.ui
.WindowManager
.static.sizes
[ this.getSize() ].width
- 20;
8330 if ( 2 * biggerWidth
+ labelWidth
< navigationWidth
) {
8331 // We have enough space to center the label
8332 leftWidth
= rightWidth
= biggerWidth
;
8334 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
8335 if ( this.getDir() === 'ltr' ) {
8336 leftWidth
= safeWidth
;
8337 rightWidth
= primaryWidth
;
8339 leftWidth
= primaryWidth
;
8340 rightWidth
= safeWidth
;
8344 this.$location
.css( { paddingLeft
: leftWidth
, paddingRight
: rightWidth
} );
8350 * Handle errors that occurred during accept or reject processes.
8353 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
8355 OO
.ui
.ProcessDialog
.prototype.showErrors = function ( errors
) {
8356 var i
, len
, $item
, actions
,
8362 if ( errors
instanceof OO
.ui
.Error
) {
8363 errors
= [ errors
];
8366 for ( i
= 0, len
= errors
.length
; i
< len
; i
++ ) {
8367 if ( !errors
[ i
].isRecoverable() ) {
8368 recoverable
= false;
8370 if ( errors
[ i
].isWarning() ) {
8373 $item
= $( '<div>' )
8374 .addClass( 'oo-ui-processDialog-error' )
8375 .append( errors
[ i
].getMessage() );
8376 items
.push( $item
[ 0 ] );
8378 this.$errorItems
= $( items
);
8379 if ( recoverable
) {
8380 abilities
[this.currentAction
] = true;
8381 // Copy the flags from the first matching action
8382 actions
= this.actions
.get( { actions
: this.currentAction
} );
8383 if ( actions
.length
) {
8384 this.retryButton
.clearFlags().setFlags( actions
[0].getFlags() );
8387 abilities
[this.currentAction
] = false;
8388 this.actions
.setAbilities( abilities
);
8391 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-continue' ) );
8393 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-retry' ) );
8395 this.retryButton
.toggle( recoverable
);
8396 this.$errorsTitle
.after( this.$errorItems
);
8397 this.$errors
.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
8405 OO
.ui
.ProcessDialog
.prototype.hideErrors = function () {
8406 this.$errors
.addClass( 'oo-ui-element-hidden' );
8407 if ( this.$errorItems
) {
8408 this.$errorItems
.remove();
8409 this.$errorItems
= null;
8416 OO
.ui
.ProcessDialog
.prototype.getTeardownProcess = function ( data
) {
8418 return OO
.ui
.ProcessDialog
.parent
.prototype.getTeardownProcess
.call( this, data
)
8419 .first( function () {
8420 // Make sure to hide errors
8426 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8427 * which is a widget that is specified by reference before any optional configuration settings.
8429 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8431 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8432 * A left-alignment is used for forms with many fields.
8433 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8434 * A right-alignment is used for long but familiar forms which users tab through,
8435 * verifying the current field with a quick glance at the label.
8436 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8437 * that users fill out from top to bottom.
8438 * - **inline**: The label is placed after the field-widget and aligned to the left.
8439 * An inline-alignment is best used with checkboxes or radio buttons.
8441 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
8442 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
8444 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8446 * @extends OO.ui.Layout
8447 * @mixins OO.ui.mixin.LabelElement
8450 * @param {OO.ui.Widget} fieldWidget Field widget
8451 * @param {Object} [config] Configuration options
8452 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8453 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a help icon will appear
8454 * in the upper-right corner of the rendered field.
8456 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
8457 // Allow passing positional parameters inside the config object
8458 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
8459 config
= fieldWidget
;
8460 fieldWidget
= config
.fieldWidget
;
8463 var hasInputWidget
= fieldWidget
.constructor.static.supportsSimpleLabel
,
8466 // Configuration initialization
8467 config
= $.extend( { align
: 'left' }, config
);
8469 // Parent constructor
8470 OO
.ui
.FieldLayout
.parent
.call( this, config
);
8472 // Mixin constructors
8473 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8476 this.fieldWidget
= fieldWidget
;
8477 this.$field
= $( '<div>' );
8478 this.$body
= $( '<' + ( hasInputWidget
? 'label' : 'div' ) + '>' );
8480 if ( config
.help
) {
8481 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
8482 classes
: [ 'oo-ui-fieldLayout-help' ],
8488 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
8489 div
.html( config
.help
.toString() );
8491 div
.text( config
.help
);
8493 this.popupButtonWidget
.getPopup().$body
.append(
8494 div
.addClass( 'oo-ui-fieldLayout-help-content' )
8496 this.$help
= this.popupButtonWidget
.$element
;
8498 this.$help
= $( [] );
8502 if ( hasInputWidget
) {
8503 this.$label
.on( 'click', this.onLabelClick
.bind( this ) );
8505 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
8509 .addClass( 'oo-ui-fieldLayout' )
8510 .append( this.$help
, this.$body
);
8511 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
8513 .addClass( 'oo-ui-fieldLayout-field' )
8514 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget
.isDisabled() )
8515 .append( this.fieldWidget
.$element
);
8517 this.setAlignment( config
.align
);
8522 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
8523 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
8528 * Handle field disable events.
8531 * @param {boolean} value Field is disabled
8533 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
8534 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
8538 * Handle label mouse click events.
8541 * @param {jQuery.Event} e Mouse click event
8543 OO
.ui
.FieldLayout
.prototype.onLabelClick = function () {
8544 this.fieldWidget
.simulateLabelClick();
8549 * Get the widget contained by the field.
8551 * @return {OO.ui.Widget} Field widget
8553 OO
.ui
.FieldLayout
.prototype.getField = function () {
8554 return this.fieldWidget
;
8558 * Set the field alignment mode.
8561 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
8564 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
8565 if ( value
!== this.align
) {
8566 // Default to 'left'
8567 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
8571 if ( value
=== 'inline' ) {
8572 this.$body
.append( this.$field
, this.$label
);
8574 this.$body
.append( this.$label
, this.$field
);
8576 // Set classes. The following classes can be used here:
8577 // * oo-ui-fieldLayout-align-left
8578 // * oo-ui-fieldLayout-align-right
8579 // * oo-ui-fieldLayout-align-top
8580 // * oo-ui-fieldLayout-align-inline
8582 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
8584 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
8592 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
8593 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
8594 * is required and is specified before any optional configuration settings.
8596 * Labels can be aligned in one of four ways:
8598 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8599 * A left-alignment is used for forms with many fields.
8600 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8601 * A right-alignment is used for long but familiar forms which users tab through,
8602 * verifying the current field with a quick glance at the label.
8603 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8604 * that users fill out from top to bottom.
8605 * - **inline**: The label is placed after the field-widget and aligned to the left.
8606 * An inline-alignment is best used with checkboxes or radio buttons.
8608 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
8609 * text is specified.
8612 * // Example of an ActionFieldLayout
8613 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
8614 * new OO.ui.TextInputWidget( {
8615 * placeholder: 'Field widget'
8617 * new OO.ui.ButtonWidget( {
8621 * label: 'An ActionFieldLayout. This label is aligned top',
8623 * help: 'This is help text'
8627 * $( 'body' ).append( actionFieldLayout.$element );
8631 * @extends OO.ui.FieldLayout
8634 * @param {OO.ui.Widget} fieldWidget Field widget
8635 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
8637 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
8638 // Allow passing positional parameters inside the config object
8639 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
8640 config
= fieldWidget
;
8641 fieldWidget
= config
.fieldWidget
;
8642 buttonWidget
= config
.buttonWidget
;
8645 // Parent constructor
8646 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
8649 this.buttonWidget
= buttonWidget
;
8650 this.$button
= $( '<div>' );
8651 this.$input
= $( '<div>' );
8655 .addClass( 'oo-ui-actionFieldLayout' );
8657 .addClass( 'oo-ui-actionFieldLayout-button' )
8658 .append( this.buttonWidget
.$element
);
8660 .addClass( 'oo-ui-actionFieldLayout-input' )
8661 .append( this.fieldWidget
.$element
);
8663 .append( this.$input
, this.$button
);
8668 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
8671 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
8672 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
8673 * configured with a label as well. For more information and examples,
8674 * please see the [OOjs UI documentation on MediaWiki][1].
8677 * // Example of a fieldset layout
8678 * var input1 = new OO.ui.TextInputWidget( {
8679 * placeholder: 'A text input field'
8682 * var input2 = new OO.ui.TextInputWidget( {
8683 * placeholder: 'A text input field'
8686 * var fieldset = new OO.ui.FieldsetLayout( {
8687 * label: 'Example of a fieldset layout'
8690 * fieldset.addItems( [
8691 * new OO.ui.FieldLayout( input1, {
8692 * label: 'Field One'
8694 * new OO.ui.FieldLayout( input2, {
8695 * label: 'Field Two'
8698 * $( 'body' ).append( fieldset.$element );
8700 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8703 * @extends OO.ui.Layout
8704 * @mixins OO.ui.mixin.IconElement
8705 * @mixins OO.ui.mixin.LabelElement
8706 * @mixins OO.ui.mixin.GroupElement
8709 * @param {Object} [config] Configuration options
8710 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
8712 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
8713 // Configuration initialization
8714 config
= config
|| {};
8716 // Parent constructor
8717 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
8719 // Mixin constructors
8720 OO
.ui
.mixin
.IconElement
.call( this, config
);
8721 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8722 OO
.ui
.mixin
.GroupElement
.call( this, config
);
8724 if ( config
.help
) {
8725 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
8726 classes
: [ 'oo-ui-fieldsetLayout-help' ],
8731 this.popupButtonWidget
.getPopup().$body
.append(
8733 .text( config
.help
)
8734 .addClass( 'oo-ui-fieldsetLayout-help-content' )
8736 this.$help
= this.popupButtonWidget
.$element
;
8738 this.$help
= $( [] );
8743 .addClass( 'oo-ui-fieldsetLayout' )
8744 .prepend( this.$help
, this.$icon
, this.$label
, this.$group
);
8745 if ( Array
.isArray( config
.items
) ) {
8746 this.addItems( config
.items
);
8752 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
8753 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
8754 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
8755 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
8758 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
8759 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
8760 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
8761 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
8763 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
8764 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
8765 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
8766 * some fancier controls. Some controls have both regular and InputWidget variants, for example
8767 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
8768 * often have simplified APIs to match the capabilities of HTML forms.
8769 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
8771 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
8772 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8775 * // Example of a form layout that wraps a fieldset layout
8776 * var input1 = new OO.ui.TextInputWidget( {
8777 * placeholder: 'Username'
8779 * var input2 = new OO.ui.TextInputWidget( {
8780 * placeholder: 'Password',
8783 * var submit = new OO.ui.ButtonInputWidget( {
8787 * var fieldset = new OO.ui.FieldsetLayout( {
8788 * label: 'A form layout'
8790 * fieldset.addItems( [
8791 * new OO.ui.FieldLayout( input1, {
8792 * label: 'Username',
8795 * new OO.ui.FieldLayout( input2, {
8796 * label: 'Password',
8799 * new OO.ui.FieldLayout( submit )
8801 * var form = new OO.ui.FormLayout( {
8802 * items: [ fieldset ],
8803 * action: '/api/formhandler',
8806 * $( 'body' ).append( form.$element );
8809 * @extends OO.ui.Layout
8810 * @mixins OO.ui.mixin.GroupElement
8813 * @param {Object} [config] Configuration options
8814 * @cfg {string} [method] HTML form `method` attribute
8815 * @cfg {string} [action] HTML form `action` attribute
8816 * @cfg {string} [enctype] HTML form `enctype` attribute
8817 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
8819 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
8820 // Configuration initialization
8821 config
= config
|| {};
8823 // Parent constructor
8824 OO
.ui
.FormLayout
.parent
.call( this, config
);
8826 // Mixin constructors
8827 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
8830 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
8834 .addClass( 'oo-ui-formLayout' )
8836 method
: config
.method
,
8837 action
: config
.action
,
8838 enctype
: config
.enctype
8840 if ( Array
.isArray( config
.items
) ) {
8841 this.addItems( config
.items
);
8847 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
8848 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
8853 * A 'submit' event is emitted when the form is submitted.
8858 /* Static Properties */
8860 OO
.ui
.FormLayout
.static.tagName
= 'form';
8865 * Handle form submit events.
8868 * @param {jQuery.Event} e Submit event
8871 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
8872 if ( this.emit( 'submit' ) ) {
8878 * 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)
8879 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
8882 * var menuLayout = new OO.ui.MenuLayout( {
8885 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
8886 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
8887 * select = new OO.ui.SelectWidget( {
8889 * new OO.ui.OptionWidget( {
8893 * new OO.ui.OptionWidget( {
8897 * new OO.ui.OptionWidget( {
8901 * new OO.ui.OptionWidget( {
8906 * } ).on( 'select', function ( item ) {
8907 * menuLayout.setMenuPosition( item.getData() );
8910 * menuLayout.$menu.append(
8911 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
8913 * menuLayout.$content.append(
8914 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
8916 * $( 'body' ).append( menuLayout.$element );
8918 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
8919 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
8920 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
8923 * .oo-ui-menuLayout-menu {
8927 * .oo-ui-menuLayout-content {
8935 * @extends OO.ui.Layout
8938 * @param {Object} [config] Configuration options
8939 * @cfg {boolean} [showMenu=true] Show menu
8940 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
8942 OO
.ui
.MenuLayout
= function OoUiMenuLayout( config
) {
8943 // Configuration initialization
8944 config
= $.extend( {
8946 menuPosition
: 'before'
8949 // Parent constructor
8950 OO
.ui
.MenuLayout
.parent
.call( this, config
);
8955 * @property {jQuery}
8957 this.$menu
= $( '<div>' );
8961 * @property {jQuery}
8963 this.$content
= $( '<div>' );
8967 .addClass( 'oo-ui-menuLayout-menu' );
8968 this.$content
.addClass( 'oo-ui-menuLayout-content' );
8970 .addClass( 'oo-ui-menuLayout' )
8971 .append( this.$content
, this.$menu
);
8972 this.setMenuPosition( config
.menuPosition
);
8973 this.toggleMenu( config
.showMenu
);
8978 OO
.inheritClass( OO
.ui
.MenuLayout
, OO
.ui
.Layout
);
8985 * @param {boolean} showMenu Show menu, omit to toggle
8988 OO
.ui
.MenuLayout
.prototype.toggleMenu = function ( showMenu
) {
8989 showMenu
= showMenu
=== undefined ? !this.showMenu
: !!showMenu
;
8991 if ( this.showMenu
!== showMenu
) {
8992 this.showMenu
= showMenu
;
8994 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu
)
8995 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu
);
9002 * Check if menu is visible
9004 * @return {boolean} Menu is visible
9006 OO
.ui
.MenuLayout
.prototype.isMenuVisible = function () {
9007 return this.showMenu
;
9011 * Set menu position.
9013 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9014 * @throws {Error} If position value is not supported
9017 OO
.ui
.MenuLayout
.prototype.setMenuPosition = function ( position
) {
9018 this.$element
.removeClass( 'oo-ui-menuLayout-' + this.menuPosition
);
9019 this.menuPosition
= position
;
9020 this.$element
.addClass( 'oo-ui-menuLayout-' + position
);
9026 * Get menu position.
9028 * @return {string} Menu position
9030 OO
.ui
.MenuLayout
.prototype.getMenuPosition = function () {
9031 return this.menuPosition
;
9035 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9036 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9037 * through the pages and select which one to display. By default, only one page is
9038 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9039 * the booklet layout automatically focuses on the first focusable element, unless the
9040 * default setting is changed. Optionally, booklets can be configured to show
9041 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9044 * // Example of a BookletLayout that contains two PageLayouts.
9046 * function PageOneLayout( name, config ) {
9047 * PageOneLayout.parent.call( this, name, config );
9048 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9050 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9051 * PageOneLayout.prototype.setupOutlineItem = function () {
9052 * this.outlineItem.setLabel( 'Page One' );
9055 * function PageTwoLayout( name, config ) {
9056 * PageTwoLayout.parent.call( this, name, config );
9057 * this.$element.append( '<p>Second page</p>' );
9059 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9060 * PageTwoLayout.prototype.setupOutlineItem = function () {
9061 * this.outlineItem.setLabel( 'Page Two' );
9064 * var page1 = new PageOneLayout( 'one' ),
9065 * page2 = new PageTwoLayout( 'two' );
9067 * var booklet = new OO.ui.BookletLayout( {
9071 * booklet.addPages ( [ page1, page2 ] );
9072 * $( 'body' ).append( booklet.$element );
9075 * @extends OO.ui.MenuLayout
9078 * @param {Object} [config] Configuration options
9079 * @cfg {boolean} [continuous=false] Show all pages, one after another
9080 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9081 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9082 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9084 OO
.ui
.BookletLayout
= function OoUiBookletLayout( config
) {
9085 // Configuration initialization
9086 config
= config
|| {};
9088 // Parent constructor
9089 OO
.ui
.BookletLayout
.parent
.call( this, config
);
9092 this.currentPageName
= null;
9094 this.ignoreFocus
= false;
9095 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
9096 this.$content
.append( this.stackLayout
.$element
);
9097 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
9098 this.outlineVisible
= false;
9099 this.outlined
= !!config
.outlined
;
9100 if ( this.outlined
) {
9101 this.editable
= !!config
.editable
;
9102 this.outlineControlsWidget
= null;
9103 this.outlineSelectWidget
= new OO
.ui
.OutlineSelectWidget();
9104 this.outlinePanel
= new OO
.ui
.PanelLayout( { scrollable
: true } );
9105 this.$menu
.append( this.outlinePanel
.$element
);
9106 this.outlineVisible
= true;
9107 if ( this.editable
) {
9108 this.outlineControlsWidget
= new OO
.ui
.OutlineControlsWidget(
9109 this.outlineSelectWidget
9113 this.toggleMenu( this.outlined
);
9116 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
9117 if ( this.outlined
) {
9118 this.outlineSelectWidget
.connect( this, { select
: 'onOutlineSelectWidgetSelect' } );
9120 if ( this.autoFocus
) {
9121 // Event 'focus' does not bubble, but 'focusin' does
9122 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
9126 this.$element
.addClass( 'oo-ui-bookletLayout' );
9127 this.stackLayout
.$element
.addClass( 'oo-ui-bookletLayout-stackLayout' );
9128 if ( this.outlined
) {
9129 this.outlinePanel
.$element
9130 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
9131 .append( this.outlineSelectWidget
.$element
);
9132 if ( this.editable
) {
9133 this.outlinePanel
.$element
9134 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
9135 .append( this.outlineControlsWidget
.$element
);
9142 OO
.inheritClass( OO
.ui
.BookletLayout
, OO
.ui
.MenuLayout
);
9147 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
9149 * @param {OO.ui.PageLayout} page Current page
9153 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
9156 * @param {OO.ui.PageLayout[]} page Added pages
9157 * @param {number} index Index pages were added at
9161 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
9162 * {@link #removePages removed} from the booklet.
9165 * @param {OO.ui.PageLayout[]} pages Removed pages
9171 * Handle stack layout focus.
9174 * @param {jQuery.Event} e Focusin event
9176 OO
.ui
.BookletLayout
.prototype.onStackLayoutFocus = function ( e
) {
9179 // Find the page that an element was focused within
9180 $target
= $( e
.target
).closest( '.oo-ui-pageLayout' );
9181 for ( name
in this.pages
) {
9182 // Check for page match, exclude current page to find only page changes
9183 if ( this.pages
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentPageName
) {
9184 this.setPage( name
);
9191 * Handle stack layout set events.
9194 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
9196 OO
.ui
.BookletLayout
.prototype.onStackLayoutSet = function ( page
) {
9199 page
.scrollElementIntoView( { complete: function () {
9200 if ( layout
.autoFocus
) {
9208 * Focus the first input in the current page.
9210 * If no page is selected, the first selectable page will be selected.
9211 * If the focus is already in an element on the current page, nothing will happen.
9212 * @param {number} [itemIndex] A specific item to focus on
9214 OO
.ui
.BookletLayout
.prototype.focus = function ( itemIndex
) {
9216 items
= this.stackLayout
.getItems();
9218 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
9219 page
= items
[ itemIndex
];
9221 page
= this.stackLayout
.getCurrentItem();
9224 if ( !page
&& this.outlined
) {
9225 this.selectFirstSelectablePage();
9226 page
= this.stackLayout
.getCurrentItem();
9231 // Only change the focus if is not already in the current page
9232 if ( !page
.$element
.find( ':focus' ).length
) {
9233 $input
= page
.$element
.find( ':input:first' );
9234 if ( $input
.length
) {
9235 $input
[ 0 ].focus();
9241 * Find the first focusable input in the booklet layout and focus
9244 OO
.ui
.BookletLayout
.prototype.focusFirstFocusable = function () {
9247 items
= this.stackLayout
.getItems(),
9248 checkAndFocus = function () {
9249 if ( OO
.ui
.isFocusableElement( $( this ) ) ) {
9256 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
9260 // Find all potentially focusable elements in the item
9261 // and check if they are focusable
9263 .find( 'input, select, textarea, button, object' )
9264 /* jshint loopfunc:true */
9265 .each( checkAndFocus
);
9270 * Handle outline widget select events.
9273 * @param {OO.ui.OptionWidget|null} item Selected item
9275 OO
.ui
.BookletLayout
.prototype.onOutlineSelectWidgetSelect = function ( item
) {
9277 this.setPage( item
.getData() );
9282 * Check if booklet has an outline.
9284 * @return {boolean} Booklet has an outline
9286 OO
.ui
.BookletLayout
.prototype.isOutlined = function () {
9287 return this.outlined
;
9291 * Check if booklet has editing controls.
9293 * @return {boolean} Booklet is editable
9295 OO
.ui
.BookletLayout
.prototype.isEditable = function () {
9296 return this.editable
;
9300 * Check if booklet has a visible outline.
9302 * @return {boolean} Outline is visible
9304 OO
.ui
.BookletLayout
.prototype.isOutlineVisible = function () {
9305 return this.outlined
&& this.outlineVisible
;
9309 * Hide or show the outline.
9311 * @param {boolean} [show] Show outline, omit to invert current state
9314 OO
.ui
.BookletLayout
.prototype.toggleOutline = function ( show
) {
9315 if ( this.outlined
) {
9316 show
= show
=== undefined ? !this.outlineVisible
: !!show
;
9317 this.outlineVisible
= show
;
9318 this.toggleMenu( show
);
9325 * Get the page closest to the specified page.
9327 * @param {OO.ui.PageLayout} page Page to use as a reference point
9328 * @return {OO.ui.PageLayout|null} Page closest to the specified page
9330 OO
.ui
.BookletLayout
.prototype.getClosestPage = function ( page
) {
9331 var next
, prev
, level
,
9332 pages
= this.stackLayout
.getItems(),
9333 index
= $.inArray( page
, pages
);
9335 if ( index
!== -1 ) {
9336 next
= pages
[ index
+ 1 ];
9337 prev
= pages
[ index
- 1 ];
9338 // Prefer adjacent pages at the same level
9339 if ( this.outlined
) {
9340 level
= this.outlineSelectWidget
.getItemFromData( page
.getName() ).getLevel();
9343 level
=== this.outlineSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
9349 level
=== this.outlineSelectWidget
.getItemFromData( next
.getName() ).getLevel()
9355 return prev
|| next
|| null;
9359 * Get the outline widget.
9361 * If the booklet is not outlined, the method will return `null`.
9363 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
9365 OO
.ui
.BookletLayout
.prototype.getOutline = function () {
9366 return this.outlineSelectWidget
;
9370 * Get the outline controls widget.
9372 * If the outline is not editable, the method will return `null`.
9374 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
9376 OO
.ui
.BookletLayout
.prototype.getOutlineControls = function () {
9377 return this.outlineControlsWidget
;
9381 * Get a page by its symbolic name.
9383 * @param {string} name Symbolic name of page
9384 * @return {OO.ui.PageLayout|undefined} Page, if found
9386 OO
.ui
.BookletLayout
.prototype.getPage = function ( name
) {
9387 return this.pages
[ name
];
9391 * Get the current page.
9393 * @return {OO.ui.PageLayout|undefined} Current page, if found
9395 OO
.ui
.BookletLayout
.prototype.getCurrentPage = function () {
9396 var name
= this.getCurrentPageName();
9397 return name
? this.getPage( name
) : undefined;
9401 * Get the symbolic name of the current page.
9403 * @return {string|null} Symbolic name of the current page
9405 OO
.ui
.BookletLayout
.prototype.getCurrentPageName = function () {
9406 return this.currentPageName
;
9410 * Add pages to the booklet layout
9412 * When pages are added with the same names as existing pages, the existing pages will be
9413 * automatically removed before the new pages are added.
9415 * @param {OO.ui.PageLayout[]} pages Pages to add
9416 * @param {number} index Index of the insertion point
9420 OO
.ui
.BookletLayout
.prototype.addPages = function ( pages
, index
) {
9421 var i
, len
, name
, page
, item
, currentIndex
,
9422 stackLayoutPages
= this.stackLayout
.getItems(),
9426 // Remove pages with same names
9427 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9429 name
= page
.getName();
9431 if ( Object
.prototype.hasOwnProperty
.call( this.pages
, name
) ) {
9432 // Correct the insertion index
9433 currentIndex
= $.inArray( this.pages
[ name
], stackLayoutPages
);
9434 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
9437 remove
.push( this.pages
[ name
] );
9440 if ( remove
.length
) {
9441 this.removePages( remove
);
9445 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9447 name
= page
.getName();
9448 this.pages
[ page
.getName() ] = page
;
9449 if ( this.outlined
) {
9450 item
= new OO
.ui
.OutlineOptionWidget( { data
: name
} );
9451 page
.setOutlineItem( item
);
9456 if ( this.outlined
&& items
.length
) {
9457 this.outlineSelectWidget
.addItems( items
, index
);
9458 this.selectFirstSelectablePage();
9460 this.stackLayout
.addItems( pages
, index
);
9461 this.emit( 'add', pages
, index
);
9467 * Remove the specified pages from the booklet layout.
9469 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
9471 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
9475 OO
.ui
.BookletLayout
.prototype.removePages = function ( pages
) {
9476 var i
, len
, name
, page
,
9479 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9481 name
= page
.getName();
9482 delete this.pages
[ name
];
9483 if ( this.outlined
) {
9484 items
.push( this.outlineSelectWidget
.getItemFromData( name
) );
9485 page
.setOutlineItem( null );
9488 if ( this.outlined
&& items
.length
) {
9489 this.outlineSelectWidget
.removeItems( items
);
9490 this.selectFirstSelectablePage();
9492 this.stackLayout
.removeItems( pages
);
9493 this.emit( 'remove', pages
);
9499 * Clear all pages from the booklet layout.
9501 * To remove only a subset of pages from the booklet, use the #removePages method.
9506 OO
.ui
.BookletLayout
.prototype.clearPages = function () {
9508 pages
= this.stackLayout
.getItems();
9511 this.currentPageName
= null;
9512 if ( this.outlined
) {
9513 this.outlineSelectWidget
.clearItems();
9514 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9515 pages
[ i
].setOutlineItem( null );
9518 this.stackLayout
.clearItems();
9520 this.emit( 'remove', pages
);
9526 * Set the current page by symbolic name.
9529 * @param {string} name Symbolic name of page
9531 OO
.ui
.BookletLayout
.prototype.setPage = function ( name
) {
9534 page
= this.pages
[ name
];
9536 if ( name
!== this.currentPageName
) {
9537 if ( this.outlined
) {
9538 selectedItem
= this.outlineSelectWidget
.getSelectedItem();
9539 if ( selectedItem
&& selectedItem
.getData() !== name
) {
9540 this.outlineSelectWidget
.selectItemByData( name
);
9544 if ( this.currentPageName
&& this.pages
[ this.currentPageName
] ) {
9545 this.pages
[ this.currentPageName
].setActive( false );
9546 // Blur anything focused if the next page doesn't have anything focusable - this
9547 // is not needed if the next page has something focusable because once it is focused
9548 // this blur happens automatically
9549 if ( this.autoFocus
&& !page
.$element
.find( ':input' ).length
) {
9550 $focused
= this.pages
[ this.currentPageName
].$element
.find( ':focus' );
9551 if ( $focused
.length
) {
9552 $focused
[ 0 ].blur();
9556 this.currentPageName
= name
;
9557 this.stackLayout
.setItem( page
);
9558 page
.setActive( true );
9559 this.emit( 'set', page
);
9565 * Select the first selectable page.
9569 OO
.ui
.BookletLayout
.prototype.selectFirstSelectablePage = function () {
9570 if ( !this.outlineSelectWidget
.getSelectedItem() ) {
9571 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getFirstSelectableItem() );
9578 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
9579 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
9580 * select which one to display. By default, only one card is displayed at a time. When a user
9581 * navigates to a new card, the index layout automatically focuses on the first focusable element,
9582 * unless the default setting is changed.
9584 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
9587 * // Example of a IndexLayout that contains two CardLayouts.
9589 * function CardOneLayout( name, config ) {
9590 * CardOneLayout.parent.call( this, name, config );
9591 * this.$element.append( '<p>First card</p>' );
9593 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
9594 * CardOneLayout.prototype.setupTabItem = function () {
9595 * this.tabItem.setLabel( 'Card One' );
9598 * function CardTwoLayout( name, config ) {
9599 * CardTwoLayout.parent.call( this, name, config );
9600 * this.$element.append( '<p>Second card</p>' );
9602 * OO.inheritClass( CardTwoLayout, OO.ui.CardLayout );
9603 * CardTwoLayout.prototype.setupTabItem = function () {
9604 * this.tabItem.setLabel( 'Card Two' );
9607 * var card1 = new CardOneLayout( 'one' ),
9608 * card2 = new CardTwoLayout( 'two' );
9610 * var index = new OO.ui.IndexLayout();
9612 * index.addCards ( [ card1, card2 ] );
9613 * $( 'body' ).append( index.$element );
9616 * @extends OO.ui.MenuLayout
9619 * @param {Object} [config] Configuration options
9620 * @cfg {boolean} [continuous=false] Show all cards, one after another
9621 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
9623 OO
.ui
.IndexLayout
= function OoUiIndexLayout( config
) {
9624 // Configuration initialization
9625 config
= $.extend( {}, config
, { menuPosition
: 'top' } );
9627 // Parent constructor
9628 OO
.ui
.IndexLayout
.parent
.call( this, config
);
9631 this.currentCardName
= null;
9633 this.ignoreFocus
= false;
9634 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
9635 this.$content
.append( this.stackLayout
.$element
);
9636 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
9638 this.tabSelectWidget
= new OO
.ui
.TabSelectWidget();
9639 this.tabPanel
= new OO
.ui
.PanelLayout();
9640 this.$menu
.append( this.tabPanel
.$element
);
9642 this.toggleMenu( true );
9645 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
9646 this.tabSelectWidget
.connect( this, { select
: 'onTabSelectWidgetSelect' } );
9647 if ( this.autoFocus
) {
9648 // Event 'focus' does not bubble, but 'focusin' does
9649 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
9653 this.$element
.addClass( 'oo-ui-indexLayout' );
9654 this.stackLayout
.$element
.addClass( 'oo-ui-indexLayout-stackLayout' );
9655 this.tabPanel
.$element
9656 .addClass( 'oo-ui-indexLayout-tabPanel' )
9657 .append( this.tabSelectWidget
.$element
);
9662 OO
.inheritClass( OO
.ui
.IndexLayout
, OO
.ui
.MenuLayout
);
9667 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
9669 * @param {OO.ui.CardLayout} card Current card
9673 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
9676 * @param {OO.ui.CardLayout[]} card Added cards
9677 * @param {number} index Index cards were added at
9681 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
9682 * {@link #removeCards removed} from the index.
9685 * @param {OO.ui.CardLayout[]} cards Removed cards
9691 * Handle stack layout focus.
9694 * @param {jQuery.Event} e Focusin event
9696 OO
.ui
.IndexLayout
.prototype.onStackLayoutFocus = function ( e
) {
9699 // Find the card that an element was focused within
9700 $target
= $( e
.target
).closest( '.oo-ui-cardLayout' );
9701 for ( name
in this.cards
) {
9702 // Check for card match, exclude current card to find only card changes
9703 if ( this.cards
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentCardName
) {
9704 this.setCard( name
);
9711 * Handle stack layout set events.
9714 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
9716 OO
.ui
.IndexLayout
.prototype.onStackLayoutSet = function ( card
) {
9719 card
.scrollElementIntoView( { complete: function () {
9720 if ( layout
.autoFocus
) {
9728 * Focus the first input in the current card.
9730 * If no card is selected, the first selectable card will be selected.
9731 * If the focus is already in an element on the current card, nothing will happen.
9732 * @param {number} [itemIndex] A specific item to focus on
9734 OO
.ui
.IndexLayout
.prototype.focus = function ( itemIndex
) {
9736 items
= this.stackLayout
.getItems();
9738 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
9739 card
= items
[ itemIndex
];
9741 card
= this.stackLayout
.getCurrentItem();
9745 this.selectFirstSelectableCard();
9746 card
= this.stackLayout
.getCurrentItem();
9751 // Only change the focus if is not already in the current card
9752 if ( !card
.$element
.find( ':focus' ).length
) {
9753 $input
= card
.$element
.find( ':input:first' );
9754 if ( $input
.length
) {
9755 $input
[ 0 ].focus();
9761 * Find the first focusable input in the index layout and focus
9764 OO
.ui
.IndexLayout
.prototype.focusFirstFocusable = function () {
9767 items
= this.stackLayout
.getItems(),
9768 checkAndFocus = function () {
9769 if ( OO
.ui
.isFocusableElement( $( this ) ) ) {
9776 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
9780 // Find all potentially focusable elements in the item
9781 // and check if they are focusable
9783 .find( 'input, select, textarea, button, object' )
9784 .each( checkAndFocus
);
9789 * Handle tab widget select events.
9792 * @param {OO.ui.OptionWidget|null} item Selected item
9794 OO
.ui
.IndexLayout
.prototype.onTabSelectWidgetSelect = function ( item
) {
9796 this.setCard( item
.getData() );
9801 * Get the card closest to the specified card.
9803 * @param {OO.ui.CardLayout} card Card to use as a reference point
9804 * @return {OO.ui.CardLayout|null} Card closest to the specified card
9806 OO
.ui
.IndexLayout
.prototype.getClosestCard = function ( card
) {
9807 var next
, prev
, level
,
9808 cards
= this.stackLayout
.getItems(),
9809 index
= $.inArray( card
, cards
);
9811 if ( index
!== -1 ) {
9812 next
= cards
[ index
+ 1 ];
9813 prev
= cards
[ index
- 1 ];
9814 // Prefer adjacent cards at the same level
9815 level
= this.tabSelectWidget
.getItemFromData( card
.getName() ).getLevel();
9818 level
=== this.tabSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
9824 level
=== this.tabSelectWidget
.getItemFromData( next
.getName() ).getLevel()
9829 return prev
|| next
|| null;
9833 * Get the tabs widget.
9835 * @return {OO.ui.TabSelectWidget} Tabs widget
9837 OO
.ui
.IndexLayout
.prototype.getTabs = function () {
9838 return this.tabSelectWidget
;
9842 * Get a card by its symbolic name.
9844 * @param {string} name Symbolic name of card
9845 * @return {OO.ui.CardLayout|undefined} Card, if found
9847 OO
.ui
.IndexLayout
.prototype.getCard = function ( name
) {
9848 return this.cards
[ name
];
9852 * Get the current card.
9854 * @return {OO.ui.CardLayout|undefined} Current card, if found
9856 OO
.ui
.IndexLayout
.prototype.getCurrentCard = function () {
9857 var name
= this.getCurrentCardName();
9858 return name
? this.getCard( name
) : undefined;
9862 * Get the symbolic name of the current card.
9864 * @return {string|null} Symbolic name of the current card
9866 OO
.ui
.IndexLayout
.prototype.getCurrentCardName = function () {
9867 return this.currentCardName
;
9871 * Add cards to the index layout
9873 * When cards are added with the same names as existing cards, the existing cards will be
9874 * automatically removed before the new cards are added.
9876 * @param {OO.ui.CardLayout[]} cards Cards to add
9877 * @param {number} index Index of the insertion point
9881 OO
.ui
.IndexLayout
.prototype.addCards = function ( cards
, index
) {
9882 var i
, len
, name
, card
, item
, currentIndex
,
9883 stackLayoutCards
= this.stackLayout
.getItems(),
9887 // Remove cards with same names
9888 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
9890 name
= card
.getName();
9892 if ( Object
.prototype.hasOwnProperty
.call( this.cards
, name
) ) {
9893 // Correct the insertion index
9894 currentIndex
= $.inArray( this.cards
[ name
], stackLayoutCards
);
9895 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
9898 remove
.push( this.cards
[ name
] );
9901 if ( remove
.length
) {
9902 this.removeCards( remove
);
9906 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
9908 name
= card
.getName();
9909 this.cards
[ card
.getName() ] = card
;
9910 item
= new OO
.ui
.TabOptionWidget( { data
: name
} );
9911 card
.setTabItem( item
);
9915 if ( items
.length
) {
9916 this.tabSelectWidget
.addItems( items
, index
);
9917 this.selectFirstSelectableCard();
9919 this.stackLayout
.addItems( cards
, index
);
9920 this.emit( 'add', cards
, index
);
9926 * Remove the specified cards from the index layout.
9928 * To remove all cards from the index, you may wish to use the #clearCards method instead.
9930 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
9934 OO
.ui
.IndexLayout
.prototype.removeCards = function ( cards
) {
9935 var i
, len
, name
, card
,
9938 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
9940 name
= card
.getName();
9941 delete this.cards
[ name
];
9942 items
.push( this.tabSelectWidget
.getItemFromData( name
) );
9943 card
.setTabItem( null );
9945 if ( items
.length
) {
9946 this.tabSelectWidget
.removeItems( items
);
9947 this.selectFirstSelectableCard();
9949 this.stackLayout
.removeItems( cards
);
9950 this.emit( 'remove', cards
);
9956 * Clear all cards from the index layout.
9958 * To remove only a subset of cards from the index, use the #removeCards method.
9963 OO
.ui
.IndexLayout
.prototype.clearCards = function () {
9965 cards
= this.stackLayout
.getItems();
9968 this.currentCardName
= null;
9969 this.tabSelectWidget
.clearItems();
9970 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
9971 cards
[ i
].setTabItem( null );
9973 this.stackLayout
.clearItems();
9975 this.emit( 'remove', cards
);
9981 * Set the current card by symbolic name.
9984 * @param {string} name Symbolic name of card
9986 OO
.ui
.IndexLayout
.prototype.setCard = function ( name
) {
9989 card
= this.cards
[ name
];
9991 if ( name
!== this.currentCardName
) {
9992 selectedItem
= this.tabSelectWidget
.getSelectedItem();
9993 if ( selectedItem
&& selectedItem
.getData() !== name
) {
9994 this.tabSelectWidget
.selectItemByData( name
);
9997 if ( this.currentCardName
&& this.cards
[ this.currentCardName
] ) {
9998 this.cards
[ this.currentCardName
].setActive( false );
9999 // Blur anything focused if the next card doesn't have anything focusable - this
10000 // is not needed if the next card has something focusable because once it is focused
10001 // this blur happens automatically
10002 if ( this.autoFocus
&& !card
.$element
.find( ':input' ).length
) {
10003 $focused
= this.cards
[ this.currentCardName
].$element
.find( ':focus' );
10004 if ( $focused
.length
) {
10005 $focused
[ 0 ].blur();
10009 this.currentCardName
= name
;
10010 this.stackLayout
.setItem( card
);
10011 card
.setActive( true );
10012 this.emit( 'set', card
);
10018 * Select the first selectable card.
10022 OO
.ui
.IndexLayout
.prototype.selectFirstSelectableCard = function () {
10023 if ( !this.tabSelectWidget
.getSelectedItem() ) {
10024 this.tabSelectWidget
.selectItem( this.tabSelectWidget
.getFirstSelectableItem() );
10031 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10032 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10035 * // Example of a panel layout
10036 * var panel = new OO.ui.PanelLayout( {
10040 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10042 * $( 'body' ).append( panel.$element );
10045 * @extends OO.ui.Layout
10048 * @param {Object} [config] Configuration options
10049 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10050 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10051 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10052 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10054 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
10055 // Configuration initialization
10056 config
= $.extend( {
10063 // Parent constructor
10064 OO
.ui
.PanelLayout
.parent
.call( this, config
);
10067 this.$element
.addClass( 'oo-ui-panelLayout' );
10068 if ( config
.scrollable
) {
10069 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
10071 if ( config
.padded
) {
10072 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
10074 if ( config
.expanded
) {
10075 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
10077 if ( config
.framed
) {
10078 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
10084 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
10087 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10088 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10089 * rather extended to include the required content and functionality.
10091 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10092 * item is customized (with a label) using the #setupTabItem method. See
10093 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10096 * @extends OO.ui.PanelLayout
10099 * @param {string} name Unique symbolic name of card
10100 * @param {Object} [config] Configuration options
10102 OO
.ui
.CardLayout
= function OoUiCardLayout( name
, config
) {
10103 // Allow passing positional parameters inside the config object
10104 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
10106 name
= config
.name
;
10109 // Configuration initialization
10110 config
= $.extend( { scrollable
: true }, config
);
10112 // Parent constructor
10113 OO
.ui
.CardLayout
.parent
.call( this, config
);
10117 this.tabItem
= null;
10118 this.active
= false;
10121 this.$element
.addClass( 'oo-ui-cardLayout' );
10126 OO
.inheritClass( OO
.ui
.CardLayout
, OO
.ui
.PanelLayout
);
10131 * An 'active' event is emitted when the card becomes active. Cards become active when they are
10132 * shown in a index layout that is configured to display only one card at a time.
10135 * @param {boolean} active Card is active
10141 * Get the symbolic name of the card.
10143 * @return {string} Symbolic name of card
10145 OO
.ui
.CardLayout
.prototype.getName = function () {
10150 * Check if card is active.
10152 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
10153 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
10155 * @return {boolean} Card is active
10157 OO
.ui
.CardLayout
.prototype.isActive = function () {
10158 return this.active
;
10164 * The tab item allows users to access the card from the index's tab
10165 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
10167 * @return {OO.ui.TabOptionWidget|null} Tab option widget
10169 OO
.ui
.CardLayout
.prototype.getTabItem = function () {
10170 return this.tabItem
;
10174 * Set or unset the tab item.
10176 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
10177 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
10178 * level), use #setupTabItem instead of this method.
10180 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
10183 OO
.ui
.CardLayout
.prototype.setTabItem = function ( tabItem
) {
10184 this.tabItem
= tabItem
|| null;
10186 this.setupTabItem();
10192 * Set up the tab item.
10194 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
10195 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
10196 * the #setTabItem method instead.
10198 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
10201 OO
.ui
.CardLayout
.prototype.setupTabItem = function () {
10206 * Set the card to its 'active' state.
10208 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
10209 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
10210 * context, setting the active state on a card does nothing.
10212 * @param {boolean} value Card is active
10215 OO
.ui
.CardLayout
.prototype.setActive = function ( active
) {
10218 if ( active
!== this.active
) {
10219 this.active
= active
;
10220 this.$element
.toggleClass( 'oo-ui-cardLayout-active', this.active
);
10221 this.emit( 'active', this.active
);
10226 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
10227 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
10228 * rather extended to include the required content and functionality.
10230 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
10231 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
10232 * {@link OO.ui.BookletLayout BookletLayout} for an example.
10235 * @extends OO.ui.PanelLayout
10238 * @param {string} name Unique symbolic name of page
10239 * @param {Object} [config] Configuration options
10241 OO
.ui
.PageLayout
= function OoUiPageLayout( name
, config
) {
10242 // Allow passing positional parameters inside the config object
10243 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
10245 name
= config
.name
;
10248 // Configuration initialization
10249 config
= $.extend( { scrollable
: true }, config
);
10251 // Parent constructor
10252 OO
.ui
.PageLayout
.parent
.call( this, config
);
10256 this.outlineItem
= null;
10257 this.active
= false;
10260 this.$element
.addClass( 'oo-ui-pageLayout' );
10265 OO
.inheritClass( OO
.ui
.PageLayout
, OO
.ui
.PanelLayout
);
10270 * An 'active' event is emitted when the page becomes active. Pages become active when they are
10271 * shown in a booklet layout that is configured to display only one page at a time.
10274 * @param {boolean} active Page is active
10280 * Get the symbolic name of the page.
10282 * @return {string} Symbolic name of page
10284 OO
.ui
.PageLayout
.prototype.getName = function () {
10289 * Check if page is active.
10291 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
10292 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
10294 * @return {boolean} Page is active
10296 OO
.ui
.PageLayout
.prototype.isActive = function () {
10297 return this.active
;
10301 * Get outline item.
10303 * The outline item allows users to access the page from the booklet's outline
10304 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
10306 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
10308 OO
.ui
.PageLayout
.prototype.getOutlineItem = function () {
10309 return this.outlineItem
;
10313 * Set or unset the outline item.
10315 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
10316 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
10317 * level), use #setupOutlineItem instead of this method.
10319 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
10322 OO
.ui
.PageLayout
.prototype.setOutlineItem = function ( outlineItem
) {
10323 this.outlineItem
= outlineItem
|| null;
10324 if ( outlineItem
) {
10325 this.setupOutlineItem();
10331 * Set up the outline item.
10333 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
10334 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
10335 * the #setOutlineItem method instead.
10337 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
10340 OO
.ui
.PageLayout
.prototype.setupOutlineItem = function () {
10345 * Set the page to its 'active' state.
10347 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
10348 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
10349 * context, setting the active state on a page does nothing.
10351 * @param {boolean} value Page is active
10354 OO
.ui
.PageLayout
.prototype.setActive = function ( active
) {
10357 if ( active
!== this.active
) {
10358 this.active
= active
;
10359 this.$element
.toggleClass( 'oo-ui-pageLayout-active', active
);
10360 this.emit( 'active', this.active
);
10365 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
10366 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
10367 * by setting the #continuous option to 'true'.
10370 * // A stack layout with two panels, configured to be displayed continously
10371 * var myStack = new OO.ui.StackLayout( {
10373 * new OO.ui.PanelLayout( {
10374 * $content: $( '<p>Panel One</p>' ),
10378 * new OO.ui.PanelLayout( {
10379 * $content: $( '<p>Panel Two</p>' ),
10386 * $( 'body' ).append( myStack.$element );
10389 * @extends OO.ui.PanelLayout
10390 * @mixins OO.ui.mixin.GroupElement
10393 * @param {Object} [config] Configuration options
10394 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
10395 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
10397 OO
.ui
.StackLayout
= function OoUiStackLayout( config
) {
10398 // Configuration initialization
10399 config
= $.extend( { scrollable
: true }, config
);
10401 // Parent constructor
10402 OO
.ui
.StackLayout
.parent
.call( this, config
);
10404 // Mixin constructors
10405 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
10408 this.currentItem
= null;
10409 this.continuous
= !!config
.continuous
;
10412 this.$element
.addClass( 'oo-ui-stackLayout' );
10413 if ( this.continuous
) {
10414 this.$element
.addClass( 'oo-ui-stackLayout-continuous' );
10416 if ( Array
.isArray( config
.items
) ) {
10417 this.addItems( config
.items
);
10423 OO
.inheritClass( OO
.ui
.StackLayout
, OO
.ui
.PanelLayout
);
10424 OO
.mixinClass( OO
.ui
.StackLayout
, OO
.ui
.mixin
.GroupElement
);
10429 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
10430 * {@link #clearItems cleared} or {@link #setItem displayed}.
10433 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
10439 * Get the current panel.
10441 * @return {OO.ui.Layout|null}
10443 OO
.ui
.StackLayout
.prototype.getCurrentItem = function () {
10444 return this.currentItem
;
10448 * Unset the current item.
10451 * @param {OO.ui.StackLayout} layout
10454 OO
.ui
.StackLayout
.prototype.unsetCurrentItem = function () {
10455 var prevItem
= this.currentItem
;
10456 if ( prevItem
=== null ) {
10460 this.currentItem
= null;
10461 this.emit( 'set', null );
10465 * Add panel layouts to the stack layout.
10467 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
10468 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
10471 * @param {OO.ui.Layout[]} items Panels to add
10472 * @param {number} [index] Index of the insertion point
10475 OO
.ui
.StackLayout
.prototype.addItems = function ( items
, index
) {
10476 // Update the visibility
10477 this.updateHiddenState( items
, this.currentItem
);
10480 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
, index
);
10482 if ( !this.currentItem
&& items
.length
) {
10483 this.setItem( items
[ 0 ] );
10490 * Remove the specified panels from the stack layout.
10492 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
10493 * you may wish to use the #clearItems method instead.
10495 * @param {OO.ui.Layout[]} items Panels to remove
10499 OO
.ui
.StackLayout
.prototype.removeItems = function ( items
) {
10501 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
10503 if ( $.inArray( this.currentItem
, items
) !== -1 ) {
10504 if ( this.items
.length
) {
10505 this.setItem( this.items
[ 0 ] );
10507 this.unsetCurrentItem();
10515 * Clear all panels from the stack layout.
10517 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
10518 * a subset of panels, use the #removeItems method.
10523 OO
.ui
.StackLayout
.prototype.clearItems = function () {
10524 this.unsetCurrentItem();
10525 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
10531 * Show the specified panel.
10533 * If another panel is currently displayed, it will be hidden.
10535 * @param {OO.ui.Layout} item Panel to show
10539 OO
.ui
.StackLayout
.prototype.setItem = function ( item
) {
10540 if ( item
!== this.currentItem
) {
10541 this.updateHiddenState( this.items
, item
);
10543 if ( $.inArray( item
, this.items
) !== -1 ) {
10544 this.currentItem
= item
;
10545 this.emit( 'set', item
);
10547 this.unsetCurrentItem();
10555 * Update the visibility of all items in case of non-continuous view.
10557 * Ensure all items are hidden except for the selected one.
10558 * This method does nothing when the stack is continuous.
10561 * @param {OO.ui.Layout[]} items Item list iterate over
10562 * @param {OO.ui.Layout} [selectedItem] Selected item to show
10564 OO
.ui
.StackLayout
.prototype.updateHiddenState = function ( items
, selectedItem
) {
10567 if ( !this.continuous
) {
10568 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
10569 if ( !selectedItem
|| selectedItem
!== items
[ i
] ) {
10570 items
[ i
].$element
.addClass( 'oo-ui-element-hidden' );
10573 if ( selectedItem
) {
10574 selectedItem
.$element
.removeClass( 'oo-ui-element-hidden' );
10580 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
10581 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
10582 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
10583 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
10586 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
10590 * // Example of a BarToolGroup with two tools
10591 * var toolFactory = new OO.ui.ToolFactory();
10592 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
10593 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
10595 * // We will be placing status text in this element when tools are used
10596 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
10598 * // Define the tools that we're going to place in our toolbar
10600 * // Create a class inheriting from OO.ui.Tool
10601 * function PictureTool() {
10602 * PictureTool.parent.apply( this, arguments );
10604 * OO.inheritClass( PictureTool, OO.ui.Tool );
10605 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
10606 * // of 'icon' and 'title' (displayed icon and text).
10607 * PictureTool.static.name = 'picture';
10608 * PictureTool.static.icon = 'picture';
10609 * PictureTool.static.title = 'Insert picture';
10610 * // Defines the action that will happen when this tool is selected (clicked).
10611 * PictureTool.prototype.onSelect = function () {
10612 * $area.text( 'Picture tool clicked!' );
10613 * // Never display this tool as "active" (selected).
10614 * this.setActive( false );
10616 * // Make this tool available in our toolFactory and thus our toolbar
10617 * toolFactory.register( PictureTool );
10619 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
10620 * // little popup window (a PopupWidget).
10621 * function HelpTool( toolGroup, config ) {
10622 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
10627 * this.popup.$body.append( '<p>I am helpful!</p>' );
10629 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
10630 * HelpTool.static.name = 'help';
10631 * HelpTool.static.icon = 'help';
10632 * HelpTool.static.title = 'Help';
10633 * toolFactory.register( HelpTool );
10635 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
10636 * // used once (but not all defined tools must be used).
10639 * // 'bar' tool groups display tools by icon only
10641 * include: [ 'picture', 'help' ]
10645 * // Create some UI around the toolbar and place it in the document
10646 * var frame = new OO.ui.PanelLayout( {
10650 * var contentFrame = new OO.ui.PanelLayout( {
10654 * frame.$element.append(
10655 * toolbar.$element,
10656 * contentFrame.$element.append( $area )
10658 * $( 'body' ).append( frame.$element );
10660 * // Here is where the toolbar is actually built. This must be done after inserting it into the
10662 * toolbar.initialize();
10664 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
10665 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
10667 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
10670 * @extends OO.ui.ToolGroup
10673 * @param {OO.ui.Toolbar} toolbar
10674 * @param {Object} [config] Configuration options
10676 OO
.ui
.BarToolGroup
= function OoUiBarToolGroup( toolbar
, config
) {
10677 // Allow passing positional parameters inside the config object
10678 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
10680 toolbar
= config
.toolbar
;
10683 // Parent constructor
10684 OO
.ui
.BarToolGroup
.parent
.call( this, toolbar
, config
);
10687 this.$element
.addClass( 'oo-ui-barToolGroup' );
10692 OO
.inheritClass( OO
.ui
.BarToolGroup
, OO
.ui
.ToolGroup
);
10694 /* Static Properties */
10696 OO
.ui
.BarToolGroup
.static.titleTooltips
= true;
10698 OO
.ui
.BarToolGroup
.static.accelTooltips
= true;
10700 OO
.ui
.BarToolGroup
.static.name
= 'bar';
10703 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
10704 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
10705 * optional icon and label. This class can be used for other base classes that also use this functionality.
10709 * @extends OO.ui.ToolGroup
10710 * @mixins OO.ui.mixin.IconElement
10711 * @mixins OO.ui.mixin.IndicatorElement
10712 * @mixins OO.ui.mixin.LabelElement
10713 * @mixins OO.ui.mixin.TitledElement
10714 * @mixins OO.ui.mixin.ClippableElement
10715 * @mixins OO.ui.mixin.TabIndexedElement
10718 * @param {OO.ui.Toolbar} toolbar
10719 * @param {Object} [config] Configuration options
10720 * @cfg {string} [header] Text to display at the top of the popup
10722 OO
.ui
.PopupToolGroup
= function OoUiPopupToolGroup( toolbar
, config
) {
10723 // Allow passing positional parameters inside the config object
10724 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
10726 toolbar
= config
.toolbar
;
10729 // Configuration initialization
10730 config
= config
|| {};
10732 // Parent constructor
10733 OO
.ui
.PopupToolGroup
.parent
.call( this, toolbar
, config
);
10736 this.active
= false;
10737 this.dragging
= false;
10738 this.onBlurHandler
= this.onBlur
.bind( this );
10739 this.$handle
= $( '<span>' );
10741 // Mixin constructors
10742 OO
.ui
.mixin
.IconElement
.call( this, config
);
10743 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
10744 OO
.ui
.mixin
.LabelElement
.call( this, config
);
10745 OO
.ui
.mixin
.TitledElement
.call( this, config
);
10746 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
10747 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
10751 keydown
: this.onHandleMouseKeyDown
.bind( this ),
10752 keyup
: this.onHandleMouseKeyUp
.bind( this ),
10753 mousedown
: this.onHandleMouseKeyDown
.bind( this ),
10754 mouseup
: this.onHandleMouseKeyUp
.bind( this )
10759 .addClass( 'oo-ui-popupToolGroup-handle' )
10760 .append( this.$icon
, this.$label
, this.$indicator
);
10761 // If the pop-up should have a header, add it to the top of the toolGroup.
10762 // Note: If this feature is useful for other widgets, we could abstract it into an
10763 // OO.ui.HeaderedElement mixin constructor.
10764 if ( config
.header
!== undefined ) {
10766 .prepend( $( '<span>' )
10767 .addClass( 'oo-ui-popupToolGroup-header' )
10768 .text( config
.header
)
10772 .addClass( 'oo-ui-popupToolGroup' )
10773 .prepend( this.$handle
);
10778 OO
.inheritClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ToolGroup
);
10779 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.IconElement
);
10780 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.IndicatorElement
);
10781 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.LabelElement
);
10782 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.TitledElement
);
10783 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.ClippableElement
);
10784 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.TabIndexedElement
);
10791 OO
.ui
.PopupToolGroup
.prototype.setDisabled = function () {
10793 OO
.ui
.PopupToolGroup
.parent
.prototype.setDisabled
.apply( this, arguments
);
10795 if ( this.isDisabled() && this.isElementAttached() ) {
10796 this.setActive( false );
10801 * Handle focus being lost.
10803 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
10806 * @param {jQuery.Event} e Mouse up or key up event
10808 OO
.ui
.PopupToolGroup
.prototype.onBlur = function ( e
) {
10809 // Only deactivate when clicking outside the dropdown element
10810 if ( $( e
.target
).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element
[ 0 ] ) {
10811 this.setActive( false );
10818 OO
.ui
.PopupToolGroup
.prototype.onMouseKeyUp = function ( e
) {
10819 // Only close toolgroup when a tool was actually selected
10821 !this.isDisabled() && this.pressed
&& this.pressed
=== this.getTargetTool( e
) &&
10822 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
10824 this.setActive( false );
10826 return OO
.ui
.PopupToolGroup
.parent
.prototype.onMouseKeyUp
.call( this, e
);
10830 * Handle mouse up and key up events.
10833 * @param {jQuery.Event} e Mouse up or key up event
10835 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyUp = function ( e
) {
10837 !this.isDisabled() &&
10838 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
10845 * Handle mouse down and key down events.
10848 * @param {jQuery.Event} e Mouse down or key down event
10850 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyDown = function ( e
) {
10852 !this.isDisabled() &&
10853 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
10855 this.setActive( !this.active
);
10861 * Switch into 'active' mode.
10863 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
10866 OO
.ui
.PopupToolGroup
.prototype.setActive = function ( value
) {
10868 if ( this.active
!== value
) {
10869 this.active
= value
;
10871 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler
, true );
10872 this.getElementDocument().addEventListener( 'keyup', this.onBlurHandler
, true );
10874 // Try anchoring the popup to the left first
10875 this.$element
.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
10876 this.toggleClipping( true );
10877 if ( this.isClippedHorizontally() ) {
10878 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
10879 this.toggleClipping( false );
10881 .removeClass( 'oo-ui-popupToolGroup-left' )
10882 .addClass( 'oo-ui-popupToolGroup-right' );
10883 this.toggleClipping( true );
10886 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler
, true );
10887 this.getElementDocument().removeEventListener( 'keyup', this.onBlurHandler
, true );
10888 this.$element
.removeClass(
10889 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
10891 this.toggleClipping( false );
10897 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
10898 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
10899 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
10900 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
10901 * with a label, icon, indicator, header, and title.
10903 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
10904 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
10905 * users to collapse the list again.
10907 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
10908 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
10909 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
10912 * // Example of a ListToolGroup
10913 * var toolFactory = new OO.ui.ToolFactory();
10914 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
10915 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
10917 * // Configure and register two tools
10918 * function SettingsTool() {
10919 * SettingsTool.parent.apply( this, arguments );
10921 * OO.inheritClass( SettingsTool, OO.ui.Tool );
10922 * SettingsTool.static.name = 'settings';
10923 * SettingsTool.static.icon = 'settings';
10924 * SettingsTool.static.title = 'Change settings';
10925 * SettingsTool.prototype.onSelect = function () {
10926 * this.setActive( false );
10928 * toolFactory.register( SettingsTool );
10929 * // Register two more tools, nothing interesting here
10930 * function StuffTool() {
10931 * StuffTool.parent.apply( this, arguments );
10933 * OO.inheritClass( StuffTool, OO.ui.Tool );
10934 * StuffTool.static.name = 'stuff';
10935 * StuffTool.static.icon = 'ellipsis';
10936 * StuffTool.static.title = 'Change the world';
10937 * StuffTool.prototype.onSelect = function () {
10938 * this.setActive( false );
10940 * toolFactory.register( StuffTool );
10943 * // Configurations for list toolgroup.
10945 * label: 'ListToolGroup',
10946 * indicator: 'down',
10948 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
10949 * header: 'This is the header',
10950 * include: [ 'settings', 'stuff' ],
10951 * allowCollapse: ['stuff']
10955 * // Create some UI around the toolbar and place it in the document
10956 * var frame = new OO.ui.PanelLayout( {
10960 * frame.$element.append(
10963 * $( 'body' ).append( frame.$element );
10964 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
10965 * toolbar.initialize();
10967 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
10969 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
10972 * @extends OO.ui.PopupToolGroup
10975 * @param {OO.ui.Toolbar} toolbar
10976 * @param {Object} [config] Configuration options
10977 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
10978 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
10979 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
10980 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
10981 * To open a collapsible list in its expanded state, set #expanded to 'true'.
10982 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
10983 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
10984 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
10985 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
10986 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
10988 OO
.ui
.ListToolGroup
= function OoUiListToolGroup( toolbar
, config
) {
10989 // Allow passing positional parameters inside the config object
10990 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
10992 toolbar
= config
.toolbar
;
10995 // Configuration initialization
10996 config
= config
|| {};
10998 // Properties (must be set before parent constructor, which calls #populate)
10999 this.allowCollapse
= config
.allowCollapse
;
11000 this.forceExpand
= config
.forceExpand
;
11001 this.expanded
= config
.expanded
!== undefined ? config
.expanded
: false;
11002 this.collapsibleTools
= [];
11004 // Parent constructor
11005 OO
.ui
.ListToolGroup
.parent
.call( this, toolbar
, config
);
11008 this.$element
.addClass( 'oo-ui-listToolGroup' );
11013 OO
.inheritClass( OO
.ui
.ListToolGroup
, OO
.ui
.PopupToolGroup
);
11015 /* Static Properties */
11017 OO
.ui
.ListToolGroup
.static.name
= 'list';
11024 OO
.ui
.ListToolGroup
.prototype.populate = function () {
11025 var i
, len
, allowCollapse
= [];
11027 OO
.ui
.ListToolGroup
.parent
.prototype.populate
.call( this );
11029 // Update the list of collapsible tools
11030 if ( this.allowCollapse
!== undefined ) {
11031 allowCollapse
= this.allowCollapse
;
11032 } else if ( this.forceExpand
!== undefined ) {
11033 allowCollapse
= OO
.simpleArrayDifference( Object
.keys( this.tools
), this.forceExpand
);
11036 this.collapsibleTools
= [];
11037 for ( i
= 0, len
= allowCollapse
.length
; i
< len
; i
++ ) {
11038 if ( this.tools
[ allowCollapse
[ i
] ] !== undefined ) {
11039 this.collapsibleTools
.push( this.tools
[ allowCollapse
[ i
] ] );
11043 // Keep at the end, even when tools are added
11044 this.$group
.append( this.getExpandCollapseTool().$element
);
11046 this.getExpandCollapseTool().toggle( this.collapsibleTools
.length
!== 0 );
11047 this.updateCollapsibleState();
11050 OO
.ui
.ListToolGroup
.prototype.getExpandCollapseTool = function () {
11051 if ( this.expandCollapseTool
=== undefined ) {
11052 var ExpandCollapseTool = function () {
11053 ExpandCollapseTool
.parent
.apply( this, arguments
);
11056 OO
.inheritClass( ExpandCollapseTool
, OO
.ui
.Tool
);
11058 ExpandCollapseTool
.prototype.onSelect = function () {
11059 this.toolGroup
.expanded
= !this.toolGroup
.expanded
;
11060 this.toolGroup
.updateCollapsibleState();
11061 this.setActive( false );
11063 ExpandCollapseTool
.prototype.onUpdateState = function () {
11064 // Do nothing. Tool interface requires an implementation of this function.
11067 ExpandCollapseTool
.static.name
= 'more-fewer';
11069 this.expandCollapseTool
= new ExpandCollapseTool( this );
11071 return this.expandCollapseTool
;
11077 OO
.ui
.ListToolGroup
.prototype.onMouseKeyUp = function ( e
) {
11078 // Do not close the popup when the user wants to show more/fewer tools
11080 $( e
.target
).closest( '.oo-ui-tool-name-more-fewer' ).length
&&
11081 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11083 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
11084 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
11085 return OO
.ui
.ListToolGroup
.parent
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11087 return OO
.ui
.ListToolGroup
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11091 OO
.ui
.ListToolGroup
.prototype.updateCollapsibleState = function () {
11094 this.getExpandCollapseTool()
11095 .setIcon( this.expanded
? 'collapse' : 'expand' )
11096 .setTitle( OO
.ui
.msg( this.expanded
? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
11098 for ( i
= 0, len
= this.collapsibleTools
.length
; i
< len
; i
++ ) {
11099 this.collapsibleTools
[ i
].toggle( this.expanded
);
11104 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11105 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
11106 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
11107 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
11108 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
11109 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
11111 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
11112 * is set up. Note that all tools must define an {@link OO.ui.Tool#onUpdateState onUpdateState} method if
11113 * a MenuToolGroup is used.
11116 * // Example of a MenuToolGroup
11117 * var toolFactory = new OO.ui.ToolFactory();
11118 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11119 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11121 * // We will be placing status text in this element when tools are used
11122 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
11124 * // Define the tools that we're going to place in our toolbar
11126 * function SettingsTool() {
11127 * SettingsTool.parent.apply( this, arguments );
11128 * this.reallyActive = false;
11130 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11131 * SettingsTool.static.name = 'settings';
11132 * SettingsTool.static.icon = 'settings';
11133 * SettingsTool.static.title = 'Change settings';
11134 * SettingsTool.prototype.onSelect = function () {
11135 * $area.text( 'Settings tool clicked!' );
11136 * // Toggle the active state on each click
11137 * this.reallyActive = !this.reallyActive;
11138 * this.setActive( this.reallyActive );
11139 * // To update the menu label
11140 * this.toolbar.emit( 'updateState' );
11142 * SettingsTool.prototype.onUpdateState = function () {
11144 * toolFactory.register( SettingsTool );
11146 * function StuffTool() {
11147 * StuffTool.parent.apply( this, arguments );
11148 * this.reallyActive = false;
11150 * OO.inheritClass( StuffTool, OO.ui.Tool );
11151 * StuffTool.static.name = 'stuff';
11152 * StuffTool.static.icon = 'ellipsis';
11153 * StuffTool.static.title = 'More stuff';
11154 * StuffTool.prototype.onSelect = function () {
11155 * $area.text( 'More stuff tool clicked!' );
11156 * // Toggle the active state on each click
11157 * this.reallyActive = !this.reallyActive;
11158 * this.setActive( this.reallyActive );
11159 * // To update the menu label
11160 * this.toolbar.emit( 'updateState' );
11162 * StuffTool.prototype.onUpdateState = function () {
11164 * toolFactory.register( StuffTool );
11166 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11167 * // used once (but not all defined tools must be used).
11171 * header: 'This is the (optional) header',
11172 * title: 'This is the (optional) title',
11173 * indicator: 'down',
11174 * include: [ 'settings', 'stuff' ]
11178 * // Create some UI around the toolbar and place it in the document
11179 * var frame = new OO.ui.PanelLayout( {
11183 * var contentFrame = new OO.ui.PanelLayout( {
11187 * frame.$element.append(
11188 * toolbar.$element,
11189 * contentFrame.$element.append( $area )
11191 * $( 'body' ).append( frame.$element );
11193 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11195 * toolbar.initialize();
11196 * toolbar.emit( 'updateState' );
11198 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11199 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
11201 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11204 * @extends OO.ui.PopupToolGroup
11207 * @param {OO.ui.Toolbar} toolbar
11208 * @param {Object} [config] Configuration options
11210 OO
.ui
.MenuToolGroup
= function OoUiMenuToolGroup( toolbar
, config
) {
11211 // Allow passing positional parameters inside the config object
11212 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11214 toolbar
= config
.toolbar
;
11217 // Configuration initialization
11218 config
= config
|| {};
11220 // Parent constructor
11221 OO
.ui
.MenuToolGroup
.parent
.call( this, toolbar
, config
);
11224 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
11227 this.$element
.addClass( 'oo-ui-menuToolGroup' );
11232 OO
.inheritClass( OO
.ui
.MenuToolGroup
, OO
.ui
.PopupToolGroup
);
11234 /* Static Properties */
11236 OO
.ui
.MenuToolGroup
.static.name
= 'menu';
11241 * Handle the toolbar state being updated.
11243 * When the state changes, the title of each active item in the menu will be joined together and
11244 * used as a label for the group. The label will be empty if none of the items are active.
11248 OO
.ui
.MenuToolGroup
.prototype.onUpdateState = function () {
11252 for ( name
in this.tools
) {
11253 if ( this.tools
[ name
].isActive() ) {
11254 labelTexts
.push( this.tools
[ name
].getTitle() );
11258 this.setLabel( labelTexts
.join( ', ' ) || ' ' );
11262 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
11263 * 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
11264 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
11266 * // Example of a popup tool. When selected, a popup tool displays
11267 * // a popup window.
11268 * function HelpTool( toolGroup, config ) {
11269 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11274 * this.popup.$body.append( '<p>I am helpful!</p>' );
11276 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11277 * HelpTool.static.name = 'help';
11278 * HelpTool.static.icon = 'help';
11279 * HelpTool.static.title = 'Help';
11280 * toolFactory.register( HelpTool );
11282 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
11283 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
11285 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11289 * @extends OO.ui.Tool
11290 * @mixins OO.ui.mixin.PopupElement
11293 * @param {OO.ui.ToolGroup} toolGroup
11294 * @param {Object} [config] Configuration options
11296 OO
.ui
.PopupTool
= function OoUiPopupTool( toolGroup
, config
) {
11297 // Allow passing positional parameters inside the config object
11298 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
11299 config
= toolGroup
;
11300 toolGroup
= config
.toolGroup
;
11303 // Parent constructor
11304 OO
.ui
.PopupTool
.parent
.call( this, toolGroup
, config
);
11306 // Mixin constructors
11307 OO
.ui
.mixin
.PopupElement
.call( this, config
);
11311 .addClass( 'oo-ui-popupTool' )
11312 .append( this.popup
.$element
);
11317 OO
.inheritClass( OO
.ui
.PopupTool
, OO
.ui
.Tool
);
11318 OO
.mixinClass( OO
.ui
.PopupTool
, OO
.ui
.mixin
.PopupElement
);
11323 * Handle the tool being selected.
11327 OO
.ui
.PopupTool
.prototype.onSelect = function () {
11328 if ( !this.isDisabled() ) {
11329 this.popup
.toggle();
11331 this.setActive( false );
11336 * Handle the toolbar state being updated.
11340 OO
.ui
.PopupTool
.prototype.onUpdateState = function () {
11341 this.setActive( false );
11345 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
11346 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
11347 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
11348 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
11349 * when the ToolGroupTool is selected.
11351 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
11353 * function SettingsTool() {
11354 * SettingsTool.parent.apply( this, arguments );
11356 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
11357 * SettingsTool.static.name = 'settings';
11358 * SettingsTool.static.title = 'Change settings';
11359 * SettingsTool.static.groupConfig = {
11360 * icon: 'settings',
11361 * label: 'ToolGroupTool',
11362 * include: [ 'setting1', 'setting2' ]
11364 * toolFactory.register( SettingsTool );
11366 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
11368 * Please note that this implementation is subject to change per [T74159] [2].
11370 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
11371 * [2]: https://phabricator.wikimedia.org/T74159
11375 * @extends OO.ui.Tool
11378 * @param {OO.ui.ToolGroup} toolGroup
11379 * @param {Object} [config] Configuration options
11381 OO
.ui
.ToolGroupTool
= function OoUiToolGroupTool( toolGroup
, config
) {
11382 // Allow passing positional parameters inside the config object
11383 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
11384 config
= toolGroup
;
11385 toolGroup
= config
.toolGroup
;
11388 // Parent constructor
11389 OO
.ui
.ToolGroupTool
.parent
.call( this, toolGroup
, config
);
11392 this.innerToolGroup
= this.createGroup( this.constructor.static.groupConfig
);
11395 this.innerToolGroup
.connect( this, { disable
: 'onToolGroupDisable' } );
11398 this.$link
.remove();
11400 .addClass( 'oo-ui-toolGroupTool' )
11401 .append( this.innerToolGroup
.$element
);
11406 OO
.inheritClass( OO
.ui
.ToolGroupTool
, OO
.ui
.Tool
);
11408 /* Static Properties */
11411 * Toolgroup configuration.
11413 * The toolgroup configuration consists of the tools to include, as well as an icon and label
11414 * to use for the bar item. Tools can be included by symbolic name, group, or with the
11415 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
11417 * @property {Object.<string,Array>}
11419 OO
.ui
.ToolGroupTool
.static.groupConfig
= {};
11424 * Handle the tool being selected.
11428 OO
.ui
.ToolGroupTool
.prototype.onSelect = function () {
11429 this.innerToolGroup
.setActive( !this.innerToolGroup
.active
);
11434 * Synchronize disabledness state of the tool with the inner toolgroup.
11437 * @param {boolean} disabled Element is disabled
11439 OO
.ui
.ToolGroupTool
.prototype.onToolGroupDisable = function ( disabled
) {
11440 this.setDisabled( disabled
);
11444 * Handle the toolbar state being updated.
11448 OO
.ui
.ToolGroupTool
.prototype.onUpdateState = function () {
11449 this.setActive( false );
11453 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
11455 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
11456 * more information.
11457 * @return {OO.ui.ListToolGroup}
11459 OO
.ui
.ToolGroupTool
.prototype.createGroup = function ( group
) {
11460 if ( group
.include
=== '*' ) {
11461 // Apply defaults to catch-all groups
11462 if ( group
.label
=== undefined ) {
11463 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
11467 return this.toolbar
.getToolGroupFactory().create( 'list', this.toolbar
, group
);
11471 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
11473 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
11478 * @extends OO.ui.mixin.GroupElement
11481 * @param {Object} [config] Configuration options
11483 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
11484 // Parent constructor
11485 OO
.ui
.mixin
.GroupWidget
.parent
.call( this, config
);
11490 OO
.inheritClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
11495 * Set the disabled state of the widget.
11497 * This will also update the disabled state of child widgets.
11499 * @param {boolean} disabled Disable widget
11502 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
11506 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
11507 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
11509 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
11510 if ( this.items
) {
11511 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
11512 this.items
[ i
].updateDisabled();
11520 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
11522 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
11523 * allows bidirectional communication.
11525 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
11533 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
11540 * Check if widget is disabled.
11542 * Checks parent if present, making disabled state inheritable.
11544 * @return {boolean} Widget is disabled
11546 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
11547 return this.disabled
||
11548 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
11552 * Set group element is in.
11554 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
11557 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
11559 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
11560 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
11562 // Initialize item disabled states
11563 this.updateDisabled();
11569 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
11570 * Controls include moving items up and down, removing items, and adding different kinds of items.
11572 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
11575 * @extends OO.ui.Widget
11576 * @mixins OO.ui.mixin.GroupElement
11577 * @mixins OO.ui.mixin.IconElement
11580 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
11581 * @param {Object} [config] Configuration options
11582 * @cfg {Object} [abilities] List of abilties
11583 * @cfg {boolean} [abilities.move=true] Allow moving movable items
11584 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
11586 OO
.ui
.OutlineControlsWidget
= function OoUiOutlineControlsWidget( outline
, config
) {
11587 // Allow passing positional parameters inside the config object
11588 if ( OO
.isPlainObject( outline
) && config
=== undefined ) {
11590 outline
= config
.outline
;
11593 // Configuration initialization
11594 config
= $.extend( { icon
: 'add' }, config
);
11596 // Parent constructor
11597 OO
.ui
.OutlineControlsWidget
.parent
.call( this, config
);
11599 // Mixin constructors
11600 OO
.ui
.mixin
.GroupElement
.call( this, config
);
11601 OO
.ui
.mixin
.IconElement
.call( this, config
);
11604 this.outline
= outline
;
11605 this.$movers
= $( '<div>' );
11606 this.upButton
= new OO
.ui
.ButtonWidget( {
11609 title
: OO
.ui
.msg( 'ooui-outline-control-move-up' )
11611 this.downButton
= new OO
.ui
.ButtonWidget( {
11614 title
: OO
.ui
.msg( 'ooui-outline-control-move-down' )
11616 this.removeButton
= new OO
.ui
.ButtonWidget( {
11619 title
: OO
.ui
.msg( 'ooui-outline-control-remove' )
11621 this.abilities
= { move: true, remove
: true };
11624 outline
.connect( this, {
11625 select
: 'onOutlineChange',
11626 add
: 'onOutlineChange',
11627 remove
: 'onOutlineChange'
11629 this.upButton
.connect( this, { click
: [ 'emit', 'move', -1 ] } );
11630 this.downButton
.connect( this, { click
: [ 'emit', 'move', 1 ] } );
11631 this.removeButton
.connect( this, { click
: [ 'emit', 'remove' ] } );
11634 this.$element
.addClass( 'oo-ui-outlineControlsWidget' );
11635 this.$group
.addClass( 'oo-ui-outlineControlsWidget-items' );
11637 .addClass( 'oo-ui-outlineControlsWidget-movers' )
11638 .append( this.removeButton
.$element
, this.upButton
.$element
, this.downButton
.$element
);
11639 this.$element
.append( this.$icon
, this.$group
, this.$movers
);
11640 this.setAbilities( config
.abilities
|| {} );
11645 OO
.inheritClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.Widget
);
11646 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.GroupElement
);
11647 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.IconElement
);
11653 * @param {number} places Number of places to move
11665 * @param {Object} abilities List of abilties
11666 * @param {boolean} [abilities.move] Allow moving movable items
11667 * @param {boolean} [abilities.remove] Allow removing removable items
11669 OO
.ui
.OutlineControlsWidget
.prototype.setAbilities = function ( abilities
) {
11672 for ( ability
in this.abilities
) {
11673 if ( abilities
[ability
] !== undefined ) {
11674 this.abilities
[ability
] = !!abilities
[ability
];
11678 this.onOutlineChange();
11684 * Handle outline change events.
11686 OO
.ui
.OutlineControlsWidget
.prototype.onOutlineChange = function () {
11687 var i
, len
, firstMovable
, lastMovable
,
11688 items
= this.outline
.getItems(),
11689 selectedItem
= this.outline
.getSelectedItem(),
11690 movable
= this.abilities
.move && selectedItem
&& selectedItem
.isMovable(),
11691 removable
= this.abilities
.remove
&& selectedItem
&& selectedItem
.isRemovable();
11695 len
= items
.length
;
11696 while ( ++i
< len
) {
11697 if ( items
[ i
].isMovable() ) {
11698 firstMovable
= items
[ i
];
11704 if ( items
[ i
].isMovable() ) {
11705 lastMovable
= items
[ i
];
11710 this.upButton
.setDisabled( !movable
|| selectedItem
=== firstMovable
);
11711 this.downButton
.setDisabled( !movable
|| selectedItem
=== lastMovable
);
11712 this.removeButton
.setDisabled( !removable
);
11716 * ToggleWidget implements basic behavior of widgets with an on/off state.
11717 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
11721 * @extends OO.ui.Widget
11724 * @param {Object} [config] Configuration options
11725 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
11726 * By default, the toggle is in the 'off' state.
11728 OO
.ui
.ToggleWidget
= function OoUiToggleWidget( config
) {
11729 // Configuration initialization
11730 config
= config
|| {};
11732 // Parent constructor
11733 OO
.ui
.ToggleWidget
.parent
.call( this, config
);
11739 this.$element
.addClass( 'oo-ui-toggleWidget' );
11740 this.setValue( !!config
.value
);
11745 OO
.inheritClass( OO
.ui
.ToggleWidget
, OO
.ui
.Widget
);
11752 * A change event is emitted when the on/off state of the toggle changes.
11754 * @param {boolean} value Value representing the new state of the toggle
11760 * Get the value representing the toggle’s state.
11762 * @return {boolean} The on/off state of the toggle
11764 OO
.ui
.ToggleWidget
.prototype.getValue = function () {
11769 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
11771 * @param {boolean} value The state of the toggle
11775 OO
.ui
.ToggleWidget
.prototype.setValue = function ( value
) {
11777 if ( this.value
!== value
) {
11778 this.value
= value
;
11779 this.emit( 'change', value
);
11780 this.$element
.toggleClass( 'oo-ui-toggleWidget-on', value
);
11781 this.$element
.toggleClass( 'oo-ui-toggleWidget-off', !value
);
11782 this.$element
.attr( 'aria-checked', value
.toString() );
11788 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
11789 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
11790 * removed, and cleared from the group.
11793 * // Example: A ButtonGroupWidget with two buttons
11794 * var button1 = new OO.ui.PopupButtonWidget( {
11795 * label: 'Select a category',
11798 * $content: $( '<p>List of categories...</p>' ),
11803 * var button2 = new OO.ui.ButtonWidget( {
11804 * label: 'Add item'
11806 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
11807 * items: [button1, button2]
11809 * $( 'body' ).append( buttonGroup.$element );
11812 * @extends OO.ui.Widget
11813 * @mixins OO.ui.mixin.GroupElement
11816 * @param {Object} [config] Configuration options
11817 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
11819 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
11820 // Configuration initialization
11821 config
= config
|| {};
11823 // Parent constructor
11824 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
11826 // Mixin constructors
11827 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11830 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
11831 if ( Array
.isArray( config
.items
) ) {
11832 this.addItems( config
.items
);
11838 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
11839 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
11842 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
11843 * feels, and functionality can be customized via the class’s configuration options
11844 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
11847 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
11850 * // A button widget
11851 * var button = new OO.ui.ButtonWidget( {
11852 * label: 'Button with Icon',
11854 * iconTitle: 'Remove'
11856 * $( 'body' ).append( button.$element );
11858 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
11861 * @extends OO.ui.Widget
11862 * @mixins OO.ui.mixin.ButtonElement
11863 * @mixins OO.ui.mixin.IconElement
11864 * @mixins OO.ui.mixin.IndicatorElement
11865 * @mixins OO.ui.mixin.LabelElement
11866 * @mixins OO.ui.mixin.TitledElement
11867 * @mixins OO.ui.mixin.FlaggedElement
11868 * @mixins OO.ui.mixin.TabIndexedElement
11871 * @param {Object} [config] Configuration options
11872 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
11873 * @cfg {string} [target] The frame or window in which to open the hyperlink.
11874 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
11876 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
11877 // Configuration initialization
11878 config
= config
|| {};
11880 // Parent constructor
11881 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
11883 // Mixin constructors
11884 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
11885 OO
.ui
.mixin
.IconElement
.call( this, config
);
11886 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
11887 OO
.ui
.mixin
.LabelElement
.call( this, config
);
11888 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
11889 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
11890 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
11894 this.target
= null;
11895 this.noFollow
= false;
11898 this.connect( this, { disable
: 'onDisable' } );
11901 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
11903 .addClass( 'oo-ui-buttonWidget' )
11904 .append( this.$button
);
11905 this.setHref( config
.href
);
11906 this.setTarget( config
.target
);
11907 this.setNoFollow( config
.noFollow
);
11912 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
11913 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
11914 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
11915 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
11916 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
11917 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
11918 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
11919 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
11926 OO
.ui
.ButtonWidget
.prototype.onMouseDown = function ( e
) {
11927 if ( !this.isDisabled() ) {
11928 // Remove the tab-index while the button is down to prevent the button from stealing focus
11929 this.$button
.removeAttr( 'tabindex' );
11932 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown
.call( this, e
);
11938 OO
.ui
.ButtonWidget
.prototype.onMouseUp = function ( e
) {
11939 if ( !this.isDisabled() ) {
11940 // Restore the tab-index after the button is up to restore the button's accessibility
11941 this.$button
.attr( 'tabindex', this.tabIndex
);
11944 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp
.call( this, e
);
11948 * Get hyperlink location.
11950 * @return {string} Hyperlink location
11952 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
11957 * Get hyperlink target.
11959 * @return {string} Hyperlink target
11961 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
11962 return this.target
;
11966 * Get search engine traversal hint.
11968 * @return {boolean} Whether search engines should avoid traversing this hyperlink
11970 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
11971 return this.noFollow
;
11975 * Set hyperlink location.
11977 * @param {string|null} href Hyperlink location, null to remove
11979 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
11980 href
= typeof href
=== 'string' ? href
: null;
11982 if ( href
!== this.href
) {
11991 * Update the `href` attribute, in case of changes to href or
11997 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
11998 if ( this.href
!== null && !this.isDisabled() ) {
11999 this.$button
.attr( 'href', this.href
);
12001 this.$button
.removeAttr( 'href' );
12008 * Handle disable events.
12011 * @param {boolean} disabled Element is disabled
12013 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
12018 * Set hyperlink target.
12020 * @param {string|null} target Hyperlink target, null to remove
12022 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
12023 target
= typeof target
=== 'string' ? target
: null;
12025 if ( target
!== this.target
) {
12026 this.target
= target
;
12027 if ( target
!== null ) {
12028 this.$button
.attr( 'target', target
);
12030 this.$button
.removeAttr( 'target' );
12038 * Set search engine traversal hint.
12040 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
12042 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
12043 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
12045 if ( noFollow
!== this.noFollow
) {
12046 this.noFollow
= noFollow
;
12048 this.$button
.attr( 'rel', 'nofollow' );
12050 this.$button
.removeAttr( 'rel' );
12058 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
12059 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
12062 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
12063 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12066 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
12069 * @extends OO.ui.ButtonWidget
12070 * @mixins OO.ui.mixin.PendingElement
12073 * @param {Object} [config] Configuration options
12074 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12075 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
12076 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
12077 * for more information about setting modes.
12078 * @cfg {boolean} [framed=false] Render the action button with a frame
12080 OO
.ui
.ActionWidget
= function OoUiActionWidget( config
) {
12081 // Configuration initialization
12082 config
= $.extend( { framed
: false }, config
);
12084 // Parent constructor
12085 OO
.ui
.ActionWidget
.parent
.call( this, config
);
12087 // Mixin constructors
12088 OO
.ui
.mixin
.PendingElement
.call( this, config
);
12091 this.action
= config
.action
|| '';
12092 this.modes
= config
.modes
|| [];
12097 this.$element
.addClass( 'oo-ui-actionWidget' );
12102 OO
.inheritClass( OO
.ui
.ActionWidget
, OO
.ui
.ButtonWidget
);
12103 OO
.mixinClass( OO
.ui
.ActionWidget
, OO
.ui
.mixin
.PendingElement
);
12108 * A resize event is emitted when the size of the widget changes.
12116 * Check if the action is configured to be available in the specified `mode`.
12118 * @param {string} mode Name of mode
12119 * @return {boolean} The action is configured with the mode
12121 OO
.ui
.ActionWidget
.prototype.hasMode = function ( mode
) {
12122 return this.modes
.indexOf( mode
) !== -1;
12126 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12130 OO
.ui
.ActionWidget
.prototype.getAction = function () {
12131 return this.action
;
12135 * Get the symbolic name of the mode or modes for which the action is configured to be available.
12137 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
12138 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
12141 * @return {string[]}
12143 OO
.ui
.ActionWidget
.prototype.getModes = function () {
12144 return this.modes
.slice();
12148 * Emit a resize event if the size has changed.
12153 OO
.ui
.ActionWidget
.prototype.propagateResize = function () {
12156 if ( this.isElementAttached() ) {
12157 width
= this.$element
.width();
12158 height
= this.$element
.height();
12160 if ( width
!== this.width
|| height
!== this.height
) {
12161 this.width
= width
;
12162 this.height
= height
;
12163 this.emit( 'resize' );
12173 OO
.ui
.ActionWidget
.prototype.setIcon = function () {
12175 OO
.ui
.mixin
.IconElement
.prototype.setIcon
.apply( this, arguments
);
12176 this.propagateResize();
12184 OO
.ui
.ActionWidget
.prototype.setLabel = function () {
12186 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.apply( this, arguments
);
12187 this.propagateResize();
12195 OO
.ui
.ActionWidget
.prototype.setFlags = function () {
12197 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags
.apply( this, arguments
);
12198 this.propagateResize();
12206 OO
.ui
.ActionWidget
.prototype.clearFlags = function () {
12208 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags
.apply( this, arguments
);
12209 this.propagateResize();
12215 * Toggle the visibility of the action button.
12217 * @param {boolean} [show] Show button, omit to toggle visibility
12220 OO
.ui
.ActionWidget
.prototype.toggle = function () {
12222 OO
.ui
.ActionWidget
.parent
.prototype.toggle
.apply( this, arguments
);
12223 this.propagateResize();
12229 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
12230 * which is used to display additional information or options.
12233 * // Example of a popup button.
12234 * var popupButton = new OO.ui.PopupButtonWidget( {
12235 * label: 'Popup button with options',
12238 * $content: $( '<p>Additional options here.</p>' ),
12240 * align: 'force-left'
12243 * // Append the button to the DOM.
12244 * $( 'body' ).append( popupButton.$element );
12247 * @extends OO.ui.ButtonWidget
12248 * @mixins OO.ui.mixin.PopupElement
12251 * @param {Object} [config] Configuration options
12253 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
12254 // Parent constructor
12255 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
12257 // Mixin constructors
12258 OO
.ui
.mixin
.PopupElement
.call( this, config
);
12261 this.connect( this, { click
: 'onAction' } );
12265 .addClass( 'oo-ui-popupButtonWidget' )
12266 .attr( 'aria-haspopup', 'true' )
12267 .append( this.popup
.$element
);
12272 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
12273 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
12278 * Handle the button action being triggered.
12282 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
12283 this.popup
.toggle();
12287 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
12288 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
12289 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
12290 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
12291 * and {@link OO.ui.mixin.LabelElement labels}. Please see
12292 * the [OOjs UI documentation][1] on MediaWiki for more information.
12295 * // Toggle buttons in the 'off' and 'on' state.
12296 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
12297 * label: 'Toggle Button off'
12299 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
12300 * label: 'Toggle Button on',
12303 * // Append the buttons to the DOM.
12304 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
12306 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
12309 * @extends OO.ui.ToggleWidget
12310 * @mixins OO.ui.mixin.ButtonElement
12311 * @mixins OO.ui.mixin.IconElement
12312 * @mixins OO.ui.mixin.IndicatorElement
12313 * @mixins OO.ui.mixin.LabelElement
12314 * @mixins OO.ui.mixin.TitledElement
12315 * @mixins OO.ui.mixin.FlaggedElement
12316 * @mixins OO.ui.mixin.TabIndexedElement
12319 * @param {Object} [config] Configuration options
12320 * @cfg {boolean} [value=false] The toggle button’s initial on/off
12321 * state. By default, the button is in the 'off' state.
12323 OO
.ui
.ToggleButtonWidget
= function OoUiToggleButtonWidget( config
) {
12324 // Configuration initialization
12325 config
= config
|| {};
12327 // Parent constructor
12328 OO
.ui
.ToggleButtonWidget
.parent
.call( this, config
);
12330 // Mixin constructors
12331 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
12332 OO
.ui
.mixin
.IconElement
.call( this, config
);
12333 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12334 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12335 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
12336 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
12337 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
12340 this.connect( this, { click
: 'onAction' } );
12343 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
12345 .addClass( 'oo-ui-toggleButtonWidget' )
12346 .append( this.$button
);
12351 OO
.inheritClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ToggleWidget
);
12352 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
12353 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IconElement
);
12354 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
12355 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.LabelElement
);
12356 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TitledElement
);
12357 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
12358 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
12363 * Handle the button action being triggered.
12367 OO
.ui
.ToggleButtonWidget
.prototype.onAction = function () {
12368 this.setValue( !this.value
);
12374 OO
.ui
.ToggleButtonWidget
.prototype.setValue = function ( value
) {
12376 if ( value
!== this.value
) {
12377 // Might be called from parent constructor before ButtonElement constructor
12378 if ( this.$button
) {
12379 this.$button
.attr( 'aria-pressed', value
.toString() );
12381 this.setActive( value
);
12385 OO
.ui
.ToggleButtonWidget
.parent
.prototype.setValue
.call( this, value
);
12393 OO
.ui
.ToggleButtonWidget
.prototype.setButtonElement = function ( $button
) {
12394 if ( this.$button
) {
12395 this.$button
.removeAttr( 'aria-pressed' );
12397 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement
.call( this, $button
);
12398 this.$button
.attr( 'aria-pressed', this.value
.toString() );
12402 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
12403 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
12404 * users can interact with it.
12406 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
12407 * OO.ui.DropdownInputWidget instead.
12410 * // Example: A DropdownWidget with a menu that contains three options
12411 * var dropDown = new OO.ui.DropdownWidget( {
12412 * label: 'Dropdown menu: Select a menu option',
12415 * new OO.ui.MenuOptionWidget( {
12419 * new OO.ui.MenuOptionWidget( {
12423 * new OO.ui.MenuOptionWidget( {
12431 * $( 'body' ).append( dropDown.$element );
12433 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
12435 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12438 * @extends OO.ui.Widget
12439 * @mixins OO.ui.mixin.IconElement
12440 * @mixins OO.ui.mixin.IndicatorElement
12441 * @mixins OO.ui.mixin.LabelElement
12442 * @mixins OO.ui.mixin.TitledElement
12443 * @mixins OO.ui.mixin.TabIndexedElement
12446 * @param {Object} [config] Configuration options
12447 * @cfg {Object} [menu] Configuration options to pass to menu widget
12449 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
12450 // Configuration initialization
12451 config
= $.extend( { indicator
: 'down' }, config
);
12453 // Parent constructor
12454 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
12456 // Properties (must be set before TabIndexedElement constructor call)
12457 this.$handle
= this.$( '<span>' );
12459 // Mixin constructors
12460 OO
.ui
.mixin
.IconElement
.call( this, config
);
12461 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12462 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12463 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
12464 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
12467 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend( { widget
: this }, config
.menu
) );
12471 click
: this.onClick
.bind( this ),
12472 keypress
: this.onKeyPress
.bind( this )
12474 this.menu
.connect( this, { select
: 'onMenuSelect' } );
12478 .addClass( 'oo-ui-dropdownWidget-handle' )
12479 .append( this.$icon
, this.$label
, this.$indicator
);
12481 .addClass( 'oo-ui-dropdownWidget' )
12482 .append( this.$handle
, this.menu
.$element
);
12487 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
12488 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
12489 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
12490 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
12491 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
12492 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
12499 * @return {OO.ui.MenuSelectWidget} Menu of widget
12501 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
12506 * Handles menu select events.
12509 * @param {OO.ui.MenuOptionWidget} item Selected menu item
12511 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
12515 this.setLabel( null );
12519 selectedLabel
= item
.getLabel();
12521 // If the label is a DOM element, clone it, because setLabel will append() it
12522 if ( selectedLabel
instanceof jQuery
) {
12523 selectedLabel
= selectedLabel
.clone();
12526 this.setLabel( selectedLabel
);
12530 * Handle mouse click events.
12533 * @param {jQuery.Event} e Mouse click event
12535 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
12536 if ( !this.isDisabled() && e
.which
=== 1 ) {
12537 this.menu
.toggle();
12543 * Handle key press events.
12546 * @param {jQuery.Event} e Key press event
12548 OO
.ui
.DropdownWidget
.prototype.onKeyPress = function ( e
) {
12549 if ( !this.isDisabled() &&
12550 ( ( e
.which
=== OO
.ui
.Keys
.SPACE
&& !this.menu
.isVisible() ) || e
.which
=== OO
.ui
.Keys
.ENTER
)
12552 this.menu
.toggle();
12558 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
12559 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
12560 * OO.ui.mixin.IndicatorElement indicators}.
12561 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
12564 * // Example of a file select widget
12565 * var selectFile = new OO.ui.SelectFileWidget();
12566 * $( 'body' ).append( selectFile.$element );
12568 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
12571 * @extends OO.ui.Widget
12572 * @mixins OO.ui.mixin.IconElement
12573 * @mixins OO.ui.mixin.IndicatorElement
12574 * @mixins OO.ui.mixin.PendingElement
12575 * @mixins OO.ui.mixin.LabelElement
12576 * @mixins OO.ui.mixin.TabIndexedElement
12579 * @param {Object} [config] Configuration options
12580 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
12581 * @cfg {string} [placeholder] Text to display when no file is selected.
12582 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
12583 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
12585 OO
.ui
.SelectFileWidget
= function OoUiSelectFileWidget( config
) {
12588 // Configuration initialization
12589 config
= $.extend( {
12591 placeholder
: OO
.ui
.msg( 'ooui-selectfile-placeholder' ),
12592 notsupported
: OO
.ui
.msg( 'ooui-selectfile-not-supported' ),
12596 // Parent constructor
12597 OO
.ui
.SelectFileWidget
.parent
.call( this, config
);
12599 // Properties (must be set before TabIndexedElement constructor call)
12600 this.$handle
= $( '<span>' );
12602 // Mixin constructors
12603 OO
.ui
.mixin
.IconElement
.call( this, config
);
12604 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12605 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$handle
} ) );
12606 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { autoFitLabel
: true } ) );
12607 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
12610 this.isSupported
= this.constructor.static.isSupported();
12611 this.currentFile
= null;
12612 if ( Array
.isArray( config
.accept
) ) {
12613 this.accept
= config
.accept
;
12615 this.accept
= null;
12617 this.placeholder
= config
.placeholder
;
12618 this.notsupported
= config
.notsupported
;
12619 this.onFileSelectedHandler
= this.onFileSelected
.bind( this );
12621 this.clearButton
= new OO
.ui
.ButtonWidget( {
12622 classes
: [ 'oo-ui-selectFileWidget-clearButton' ],
12625 disabled
: this.disabled
12630 keypress
: this.onKeyPress
.bind( this )
12632 this.clearButton
.connect( this, {
12633 click
: 'onClearClick'
12635 if ( config
.droppable
) {
12636 dragHandler
= this.onDragEnterOrOver
.bind( this );
12638 dragenter
: dragHandler
,
12639 dragover
: dragHandler
,
12640 dragleave
: this.onDragLeave
.bind( this ),
12641 drop
: this.onDrop
.bind( this )
12648 this.$label
.addClass( 'oo-ui-selectFileWidget-label' );
12650 .addClass( 'oo-ui-selectFileWidget-handle' )
12651 .append( this.$icon
, this.$label
, this.clearButton
.$element
, this.$indicator
);
12653 .addClass( 'oo-ui-selectFileWidget' )
12654 .append( this.$handle
);
12655 if ( config
.droppable
) {
12656 this.$element
.addClass( 'oo-ui-selectFileWidget-droppable' );
12662 OO
.inheritClass( OO
.ui
.SelectFileWidget
, OO
.ui
.Widget
);
12663 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IconElement
);
12664 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IndicatorElement
);
12665 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.PendingElement
);
12666 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.LabelElement
);
12667 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.TabIndexedElement
);
12669 /* Static Properties */
12672 * Check if this widget is supported
12675 * @return {boolean}
12677 OO
.ui
.SelectFileWidget
.static.isSupported = function () {
12679 if ( OO
.ui
.SelectFileWidget
.static.isSupportedCache
=== null ) {
12680 $input
= $( '<input type="file">' );
12681 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= $input
[0].files
!== undefined;
12683 return OO
.ui
.SelectFileWidget
.static.isSupportedCache
;
12686 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= null;
12693 * A change event is emitted when the on/off state of the toggle changes.
12695 * @param {File|null} value New value
12701 * Get the current value of the field
12703 * @return {File|null}
12705 OO
.ui
.SelectFileWidget
.prototype.getValue = function () {
12706 return this.currentFile
;
12710 * Set the current value of the field
12712 * @param {File|null} file File to select
12714 OO
.ui
.SelectFileWidget
.prototype.setValue = function ( file
) {
12715 if ( this.currentFile
!== file
) {
12716 this.currentFile
= file
;
12718 this.emit( 'change', this.currentFile
);
12723 * Update the user interface when a file is selected or unselected
12727 OO
.ui
.SelectFileWidget
.prototype.updateUI = function () {
12728 if ( !this.isSupported
) {
12729 this.$element
.addClass( 'oo-ui-selectFileWidget-notsupported' );
12730 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
12731 this.setLabel( this.notsupported
);
12732 } else if ( this.currentFile
) {
12733 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
12734 this.setLabel( this.currentFile
.name
+
12735 ( this.currentFile
.type
!== '' ? OO
.ui
.msg( 'ooui-semicolon-separator' ) + this.currentFile
.type
: '' )
12738 this.$element
.addClass( 'oo-ui-selectFileWidget-empty' );
12739 this.setLabel( this.placeholder
);
12742 if ( this.$input
) {
12743 this.$input
.attr( 'title', this.getLabel() );
12748 * Add the input to the handle
12752 OO
.ui
.SelectFileWidget
.prototype.addInput = function () {
12753 if ( this.$input
) {
12754 this.$input
.remove();
12757 if ( !this.isSupported
) {
12758 this.$input
= null;
12762 this.$input
= $( '<input type="file">' );
12763 this.$input
.on( 'change', this.onFileSelectedHandler
);
12764 this.$input
.attr( {
12766 title
: this.getLabel()
12768 if ( this.accept
) {
12769 this.$input
.attr( 'accept', this.accept
.join( ', ' ) );
12771 this.$handle
.append( this.$input
);
12775 * Determine if we should accept this file
12778 * @param {File} file
12779 * @return {boolean}
12781 OO
.ui
.SelectFileWidget
.prototype.isFileAcceptable = function ( file
) {
12782 var i
, mime
, mimeTest
;
12784 if ( !this.accept
|| file
.type
=== '' ) {
12789 for ( i
= 0; i
< this.accept
.length
; i
++ ) {
12790 mimeTest
= this.accept
[i
];
12791 if ( mimeTest
=== mime
) {
12793 } else if ( mimeTest
.substr( -2 ) === '/*' ) {
12794 mimeTest
= mimeTest
.substr( 0, mimeTest
.length
- 1 );
12795 if ( mime
.substr( 0, mimeTest
.length
) === mimeTest
) {
12805 * Handle file selection from the input
12808 * @param {jQuery.Event} e
12810 OO
.ui
.SelectFileWidget
.prototype.onFileSelected = function ( e
) {
12813 if ( e
.target
.files
&& e
.target
.files
[0] ) {
12814 file
= e
.target
.files
[0];
12815 if ( !this.isFileAcceptable( file
) ) {
12820 this.setValue( file
);
12825 * Handle clear button click events.
12829 OO
.ui
.SelectFileWidget
.prototype.onClearClick = function () {
12830 this.setValue( null );
12835 * Handle key press events.
12838 * @param {jQuery.Event} e Key press event
12840 OO
.ui
.SelectFileWidget
.prototype.onKeyPress = function ( e
) {
12841 if ( this.isSupported
&& !this.isDisabled() && this.$input
&&
12842 ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
12844 this.$input
.click();
12850 * Handle drag enter and over events
12853 * @param {jQuery.Event} e Drag event
12855 OO
.ui
.SelectFileWidget
.prototype.onDragEnterOrOver = function ( e
) {
12857 dt
= e
.originalEvent
.dataTransfer
;
12859 e
.preventDefault();
12860 e
.stopPropagation();
12862 if ( this.isDisabled() || !this.isSupported
) {
12863 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
12864 dt
.dropEffect
= 'none';
12868 if ( dt
&& dt
.files
&& dt
.files
[0] ) {
12869 file
= dt
.files
[0];
12870 if ( !this.isFileAcceptable( file
) ) {
12873 } else if ( dt
&& dt
.types
&& $.inArray( 'Files', dt
.types
) ) {
12874 // We know we have files so set 'file' to something truthy, we just
12875 // can't know any details about them.
12876 // * https://bugzilla.mozilla.org/show_bug.cgi?id=640534
12877 file
= 'Files exist, but details are unknown';
12880 this.$element
.addClass( 'oo-ui-selectFileWidget-canDrop' );
12882 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
12883 dt
.dropEffect
= 'none';
12890 * Handle drag leave events
12893 * @param {jQuery.Event} e Drag event
12895 OO
.ui
.SelectFileWidget
.prototype.onDragLeave = function () {
12896 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
12900 * Handle drop events
12903 * @param {jQuery.Event} e Drop event
12905 OO
.ui
.SelectFileWidget
.prototype.onDrop = function ( e
) {
12907 dt
= e
.originalEvent
.dataTransfer
;
12909 e
.preventDefault();
12910 e
.stopPropagation();
12911 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
12913 if ( this.isDisabled() || !this.isSupported
) {
12917 if ( dt
&& dt
.files
&& dt
.files
[0] ) {
12918 file
= dt
.files
[0];
12919 if ( !this.isFileAcceptable( file
) ) {
12924 this.setValue( file
);
12933 OO
.ui
.SelectFileWidget
.prototype.setDisabled = function ( state
) {
12934 OO
.ui
.SelectFileWidget
.parent
.prototype.setDisabled
.call( this, state
);
12935 if ( this.clearButton
) {
12936 this.clearButton
.setDisabled( state
);
12942 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
12943 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
12944 * for a list of icons included in the library.
12947 * // An icon widget with a label
12948 * var myIcon = new OO.ui.IconWidget( {
12950 * iconTitle: 'Help'
12952 * // Create a label.
12953 * var iconLabel = new OO.ui.LabelWidget( {
12956 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
12958 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
12961 * @extends OO.ui.Widget
12962 * @mixins OO.ui.mixin.IconElement
12963 * @mixins OO.ui.mixin.TitledElement
12964 * @mixins OO.ui.mixin.FlaggedElement
12967 * @param {Object} [config] Configuration options
12969 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
12970 // Configuration initialization
12971 config
= config
|| {};
12973 // Parent constructor
12974 OO
.ui
.IconWidget
.parent
.call( this, config
);
12976 // Mixin constructors
12977 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
12978 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
12979 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
12982 this.$element
.addClass( 'oo-ui-iconWidget' );
12987 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
12988 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
12989 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
12990 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
12992 /* Static Properties */
12994 OO
.ui
.IconWidget
.static.tagName
= 'span';
12997 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
12998 * attention to the status of an item or to clarify the function of a control. For a list of
12999 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
13002 * // Example of an indicator widget
13003 * var indicator1 = new OO.ui.IndicatorWidget( {
13004 * indicator: 'alert'
13007 * // Create a fieldset layout to add a label
13008 * var fieldset = new OO.ui.FieldsetLayout();
13009 * fieldset.addItems( [
13010 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
13012 * $( 'body' ).append( fieldset.$element );
13014 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
13017 * @extends OO.ui.Widget
13018 * @mixins OO.ui.mixin.IndicatorElement
13019 * @mixins OO.ui.mixin.TitledElement
13022 * @param {Object} [config] Configuration options
13024 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
13025 // Configuration initialization
13026 config
= config
|| {};
13028 // Parent constructor
13029 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
13031 // Mixin constructors
13032 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
13033 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
13036 this.$element
.addClass( 'oo-ui-indicatorWidget' );
13041 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
13042 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
13043 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
13045 /* Static Properties */
13047 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
13050 * InputWidget is the base class for all input widgets, which
13051 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
13052 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
13053 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
13055 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
13059 * @extends OO.ui.Widget
13060 * @mixins OO.ui.mixin.FlaggedElement
13061 * @mixins OO.ui.mixin.TabIndexedElement
13064 * @param {Object} [config] Configuration options
13065 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
13066 * @cfg {string} [value=''] The value of the input.
13067 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
13068 * before it is accepted.
13070 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
13071 // Configuration initialization
13072 config
= config
|| {};
13074 // Parent constructor
13075 OO
.ui
.InputWidget
.parent
.call( this, config
);
13078 this.$input
= this.getInputElement( config
);
13080 this.inputFilter
= config
.inputFilter
;
13082 // Mixin constructors
13083 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
13084 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
13087 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
13091 .attr( 'name', config
.name
)
13092 .prop( 'disabled', this.isDisabled() );
13094 .addClass( 'oo-ui-inputWidget' )
13095 .append( this.$input
);
13096 this.setValue( config
.value
);
13101 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
13102 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
13103 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13105 /* Static Properties */
13107 OO
.ui
.InputWidget
.static.supportsSimpleLabel
= true;
13114 * A change event is emitted when the value of the input changes.
13116 * @param {string} value
13122 * Get input element.
13124 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
13125 * different circumstances. The element must have a `value` property (like form elements).
13128 * @param {Object} config Configuration options
13129 * @return {jQuery} Input element
13131 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
13132 return $( '<input>' );
13136 * Handle potentially value-changing events.
13139 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
13141 OO
.ui
.InputWidget
.prototype.onEdit = function () {
13143 if ( !this.isDisabled() ) {
13144 // Allow the stack to clear so the value will be updated
13145 setTimeout( function () {
13146 widget
.setValue( widget
.$input
.val() );
13152 * Get the value of the input.
13154 * @return {string} Input value
13156 OO
.ui
.InputWidget
.prototype.getValue = function () {
13157 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
13158 // it, and we won't know unless they're kind enough to trigger a 'change' event.
13159 var value
= this.$input
.val();
13160 if ( this.value
!== value
) {
13161 this.setValue( value
);
13167 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
13169 * @param {boolean} isRTL
13170 * Direction is right-to-left
13172 OO
.ui
.InputWidget
.prototype.setRTL = function ( isRTL
) {
13173 this.$input
.prop( 'dir', isRTL
? 'rtl' : 'ltr' );
13177 * Set the value of the input.
13179 * @param {string} value New value
13183 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
13184 value
= this.cleanUpValue( value
);
13185 // Update the DOM if it has changed. Note that with cleanUpValue, it
13186 // is possible for the DOM value to change without this.value changing.
13187 if ( this.$input
.val() !== value
) {
13188 this.$input
.val( value
);
13190 if ( this.value
!== value
) {
13191 this.value
= value
;
13192 this.emit( 'change', this.value
);
13198 * Clean up incoming value.
13200 * Ensures value is a string, and converts undefined and null to empty string.
13203 * @param {string} value Original value
13204 * @return {string} Cleaned up value
13206 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
13207 if ( value
=== undefined || value
=== null ) {
13209 } else if ( this.inputFilter
) {
13210 return this.inputFilter( String( value
) );
13212 return String( value
);
13217 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
13218 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
13221 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
13222 if ( !this.isDisabled() ) {
13223 if ( this.$input
.is( ':checkbox, :radio' ) ) {
13224 this.$input
.click();
13226 if ( this.$input
.is( ':input' ) ) {
13227 this.$input
[ 0 ].focus();
13235 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
13236 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
13237 if ( this.$input
) {
13238 this.$input
.prop( 'disabled', this.isDisabled() );
13248 OO
.ui
.InputWidget
.prototype.focus = function () {
13249 this.$input
[ 0 ].focus();
13258 OO
.ui
.InputWidget
.prototype.blur = function () {
13259 this.$input
[ 0 ].blur();
13264 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
13265 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
13266 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
13267 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
13268 * [OOjs UI documentation on MediaWiki] [1] for more information.
13271 * // A ButtonInputWidget rendered as an HTML button, the default.
13272 * var button = new OO.ui.ButtonInputWidget( {
13273 * label: 'Input button',
13277 * $( 'body' ).append( button.$element );
13279 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
13282 * @extends OO.ui.InputWidget
13283 * @mixins OO.ui.mixin.ButtonElement
13284 * @mixins OO.ui.mixin.IconElement
13285 * @mixins OO.ui.mixin.IndicatorElement
13286 * @mixins OO.ui.mixin.LabelElement
13287 * @mixins OO.ui.mixin.TitledElement
13290 * @param {Object} [config] Configuration options
13291 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
13292 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
13293 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
13294 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
13295 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
13297 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
13298 // Configuration initialization
13299 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
13301 // Properties (must be set before parent constructor, which calls #setValue)
13302 this.useInputTag
= config
.useInputTag
;
13304 // Parent constructor
13305 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
13307 // Mixin constructors
13308 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
13309 OO
.ui
.mixin
.IconElement
.call( this, config
);
13310 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13311 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13312 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
13315 if ( !config
.useInputTag
) {
13316 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
13318 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
13323 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
13324 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
13325 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
13326 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
13327 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
13328 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
13330 /* Static Properties */
13333 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
13334 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
13336 OO
.ui
.ButtonInputWidget
.static.supportsSimpleLabel
= false;
13344 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
13345 var type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ?
13348 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
13354 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
13356 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
13357 * text, or `null` for no label
13360 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
13361 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
13363 if ( this.useInputTag
) {
13364 if ( typeof label
=== 'function' ) {
13365 label
= OO
.ui
.resolveMsg( label
);
13367 if ( label
instanceof jQuery
) {
13368 label
= label
.text();
13373 this.$input
.val( label
);
13380 * Set the value of the input.
13382 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
13383 * they do not support {@link #value values}.
13385 * @param {string} value New value
13388 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
13389 if ( !this.useInputTag
) {
13390 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
13396 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
13397 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
13398 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
13399 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
13401 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
13404 * // An example of selected, unselected, and disabled checkbox inputs
13405 * var checkbox1=new OO.ui.CheckboxInputWidget( {
13409 * var checkbox2=new OO.ui.CheckboxInputWidget( {
13412 * var checkbox3=new OO.ui.CheckboxInputWidget( {
13416 * // Create a fieldset layout with fields for each checkbox.
13417 * var fieldset = new OO.ui.FieldsetLayout( {
13418 * label: 'Checkboxes'
13420 * fieldset.addItems( [
13421 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
13422 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
13423 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
13425 * $( 'body' ).append( fieldset.$element );
13427 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
13430 * @extends OO.ui.InputWidget
13433 * @param {Object} [config] Configuration options
13434 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
13436 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
13437 // Configuration initialization
13438 config
= config
|| {};
13440 // Parent constructor
13441 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
13445 .addClass( 'oo-ui-checkboxInputWidget' )
13446 // Required for pretty styling in MediaWiki theme
13447 .append( $( '<span>' ) );
13448 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
13453 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
13461 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
13462 return $( '<input type="checkbox" />' );
13468 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
13470 if ( !this.isDisabled() ) {
13471 // Allow the stack to clear so the value will be updated
13472 setTimeout( function () {
13473 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
13479 * Set selection state of this checkbox.
13481 * @param {boolean} state `true` for selected
13484 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
13486 if ( this.selected
!== state
) {
13487 this.selected
= state
;
13488 this.$input
.prop( 'checked', this.selected
);
13489 this.emit( 'change', this.selected
);
13495 * Check if this checkbox is selected.
13497 * @return {boolean} Checkbox is selected
13499 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
13500 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
13501 // it, and we won't know unless they're kind enough to trigger a 'change' event.
13502 var selected
= this.$input
.prop( 'checked' );
13503 if ( this.selected
!== selected
) {
13504 this.setSelected( selected
);
13506 return this.selected
;
13510 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
13511 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
13512 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
13513 * more information about input widgets.
13515 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
13516 * are no options. If no `value` configuration option is provided, the first option is selected.
13517 * If you need a state representing no value (no option being selected), use a DropdownWidget.
13519 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
13522 * // Example: A DropdownInputWidget with three options
13523 * var dropdownInput = new OO.ui.DropdownInputWidget( {
13525 * { data: 'a', label: 'First' },
13526 * { data: 'b', label: 'Second'},
13527 * { data: 'c', label: 'Third' }
13530 * $( 'body' ).append( dropdownInput.$element );
13532 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
13535 * @extends OO.ui.InputWidget
13538 * @param {Object} [config] Configuration options
13539 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
13541 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
13542 // Configuration initialization
13543 config
= config
|| {};
13545 // Properties (must be done before parent constructor which calls #setDisabled)
13546 this.dropdownWidget
= new OO
.ui
.DropdownWidget();
13548 // Parent constructor
13549 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
13552 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
13555 this.setOptions( config
.options
|| [] );
13557 .addClass( 'oo-ui-dropdownInputWidget' )
13558 .append( this.dropdownWidget
.$element
);
13563 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
13571 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
13572 return $( '<input type="hidden">' );
13576 * Handles menu select events.
13579 * @param {OO.ui.MenuOptionWidget} item Selected menu item
13581 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
13582 this.setValue( item
.getData() );
13588 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
13589 value
= this.cleanUpValue( value
);
13590 this.dropdownWidget
.getMenu().selectItemByData( value
);
13591 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
13598 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
13599 this.dropdownWidget
.setDisabled( state
);
13600 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
13605 * Set the options available for this input.
13607 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
13610 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
13612 value
= this.getValue(),
13615 // Rebuild the dropdown menu
13616 this.dropdownWidget
.getMenu()
13618 .addItems( options
.map( function ( opt
) {
13619 var optValue
= widget
.cleanUpValue( opt
.data
);
13620 return new OO
.ui
.MenuOptionWidget( {
13622 label
: opt
.label
!== undefined ? opt
.label
: optValue
13626 // Restore the previous value, or reset to something sensible
13627 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
13628 // Previous value is still available, ensure consistency with the dropdown
13629 this.setValue( value
);
13631 // No longer valid, reset
13632 if ( options
.length
) {
13633 this.setValue( options
[ 0 ].data
);
13643 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
13644 this.dropdownWidget
.getMenu().toggle( true );
13651 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
13652 this.dropdownWidget
.getMenu().toggle( false );
13657 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
13658 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
13659 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
13660 * please see the [OOjs UI documentation on MediaWiki][1].
13662 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
13665 * // An example of selected, unselected, and disabled radio inputs
13666 * var radio1 = new OO.ui.RadioInputWidget( {
13670 * var radio2 = new OO.ui.RadioInputWidget( {
13673 * var radio3 = new OO.ui.RadioInputWidget( {
13677 * // Create a fieldset layout with fields for each radio button.
13678 * var fieldset = new OO.ui.FieldsetLayout( {
13679 * label: 'Radio inputs'
13681 * fieldset.addItems( [
13682 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
13683 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
13684 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
13686 * $( 'body' ).append( fieldset.$element );
13688 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
13691 * @extends OO.ui.InputWidget
13694 * @param {Object} [config] Configuration options
13695 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
13697 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
13698 // Configuration initialization
13699 config
= config
|| {};
13701 // Parent constructor
13702 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
13706 .addClass( 'oo-ui-radioInputWidget' )
13707 // Required for pretty styling in MediaWiki theme
13708 .append( $( '<span>' ) );
13709 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
13714 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
13722 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
13723 return $( '<input type="radio" />' );
13729 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
13730 // RadioInputWidget doesn't track its state.
13734 * Set selection state of this radio button.
13736 * @param {boolean} state `true` for selected
13739 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
13740 // RadioInputWidget doesn't track its state.
13741 this.$input
.prop( 'checked', state
);
13746 * Check if this radio button is selected.
13748 * @return {boolean} Radio is selected
13750 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
13751 return this.$input
.prop( 'checked' );
13755 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
13756 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
13757 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
13758 * more information about input widgets.
13760 * This and OO.ui.DropdownInputWidget support the same configuration options.
13763 * // Example: A RadioSelectInputWidget with three options
13764 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
13766 * { data: 'a', label: 'First' },
13767 * { data: 'b', label: 'Second'},
13768 * { data: 'c', label: 'Third' }
13771 * $( 'body' ).append( radioSelectInput.$element );
13773 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
13776 * @extends OO.ui.InputWidget
13779 * @param {Object} [config] Configuration options
13780 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
13782 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
13783 // Configuration initialization
13784 config
= config
|| {};
13786 // Properties (must be done before parent constructor which calls #setDisabled)
13787 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
13789 // Parent constructor
13790 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
13793 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
13796 this.setOptions( config
.options
|| [] );
13798 .addClass( 'oo-ui-radioSelectInputWidget' )
13799 .append( this.radioSelectWidget
.$element
);
13804 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
13806 /* Static Properties */
13808 OO
.ui
.RadioSelectInputWidget
.static.supportsSimpleLabel
= false;
13816 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
13817 return $( '<input type="hidden">' );
13821 * Handles menu select events.
13824 * @param {OO.ui.RadioOptionWidget} item Selected menu item
13826 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
13827 this.setValue( item
.getData() );
13833 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
13834 value
= this.cleanUpValue( value
);
13835 this.radioSelectWidget
.selectItemByData( value
);
13836 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
13843 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
13844 this.radioSelectWidget
.setDisabled( state
);
13845 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
13850 * Set the options available for this input.
13852 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
13855 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
13857 value
= this.getValue(),
13860 // Rebuild the radioSelect menu
13861 this.radioSelectWidget
13863 .addItems( options
.map( function ( opt
) {
13864 var optValue
= widget
.cleanUpValue( opt
.data
);
13865 return new OO
.ui
.RadioOptionWidget( {
13867 label
: opt
.label
!== undefined ? opt
.label
: optValue
13871 // Restore the previous value, or reset to something sensible
13872 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
13873 // Previous value is still available, ensure consistency with the radioSelect
13874 this.setValue( value
);
13876 // No longer valid, reset
13877 if ( options
.length
) {
13878 this.setValue( options
[ 0 ].data
);
13886 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
13887 * size of the field as well as its presentation. In addition, these widgets can be configured
13888 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
13889 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
13890 * which modifies incoming values rather than validating them.
13891 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
13893 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
13896 * // Example of a text input widget
13897 * var textInput = new OO.ui.TextInputWidget( {
13898 * value: 'Text input'
13900 * $( 'body' ).append( textInput.$element );
13902 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
13905 * @extends OO.ui.InputWidget
13906 * @mixins OO.ui.mixin.IconElement
13907 * @mixins OO.ui.mixin.IndicatorElement
13908 * @mixins OO.ui.mixin.PendingElement
13909 * @mixins OO.ui.mixin.LabelElement
13912 * @param {Object} [config] Configuration options
13913 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
13914 * 'email' or 'url'. Ignored if `multiline` is true.
13916 * Some values of `type` result in additional behaviors:
13918 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
13919 * empties the text field
13920 * @cfg {string} [placeholder] Placeholder text
13921 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
13922 * instruct the browser to focus this widget.
13923 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
13924 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
13925 * @cfg {boolean} [multiline=false] Allow multiple lines of text
13926 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
13927 * specifies minimum number of rows to display.
13928 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
13929 * Use the #maxRows config to specify a maximum number of displayed rows.
13930 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
13931 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
13932 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
13933 * the value or placeholder text: `'before'` or `'after'`
13934 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
13935 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
13936 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
13937 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
13938 * (the value must contain only numbers); when RegExp, a regular expression that must match the
13939 * value for it to be considered valid; when Function, a function receiving the value as parameter
13940 * that must return true, or promise resolving to true, for it to be considered valid.
13942 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
13943 // Configuration initialization
13944 config
= $.extend( {
13946 labelPosition
: 'after'
13948 if ( config
.type
=== 'search' ) {
13949 if ( config
.icon
=== undefined ) {
13950 config
.icon
= 'search';
13952 // indicator: 'clear' is set dynamically later, depending on value
13954 if ( config
.required
) {
13955 if ( config
.indicator
=== undefined ) {
13956 config
.indicator
= 'required';
13960 // Parent constructor
13961 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
13963 // Mixin constructors
13964 OO
.ui
.mixin
.IconElement
.call( this, config
);
13965 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13966 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
13967 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13970 this.type
= this.getSaneType( config
);
13971 this.readOnly
= false;
13972 this.multiline
= !!config
.multiline
;
13973 this.autosize
= !!config
.autosize
;
13974 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
13975 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
13976 this.validate
= null;
13978 // Clone for resizing
13979 if ( this.autosize
) {
13980 this.$clone
= this.$input
13982 .insertAfter( this.$input
)
13983 .attr( 'aria-hidden', 'true' )
13984 .addClass( 'oo-ui-element-hidden' );
13987 this.setValidation( config
.validate
);
13988 this.setLabelPosition( config
.labelPosition
);
13992 keypress
: this.onKeyPress
.bind( this ),
13993 blur
: this.onBlur
.bind( this )
13996 focus
: this.onElementAttach
.bind( this )
13998 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
13999 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
14000 this.on( 'labelChange', this.updatePosition
.bind( this ) );
14001 this.connect( this, {
14002 change
: 'onChange',
14003 disable
: 'onDisable'
14008 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
14009 .append( this.$icon
, this.$indicator
);
14010 this.setReadOnly( !!config
.readOnly
);
14011 this.updateSearchIndicator();
14012 if ( config
.placeholder
) {
14013 this.$input
.attr( 'placeholder', config
.placeholder
);
14015 if ( config
.maxLength
!== undefined ) {
14016 this.$input
.attr( 'maxlength', config
.maxLength
);
14018 if ( config
.autofocus
) {
14019 this.$input
.attr( 'autofocus', 'autofocus' );
14021 if ( config
.required
) {
14022 this.$input
.attr( 'required', 'required' );
14023 this.$input
.attr( 'aria-required', 'true' );
14025 if ( config
.autocomplete
=== false ) {
14026 this.$input
.attr( 'autocomplete', 'off' );
14028 if ( this.multiline
&& config
.rows
) {
14029 this.$input
.attr( 'rows', config
.rows
);
14031 if ( this.label
|| config
.autosize
) {
14032 this.installParentChangeDetector();
14038 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
14039 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
14040 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
14041 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
14042 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
14044 /* Static Properties */
14046 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
14054 * An `enter` event is emitted when the user presses 'enter' inside the text box.
14056 * Not emitted if the input is multiline.
14064 * Handle icon mouse down events.
14067 * @param {jQuery.Event} e Mouse down event
14070 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
14071 if ( e
.which
=== 1 ) {
14072 this.$input
[ 0 ].focus();
14078 * Handle indicator mouse down events.
14081 * @param {jQuery.Event} e Mouse down event
14084 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
14085 if ( e
.which
=== 1 ) {
14086 if ( this.type
=== 'search' ) {
14087 // Clear the text field
14088 this.setValue( '' );
14090 this.$input
[ 0 ].focus();
14096 * Handle key press events.
14099 * @param {jQuery.Event} e Key press event
14100 * @fires enter If enter key is pressed and input is not multiline
14102 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
14103 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
14104 this.emit( 'enter', e
);
14109 * Handle blur events.
14112 * @param {jQuery.Event} e Blur event
14114 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
14115 this.setValidityFlag();
14119 * Handle element attach events.
14122 * @param {jQuery.Event} e Element attach event
14124 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
14125 // Any previously calculated size is now probably invalid if we reattached elsewhere
14126 this.valCache
= null;
14128 this.positionLabel();
14132 * Handle change events.
14134 * @param {string} value
14137 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
14138 this.updateSearchIndicator();
14139 this.setValidityFlag();
14144 * Handle disable events.
14146 * @param {boolean} disabled Element is disabled
14149 OO
.ui
.TextInputWidget
.prototype.onDisable = function () {
14150 this.updateSearchIndicator();
14154 * Check if the input is {@link #readOnly read-only}.
14156 * @return {boolean}
14158 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
14159 return this.readOnly
;
14163 * Set the {@link #readOnly read-only} state of the input.
14165 * @param {boolean} state Make input read-only
14168 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
14169 this.readOnly
= !!state
;
14170 this.$input
.prop( 'readOnly', this.readOnly
);
14171 this.updateSearchIndicator();
14176 * Support function for making #onElementAttach work across browsers.
14178 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
14179 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
14181 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
14182 * first time that the element gets attached to the documented.
14184 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
14185 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
14186 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
14189 if ( MutationObserver
) {
14190 // The new way. If only it wasn't so ugly.
14192 if ( this.$element
.closest( 'html' ).length
) {
14193 // Widget is attached already, do nothing. This breaks the functionality of this function when
14194 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
14195 // would require observation of the whole document, which would hurt performance of other,
14196 // more important code.
14200 // Find topmost node in the tree
14201 topmostNode
= this.$element
[0];
14202 while ( topmostNode
.parentNode
) {
14203 topmostNode
= topmostNode
.parentNode
;
14206 // We have no way to detect the $element being attached somewhere without observing the entire
14207 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
14208 // parent node of $element, and instead detect when $element is removed from it (and thus
14209 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
14210 // doesn't get attached, we end up back here and create the parent.
14212 mutationObserver
= new MutationObserver( function ( mutations
) {
14213 var i
, j
, removedNodes
;
14214 for ( i
= 0; i
< mutations
.length
; i
++ ) {
14215 removedNodes
= mutations
[ i
].removedNodes
;
14216 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
14217 if ( removedNodes
[ j
] === topmostNode
) {
14218 setTimeout( onRemove
, 0 );
14225 onRemove = function () {
14226 // If the node was attached somewhere else, report it
14227 if ( widget
.$element
.closest( 'html' ).length
) {
14228 widget
.onElementAttach();
14230 mutationObserver
.disconnect();
14231 widget
.installParentChangeDetector();
14234 // Create a fake parent and observe it
14235 fakeParentNode
= $( '<div>' ).append( topmostNode
)[0];
14236 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
14238 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
14239 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
14240 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
14245 * Automatically adjust the size of the text input.
14247 * This only affects #multiline inputs that are {@link #autosize autosized}.
14251 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
14252 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
, idealHeight
;
14254 if ( this.multiline
&& this.autosize
&& this.$input
.val() !== this.valCache
) {
14256 .val( this.$input
.val() )
14257 .attr( 'rows', this.minRows
)
14258 // Set inline height property to 0 to measure scroll height
14259 .css( 'height', 0 );
14261 this.$clone
.removeClass( 'oo-ui-element-hidden' );
14263 this.valCache
= this.$input
.val();
14265 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
14267 // Remove inline height property to measure natural heights
14268 this.$clone
.css( 'height', '' );
14269 innerHeight
= this.$clone
.innerHeight();
14270 outerHeight
= this.$clone
.outerHeight();
14272 // Measure max rows height
14274 .attr( 'rows', this.maxRows
)
14275 .css( 'height', 'auto' )
14277 maxInnerHeight
= this.$clone
.innerHeight();
14279 // Difference between reported innerHeight and scrollHeight with no scrollbars present
14280 // Equals 1 on Blink-based browsers and 0 everywhere else
14281 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
14282 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
14284 this.$clone
.addClass( 'oo-ui-element-hidden' );
14286 // Only apply inline height when expansion beyond natural height is needed
14287 if ( idealHeight
> innerHeight
) {
14288 // Use the difference between the inner and outer height as a buffer
14289 this.$input
.css( 'height', idealHeight
+ ( outerHeight
- innerHeight
) );
14291 this.$input
.css( 'height', '' );
14301 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
14302 return config
.multiline
?
14303 $( '<textarea>' ) :
14304 $( '<input type="' + this.getSaneType( config
) + '" />' );
14308 * Get sanitized value for 'type' for given config.
14310 * @param {Object} config Configuration options
14311 * @return {string|null}
14314 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
14315 var type
= [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config
.type
) !== -1 ?
14318 return config
.multiline
? 'multiline' : type
;
14322 * Check if the input supports multiple lines.
14324 * @return {boolean}
14326 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
14327 return !!this.multiline
;
14331 * Check if the input automatically adjusts its size.
14333 * @return {boolean}
14335 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
14336 return !!this.autosize
;
14340 * Select the entire text of the input.
14344 OO
.ui
.TextInputWidget
.prototype.select = function () {
14345 this.$input
.select();
14350 * Set the validation pattern.
14352 * The validation pattern is either a regular expression, a function, or the symbolic name of a
14353 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
14354 * value must contain only numbers).
14356 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
14357 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
14359 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
14360 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
14361 this.validate
= validate
;
14363 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
14368 * Sets the 'invalid' flag appropriately.
14370 * @param {boolean} [isValid] Optionally override validation result
14372 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
14374 setFlag = function ( valid
) {
14376 widget
.$input
.attr( 'aria-invalid', 'true' );
14378 widget
.$input
.removeAttr( 'aria-invalid' );
14380 widget
.setFlags( { invalid
: !valid
} );
14383 if ( isValid
!== undefined ) {
14384 setFlag( isValid
);
14386 this.isValid().done( setFlag
);
14391 * Check if a value is valid.
14393 * This method returns a promise that resolves with a boolean `true` if the current value is
14394 * considered valid according to the supplied {@link #validate validation pattern}.
14396 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
14398 OO
.ui
.TextInputWidget
.prototype.isValid = function () {
14399 if ( this.validate
instanceof Function
) {
14400 var result
= this.validate( this.getValue() );
14401 if ( $.isFunction( result
.promise
) ) {
14402 return result
.promise();
14404 return $.Deferred().resolve( !!result
).promise();
14407 return $.Deferred().resolve( !!this.getValue().match( this.validate
) ).promise();
14412 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
14414 * @param {string} labelPosition Label position, 'before' or 'after'
14417 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
14418 this.labelPosition
= labelPosition
;
14419 this.updatePosition();
14424 * Deprecated alias of #setLabelPosition
14426 * @deprecated Use setLabelPosition instead.
14428 OO
.ui
.TextInputWidget
.prototype.setPosition
=
14429 OO
.ui
.TextInputWidget
.prototype.setLabelPosition
;
14432 * Update the position of the inline label.
14434 * This method is called by #setLabelPosition, and can also be called on its own if
14435 * something causes the label to be mispositioned.
14439 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
14440 var after
= this.labelPosition
=== 'after';
14443 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
14444 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
14446 if ( this.label
) {
14447 this.positionLabel();
14454 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
14455 * already empty or when it's not editable.
14457 OO
.ui
.TextInputWidget
.prototype.updateSearchIndicator = function () {
14458 if ( this.type
=== 'search' ) {
14459 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
14460 this.setIndicator( null );
14462 this.setIndicator( 'clear' );
14468 * Position the label by setting the correct padding on the input.
14473 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
14474 // Clear old values
14476 // Clear old values if present
14478 'padding-right': '',
14482 if ( this.label
) {
14483 this.$element
.append( this.$label
);
14485 this.$label
.detach();
14489 var after
= this.labelPosition
=== 'after',
14490 rtl
= this.$element
.css( 'direction' ) === 'rtl',
14491 property
= after
=== rtl
? 'padding-left' : 'padding-right';
14493 this.$input
.css( property
, this.$label
.outerWidth( true ) );
14499 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
14500 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
14501 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
14503 * - by typing a value in the text input field. If the value exactly matches the value of a menu
14504 * option, that option will appear to be selected.
14505 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
14508 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
14511 * // Example: A ComboBoxWidget.
14512 * var comboBox = new OO.ui.ComboBoxWidget( {
14513 * label: 'ComboBoxWidget',
14514 * input: { value: 'Option One' },
14517 * new OO.ui.MenuOptionWidget( {
14518 * data: 'Option 1',
14519 * label: 'Option One'
14521 * new OO.ui.MenuOptionWidget( {
14522 * data: 'Option 2',
14523 * label: 'Option Two'
14525 * new OO.ui.MenuOptionWidget( {
14526 * data: 'Option 3',
14527 * label: 'Option Three'
14529 * new OO.ui.MenuOptionWidget( {
14530 * data: 'Option 4',
14531 * label: 'Option Four'
14533 * new OO.ui.MenuOptionWidget( {
14534 * data: 'Option 5',
14535 * label: 'Option Five'
14540 * $( 'body' ).append( comboBox.$element );
14542 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
14545 * @extends OO.ui.Widget
14546 * @mixins OO.ui.mixin.TabIndexedElement
14549 * @param {Object} [config] Configuration options
14550 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
14551 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
14552 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
14553 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
14554 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
14556 OO
.ui
.ComboBoxWidget
= function OoUiComboBoxWidget( config
) {
14557 // Configuration initialization
14558 config
= config
|| {};
14560 // Parent constructor
14561 OO
.ui
.ComboBoxWidget
.parent
.call( this, config
);
14563 // Properties (must be set before TabIndexedElement constructor call)
14564 this.$indicator
= this.$( '<span>' );
14566 // Mixin constructors
14567 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
14570 this.$overlay
= config
.$overlay
|| this.$element
;
14571 this.input
= new OO
.ui
.TextInputWidget( $.extend(
14574 $indicator
: this.$indicator
,
14575 disabled
: this.isDisabled()
14579 this.input
.$input
.eq( 0 ).attr( {
14581 'aria-autocomplete': 'list'
14583 this.menu
= new OO
.ui
.TextInputMenuSelectWidget( this.input
, $.extend(
14587 disabled
: this.isDisabled()
14593 this.$indicator
.on( {
14594 click
: this.onClick
.bind( this ),
14595 keypress
: this.onKeyPress
.bind( this )
14597 this.input
.connect( this, {
14598 change
: 'onInputChange',
14599 enter
: 'onInputEnter'
14601 this.menu
.connect( this, {
14602 choose
: 'onMenuChoose',
14603 add
: 'onMenuItemsChange',
14604 remove
: 'onMenuItemsChange'
14608 this.$element
.addClass( 'oo-ui-comboBoxWidget' ).append( this.input
.$element
);
14609 this.$overlay
.append( this.menu
.$element
);
14610 this.onMenuItemsChange();
14615 OO
.inheritClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.Widget
);
14616 OO
.mixinClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.mixin
.TabIndexedElement
);
14621 * Get the combobox's menu.
14622 * @return {OO.ui.TextInputMenuSelectWidget} Menu widget
14624 OO
.ui
.ComboBoxWidget
.prototype.getMenu = function () {
14629 * Get the combobox's text input widget.
14630 * @return {OO.ui.TextInputWidget} Text input widget
14632 OO
.ui
.ComboBoxWidget
.prototype.getInput = function () {
14637 * Handle input change events.
14640 * @param {string} value New value
14642 OO
.ui
.ComboBoxWidget
.prototype.onInputChange = function ( value
) {
14643 var match
= this.menu
.getItemFromData( value
);
14645 this.menu
.selectItem( match
);
14646 if ( this.menu
.getHighlightedItem() ) {
14647 this.menu
.highlightItem( match
);
14650 if ( !this.isDisabled() ) {
14651 this.menu
.toggle( true );
14656 * Handle mouse click events.
14660 * @param {jQuery.Event} e Mouse click event
14662 OO
.ui
.ComboBoxWidget
.prototype.onClick = function ( e
) {
14663 if ( !this.isDisabled() && e
.which
=== 1 ) {
14664 this.menu
.toggle();
14665 this.input
.$input
[ 0 ].focus();
14671 * Handle key press events.
14675 * @param {jQuery.Event} e Key press event
14677 OO
.ui
.ComboBoxWidget
.prototype.onKeyPress = function ( e
) {
14678 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
14679 this.menu
.toggle();
14680 this.input
.$input
[ 0 ].focus();
14686 * Handle input enter events.
14690 OO
.ui
.ComboBoxWidget
.prototype.onInputEnter = function () {
14691 if ( !this.isDisabled() ) {
14692 this.menu
.toggle( false );
14697 * Handle menu choose events.
14700 * @param {OO.ui.OptionWidget} item Chosen item
14702 OO
.ui
.ComboBoxWidget
.prototype.onMenuChoose = function ( item
) {
14703 this.input
.setValue( item
.getData() );
14707 * Handle menu item change events.
14711 OO
.ui
.ComboBoxWidget
.prototype.onMenuItemsChange = function () {
14712 var match
= this.menu
.getItemFromData( this.input
.getValue() );
14713 this.menu
.selectItem( match
);
14714 if ( this.menu
.getHighlightedItem() ) {
14715 this.menu
.highlightItem( match
);
14717 this.$element
.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu
.isEmpty() );
14723 OO
.ui
.ComboBoxWidget
.prototype.setDisabled = function ( disabled
) {
14725 OO
.ui
.ComboBoxWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
14727 if ( this.input
) {
14728 this.input
.setDisabled( this.isDisabled() );
14731 this.menu
.setDisabled( this.isDisabled() );
14738 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
14739 * be configured with a `label` option that is set to a string, a label node, or a function:
14741 * - String: a plaintext string
14742 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
14743 * label that includes a link or special styling, such as a gray color or additional graphical elements.
14744 * - Function: a function that will produce a string in the future. Functions are used
14745 * in cases where the value of the label is not currently defined.
14747 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
14748 * will come into focus when the label is clicked.
14751 * // Examples of LabelWidgets
14752 * var label1 = new OO.ui.LabelWidget( {
14753 * label: 'plaintext label'
14755 * var label2 = new OO.ui.LabelWidget( {
14756 * label: $( '<a href="default.html">jQuery label</a>' )
14758 * // Create a fieldset layout with fields for each example
14759 * var fieldset = new OO.ui.FieldsetLayout();
14760 * fieldset.addItems( [
14761 * new OO.ui.FieldLayout( label1 ),
14762 * new OO.ui.FieldLayout( label2 )
14764 * $( 'body' ).append( fieldset.$element );
14768 * @extends OO.ui.Widget
14769 * @mixins OO.ui.mixin.LabelElement
14772 * @param {Object} [config] Configuration options
14773 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
14774 * Clicking the label will focus the specified input field.
14776 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
14777 // Configuration initialization
14778 config
= config
|| {};
14780 // Parent constructor
14781 OO
.ui
.LabelWidget
.parent
.call( this, config
);
14783 // Mixin constructors
14784 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
14785 OO
.ui
.mixin
.TitledElement
.call( this, config
);
14788 this.input
= config
.input
;
14791 if ( this.input
instanceof OO
.ui
.InputWidget
) {
14792 this.$element
.on( 'click', this.onClick
.bind( this ) );
14796 this.$element
.addClass( 'oo-ui-labelWidget' );
14801 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
14802 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
14803 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
14805 /* Static Properties */
14807 OO
.ui
.LabelWidget
.static.tagName
= 'span';
14812 * Handles label mouse click events.
14815 * @param {jQuery.Event} e Mouse click event
14817 OO
.ui
.LabelWidget
.prototype.onClick = function () {
14818 this.input
.simulateLabelClick();
14823 * OptionWidgets are special elements that can be selected and configured with data. The
14824 * data is often unique for each option, but it does not have to be. OptionWidgets are used
14825 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
14826 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
14828 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14831 * @extends OO.ui.Widget
14832 * @mixins OO.ui.mixin.LabelElement
14833 * @mixins OO.ui.mixin.FlaggedElement
14836 * @param {Object} [config] Configuration options
14838 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
14839 // Configuration initialization
14840 config
= config
|| {};
14842 // Parent constructor
14843 OO
.ui
.OptionWidget
.parent
.call( this, config
);
14845 // Mixin constructors
14846 OO
.ui
.mixin
.ItemWidget
.call( this );
14847 OO
.ui
.mixin
.LabelElement
.call( this, config
);
14848 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
14851 this.selected
= false;
14852 this.highlighted
= false;
14853 this.pressed
= false;
14857 .data( 'oo-ui-optionWidget', this )
14858 .attr( 'role', 'option' )
14859 .attr( 'aria-selected', 'false' )
14860 .addClass( 'oo-ui-optionWidget' )
14861 .append( this.$label
);
14866 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
14867 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
14868 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
14869 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
14871 /* Static Properties */
14873 OO
.ui
.OptionWidget
.static.selectable
= true;
14875 OO
.ui
.OptionWidget
.static.highlightable
= true;
14877 OO
.ui
.OptionWidget
.static.pressable
= true;
14879 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
14884 * Check if the option can be selected.
14886 * @return {boolean} Item is selectable
14888 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
14889 return this.constructor.static.selectable
&& !this.isDisabled();
14893 * Check if the option can be highlighted. A highlight indicates that the option
14894 * may be selected when a user presses enter or clicks. Disabled items cannot
14897 * @return {boolean} Item is highlightable
14899 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
14900 return this.constructor.static.highlightable
&& !this.isDisabled();
14904 * Check if the option can be pressed. The pressed state occurs when a user mouses
14905 * down on an item, but has not yet let go of the mouse.
14907 * @return {boolean} Item is pressable
14909 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
14910 return this.constructor.static.pressable
&& !this.isDisabled();
14914 * Check if the option is selected.
14916 * @return {boolean} Item is selected
14918 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
14919 return this.selected
;
14923 * Check if the option is highlighted. A highlight indicates that the
14924 * item may be selected when a user presses enter or clicks.
14926 * @return {boolean} Item is highlighted
14928 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
14929 return this.highlighted
;
14933 * Check if the option is pressed. The pressed state occurs when a user mouses
14934 * down on an item, but has not yet let go of the mouse. The item may appear
14935 * selected, but it will not be selected until the user releases the mouse.
14937 * @return {boolean} Item is pressed
14939 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
14940 return this.pressed
;
14944 * Set the option’s selected state. In general, all modifications to the selection
14945 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
14946 * method instead of this method.
14948 * @param {boolean} [state=false] Select option
14951 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
14952 if ( this.constructor.static.selectable
) {
14953 this.selected
= !!state
;
14955 .toggleClass( 'oo-ui-optionWidget-selected', state
)
14956 .attr( 'aria-selected', state
.toString() );
14957 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
14958 this.scrollElementIntoView();
14960 this.updateThemeClasses();
14966 * Set the option’s highlighted state. In general, all programmatic
14967 * modifications to the highlight should be handled by the
14968 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
14969 * method instead of this method.
14971 * @param {boolean} [state=false] Highlight option
14974 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
14975 if ( this.constructor.static.highlightable
) {
14976 this.highlighted
= !!state
;
14977 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
14978 this.updateThemeClasses();
14984 * Set the option’s pressed state. In general, all
14985 * programmatic modifications to the pressed state should be handled by the
14986 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
14987 * method instead of this method.
14989 * @param {boolean} [state=false] Press option
14992 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
14993 if ( this.constructor.static.pressable
) {
14994 this.pressed
= !!state
;
14995 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
14996 this.updateThemeClasses();
15002 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
15003 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
15004 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
15005 * options. For more information about options and selects, please see the
15006 * [OOjs UI documentation on MediaWiki][1].
15009 * // Decorated options in a select widget
15010 * var select = new OO.ui.SelectWidget( {
15012 * new OO.ui.DecoratedOptionWidget( {
15014 * label: 'Option with icon',
15017 * new OO.ui.DecoratedOptionWidget( {
15019 * label: 'Option with indicator',
15020 * indicator: 'next'
15024 * $( 'body' ).append( select.$element );
15026 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
15029 * @extends OO.ui.OptionWidget
15030 * @mixins OO.ui.mixin.IconElement
15031 * @mixins OO.ui.mixin.IndicatorElement
15034 * @param {Object} [config] Configuration options
15036 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
15037 // Parent constructor
15038 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
15040 // Mixin constructors
15041 OO
.ui
.mixin
.IconElement
.call( this, config
);
15042 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
15046 .addClass( 'oo-ui-decoratedOptionWidget' )
15047 .prepend( this.$icon
)
15048 .append( this.$indicator
);
15053 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
15054 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
15055 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
15058 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
15059 * can be selected and configured with data. The class is
15060 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
15061 * [OOjs UI documentation on MediaWiki] [1] for more information.
15063 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
15066 * @extends OO.ui.DecoratedOptionWidget
15067 * @mixins OO.ui.mixin.ButtonElement
15068 * @mixins OO.ui.mixin.TabIndexedElement
15071 * @param {Object} [config] Configuration options
15073 OO
.ui
.ButtonOptionWidget
= function OoUiButtonOptionWidget( config
) {
15074 // Configuration initialization
15075 config
= $.extend( { tabIndex
: -1 }, config
);
15077 // Parent constructor
15078 OO
.ui
.ButtonOptionWidget
.parent
.call( this, config
);
15080 // Mixin constructors
15081 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
15082 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
15085 this.$element
.addClass( 'oo-ui-buttonOptionWidget' );
15086 this.$button
.append( this.$element
.contents() );
15087 this.$element
.append( this.$button
);
15092 OO
.inheritClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
15093 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.ButtonElement
);
15094 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.TabIndexedElement
);
15096 /* Static Properties */
15098 // Allow button mouse down events to pass through so they can be handled by the parent select widget
15099 OO
.ui
.ButtonOptionWidget
.static.cancelButtonMouseDownEvents
= false;
15101 OO
.ui
.ButtonOptionWidget
.static.highlightable
= false;
15108 OO
.ui
.ButtonOptionWidget
.prototype.setSelected = function ( state
) {
15109 OO
.ui
.ButtonOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
15111 if ( this.constructor.static.selectable
) {
15112 this.setActive( state
);
15119 * RadioOptionWidget is an option widget that looks like a radio button.
15120 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
15121 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
15123 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
15126 * @extends OO.ui.OptionWidget
15129 * @param {Object} [config] Configuration options
15131 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
15132 // Configuration initialization
15133 config
= config
|| {};
15135 // Properties (must be done before parent constructor which calls #setDisabled)
15136 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
15138 // Parent constructor
15139 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
15142 this.radio
.$input
.on( 'focus', this.onInputFocus
.bind( this ) );
15145 // Remove implicit role, we're handling it ourselves
15146 this.radio
.$input
.attr( 'role', 'presentation' );
15148 .addClass( 'oo-ui-radioOptionWidget' )
15149 .attr( 'role', 'radio' )
15150 .attr( 'aria-checked', 'false' )
15151 .removeAttr( 'aria-selected' )
15152 .prepend( this.radio
.$element
);
15157 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
15159 /* Static Properties */
15161 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
15163 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
15165 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
15167 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
15172 * @param {jQuery.Event} e Focus event
15175 OO
.ui
.RadioOptionWidget
.prototype.onInputFocus = function () {
15176 this.radio
.$input
.blur();
15177 this.$element
.parent().focus();
15183 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
15184 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
15186 this.radio
.setSelected( state
);
15188 .attr( 'aria-checked', state
.toString() )
15189 .removeAttr( 'aria-selected' );
15197 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
15198 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
15200 this.radio
.setDisabled( this.isDisabled() );
15206 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
15207 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
15208 * the [OOjs UI documentation on MediaWiki] [1] for more information.
15210 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
15213 * @extends OO.ui.DecoratedOptionWidget
15216 * @param {Object} [config] Configuration options
15218 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
15219 // Configuration initialization
15220 config
= $.extend( { icon
: 'check' }, config
);
15222 // Parent constructor
15223 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
15227 .attr( 'role', 'menuitem' )
15228 .addClass( 'oo-ui-menuOptionWidget' );
15233 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
15235 /* Static Properties */
15237 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
15240 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
15241 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
15244 * var myDropdown = new OO.ui.DropdownWidget( {
15247 * new OO.ui.MenuSectionOptionWidget( {
15250 * new OO.ui.MenuOptionWidget( {
15252 * label: 'Welsh Corgi'
15254 * new OO.ui.MenuOptionWidget( {
15256 * label: 'Standard Poodle'
15258 * new OO.ui.MenuSectionOptionWidget( {
15261 * new OO.ui.MenuOptionWidget( {
15268 * $( 'body' ).append( myDropdown.$element );
15272 * @extends OO.ui.DecoratedOptionWidget
15275 * @param {Object} [config] Configuration options
15277 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
15278 // Parent constructor
15279 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
15282 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
15287 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
15289 /* Static Properties */
15291 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
15293 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
15296 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
15298 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
15299 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
15303 * @extends OO.ui.DecoratedOptionWidget
15306 * @param {Object} [config] Configuration options
15307 * @cfg {number} [level] Indentation level
15308 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
15310 OO
.ui
.OutlineOptionWidget
= function OoUiOutlineOptionWidget( config
) {
15311 // Configuration initialization
15312 config
= config
|| {};
15314 // Parent constructor
15315 OO
.ui
.OutlineOptionWidget
.parent
.call( this, config
);
15319 this.movable
= !!config
.movable
;
15320 this.removable
= !!config
.removable
;
15323 this.$element
.addClass( 'oo-ui-outlineOptionWidget' );
15324 this.setLevel( config
.level
);
15329 OO
.inheritClass( OO
.ui
.OutlineOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
15331 /* Static Properties */
15333 OO
.ui
.OutlineOptionWidget
.static.highlightable
= false;
15335 OO
.ui
.OutlineOptionWidget
.static.scrollIntoViewOnSelect
= true;
15337 OO
.ui
.OutlineOptionWidget
.static.levelClass
= 'oo-ui-outlineOptionWidget-level-';
15339 OO
.ui
.OutlineOptionWidget
.static.levels
= 3;
15344 * Check if item is movable.
15346 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
15348 * @return {boolean} Item is movable
15350 OO
.ui
.OutlineOptionWidget
.prototype.isMovable = function () {
15351 return this.movable
;
15355 * Check if item is removable.
15357 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
15359 * @return {boolean} Item is removable
15361 OO
.ui
.OutlineOptionWidget
.prototype.isRemovable = function () {
15362 return this.removable
;
15366 * Get indentation level.
15368 * @return {number} Indentation level
15370 OO
.ui
.OutlineOptionWidget
.prototype.getLevel = function () {
15377 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
15379 * @param {boolean} movable Item is movable
15382 OO
.ui
.OutlineOptionWidget
.prototype.setMovable = function ( movable
) {
15383 this.movable
= !!movable
;
15384 this.updateThemeClasses();
15389 * Set removability.
15391 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
15393 * @param {boolean} movable Item is removable
15396 OO
.ui
.OutlineOptionWidget
.prototype.setRemovable = function ( removable
) {
15397 this.removable
= !!removable
;
15398 this.updateThemeClasses();
15403 * Set indentation level.
15405 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
15408 OO
.ui
.OutlineOptionWidget
.prototype.setLevel = function ( level
) {
15409 var levels
= this.constructor.static.levels
,
15410 levelClass
= this.constructor.static.levelClass
,
15413 this.level
= level
? Math
.max( 0, Math
.min( levels
- 1, level
) ) : 0;
15415 if ( this.level
=== i
) {
15416 this.$element
.addClass( levelClass
+ i
);
15418 this.$element
.removeClass( levelClass
+ i
);
15421 this.updateThemeClasses();
15427 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
15429 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
15430 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
15434 * @extends OO.ui.OptionWidget
15437 * @param {Object} [config] Configuration options
15439 OO
.ui
.TabOptionWidget
= function OoUiTabOptionWidget( config
) {
15440 // Configuration initialization
15441 config
= config
|| {};
15443 // Parent constructor
15444 OO
.ui
.TabOptionWidget
.parent
.call( this, config
);
15447 this.$element
.addClass( 'oo-ui-tabOptionWidget' );
15452 OO
.inheritClass( OO
.ui
.TabOptionWidget
, OO
.ui
.OptionWidget
);
15454 /* Static Properties */
15456 OO
.ui
.TabOptionWidget
.static.highlightable
= false;
15459 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
15460 * By default, each popup has an anchor that points toward its origin.
15461 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
15464 * // A popup widget.
15465 * var popup = new OO.ui.PopupWidget( {
15466 * $content: $( '<p>Hi there!</p>' ),
15471 * $( 'body' ).append( popup.$element );
15472 * // To display the popup, toggle the visibility to 'true'.
15473 * popup.toggle( true );
15475 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
15478 * @extends OO.ui.Widget
15479 * @mixins OO.ui.mixin.LabelElement
15482 * @param {Object} [config] Configuration options
15483 * @cfg {number} [width=320] Width of popup in pixels
15484 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
15485 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
15486 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
15487 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
15488 * popup is leaning towards the right of the screen.
15489 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
15490 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
15491 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
15492 * sentence in the given language.
15493 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
15494 * See the [OOjs UI docs on MediaWiki][3] for an example.
15495 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
15496 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
15497 * @cfg {jQuery} [$content] Content to append to the popup's body
15498 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
15499 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
15500 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
15502 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
15503 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
15505 * @cfg {boolean} [padded] Add padding to the popup's body
15507 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
15508 // Configuration initialization
15509 config
= config
|| {};
15511 // Parent constructor
15512 OO
.ui
.PopupWidget
.parent
.call( this, config
);
15514 // Properties (must be set before ClippableElement constructor call)
15515 this.$body
= $( '<div>' );
15517 // Mixin constructors
15518 OO
.ui
.mixin
.LabelElement
.call( this, config
);
15519 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$body
} ) );
15522 this.$popup
= $( '<div>' );
15523 this.$head
= $( '<div>' );
15524 this.$anchor
= $( '<div>' );
15525 // If undefined, will be computed lazily in updateDimensions()
15526 this.$container
= config
.$container
;
15527 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
15528 this.autoClose
= !!config
.autoClose
;
15529 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
15530 this.transitionTimeout
= null;
15531 this.anchor
= null;
15532 this.width
= config
.width
!== undefined ? config
.width
: 320;
15533 this.height
= config
.height
!== undefined ? config
.height
: null;
15534 this.setAlignment( config
.align
);
15535 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
15536 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
15537 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
15540 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
15543 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
15544 this.$body
.addClass( 'oo-ui-popupWidget-body' );
15545 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
15547 .addClass( 'oo-ui-popupWidget-head' )
15548 .append( this.$label
, this.closeButton
.$element
);
15549 if ( !config
.head
) {
15550 this.$head
.addClass( 'oo-ui-element-hidden' );
15553 .addClass( 'oo-ui-popupWidget-popup' )
15554 .append( this.$head
, this.$body
);
15556 .addClass( 'oo-ui-popupWidget' )
15557 .append( this.$popup
, this.$anchor
);
15558 // Move content, which was added to #$element by OO.ui.Widget, to the body
15559 if ( config
.$content
instanceof jQuery
) {
15560 this.$body
.append( config
.$content
);
15562 if ( config
.padded
) {
15563 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
15566 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
15567 // that reference properties not initialized at that time of parent class construction
15568 // TODO: Find a better way to handle post-constructor setup
15569 this.visible
= false;
15570 this.$element
.addClass( 'oo-ui-element-hidden' );
15575 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
15576 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
15577 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
15582 * Handles mouse down events.
15585 * @param {MouseEvent} e Mouse down event
15587 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
15589 this.isVisible() &&
15590 !$.contains( this.$element
[ 0 ], e
.target
) &&
15591 ( !this.$autoCloseIgnore
|| !this.$autoCloseIgnore
.has( e
.target
).length
)
15593 this.toggle( false );
15598 * Bind mouse down listener.
15602 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
15603 // Capture clicks outside popup
15604 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler
, true );
15608 * Handles close button click events.
15612 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
15613 if ( this.isVisible() ) {
15614 this.toggle( false );
15619 * Unbind mouse down listener.
15623 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
15624 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler
, true );
15628 * Handles key down events.
15631 * @param {KeyboardEvent} e Key down event
15633 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
15635 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
15638 this.toggle( false );
15639 e
.preventDefault();
15640 e
.stopPropagation();
15645 * Bind key down listener.
15649 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
15650 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
15654 * Unbind key down listener.
15658 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
15659 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
15663 * Show, hide, or toggle the visibility of the anchor.
15665 * @param {boolean} [show] Show anchor, omit to toggle
15667 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
15668 show
= show
=== undefined ? !this.anchored
: !!show
;
15670 if ( this.anchored
!== show
) {
15672 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
15674 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
15676 this.anchored
= show
;
15681 * Check if the anchor is visible.
15683 * @return {boolean} Anchor is visible
15685 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
15686 return this.anchor
;
15692 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
15693 show
= show
=== undefined ? !this.isVisible() : !!show
;
15695 var change
= show
!== this.isVisible();
15698 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
15702 if ( this.autoClose
) {
15703 this.bindMouseDownListener();
15704 this.bindKeyDownListener();
15706 this.updateDimensions();
15707 this.toggleClipping( true );
15709 this.toggleClipping( false );
15710 if ( this.autoClose
) {
15711 this.unbindMouseDownListener();
15712 this.unbindKeyDownListener();
15721 * Set the size of the popup.
15723 * Changing the size may also change the popup's position depending on the alignment.
15725 * @param {number} width Width in pixels
15726 * @param {number} height Height in pixels
15727 * @param {boolean} [transition=false] Use a smooth transition
15730 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
15731 this.width
= width
;
15732 this.height
= height
!== undefined ? height
: null;
15733 if ( this.isVisible() ) {
15734 this.updateDimensions( transition
);
15739 * Update the size and position.
15741 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
15742 * be called automatically.
15744 * @param {boolean} [transition=false] Use a smooth transition
15747 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
15748 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
15749 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
15750 align
= this.align
,
15753 if ( !this.$container
) {
15754 // Lazy-initialize $container if not specified in constructor
15755 this.$container
= $( this.getClosestScrollableElementContainer() );
15758 // Set height and width before measuring things, since it might cause our measurements
15759 // to change (e.g. due to scrollbars appearing or disappearing)
15762 height
: this.height
!== null ? this.height
: 'auto'
15765 // If we are in RTL, we need to flip the alignment, unless it is center
15766 if ( align
=== 'forwards' || align
=== 'backwards' ) {
15767 if ( this.$container
.css( 'direction' ) === 'rtl' ) {
15768 align
= ( { forwards
: 'force-left', backwards
: 'force-right' } )[ this.align
];
15770 align
= ( { forwards
: 'force-right', backwards
: 'force-left' } )[ this.align
];
15775 // Compute initial popupOffset based on alignment
15776 popupOffset
= this.width
* ( { 'force-left': -1, center
: -0.5, 'force-right': 0 } )[ align
];
15778 // Figure out if this will cause the popup to go beyond the edge of the container
15779 originOffset
= this.$element
.offset().left
;
15780 containerLeft
= this.$container
.offset().left
;
15781 containerWidth
= this.$container
.innerWidth();
15782 containerRight
= containerLeft
+ containerWidth
;
15783 popupLeft
= popupOffset
- this.containerPadding
;
15784 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
15785 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
15786 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
15788 // Adjust offset to make the popup not go beyond the edge, if needed
15789 if ( overlapRight
< 0 ) {
15790 popupOffset
+= overlapRight
;
15791 } else if ( overlapLeft
< 0 ) {
15792 popupOffset
-= overlapLeft
;
15795 // Adjust offset to avoid anchor being rendered too close to the edge
15796 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
15797 // TODO: Find a measurement that works for CSS anchors and image anchors
15798 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
15799 if ( popupOffset
+ this.width
< anchorWidth
) {
15800 popupOffset
= anchorWidth
- this.width
;
15801 } else if ( -popupOffset
< anchorWidth
) {
15802 popupOffset
= -anchorWidth
;
15805 // Prevent transition from being interrupted
15806 clearTimeout( this.transitionTimeout
);
15807 if ( transition
) {
15808 // Enable transition
15809 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
15812 // Position body relative to anchor
15813 this.$popup
.css( 'margin-left', popupOffset
);
15815 if ( transition
) {
15816 // Prevent transitioning after transition is complete
15817 this.transitionTimeout
= setTimeout( function () {
15818 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
15821 // Prevent transitioning immediately
15822 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
15825 // Reevaluate clipping state since we've relocated and resized the popup
15832 * Set popup alignment
15833 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
15834 * `backwards` or `forwards`.
15836 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
15837 // Validate alignment and transform deprecated values
15838 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
15839 this.align
= { left
: 'force-right', right
: 'force-left' }[ align
] || align
;
15841 this.align
= 'center';
15846 * Get popup alignment
15847 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
15848 * `backwards` or `forwards`.
15850 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
15855 * Progress bars visually display the status of an operation, such as a download,
15856 * and can be either determinate or indeterminate:
15858 * - **determinate** process bars show the percent of an operation that is complete.
15860 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
15861 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
15862 * not use percentages.
15864 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
15867 * // Examples of determinate and indeterminate progress bars.
15868 * var progressBar1 = new OO.ui.ProgressBarWidget( {
15871 * var progressBar2 = new OO.ui.ProgressBarWidget();
15873 * // Create a FieldsetLayout to layout progress bars
15874 * var fieldset = new OO.ui.FieldsetLayout;
15875 * fieldset.addItems( [
15876 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
15877 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
15879 * $( 'body' ).append( fieldset.$element );
15882 * @extends OO.ui.Widget
15885 * @param {Object} [config] Configuration options
15886 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
15887 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
15888 * By default, the progress bar is indeterminate.
15890 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
15891 // Configuration initialization
15892 config
= config
|| {};
15894 // Parent constructor
15895 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
15898 this.$bar
= $( '<div>' );
15899 this.progress
= null;
15902 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
15903 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
15906 role
: 'progressbar',
15907 'aria-valuemin': 0,
15908 'aria-valuemax': 100
15910 .addClass( 'oo-ui-progressBarWidget' )
15911 .append( this.$bar
);
15916 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
15918 /* Static Properties */
15920 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
15925 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
15927 * @return {number|boolean} Progress percent
15929 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
15930 return this.progress
;
15934 * Set the percent of the process completed or `false` for an indeterminate process.
15936 * @param {number|boolean} progress Progress percent or `false` for indeterminate
15938 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
15939 this.progress
= progress
;
15941 if ( progress
!== false ) {
15942 this.$bar
.css( 'width', this.progress
+ '%' );
15943 this.$element
.attr( 'aria-valuenow', this.progress
);
15945 this.$bar
.css( 'width', '' );
15946 this.$element
.removeAttr( 'aria-valuenow' );
15948 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress
);
15952 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
15953 * and a {@link OO.ui.TextInputMenuSelectWidget menu} of search results, which is displayed beneath the query
15954 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
15955 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
15956 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
15958 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
15959 * the [OOjs UI demos][1] for an example.
15961 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
15964 * @extends OO.ui.Widget
15967 * @param {Object} [config] Configuration options
15968 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
15969 * @cfg {string} [value] Initial query value
15971 OO
.ui
.SearchWidget
= function OoUiSearchWidget( config
) {
15972 // Configuration initialization
15973 config
= config
|| {};
15975 // Parent constructor
15976 OO
.ui
.SearchWidget
.parent
.call( this, config
);
15979 this.query
= new OO
.ui
.TextInputWidget( {
15981 placeholder
: config
.placeholder
,
15982 value
: config
.value
15984 this.results
= new OO
.ui
.SelectWidget();
15985 this.$query
= $( '<div>' );
15986 this.$results
= $( '<div>' );
15989 this.query
.connect( this, {
15990 change
: 'onQueryChange',
15991 enter
: 'onQueryEnter'
15993 this.query
.$input
.on( 'keydown', this.onQueryKeydown
.bind( this ) );
15997 .addClass( 'oo-ui-searchWidget-query' )
15998 .append( this.query
.$element
);
16000 .addClass( 'oo-ui-searchWidget-results' )
16001 .append( this.results
.$element
);
16003 .addClass( 'oo-ui-searchWidget' )
16004 .append( this.$results
, this.$query
);
16009 OO
.inheritClass( OO
.ui
.SearchWidget
, OO
.ui
.Widget
);
16014 * Handle query key down events.
16017 * @param {jQuery.Event} e Key down event
16019 OO
.ui
.SearchWidget
.prototype.onQueryKeydown = function ( e
) {
16020 var highlightedItem
, nextItem
,
16021 dir
= e
.which
=== OO
.ui
.Keys
.DOWN
? 1 : ( e
.which
=== OO
.ui
.Keys
.UP
? -1 : 0 );
16024 highlightedItem
= this.results
.getHighlightedItem();
16025 if ( !highlightedItem
) {
16026 highlightedItem
= this.results
.getSelectedItem();
16028 nextItem
= this.results
.getRelativeSelectableItem( highlightedItem
, dir
);
16029 this.results
.highlightItem( nextItem
);
16030 nextItem
.scrollElementIntoView();
16035 * Handle select widget select events.
16037 * Clears existing results. Subclasses should repopulate items according to new query.
16040 * @param {string} value New value
16042 OO
.ui
.SearchWidget
.prototype.onQueryChange = function () {
16044 this.results
.clearItems();
16048 * Handle select widget enter key events.
16050 * Chooses highlighted item.
16053 * @param {string} value New value
16055 OO
.ui
.SearchWidget
.prototype.onQueryEnter = function () {
16057 this.results
.chooseItem( this.results
.getHighlightedItem() );
16061 * Get the query input.
16063 * @return {OO.ui.TextInputWidget} Query input
16065 OO
.ui
.SearchWidget
.prototype.getQuery = function () {
16070 * Get the search results menu.
16072 * @return {OO.ui.SelectWidget} Menu of search results
16074 OO
.ui
.SearchWidget
.prototype.getResults = function () {
16075 return this.results
;
16079 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
16080 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
16081 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
16084 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
16085 * information, please see the [OOjs UI documentation on MediaWiki][1].
16088 * // Example of a select widget with three options
16089 * var select = new OO.ui.SelectWidget( {
16091 * new OO.ui.OptionWidget( {
16093 * label: 'Option One',
16095 * new OO.ui.OptionWidget( {
16097 * label: 'Option Two',
16099 * new OO.ui.OptionWidget( {
16101 * label: 'Option Three',
16105 * $( 'body' ).append( select.$element );
16107 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16111 * @extends OO.ui.Widget
16112 * @mixins OO.ui.mixin.GroupElement
16115 * @param {Object} [config] Configuration options
16116 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
16117 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
16118 * the [OOjs UI documentation on MediaWiki] [2] for examples.
16119 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16121 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
16122 // Configuration initialization
16123 config
= config
|| {};
16125 // Parent constructor
16126 OO
.ui
.SelectWidget
.parent
.call( this, config
);
16128 // Mixin constructors
16129 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
16132 this.pressed
= false;
16133 this.selecting
= null;
16134 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
16135 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
16136 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
16137 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
16138 this.keyPressBuffer
= '';
16139 this.keyPressBufferTimer
= null;
16142 this.connect( this, {
16145 this.$element
.on( {
16146 mousedown
: this.onMouseDown
.bind( this ),
16147 mouseover
: this.onMouseOver
.bind( this ),
16148 mouseleave
: this.onMouseLeave
.bind( this )
16153 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
16154 .attr( 'role', 'listbox' );
16155 if ( Array
.isArray( config
.items
) ) {
16156 this.addItems( config
.items
);
16162 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
16164 // Need to mixin base class as well
16165 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupElement
);
16166 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
16169 OO
.ui
.SelectWidget
.static.passAllFilter = function () {
16178 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
16180 * @param {OO.ui.OptionWidget|null} item Highlighted item
16186 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
16187 * pressed state of an option.
16189 * @param {OO.ui.OptionWidget|null} item Pressed item
16195 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
16197 * @param {OO.ui.OptionWidget|null} item Selected item
16202 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
16203 * @param {OO.ui.OptionWidget} item Chosen item
16209 * An `add` event is emitted when options are added to the select with the #addItems method.
16211 * @param {OO.ui.OptionWidget[]} items Added items
16212 * @param {number} index Index of insertion point
16218 * A `remove` event is emitted when options are removed from the select with the #clearItems
16219 * or #removeItems methods.
16221 * @param {OO.ui.OptionWidget[]} items Removed items
16227 * Handle mouse down events.
16230 * @param {jQuery.Event} e Mouse down event
16232 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
16235 if ( !this.isDisabled() && e
.which
=== 1 ) {
16236 this.togglePressed( true );
16237 item
= this.getTargetItem( e
);
16238 if ( item
&& item
.isSelectable() ) {
16239 this.pressItem( item
);
16240 this.selecting
= item
;
16241 this.getElementDocument().addEventListener(
16243 this.onMouseUpHandler
,
16246 this.getElementDocument().addEventListener(
16248 this.onMouseMoveHandler
,
16257 * Handle mouse up events.
16260 * @param {jQuery.Event} e Mouse up event
16262 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
16265 this.togglePressed( false );
16266 if ( !this.selecting
) {
16267 item
= this.getTargetItem( e
);
16268 if ( item
&& item
.isSelectable() ) {
16269 this.selecting
= item
;
16272 if ( !this.isDisabled() && e
.which
=== 1 && this.selecting
) {
16273 this.pressItem( null );
16274 this.chooseItem( this.selecting
);
16275 this.selecting
= null;
16278 this.getElementDocument().removeEventListener(
16280 this.onMouseUpHandler
,
16283 this.getElementDocument().removeEventListener(
16285 this.onMouseMoveHandler
,
16293 * Handle mouse move events.
16296 * @param {jQuery.Event} e Mouse move event
16298 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
16301 if ( !this.isDisabled() && this.pressed
) {
16302 item
= this.getTargetItem( e
);
16303 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
16304 this.pressItem( item
);
16305 this.selecting
= item
;
16312 * Handle mouse over events.
16315 * @param {jQuery.Event} e Mouse over event
16317 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
16320 if ( !this.isDisabled() ) {
16321 item
= this.getTargetItem( e
);
16322 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
16328 * Handle mouse leave events.
16331 * @param {jQuery.Event} e Mouse over event
16333 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
16334 if ( !this.isDisabled() ) {
16335 this.highlightItem( null );
16341 * Handle key down events.
16344 * @param {jQuery.Event} e Key down event
16346 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
16349 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
16351 if ( !this.isDisabled() && this.isVisible() ) {
16352 switch ( e
.keyCode
) {
16353 case OO
.ui
.Keys
.ENTER
:
16354 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
16355 // Was only highlighted, now let's select it. No-op if already selected.
16356 this.chooseItem( currentItem
);
16360 case OO
.ui
.Keys
.UP
:
16361 case OO
.ui
.Keys
.LEFT
:
16362 this.clearKeyPressBuffer();
16363 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
16366 case OO
.ui
.Keys
.DOWN
:
16367 case OO
.ui
.Keys
.RIGHT
:
16368 this.clearKeyPressBuffer();
16369 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
16372 case OO
.ui
.Keys
.ESCAPE
:
16373 case OO
.ui
.Keys
.TAB
:
16374 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
16375 currentItem
.setHighlighted( false );
16377 this.unbindKeyDownListener();
16378 this.unbindKeyPressListener();
16379 // Don't prevent tabbing away / defocusing
16385 if ( nextItem
.constructor.static.highlightable
) {
16386 this.highlightItem( nextItem
);
16388 this.chooseItem( nextItem
);
16390 nextItem
.scrollElementIntoView();
16394 // Can't just return false, because e is not always a jQuery event
16395 e
.preventDefault();
16396 e
.stopPropagation();
16402 * Bind key down listener.
16406 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
16407 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler
, true );
16411 * Unbind key down listener.
16415 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
16416 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler
, true );
16420 * Clear the key-press buffer
16424 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
16425 if ( this.keyPressBufferTimer
) {
16426 clearTimeout( this.keyPressBufferTimer
);
16427 this.keyPressBufferTimer
= null;
16429 this.keyPressBuffer
= '';
16433 * Handle key press events.
16436 * @param {jQuery.Event} e Key press event
16438 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
16439 var c
, filter
, item
;
16441 if ( !e
.charCode
) {
16442 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
16443 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
16448 if ( String
.fromCodePoint
) {
16449 c
= String
.fromCodePoint( e
.charCode
);
16451 c
= String
.fromCharCode( e
.charCode
);
16454 if ( this.keyPressBufferTimer
) {
16455 clearTimeout( this.keyPressBufferTimer
);
16457 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
16459 item
= this.getHighlightedItem() || this.getSelectedItem();
16461 if ( this.keyPressBuffer
=== c
) {
16462 // Common (if weird) special case: typing "xxxx" will cycle through all
16463 // the items beginning with "x".
16465 item
= this.getRelativeSelectableItem( item
, 1 );
16468 this.keyPressBuffer
+= c
;
16471 filter
= this.getItemMatcher( this.keyPressBuffer
);
16472 if ( !item
|| !filter( item
) ) {
16473 item
= this.getRelativeSelectableItem( item
, 1, filter
);
16476 if ( item
.constructor.static.highlightable
) {
16477 this.highlightItem( item
);
16479 this.chooseItem( item
);
16481 item
.scrollElementIntoView();
16488 * Get a matcher for the specific string
16491 * @param {string} s String to match against items
16492 * @return {Function} function ( OO.ui.OptionItem ) => boolean
16494 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
) {
16497 if ( s
.normalize
) {
16500 re
= new RegExp( '^\\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' ), 'i' );
16501 return function ( item
) {
16502 var l
= item
.getLabel();
16503 if ( typeof l
!== 'string' ) {
16504 l
= item
.$label
.text();
16506 if ( l
.normalize
) {
16509 return re
.test( l
);
16514 * Bind key press listener.
16518 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
16519 this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler
, true );
16523 * Unbind key down listener.
16525 * If you override this, be sure to call this.clearKeyPressBuffer() from your
16530 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
16531 this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler
, true );
16532 this.clearKeyPressBuffer();
16536 * Visibility change handler
16539 * @param {boolean} visible
16541 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
16543 this.clearKeyPressBuffer();
16548 * Get the closest item to a jQuery.Event.
16551 * @param {jQuery.Event} e
16552 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
16554 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
16555 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
16559 * Get selected item.
16561 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
16563 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
16566 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
16567 if ( this.items
[ i
].isSelected() ) {
16568 return this.items
[ i
];
16575 * Get highlighted item.
16577 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
16579 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
16582 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
16583 if ( this.items
[ i
].isHighlighted() ) {
16584 return this.items
[ i
];
16591 * Toggle pressed state.
16593 * Press is a state that occurs when a user mouses down on an item, but
16594 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
16595 * until the user releases the mouse.
16597 * @param {boolean} pressed An option is being pressed
16599 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
16600 if ( pressed
=== undefined ) {
16601 pressed
= !this.pressed
;
16603 if ( pressed
!== this.pressed
) {
16605 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
16606 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
16607 this.pressed
= pressed
;
16612 * Highlight an option. If the `item` param is omitted, no options will be highlighted
16613 * and any existing highlight will be removed. The highlight is mutually exclusive.
16615 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
16619 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
16620 var i
, len
, highlighted
,
16623 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
16624 highlighted
= this.items
[ i
] === item
;
16625 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
16626 this.items
[ i
].setHighlighted( highlighted
);
16631 this.emit( 'highlight', item
);
16638 * Programmatically select an option by its data. If the `data` parameter is omitted,
16639 * or if the item does not exist, all options will be deselected.
16641 * @param {Object|string} [data] Value of the item to select, omit to deselect all
16645 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
16646 var itemFromData
= this.getItemFromData( data
);
16647 if ( data
=== undefined || !itemFromData
) {
16648 return this.selectItem();
16650 return this.selectItem( itemFromData
);
16654 * Programmatically select an option by its reference. If the `item` parameter is omitted,
16655 * all options will be deselected.
16657 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
16661 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
16662 var i
, len
, selected
,
16665 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
16666 selected
= this.items
[ i
] === item
;
16667 if ( this.items
[ i
].isSelected() !== selected
) {
16668 this.items
[ i
].setSelected( selected
);
16673 this.emit( 'select', item
);
16682 * Press is a state that occurs when a user mouses down on an item, but has not
16683 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
16684 * releases the mouse.
16686 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
16690 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
16691 var i
, len
, pressed
,
16694 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
16695 pressed
= this.items
[ i
] === item
;
16696 if ( this.items
[ i
].isPressed() !== pressed
) {
16697 this.items
[ i
].setPressed( pressed
);
16702 this.emit( 'press', item
);
16711 * Note that ‘choose’ should never be modified programmatically. A user can choose
16712 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
16713 * use the #selectItem method.
16715 * This method is identical to #selectItem, but may vary in subclasses that take additional action
16716 * when users choose an item with the keyboard or mouse.
16718 * @param {OO.ui.OptionWidget} item Item to choose
16722 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
16723 this.selectItem( item
);
16724 this.emit( 'choose', item
);
16730 * Get an option by its position relative to the specified item (or to the start of the option array,
16731 * if item is `null`). The direction in which to search through the option array is specified with a
16732 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
16733 * `null` if there are no options in the array.
16735 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
16736 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
16737 * @param {Function} filter Only consider items for which this function returns
16738 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
16739 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
16741 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
16742 var currentIndex
, nextIndex
, i
,
16743 increase
= direction
> 0 ? 1 : -1,
16744 len
= this.items
.length
;
16746 if ( !$.isFunction( filter
) ) {
16747 filter
= OO
.ui
.SelectWidget
.static.passAllFilter
;
16750 if ( item
instanceof OO
.ui
.OptionWidget
) {
16751 currentIndex
= $.inArray( item
, this.items
);
16752 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
16754 // If no item is selected and moving forward, start at the beginning.
16755 // If moving backward, start at the end.
16756 nextIndex
= direction
> 0 ? 0 : len
- 1;
16759 for ( i
= 0; i
< len
; i
++ ) {
16760 item
= this.items
[ nextIndex
];
16761 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
16764 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
16770 * Get the next selectable item or `null` if there are no selectable items.
16771 * Disabled options and menu-section markers and breaks are not selectable.
16773 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
16775 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
16778 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
16779 item
= this.items
[ i
];
16780 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
16789 * Add an array of options to the select. Optionally, an index number can be used to
16790 * specify an insertion point.
16792 * @param {OO.ui.OptionWidget[]} items Items to add
16793 * @param {number} [index] Index to insert items after
16797 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
16799 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
16801 // Always provide an index, even if it was omitted
16802 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
16808 * Remove the specified array of options from the select. Options will be detached
16809 * from the DOM, not removed, so they can be reused later. To remove all options from
16810 * the select, you may wish to use the #clearItems method instead.
16812 * @param {OO.ui.OptionWidget[]} items Items to remove
16816 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
16819 // Deselect items being removed
16820 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
16822 if ( item
.isSelected() ) {
16823 this.selectItem( null );
16828 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
16830 this.emit( 'remove', items
);
16836 * Clear all options from the select. Options will be detached from the DOM, not removed,
16837 * so that they can be reused later. To remove a subset of options from the select, use
16838 * the #removeItems method.
16843 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
16844 var items
= this.items
.slice();
16847 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
16850 this.selectItem( null );
16852 this.emit( 'remove', items
);
16858 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
16859 * button options and is used together with
16860 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
16861 * highlighting, choosing, and selecting mutually exclusive options. Please see
16862 * the [OOjs UI documentation on MediaWiki] [1] for more information.
16865 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
16866 * var option1 = new OO.ui.ButtonOptionWidget( {
16868 * label: 'Option 1',
16869 * title: 'Button option 1'
16872 * var option2 = new OO.ui.ButtonOptionWidget( {
16874 * label: 'Option 2',
16875 * title: 'Button option 2'
16878 * var option3 = new OO.ui.ButtonOptionWidget( {
16880 * label: 'Option 3',
16881 * title: 'Button option 3'
16884 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
16885 * items: [ option1, option2, option3 ]
16887 * $( 'body' ).append( buttonSelect.$element );
16889 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16892 * @extends OO.ui.SelectWidget
16893 * @mixins OO.ui.mixin.TabIndexedElement
16896 * @param {Object} [config] Configuration options
16898 OO
.ui
.ButtonSelectWidget
= function OoUiButtonSelectWidget( config
) {
16899 // Parent constructor
16900 OO
.ui
.ButtonSelectWidget
.parent
.call( this, config
);
16902 // Mixin constructors
16903 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
16906 this.$element
.on( {
16907 focus
: this.bindKeyDownListener
.bind( this ),
16908 blur
: this.unbindKeyDownListener
.bind( this )
16912 this.$element
.addClass( 'oo-ui-buttonSelectWidget' );
16917 OO
.inheritClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.SelectWidget
);
16918 OO
.mixinClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
16921 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
16922 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
16923 * an interface for adding, removing and selecting options.
16924 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
16926 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
16927 * OO.ui.RadioSelectInputWidget instead.
16930 * // A RadioSelectWidget with RadioOptions.
16931 * var option1 = new OO.ui.RadioOptionWidget( {
16933 * label: 'Selected radio option'
16936 * var option2 = new OO.ui.RadioOptionWidget( {
16938 * label: 'Unselected radio option'
16941 * var radioSelect=new OO.ui.RadioSelectWidget( {
16942 * items: [ option1, option2 ]
16945 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
16946 * radioSelect.selectItem( option1 );
16948 * $( 'body' ).append( radioSelect.$element );
16950 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16954 * @extends OO.ui.SelectWidget
16955 * @mixins OO.ui.mixin.TabIndexedElement
16958 * @param {Object} [config] Configuration options
16960 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
16961 // Parent constructor
16962 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
16964 // Mixin constructors
16965 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
16968 this.$element
.on( {
16969 focus
: this.bindKeyDownListener
.bind( this ),
16970 blur
: this.unbindKeyDownListener
.bind( this )
16975 .addClass( 'oo-ui-radioSelectWidget' )
16976 .attr( 'role', 'radiogroup' );
16981 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
16982 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
16985 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
16986 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
16987 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
16988 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
16989 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
16990 * and customized to be opened, closed, and displayed as needed.
16992 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
16993 * mouse outside the menu.
16995 * Menus also have support for keyboard interaction:
16997 * - Enter/Return key: choose and select a menu option
16998 * - Up-arrow key: highlight the previous menu option
16999 * - Down-arrow key: highlight the next menu option
17000 * - Esc key: hide the menu
17002 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
17003 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17006 * @extends OO.ui.SelectWidget
17007 * @mixins OO.ui.mixin.ClippableElement
17010 * @param {Object} [config] Configuration options
17011 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
17012 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
17013 * and {@link OO.ui.mixin.LookupElement LookupElement}
17014 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
17015 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
17016 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
17017 * that button, unless the button (or its parent widget) is passed in here.
17018 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
17020 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
17021 // Configuration initialization
17022 config
= config
|| {};
17024 // Parent constructor
17025 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
17027 // Mixin constructors
17028 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
17031 this.newItems
= null;
17032 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
17033 this.$input
= config
.input
? config
.input
.$input
: null;
17034 this.$widget
= config
.widget
? config
.widget
.$element
: null;
17035 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
17039 .addClass( 'oo-ui-menuSelectWidget' )
17040 .attr( 'role', 'menu' );
17042 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
17043 // that reference properties not initialized at that time of parent class construction
17044 // TODO: Find a better way to handle post-constructor setup
17045 this.visible
= false;
17046 this.$element
.addClass( 'oo-ui-element-hidden' );
17051 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
17052 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
17057 * Handles document mouse down events.
17060 * @param {jQuery.Event} e Key down event
17062 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
17064 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
17065 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
17067 this.toggle( false );
17074 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
17075 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
17077 if ( !this.isDisabled() && this.isVisible() ) {
17078 switch ( e
.keyCode
) {
17079 case OO
.ui
.Keys
.LEFT
:
17080 case OO
.ui
.Keys
.RIGHT
:
17081 // Do nothing if a text field is associated, arrow keys will be handled natively
17082 if ( !this.$input
) {
17083 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
17086 case OO
.ui
.Keys
.ESCAPE
:
17087 case OO
.ui
.Keys
.TAB
:
17088 if ( currentItem
) {
17089 currentItem
.setHighlighted( false );
17091 this.toggle( false );
17092 // Don't prevent tabbing away, prevent defocusing
17093 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
17094 e
.preventDefault();
17095 e
.stopPropagation();
17099 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
17108 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
17109 if ( this.$input
) {
17110 this.$input
.on( 'keydown', this.onKeyDownHandler
);
17112 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
17119 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
17120 if ( this.$input
) {
17121 this.$input
.off( 'keydown', this.onKeyDownHandler
);
17123 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
17130 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
17131 if ( !this.$input
) {
17132 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
17139 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
17140 if ( this.$input
) {
17141 this.clearKeyPressBuffer();
17143 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
17150 * When a user chooses an item, the menu is closed.
17152 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
17153 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
17154 * @param {OO.ui.OptionWidget} item Item to choose
17157 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
17158 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
17159 this.toggle( false );
17166 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
17170 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
17173 if ( !this.newItems
) {
17174 this.newItems
= [];
17177 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
17179 if ( this.isVisible() ) {
17180 // Defer fitting label until item has been attached
17183 this.newItems
.push( item
);
17187 // Reevaluate clipping
17196 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
17198 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
17200 // Reevaluate clipping
17209 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
17211 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
17213 // Reevaluate clipping
17222 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
17223 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
17226 change
= visible
!== this.isVisible();
17229 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
17233 this.bindKeyDownListener();
17234 this.bindKeyPressListener();
17236 if ( this.newItems
&& this.newItems
.length
) {
17237 for ( i
= 0, len
= this.newItems
.length
; i
< len
; i
++ ) {
17238 this.newItems
[ i
].fitLabel();
17240 this.newItems
= null;
17242 this.toggleClipping( true );
17245 if ( this.autoHide
) {
17246 this.getElementDocument().addEventListener(
17247 'mousedown', this.onDocumentMouseDownHandler
, true
17251 this.unbindKeyDownListener();
17252 this.unbindKeyPressListener();
17253 this.getElementDocument().removeEventListener(
17254 'mousedown', this.onDocumentMouseDownHandler
, true
17256 this.toggleClipping( false );
17264 * TextInputMenuSelectWidget is a menu that is specially designed to be positioned beneath
17265 * a {@link OO.ui.TextInputWidget text input} field. The menu's position is automatically
17266 * calculated and maintained when the menu is toggled or the window is resized.
17267 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
17270 * @extends OO.ui.MenuSelectWidget
17273 * @param {OO.ui.TextInputWidget} inputWidget Text input widget to provide menu for
17274 * @param {Object} [config] Configuration options
17275 * @cfg {jQuery} [$container=input.$element] Element to render menu under
17277 OO
.ui
.TextInputMenuSelectWidget
= function OoUiTextInputMenuSelectWidget( inputWidget
, config
) {
17278 // Allow passing positional parameters inside the config object
17279 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
17280 config
= inputWidget
;
17281 inputWidget
= config
.inputWidget
;
17284 // Configuration initialization
17285 config
= config
|| {};
17287 // Parent constructor
17288 OO
.ui
.TextInputMenuSelectWidget
.parent
.call( this, config
);
17291 this.inputWidget
= inputWidget
;
17292 this.$container
= config
.$container
|| this.inputWidget
.$element
;
17293 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
17296 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
17301 OO
.inheritClass( OO
.ui
.TextInputMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
17306 * Handle window resize event.
17309 * @param {jQuery.Event} e Window resize event
17311 OO
.ui
.TextInputMenuSelectWidget
.prototype.onWindowResize = function () {
17318 OO
.ui
.TextInputMenuSelectWidget
.prototype.toggle = function ( visible
) {
17319 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
17321 var change
= visible
!== this.isVisible();
17323 if ( change
&& visible
) {
17324 // Make sure the width is set before the parent method runs.
17325 // After this we have to call this.position(); again to actually
17326 // position ourselves correctly.
17331 OO
.ui
.TextInputMenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
17334 if ( this.isVisible() ) {
17336 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
17338 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
17346 * Position the menu.
17351 OO
.ui
.TextInputMenuSelectWidget
.prototype.position = function () {
17352 var $container
= this.$container
,
17353 pos
= OO
.ui
.Element
.static.getRelativePosition( $container
, this.$element
.offsetParent() );
17355 // Position under input
17356 pos
.top
+= $container
.height();
17357 this.$element
.css( pos
);
17360 this.setIdealSize( $container
.width() );
17361 // We updated the position, so re-evaluate the clipping state
17368 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
17369 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
17371 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
17374 * @extends OO.ui.SelectWidget
17375 * @mixins OO.ui.mixin.TabIndexedElement
17378 * @param {Object} [config] Configuration options
17380 OO
.ui
.OutlineSelectWidget
= function OoUiOutlineSelectWidget( config
) {
17381 // Parent constructor
17382 OO
.ui
.OutlineSelectWidget
.parent
.call( this, config
);
17384 // Mixin constructors
17385 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
17388 this.$element
.on( {
17389 focus
: this.bindKeyDownListener
.bind( this ),
17390 blur
: this.unbindKeyDownListener
.bind( this )
17394 this.$element
.addClass( 'oo-ui-outlineSelectWidget' );
17399 OO
.inheritClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.SelectWidget
);
17400 OO
.mixinClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
17403 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
17405 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
17408 * @extends OO.ui.SelectWidget
17409 * @mixins OO.ui.mixin.TabIndexedElement
17412 * @param {Object} [config] Configuration options
17414 OO
.ui
.TabSelectWidget
= function OoUiTabSelectWidget( config
) {
17415 // Parent constructor
17416 OO
.ui
.TabSelectWidget
.parent
.call( this, config
);
17418 // Mixin constructors
17419 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
17422 this.$element
.on( {
17423 focus
: this.bindKeyDownListener
.bind( this ),
17424 blur
: this.unbindKeyDownListener
.bind( this )
17428 this.$element
.addClass( 'oo-ui-tabSelectWidget' );
17433 OO
.inheritClass( OO
.ui
.TabSelectWidget
, OO
.ui
.SelectWidget
);
17434 OO
.mixinClass( OO
.ui
.TabSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
17437 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
17438 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
17439 * (to adjust the value in increments) to allow the user to enter a number.
17442 * // Example: A NumberInputWidget.
17443 * var numberInput = new OO.ui.NumberInputWidget( {
17444 * label: 'NumberInputWidget',
17445 * input: { value: 5, min: 1, max: 10 }
17447 * $( 'body' ).append( numberInput.$element );
17450 * @extends OO.ui.Widget
17453 * @param {Object} [config] Configuration options
17454 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
17455 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
17456 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
17457 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
17458 * @cfg {number} [min=-Infinity] Minimum allowed value
17459 * @cfg {number} [max=Infinity] Maximum allowed value
17460 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
17461 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
17463 OO
.ui
.NumberInputWidget
= function OoUiNumberInputWidget( config
) {
17464 // Configuration initialization
17465 config
= $.extend( {
17473 // Parent constructor
17474 OO
.ui
.NumberInputWidget
.parent
.call( this, config
);
17477 this.input
= new OO
.ui
.TextInputWidget( $.extend(
17479 disabled
: this.isDisabled()
17483 this.minusButton
= new OO
.ui
.ButtonWidget( $.extend(
17485 disabled
: this.isDisabled(),
17488 config
.minusButton
,
17490 classes
: [ 'oo-ui-numberInputWidget-minusButton' ],
17494 this.plusButton
= new OO
.ui
.ButtonWidget( $.extend(
17496 disabled
: this.isDisabled(),
17501 classes
: [ 'oo-ui-numberInputWidget-plusButton' ],
17507 this.input
.connect( this, {
17508 change
: this.emit
.bind( this, 'change' ),
17509 enter
: this.emit
.bind( this, 'enter' )
17511 this.input
.$input
.on( {
17512 keydown
: this.onKeyDown
.bind( this ),
17513 'wheel mousewheel DOMMouseScroll': this.onWheel
.bind( this )
17515 this.plusButton
.connect( this, {
17516 click
: [ 'onButtonClick', +1 ]
17518 this.minusButton
.connect( this, {
17519 click
: [ 'onButtonClick', -1 ]
17523 this.setIsInteger( !!config
.isInteger
);
17524 this.setRange( config
.min
, config
.max
);
17525 this.setStep( config
.step
, config
.pageStep
);
17527 this.$field
= $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
17529 this.minusButton
.$element
,
17530 this.input
.$element
,
17531 this.plusButton
.$element
17533 this.$element
.addClass( 'oo-ui-numberInputWidget' ).append( this.$field
);
17534 this.input
.setValidation( this.validateNumber
.bind( this ) );
17539 OO
.inheritClass( OO
.ui
.NumberInputWidget
, OO
.ui
.Widget
);
17544 * A `change` event is emitted when the value of the input changes.
17550 * An `enter` event is emitted when the user presses 'enter' inside the text box.
17558 * Set whether only integers are allowed
17559 * @param {boolean} flag
17561 OO
.ui
.NumberInputWidget
.prototype.setIsInteger = function ( flag
) {
17562 this.isInteger
= !!flag
;
17563 this.input
.setValidityFlag();
17567 * Get whether only integers are allowed
17568 * @return {boolean} Flag value
17570 OO
.ui
.NumberInputWidget
.prototype.getIsInteger = function () {
17571 return this.isInteger
;
17575 * Set the range of allowed values
17576 * @param {number} min Minimum allowed value
17577 * @param {number} max Maximum allowed value
17579 OO
.ui
.NumberInputWidget
.prototype.setRange = function ( min
, max
) {
17581 throw new Error( 'Minimum (' + min
+ ') must not be greater than maximum (' + max
+ ')' );
17585 this.input
.setValidityFlag();
17589 * Get the current range
17590 * @return {number[]} Minimum and maximum values
17592 OO
.ui
.NumberInputWidget
.prototype.getRange = function () {
17593 return [ this.min
, this.max
];
17597 * Set the stepping deltas
17598 * @param {number} step Normal step
17599 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
17601 OO
.ui
.NumberInputWidget
.prototype.setStep = function ( step
, pageStep
) {
17603 throw new Error( 'Step value must be positive' );
17605 if ( pageStep
=== null ) {
17606 pageStep
= step
* 10;
17607 } else if ( pageStep
<= 0 ) {
17608 throw new Error( 'Page step value must be positive' );
17611 this.pageStep
= pageStep
;
17615 * Get the current stepping values
17616 * @return {number[]} Step and page step
17618 OO
.ui
.NumberInputWidget
.prototype.getStep = function () {
17619 return [ this.step
, this.pageStep
];
17623 * Get the current value of the widget
17626 OO
.ui
.NumberInputWidget
.prototype.getValue = function () {
17627 return this.input
.getValue();
17631 * Get the current value of the widget as a number
17632 * @return {number} May be NaN, or an invalid number
17634 OO
.ui
.NumberInputWidget
.prototype.getNumericValue = function () {
17635 return +this.input
.getValue();
17639 * Set the value of the widget
17640 * @param {string} value Invalid values are allowed
17642 OO
.ui
.NumberInputWidget
.prototype.setValue = function ( value
) {
17643 this.input
.setValue( value
);
17647 * Adjust the value of the widget
17648 * @param {number} delta Adjustment amount
17650 OO
.ui
.NumberInputWidget
.prototype.adjustValue = function ( delta
) {
17651 var n
, v
= this.getNumericValue();
17654 if ( isNaN( delta
) || !isFinite( delta
) ) {
17655 throw new Error( 'Delta must be a finite number' );
17658 if ( isNaN( v
) ) {
17662 n
= Math
.max( Math
.min( n
, this.max
), this.min
);
17663 if ( this.isInteger
) {
17664 n
= Math
.round( n
);
17669 this.setValue( n
);
17676 * @param {string} value Field value
17677 * @return {boolean}
17679 OO
.ui
.NumberInputWidget
.prototype.validateNumber = function ( value
) {
17681 if ( isNaN( n
) || !isFinite( n
) ) {
17685 /*jshint bitwise: false */
17686 if ( this.isInteger
&& ( n
| 0 ) !== n
) {
17689 /*jshint bitwise: true */
17691 if ( n
< this.min
|| n
> this.max
) {
17699 * Handle mouse click events.
17702 * @param {number} dir +1 or -1
17704 OO
.ui
.NumberInputWidget
.prototype.onButtonClick = function ( dir
) {
17705 this.adjustValue( dir
* this.step
);
17709 * Handle mouse wheel events.
17712 * @param {jQuery.Event} event
17714 OO
.ui
.NumberInputWidget
.prototype.onWheel = function ( event
) {
17717 // Standard 'wheel' event
17718 if ( event
.originalEvent
.deltaMode
!== undefined ) {
17719 this.sawWheelEvent
= true;
17721 if ( event
.originalEvent
.deltaY
) {
17722 delta
= -event
.originalEvent
.deltaY
;
17723 } else if ( event
.originalEvent
.deltaX
) {
17724 delta
= event
.originalEvent
.deltaX
;
17727 // Non-standard events
17728 if ( !this.sawWheelEvent
) {
17729 if ( event
.originalEvent
.wheelDeltaX
) {
17730 delta
= -event
.originalEvent
.wheelDeltaX
;
17731 } else if ( event
.originalEvent
.wheelDeltaY
) {
17732 delta
= event
.originalEvent
.wheelDeltaY
;
17733 } else if ( event
.originalEvent
.wheelDelta
) {
17734 delta
= event
.originalEvent
.wheelDelta
;
17735 } else if ( event
.originalEvent
.detail
) {
17736 delta
= -event
.originalEvent
.detail
;
17741 delta
= delta
< 0 ? -1 : 1;
17742 this.adjustValue( delta
* this.step
);
17749 * Handle key down events.
17753 * @param {jQuery.Event} e Key down event
17755 OO
.ui
.NumberInputWidget
.prototype.onKeyDown = function ( e
) {
17756 if ( !this.isDisabled() ) {
17757 switch ( e
.which
) {
17758 case OO
.ui
.Keys
.UP
:
17759 this.adjustValue( this.step
);
17761 case OO
.ui
.Keys
.DOWN
:
17762 this.adjustValue( -this.step
);
17764 case OO
.ui
.Keys
.PAGEUP
:
17765 this.adjustValue( this.pageStep
);
17767 case OO
.ui
.Keys
.PAGEDOWN
:
17768 this.adjustValue( -this.pageStep
);
17777 OO
.ui
.NumberInputWidget
.prototype.setDisabled = function ( disabled
) {
17779 OO
.ui
.NumberInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
17781 if ( this.input
) {
17782 this.input
.setDisabled( this.isDisabled() );
17784 if ( this.minusButton
) {
17785 this.minusButton
.setDisabled( this.isDisabled() );
17787 if ( this.plusButton
) {
17788 this.plusButton
.setDisabled( this.isDisabled() );
17795 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
17796 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
17797 * visually by a slider in the leftmost position.
17800 * // Toggle switches in the 'off' and 'on' position.
17801 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
17802 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
17806 * // Create a FieldsetLayout to layout and label switches
17807 * var fieldset = new OO.ui.FieldsetLayout( {
17808 * label: 'Toggle switches'
17810 * fieldset.addItems( [
17811 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
17812 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
17814 * $( 'body' ).append( fieldset.$element );
17817 * @extends OO.ui.ToggleWidget
17818 * @mixins OO.ui.mixin.TabIndexedElement
17821 * @param {Object} [config] Configuration options
17822 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
17823 * By default, the toggle switch is in the 'off' position.
17825 OO
.ui
.ToggleSwitchWidget
= function OoUiToggleSwitchWidget( config
) {
17826 // Parent constructor
17827 OO
.ui
.ToggleSwitchWidget
.parent
.call( this, config
);
17829 // Mixin constructors
17830 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
17833 this.dragging
= false;
17834 this.dragStart
= null;
17835 this.sliding
= false;
17836 this.$glow
= $( '<span>' );
17837 this.$grip
= $( '<span>' );
17840 this.$element
.on( {
17841 click
: this.onClick
.bind( this ),
17842 keypress
: this.onKeyPress
.bind( this )
17846 this.$glow
.addClass( 'oo-ui-toggleSwitchWidget-glow' );
17847 this.$grip
.addClass( 'oo-ui-toggleSwitchWidget-grip' );
17849 .addClass( 'oo-ui-toggleSwitchWidget' )
17850 .attr( 'role', 'checkbox' )
17851 .append( this.$glow
, this.$grip
);
17856 OO
.inheritClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.ToggleWidget
);
17857 OO
.mixinClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.mixin
.TabIndexedElement
);
17862 * Handle mouse click events.
17865 * @param {jQuery.Event} e Mouse click event
17867 OO
.ui
.ToggleSwitchWidget
.prototype.onClick = function ( e
) {
17868 if ( !this.isDisabled() && e
.which
=== 1 ) {
17869 this.setValue( !this.value
);
17875 * Handle key press events.
17878 * @param {jQuery.Event} e Key press event
17880 OO
.ui
.ToggleSwitchWidget
.prototype.onKeyPress = function ( e
) {
17881 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
17882 this.setValue( !this.value
);
17888 * Deprecated aliases for classes in the `OO.ui.mixin` namespace.
17892 * @inheritdoc OO.ui.mixin.ButtonElement
17893 * @deprecated Use {@link OO.ui.mixin.ButtonElement} instead.
17895 OO
.ui
.ButtonElement
= OO
.ui
.mixin
.ButtonElement
;
17898 * @inheritdoc OO.ui.mixin.ClippableElement
17899 * @deprecated Use {@link OO.ui.mixin.ClippableElement} instead.
17901 OO
.ui
.ClippableElement
= OO
.ui
.mixin
.ClippableElement
;
17904 * @inheritdoc OO.ui.mixin.DraggableElement
17905 * @deprecated Use {@link OO.ui.mixin.DraggableElement} instead.
17907 OO
.ui
.DraggableElement
= OO
.ui
.mixin
.DraggableElement
;
17910 * @inheritdoc OO.ui.mixin.DraggableGroupElement
17911 * @deprecated Use {@link OO.ui.mixin.DraggableGroupElement} instead.
17913 OO
.ui
.DraggableGroupElement
= OO
.ui
.mixin
.DraggableGroupElement
;
17916 * @inheritdoc OO.ui.mixin.FlaggedElement
17917 * @deprecated Use {@link OO.ui.mixin.FlaggedElement} instead.
17919 OO
.ui
.FlaggedElement
= OO
.ui
.mixin
.FlaggedElement
;
17922 * @inheritdoc OO.ui.mixin.GroupElement
17923 * @deprecated Use {@link OO.ui.mixin.GroupElement} instead.
17925 OO
.ui
.GroupElement
= OO
.ui
.mixin
.GroupElement
;
17928 * @inheritdoc OO.ui.mixin.GroupWidget
17929 * @deprecated Use {@link OO.ui.mixin.GroupWidget} instead.
17931 OO
.ui
.GroupWidget
= OO
.ui
.mixin
.GroupWidget
;
17934 * @inheritdoc OO.ui.mixin.IconElement
17935 * @deprecated Use {@link OO.ui.mixin.IconElement} instead.
17937 OO
.ui
.IconElement
= OO
.ui
.mixin
.IconElement
;
17940 * @inheritdoc OO.ui.mixin.IndicatorElement
17941 * @deprecated Use {@link OO.ui.mixin.IndicatorElement} instead.
17943 OO
.ui
.IndicatorElement
= OO
.ui
.mixin
.IndicatorElement
;
17946 * @inheritdoc OO.ui.mixin.ItemWidget
17947 * @deprecated Use {@link OO.ui.mixin.ItemWidget} instead.
17949 OO
.ui
.ItemWidget
= OO
.ui
.mixin
.ItemWidget
;
17952 * @inheritdoc OO.ui.mixin.LabelElement
17953 * @deprecated Use {@link OO.ui.mixin.LabelElement} instead.
17955 OO
.ui
.LabelElement
= OO
.ui
.mixin
.LabelElement
;
17958 * @inheritdoc OO.ui.mixin.LookupElement
17959 * @deprecated Use {@link OO.ui.mixin.LookupElement} instead.
17961 OO
.ui
.LookupElement
= OO
.ui
.mixin
.LookupElement
;
17964 * @inheritdoc OO.ui.mixin.PendingElement
17965 * @deprecated Use {@link OO.ui.mixin.PendingElement} instead.
17967 OO
.ui
.PendingElement
= OO
.ui
.mixin
.PendingElement
;
17970 * @inheritdoc OO.ui.mixin.PopupElement
17971 * @deprecated Use {@link OO.ui.mixin.PopupElement} instead.
17973 OO
.ui
.PopupElement
= OO
.ui
.mixin
.PopupElement
;
17976 * @inheritdoc OO.ui.mixin.TabIndexedElement
17977 * @deprecated Use {@link OO.ui.mixin.TabIndexedElement} instead.
17979 OO
.ui
.TabIndexedElement
= OO
.ui
.mixin
.TabIndexedElement
;
17982 * @inheritdoc OO.ui.mixin.TitledElement
17983 * @deprecated Use {@link OO.ui.mixin.TitledElement} instead.
17985 OO
.ui
.TitledElement
= OO
.ui
.mixin
.TitledElement
;