3 * https://www.mediawiki.org/wiki/OOjs_UI
5 * Copyright 2011–2015 OOjs Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2015-04-23T00:54:26Z
16 * Namespace for all classes, static methods and static properties.
48 * Check if an element is focusable.
49 * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14
51 * @param {jQuery} element Element to test
52 * @return {Boolean} [description]
54 OO
.ui
.isFocusableElement = function ( $element
) {
55 var node
= $element
[0],
56 nodeName
= node
.nodeName
.toLowerCase(),
57 // Check if the element have tabindex set
58 isInElementGroup
= /^(input|select|textarea|button|object)$/.test( nodeName
),
59 // Check if the element is a link with href or if it has tabindex
61 ( nodeName
=== 'a' && node
.href
) ||
62 !isNaN( $element
.attr( 'tabindex' ) )
64 // Check if the element is visible
66 // This is quicker than calling $element.is( ':visible' )
67 $.expr
.filters
.visible( node
) &&
68 // Check that all parents are visible
69 !$element
.parents().addBack().filter( function () {
70 return $.css( this, 'visibility' ) === 'hidden';
75 ( isInElementGroup
? !node
.disabled
: isOtherElement
) &&
81 * Get the user's language and any fallback languages.
83 * These language codes are used to localize user interface elements in the user's language.
85 * In environments that provide a localization system, this function should be overridden to
86 * return the user's language(s). The default implementation returns English (en) only.
88 * @return {string[]} Language codes, in descending order of priority
90 OO
.ui
.getUserLanguages = function () {
95 * Get a value in an object keyed by language code.
97 * @param {Object.<string,Mixed>} obj Object keyed by language code
98 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
99 * @param {string} [fallback] Fallback code, used if no matching language can be found
100 * @return {Mixed} Local value
102 OO
.ui
.getLocalValue = function ( obj
, lang
, fallback
) {
105 // Requested language
109 // Known user language
110 langs
= OO
.ui
.getUserLanguages();
111 for ( i
= 0, len
= langs
.length
; i
< len
; i
++ ) {
118 if ( obj
[ fallback
] ) {
119 return obj
[ fallback
];
121 // First existing language
122 for ( lang
in obj
) {
130 * Check if a node is contained within another node
132 * Similar to jQuery#contains except a list of containers can be supplied
133 * and a boolean argument allows you to include the container in the match list
135 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
136 * @param {HTMLElement} contained Node to find
137 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
138 * @return {boolean} The node is in the list of target nodes
140 OO
.ui
.contains = function ( containers
, contained
, matchContainers
) {
142 if ( !Array
.isArray( containers
) ) {
143 containers
= [ containers
];
145 for ( i
= containers
.length
- 1; i
>= 0; i
-- ) {
146 if ( ( matchContainers
&& contained
=== containers
[ i
] ) || $.contains( containers
[ i
], contained
) ) {
154 * Reconstitute a JavaScript object corresponding to a widget created by
155 * the PHP implementation.
157 * This is an alias for `OO.ui.Element.static.infuse()`.
159 * @param {string|HTMLElement|jQuery} idOrNode
160 * A DOM id (if a string) or node for the widget to infuse.
161 * @return {OO.ui.Element}
162 * The `OO.ui.Element` corresponding to this (infusable) document node.
164 OO
.ui
.infuse = function ( idOrNode
) {
165 return OO
.ui
.Element
.static.infuse( idOrNode
);
170 * Message store for the default implementation of OO.ui.msg
172 * Environments that provide a localization system should not use this, but should override
173 * OO.ui.msg altogether.
178 // Tool tip for a button that moves items in a list down one place
179 'ooui-outline-control-move-down': 'Move item down',
180 // Tool tip for a button that moves items in a list up one place
181 'ooui-outline-control-move-up': 'Move item up',
182 // Tool tip for a button that removes items from a list
183 'ooui-outline-control-remove': 'Remove item',
184 // Label for the toolbar group that contains a list of all other available tools
185 'ooui-toolbar-more': 'More',
186 // Label for the fake tool that expands the full list of tools in a toolbar group
187 'ooui-toolgroup-expand': 'More',
188 // Label for the fake tool that collapses the full list of tools in a toolbar group
189 'ooui-toolgroup-collapse': 'Fewer',
190 // Default label for the accept button of a confirmation dialog
191 'ooui-dialog-message-accept': 'OK',
192 // Default label for the reject button of a confirmation dialog
193 'ooui-dialog-message-reject': 'Cancel',
194 // Title for process dialog error description
195 'ooui-dialog-process-error': 'Something went wrong',
196 // Label for process dialog dismiss error button, visible when describing errors
197 'ooui-dialog-process-dismiss': 'Dismiss',
198 // Label for process dialog retry action button, visible when describing only recoverable errors
199 'ooui-dialog-process-retry': 'Try again',
200 // Label for process dialog retry action button, visible when describing only warnings
201 'ooui-dialog-process-continue': 'Continue'
205 * Get a localized message.
207 * In environments that provide a localization system, this function should be overridden to
208 * return the message translated in the user's language. The default implementation always returns
211 * After the message key, message parameters may optionally be passed. In the default implementation,
212 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
213 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
214 * they support unnamed, ordered message parameters.
217 * @param {string} key Message key
218 * @param {Mixed...} [params] Message parameters
219 * @return {string} Translated message with parameters substituted
221 OO
.ui
.msg = function ( key
) {
222 var message
= messages
[ key
],
223 params
= Array
.prototype.slice
.call( arguments
, 1 );
224 if ( typeof message
=== 'string' ) {
225 // Perform $1 substitution
226 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
227 var i
= parseInt( n
, 10 );
228 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
231 // Return placeholder if message not found
232 message
= '[' + key
+ ']';
238 * Package a message and arguments for deferred resolution.
240 * Use this when you are statically specifying a message and the message may not yet be present.
242 * @param {string} key Message key
243 * @param {Mixed...} [params] Message parameters
244 * @return {Function} Function that returns the resolved message when executed
246 OO
.ui
.deferMsg = function () {
247 var args
= arguments
;
249 return OO
.ui
.msg
.apply( OO
.ui
, args
);
256 * If the message is a function it will be executed, otherwise it will pass through directly.
258 * @param {Function|string} msg Deferred message, or message text
259 * @return {string} Resolved message
261 OO
.ui
.resolveMsg = function ( msg
) {
262 if ( $.isFunction( msg
) ) {
271 * Element that can be marked as pending.
277 * @param {Object} [config] Configuration options
278 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
280 OO
.ui
.PendingElement
= function OoUiPendingElement( config
) {
281 // Configuration initialization
282 config
= config
|| {};
286 this.$pending
= null;
289 this.setPendingElement( config
.$pending
|| this.$element
);
294 OO
.initClass( OO
.ui
.PendingElement
);
299 * Set the pending element (and clean up any existing one).
301 * @param {jQuery} $pending The element to set to pending.
303 OO
.ui
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
304 if ( this.$pending
) {
305 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
308 this.$pending
= $pending
;
309 if ( this.pending
> 0 ) {
310 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
315 * Check if input is pending.
319 OO
.ui
.PendingElement
.prototype.isPending = function () {
320 return !!this.pending
;
324 * Increase the pending stack.
328 OO
.ui
.PendingElement
.prototype.pushPending = function () {
329 if ( this.pending
=== 0 ) {
330 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
331 this.updateThemeClasses();
339 * Reduce the pending stack.
345 OO
.ui
.PendingElement
.prototype.popPending = function () {
346 if ( this.pending
=== 1 ) {
347 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
348 this.updateThemeClasses();
350 this.pending
= Math
.max( 0, this.pending
- 1 );
356 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
357 * Actions can be made available for specific contexts (modes) and circumstances
358 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
360 * ActionSets contain two types of actions:
362 * - 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.
363 * - Other: Other actions include all non-special visible actions.
365 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
368 * // Example: An action set used in a process dialog
369 * function MyProcessDialog( config ) {
370 * MyProcessDialog.super.call( this, config );
372 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
373 * MyProcessDialog.static.title = 'An action set in a process dialog';
374 * // An action set that uses modes ('edit' and 'help' mode, in this example).
375 * MyProcessDialog.static.actions = [
376 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
377 * { action: 'help', modes: 'edit', label: 'Help' },
378 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
379 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
382 * MyProcessDialog.prototype.initialize = function () {
383 * MyProcessDialog.super.prototype.initialize.apply( this, arguments );
384 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
385 * 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>' );
386 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
387 * 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>' );
388 * this.stackLayout = new OO.ui.StackLayout( {
389 * items: [ this.panel1, this.panel2 ]
391 * this.$body.append( this.stackLayout.$element );
393 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
394 * return MyProcessDialog.super.prototype.getSetupProcess.call( this, data )
395 * .next( function () {
396 * this.actions.setMode( 'edit' );
399 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
400 * if ( action === 'help' ) {
401 * this.actions.setMode( 'help' );
402 * this.stackLayout.setItem( this.panel2 );
403 * } else if ( action === 'back' ) {
404 * this.actions.setMode( 'edit' );
405 * this.stackLayout.setItem( this.panel1 );
406 * } else if ( action === 'continue' ) {
408 * return new OO.ui.Process( function () {
412 * return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
414 * MyProcessDialog.prototype.getBodyHeight = function () {
415 * return this.panel1.$element.outerHeight( true );
417 * var windowManager = new OO.ui.WindowManager();
418 * $( 'body' ).append( windowManager.$element );
419 * var dialog = new MyProcessDialog( {
422 * windowManager.addWindows( [ dialog ] );
423 * windowManager.openWindow( dialog );
425 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
429 * @mixins OO.EventEmitter
432 * @param {Object} [config] Configuration options
434 OO
.ui
.ActionSet
= function OoUiActionSet( config
) {
435 // Configuration initialization
436 config
= config
|| {};
438 // Mixin constructors
439 OO
.EventEmitter
.call( this );
444 actions
: 'getAction',
448 this.categorized
= {};
451 this.organized
= false;
452 this.changing
= false;
453 this.changed
= false;
458 OO
.mixinClass( OO
.ui
.ActionSet
, OO
.EventEmitter
);
460 /* Static Properties */
463 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
464 * header of a {@link OO.ui.ProcessDialog process dialog}.
465 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
467 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
474 OO
.ui
.ActionSet
.static.specialFlags
= [ 'safe', 'primary' ];
481 * A 'click' event is emitted when an action is clicked.
483 * @param {OO.ui.ActionWidget} action Action that was clicked
489 * A 'resize' event is emitted when an action widget is resized.
491 * @param {OO.ui.ActionWidget} action Action that was resized
497 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
499 * @param {OO.ui.ActionWidget[]} added Actions added
505 * A 'remove' event is emitted when actions are {@link #method-remove removed}
506 * or {@link #clear cleared}.
508 * @param {OO.ui.ActionWidget[]} added Actions removed
514 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
515 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
522 * Handle action change events.
527 OO
.ui
.ActionSet
.prototype.onActionChange = function () {
528 this.organized
= false;
529 if ( this.changing
) {
532 this.emit( 'change' );
537 * Check if an action is one of the special actions.
539 * @param {OO.ui.ActionWidget} action Action to check
540 * @return {boolean} Action is special
542 OO
.ui
.ActionSet
.prototype.isSpecial = function ( action
) {
545 for ( flag
in this.special
) {
546 if ( action
=== this.special
[ flag
] ) {
555 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
558 * @param {Object} [filters] Filters to use, omit to get all actions
559 * @param {string|string[]} [filters.actions] Actions that action widgets must have
560 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
561 * @param {string|string[]} [filters.modes] Modes that action widgets must have
562 * @param {boolean} [filters.visible] Action widgets must be visible
563 * @param {boolean} [filters.disabled] Action widgets must be disabled
564 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
566 OO
.ui
.ActionSet
.prototype.get = function ( filters
) {
567 var i
, len
, list
, category
, actions
, index
, match
, matches
;
572 // Collect category candidates
574 for ( category
in this.categorized
) {
575 list
= filters
[ category
];
577 if ( !Array
.isArray( list
) ) {
580 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
581 actions
= this.categorized
[ category
][ list
[ i
] ];
582 if ( Array
.isArray( actions
) ) {
583 matches
.push
.apply( matches
, actions
);
588 // Remove by boolean filters
589 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
590 match
= matches
[ i
];
592 ( filters
.visible
!== undefined && match
.isVisible() !== filters
.visible
) ||
593 ( filters
.disabled
!== undefined && match
.isDisabled() !== filters
.disabled
)
595 matches
.splice( i
, 1 );
601 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
602 match
= matches
[ i
];
603 index
= matches
.lastIndexOf( match
);
604 while ( index
!== i
) {
605 matches
.splice( index
, 1 );
607 index
= matches
.lastIndexOf( match
);
612 return this.list
.slice();
616 * Get 'special' actions.
618 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
619 * Special flags can be configured in subclasses by changing the static #specialFlags property.
621 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
623 OO
.ui
.ActionSet
.prototype.getSpecial = function () {
625 return $.extend( {}, this.special
);
629 * Get 'other' actions.
631 * Other actions include all non-special visible action widgets.
633 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
635 OO
.ui
.ActionSet
.prototype.getOthers = function () {
637 return this.others
.slice();
641 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
642 * to be available in the specified mode will be made visible. All other actions will be hidden.
644 * @param {string} mode The mode. Only actions configured to be available in the specified
645 * mode will be made visible.
650 OO
.ui
.ActionSet
.prototype.setMode = function ( mode
) {
653 this.changing
= true;
654 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
655 action
= this.list
[ i
];
656 action
.toggle( action
.hasMode( mode
) );
659 this.organized
= false;
660 this.changing
= false;
661 this.emit( 'change' );
667 * Set the abilities of the specified actions.
669 * Action widgets that are configured with the specified actions will be enabled
670 * or disabled based on the boolean values specified in the `actions`
673 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
674 * values that indicate whether or not the action should be enabled.
677 OO
.ui
.ActionSet
.prototype.setAbilities = function ( actions
) {
678 var i
, len
, action
, item
;
680 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
681 item
= this.list
[ i
];
682 action
= item
.getAction();
683 if ( actions
[ action
] !== undefined ) {
684 item
.setDisabled( !actions
[ action
] );
692 * Executes a function once per action.
694 * When making changes to multiple actions, use this method instead of iterating over the actions
695 * manually to defer emitting a #change event until after all actions have been changed.
697 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
698 * @param {Function} callback Callback to run for each action; callback is invoked with three
699 * arguments: the action, the action's index, the list of actions being iterated over
702 OO
.ui
.ActionSet
.prototype.forEach = function ( filter
, callback
) {
703 this.changed
= false;
704 this.changing
= true;
705 this.get( filter
).forEach( callback
);
706 this.changing
= false;
707 if ( this.changed
) {
708 this.emit( 'change' );
715 * Add action widgets to the action set.
717 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
722 OO
.ui
.ActionSet
.prototype.add = function ( actions
) {
725 this.changing
= true;
726 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
727 action
= actions
[ i
];
728 action
.connect( this, {
729 click
: [ 'emit', 'click', action
],
730 resize
: [ 'emit', 'resize', action
],
731 toggle
: [ 'onActionChange' ]
733 this.list
.push( action
);
735 this.organized
= false;
736 this.emit( 'add', actions
);
737 this.changing
= false;
738 this.emit( 'change' );
744 * Remove action widgets from the set.
746 * To remove all actions, you may wish to use the #clear method instead.
748 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
753 OO
.ui
.ActionSet
.prototype.remove = function ( actions
) {
754 var i
, len
, index
, action
;
756 this.changing
= true;
757 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
758 action
= actions
[ i
];
759 index
= this.list
.indexOf( action
);
760 if ( index
!== -1 ) {
761 action
.disconnect( this );
762 this.list
.splice( index
, 1 );
765 this.organized
= false;
766 this.emit( 'remove', actions
);
767 this.changing
= false;
768 this.emit( 'change' );
774 * Remove all action widets from the set.
776 * To remove only specified actions, use the {@link #method-remove remove} method instead.
782 OO
.ui
.ActionSet
.prototype.clear = function () {
784 removed
= this.list
.slice();
786 this.changing
= true;
787 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
788 action
= this.list
[ i
];
789 action
.disconnect( this );
794 this.organized
= false;
795 this.emit( 'remove', removed
);
796 this.changing
= false;
797 this.emit( 'change' );
805 * This is called whenever organized information is requested. It will only reorganize the actions
806 * if something has changed since the last time it ran.
811 OO
.ui
.ActionSet
.prototype.organize = function () {
812 var i
, iLen
, j
, jLen
, flag
, action
, category
, list
, item
, special
,
813 specialFlags
= this.constructor.static.specialFlags
;
815 if ( !this.organized
) {
816 this.categorized
= {};
819 for ( i
= 0, iLen
= this.list
.length
; i
< iLen
; i
++ ) {
820 action
= this.list
[ i
];
821 if ( action
.isVisible() ) {
822 // Populate categories
823 for ( category
in this.categories
) {
824 if ( !this.categorized
[ category
] ) {
825 this.categorized
[ category
] = {};
827 list
= action
[ this.categories
[ category
] ]();
828 if ( !Array
.isArray( list
) ) {
831 for ( j
= 0, jLen
= list
.length
; j
< jLen
; j
++ ) {
833 if ( !this.categorized
[ category
][ item
] ) {
834 this.categorized
[ category
][ item
] = [];
836 this.categorized
[ category
][ item
].push( action
);
839 // Populate special/others
841 for ( j
= 0, jLen
= specialFlags
.length
; j
< jLen
; j
++ ) {
842 flag
= specialFlags
[ j
];
843 if ( !this.special
[ flag
] && action
.hasFlag( flag
) ) {
844 this.special
[ flag
] = action
;
850 this.others
.push( action
);
854 this.organized
= true;
861 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
862 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
863 * connected to them and can't be interacted with.
869 * @param {Object} [config] Configuration options
870 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
871 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
873 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
874 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
875 * @cfg {string} [text] Text to insert
876 * @cfg {Array} [content] An array of content elements to append (after #text).
877 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
878 * Instances of OO.ui.Element will have their $element appended.
879 * @cfg {jQuery} [$content] Content elements to append (after #text)
880 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
881 * Data can also be specified with the #setData method.
883 OO
.ui
.Element
= function OoUiElement( config
) {
884 // Configuration initialization
885 config
= config
|| {};
890 this.data
= config
.data
;
891 this.$element
= config
.$element
||
892 $( document
.createElement( this.getTagName() ) );
893 this.elementGroup
= null;
894 this.debouncedUpdateThemeClassesHandler
= this.debouncedUpdateThemeClasses
.bind( this );
895 this.updateThemeClassesPending
= false;
898 if ( Array
.isArray( config
.classes
) ) {
899 this.$element
.addClass( config
.classes
.join( ' ' ) );
902 this.$element
.attr( 'id', config
.id
);
905 this.$element
.text( config
.text
);
907 if ( config
.content
) {
908 // The `content` property treats plain strings as text; use an
909 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
910 // appropriate $element appended.
911 this.$element
.append( config
.content
.map( function ( v
) {
912 if ( typeof v
=== 'string' ) {
913 // Escape string so it is properly represented in HTML.
914 return document
.createTextNode( v
);
915 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
918 } else if ( v
instanceof OO
.ui
.Element
) {
924 if ( config
.$content
) {
925 // The `$content` property treats plain strings as HTML.
926 this.$element
.append( config
.$content
);
932 OO
.initClass( OO
.ui
.Element
);
934 /* Static Properties */
937 * The name of the HTML tag used by the element.
939 * The static value may be ignored if the #getTagName method is overridden.
945 OO
.ui
.Element
.static.tagName
= 'div';
950 * Reconstitute a JavaScript object corresponding to a widget created
951 * by the PHP implementation.
953 * @param {string|HTMLElement|jQuery} idOrNode
954 * A DOM id (if a string) or node for the widget to infuse.
955 * @return {OO.ui.Element}
956 * The `OO.ui.Element` corresponding to this (infusable) document node.
957 * For `Tag` objects emitted on the HTML side (used occasionally for content)
958 * the value returned is a newly-created Element wrapping around the existing
961 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
962 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, true );
963 // Verify that the type matches up.
964 // FIXME: uncomment after T89721 is fixed (see T90929)
966 if ( !( obj instanceof this['class'] ) ) {
967 throw new Error( 'Infusion type mismatch!' );
974 * Implementation helper for `infuse`; skips the type check and has an
975 * extra property so that only the top-level invocation touches the DOM.
977 * @param {string|HTMLElement|jQuery} idOrNode
978 * @param {boolean} top True only for top-level invocation.
979 * @return {OO.ui.Element}
981 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, top
) {
982 // look for a cached result of a previous infusion.
983 var id
, $elem
, data
, cls
, obj
;
984 if ( typeof idOrNode
=== 'string' ) {
986 $elem
= $( document
.getElementById( id
) );
988 $elem
= $( idOrNode
);
989 id
= $elem
.attr( 'id' );
991 data
= $elem
.data( 'ooui-infused' );
994 if ( data
=== true ) {
995 throw new Error( 'Circular dependency! ' + id
);
999 if ( !$elem
.length
) {
1000 throw new Error( 'Widget not found: ' + id
);
1002 data
= $elem
.attr( 'data-ooui' );
1004 throw new Error( 'No infusion data found: ' + id
);
1007 data
= $.parseJSON( data
);
1011 if ( !( data
&& data
._
) ) {
1012 throw new Error( 'No valid infusion data found: ' + id
);
1014 if ( data
._
=== 'Tag' ) {
1015 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1016 return new OO
.ui
.Element( { $element
: $elem
} );
1018 cls
= OO
.ui
[data
._
];
1020 throw new Error( 'Unknown widget type: ' + id
);
1022 $elem
.data( 'ooui-infused', true ); // prevent loops
1023 data
.id
= id
; // implicit
1024 data
= OO
.copy( data
, null, function deserialize( value
) {
1025 if ( OO
.isPlainObject( value
) ) {
1027 return OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, false );
1030 return new OO
.ui
.HtmlSnippet( value
.html
);
1034 // jscs:disable requireCapitalizedConstructors
1035 obj
= new cls( data
); // rebuild widget
1036 // now replace old DOM with this new DOM.
1038 $elem
.replaceWith( obj
.$element
);
1040 obj
.$element
.data( 'ooui-infused', obj
);
1041 // set the 'data-ooui' attribute so we can identify infused widgets
1042 obj
.$element
.attr( 'data-ooui', '' );
1047 * Get a jQuery function within a specific document.
1050 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1051 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1053 * @return {Function} Bound jQuery function
1055 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
1056 function wrapper( selector
) {
1057 return $( selector
, wrapper
.context
);
1060 wrapper
.context
= this.getDocument( context
);
1063 wrapper
.$iframe
= $iframe
;
1070 * Get the document of an element.
1073 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1074 * @return {HTMLDocument|null} Document object
1076 OO
.ui
.Element
.static.getDocument = function ( obj
) {
1077 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1078 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
1079 // Empty jQuery selections might have a context
1082 obj
.ownerDocument
||
1086 ( obj
.nodeType
=== 9 && obj
) ||
1091 * Get the window of an element or document.
1094 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1095 * @return {Window} Window object
1097 OO
.ui
.Element
.static.getWindow = function ( obj
) {
1098 var doc
= this.getDocument( obj
);
1099 return doc
.parentWindow
|| doc
.defaultView
;
1103 * Get the direction of an element or document.
1106 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1107 * @return {string} Text direction, either 'ltr' or 'rtl'
1109 OO
.ui
.Element
.static.getDir = function ( obj
) {
1112 if ( obj
instanceof jQuery
) {
1115 isDoc
= obj
.nodeType
=== 9;
1116 isWin
= obj
.document
!== undefined;
1117 if ( isDoc
|| isWin
) {
1123 return $( obj
).css( 'direction' );
1127 * Get the offset between two frames.
1129 * TODO: Make this function not use recursion.
1132 * @param {Window} from Window of the child frame
1133 * @param {Window} [to=window] Window of the parent frame
1134 * @param {Object} [offset] Offset to start with, used internally
1135 * @return {Object} Offset object, containing left and top properties
1137 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
1138 var i
, len
, frames
, frame
, rect
;
1144 offset
= { top
: 0, left
: 0 };
1146 if ( from.parent
=== from ) {
1150 // Get iframe element
1151 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
1152 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
1153 if ( frames
[ i
].contentWindow
=== from ) {
1154 frame
= frames
[ i
];
1159 // Recursively accumulate offset values
1161 rect
= frame
.getBoundingClientRect();
1162 offset
.left
+= rect
.left
;
1163 offset
.top
+= rect
.top
;
1164 if ( from !== to
) {
1165 this.getFrameOffset( from.parent
, offset
);
1172 * Get the offset between two elements.
1174 * The two elements may be in a different frame, but in that case the frame $element is in must
1175 * be contained in the frame $anchor is in.
1178 * @param {jQuery} $element Element whose position to get
1179 * @param {jQuery} $anchor Element to get $element's position relative to
1180 * @return {Object} Translated position coordinates, containing top and left properties
1182 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
1183 var iframe
, iframePos
,
1184 pos
= $element
.offset(),
1185 anchorPos
= $anchor
.offset(),
1186 elementDocument
= this.getDocument( $element
),
1187 anchorDocument
= this.getDocument( $anchor
);
1189 // If $element isn't in the same document as $anchor, traverse up
1190 while ( elementDocument
!== anchorDocument
) {
1191 iframe
= elementDocument
.defaultView
.frameElement
;
1193 throw new Error( '$element frame is not contained in $anchor frame' );
1195 iframePos
= $( iframe
).offset();
1196 pos
.left
+= iframePos
.left
;
1197 pos
.top
+= iframePos
.top
;
1198 elementDocument
= iframe
.ownerDocument
;
1200 pos
.left
-= anchorPos
.left
;
1201 pos
.top
-= anchorPos
.top
;
1206 * Get element border sizes.
1209 * @param {HTMLElement} el Element to measure
1210 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1212 OO
.ui
.Element
.static.getBorders = function ( el
) {
1213 var doc
= el
.ownerDocument
,
1214 win
= doc
.parentWindow
|| doc
.defaultView
,
1215 style
= win
&& win
.getComputedStyle
?
1216 win
.getComputedStyle( el
, null ) :
1219 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1220 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1221 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1222 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1233 * Get dimensions of an element or window.
1236 * @param {HTMLElement|Window} el Element to measure
1237 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1239 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1241 doc
= el
.ownerDocument
|| el
.document
,
1242 win
= doc
.parentWindow
|| doc
.defaultView
;
1244 if ( win
=== el
|| el
=== doc
.documentElement
) {
1247 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1249 top
: $win
.scrollTop(),
1250 left
: $win
.scrollLeft()
1252 scrollbar
: { right
: 0, bottom
: 0 },
1256 bottom
: $win
.innerHeight(),
1257 right
: $win
.innerWidth()
1263 borders
: this.getBorders( el
),
1265 top
: $el
.scrollTop(),
1266 left
: $el
.scrollLeft()
1269 right
: $el
.innerWidth() - el
.clientWidth
,
1270 bottom
: $el
.innerHeight() - el
.clientHeight
1272 rect
: el
.getBoundingClientRect()
1278 * Get scrollable object parent
1280 * documentElement can't be used to get or set the scrollTop
1281 * property on Blink. Changing and testing its value lets us
1282 * use 'body' or 'documentElement' based on what is working.
1284 * https://code.google.com/p/chromium/issues/detail?id=303131
1287 * @param {HTMLElement} el Element to find scrollable parent for
1288 * @return {HTMLElement} Scrollable parent
1290 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1291 var scrollTop
, body
;
1293 if ( OO
.ui
.scrollableElement
=== undefined ) {
1294 body
= el
.ownerDocument
.body
;
1295 scrollTop
= body
.scrollTop
;
1298 if ( body
.scrollTop
=== 1 ) {
1299 body
.scrollTop
= scrollTop
;
1300 OO
.ui
.scrollableElement
= 'body';
1302 OO
.ui
.scrollableElement
= 'documentElement';
1306 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1310 * Get closest scrollable container.
1312 * Traverses up until either a scrollable element or the root is reached, in which case the window
1316 * @param {HTMLElement} el Element to find scrollable container for
1317 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1318 * @return {HTMLElement} Closest scrollable container
1320 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1322 props
= [ 'overflow' ],
1323 $parent
= $( el
).parent();
1325 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1326 props
.push( 'overflow-' + dimension
);
1329 while ( $parent
.length
) {
1330 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1331 return $parent
[ 0 ];
1335 val
= $parent
.css( props
[ i
] );
1336 if ( val
=== 'auto' || val
=== 'scroll' ) {
1337 return $parent
[ 0 ];
1340 $parent
= $parent
.parent();
1342 return this.getDocument( el
).body
;
1346 * Scroll element into view.
1349 * @param {HTMLElement} el Element to scroll into view
1350 * @param {Object} [config] Configuration options
1351 * @param {string} [config.duration] jQuery animation duration value
1352 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1353 * to scroll in both directions
1354 * @param {Function} [config.complete] Function to call when scrolling completes
1356 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1357 // Configuration initialization
1358 config
= config
|| {};
1361 callback
= typeof config
.complete
=== 'function' && config
.complete
,
1362 sc
= this.getClosestScrollableContainer( el
, config
.direction
),
1364 eld
= this.getDimensions( el
),
1365 scd
= this.getDimensions( sc
),
1366 $win
= $( this.getWindow( el
) );
1368 // Compute the distances between the edges of el and the edges of the scroll viewport
1369 if ( $sc
.is( 'html, body' ) ) {
1370 // If the scrollable container is the root, this is easy
1373 bottom
: $win
.innerHeight() - eld
.rect
.bottom
,
1374 left
: eld
.rect
.left
,
1375 right
: $win
.innerWidth() - eld
.rect
.right
1378 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1380 top
: eld
.rect
.top
- ( scd
.rect
.top
+ scd
.borders
.top
),
1381 bottom
: scd
.rect
.bottom
- scd
.borders
.bottom
- scd
.scrollbar
.bottom
- eld
.rect
.bottom
,
1382 left
: eld
.rect
.left
- ( scd
.rect
.left
+ scd
.borders
.left
),
1383 right
: scd
.rect
.right
- scd
.borders
.right
- scd
.scrollbar
.right
- eld
.rect
.right
1387 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1388 if ( rel
.top
< 0 ) {
1389 anim
.scrollTop
= scd
.scroll
.top
+ rel
.top
;
1390 } else if ( rel
.top
> 0 && rel
.bottom
< 0 ) {
1391 anim
.scrollTop
= scd
.scroll
.top
+ Math
.min( rel
.top
, -rel
.bottom
);
1394 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1395 if ( rel
.left
< 0 ) {
1396 anim
.scrollLeft
= scd
.scroll
.left
+ rel
.left
;
1397 } else if ( rel
.left
> 0 && rel
.right
< 0 ) {
1398 anim
.scrollLeft
= scd
.scroll
.left
+ Math
.min( rel
.left
, -rel
.right
);
1401 if ( !$.isEmptyObject( anim
) ) {
1402 $sc
.stop( true ).animate( anim
, config
.duration
|| 'fast' );
1404 $sc
.queue( function ( next
) {
1417 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1418 * and reserve space for them, because it probably doesn't.
1420 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1421 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1422 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1423 * and then reattach (or show) them back.
1426 * @param {HTMLElement} el Element to reconsider the scrollbars on
1428 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1429 var i
, len
, nodes
= [];
1430 // Detach all children
1431 while ( el
.firstChild
) {
1432 nodes
.push( el
.firstChild
);
1433 el
.removeChild( el
.firstChild
);
1436 void el
.offsetHeight
;
1437 // Reattach all children
1438 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1439 el
.appendChild( nodes
[ i
] );
1446 * Toggle visibility of an element.
1448 * @param {boolean} [show] Make element visible, omit to toggle visibility
1452 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1453 show
= show
=== undefined ? !this.visible
: !!show
;
1455 if ( show
!== this.isVisible() ) {
1456 this.visible
= show
;
1457 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1458 this.emit( 'toggle', show
);
1465 * Check if element is visible.
1467 * @return {boolean} element is visible
1469 OO
.ui
.Element
.prototype.isVisible = function () {
1470 return this.visible
;
1476 * @return {Mixed} Element data
1478 OO
.ui
.Element
.prototype.getData = function () {
1485 * @param {Mixed} Element data
1488 OO
.ui
.Element
.prototype.setData = function ( data
) {
1494 * Check if element supports one or more methods.
1496 * @param {string|string[]} methods Method or list of methods to check
1497 * @return {boolean} All methods are supported
1499 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1503 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1504 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1505 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1510 return methods
.length
=== support
;
1514 * Update the theme-provided classes.
1516 * @localdoc This is called in element mixins and widget classes any time state changes.
1517 * Updating is debounced, minimizing overhead of changing multiple attributes and
1518 * guaranteeing that theme updates do not occur within an element's constructor
1520 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1521 if ( !this.updateThemeClassesPending
) {
1522 this.updateThemeClassesPending
= true;
1523 setTimeout( this.debouncedUpdateThemeClassesHandler
);
1530 OO
.ui
.Element
.prototype.debouncedUpdateThemeClasses = function () {
1531 OO
.ui
.theme
.updateElementClasses( this );
1532 this.updateThemeClassesPending
= false;
1536 * Get the HTML tag name.
1538 * Override this method to base the result on instance information.
1540 * @return {string} HTML tag name
1542 OO
.ui
.Element
.prototype.getTagName = function () {
1543 return this.constructor.static.tagName
;
1547 * Check if the element is attached to the DOM
1548 * @return {boolean} The element is attached to the DOM
1550 OO
.ui
.Element
.prototype.isElementAttached = function () {
1551 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1555 * Get the DOM document.
1557 * @return {HTMLDocument} Document object
1559 OO
.ui
.Element
.prototype.getElementDocument = function () {
1560 // Don't cache this in other ways either because subclasses could can change this.$element
1561 return OO
.ui
.Element
.static.getDocument( this.$element
);
1565 * Get the DOM window.
1567 * @return {Window} Window object
1569 OO
.ui
.Element
.prototype.getElementWindow = function () {
1570 return OO
.ui
.Element
.static.getWindow( this.$element
);
1574 * Get closest scrollable container.
1576 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1577 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1581 * Get group element is in.
1583 * @return {OO.ui.GroupElement|null} Group element, null if none
1585 OO
.ui
.Element
.prototype.getElementGroup = function () {
1586 return this.elementGroup
;
1590 * Set group element is in.
1592 * @param {OO.ui.GroupElement|null} group Group element, null if none
1595 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1596 this.elementGroup
= group
;
1601 * Scroll element into view.
1603 * @param {Object} [config] Configuration options
1605 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1606 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1610 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1611 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1612 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1613 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1614 * and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1618 * @extends OO.ui.Element
1619 * @mixins OO.EventEmitter
1622 * @param {Object} [config] Configuration options
1624 OO
.ui
.Layout
= function OoUiLayout( config
) {
1625 // Configuration initialization
1626 config
= config
|| {};
1628 // Parent constructor
1629 OO
.ui
.Layout
.super.call( this, config
);
1631 // Mixin constructors
1632 OO
.EventEmitter
.call( this );
1635 this.$element
.addClass( 'oo-ui-layout' );
1640 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1641 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1644 * Widgets are compositions of one or more OOjs UI elements that users can both view
1645 * and interact with. All widgets can be configured and modified via a standard API,
1646 * and their state can change dynamically according to a model.
1650 * @extends OO.ui.Element
1651 * @mixins OO.EventEmitter
1654 * @param {Object} [config] Configuration options
1655 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1656 * appearance reflects this state.
1658 OO
.ui
.Widget
= function OoUiWidget( config
) {
1659 // Initialize config
1660 config
= $.extend( { disabled
: false }, config
);
1662 // Parent constructor
1663 OO
.ui
.Widget
.super.call( this, config
);
1665 // Mixin constructors
1666 OO
.EventEmitter
.call( this );
1669 this.disabled
= null;
1670 this.wasDisabled
= null;
1673 this.$element
.addClass( 'oo-ui-widget' );
1674 this.setDisabled( !!config
.disabled
);
1679 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1680 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1687 * A 'disable' event is emitted when a widget is disabled.
1689 * @param {boolean} disabled Widget is disabled
1695 * A 'toggle' event is emitted when the visibility of the widget changes.
1697 * @param {boolean} visible Widget is visible
1703 * Check if the widget is disabled.
1705 * @return {boolean} Widget is disabled
1707 OO
.ui
.Widget
.prototype.isDisabled = function () {
1708 return this.disabled
;
1712 * Set the 'disabled' state of the widget.
1714 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1716 * @param {boolean} disabled Disable widget
1719 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1722 this.disabled
= !!disabled
;
1723 isDisabled
= this.isDisabled();
1724 if ( isDisabled
!== this.wasDisabled
) {
1725 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1726 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1727 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1728 this.emit( 'disable', isDisabled
);
1729 this.updateThemeClasses();
1731 this.wasDisabled
= isDisabled
;
1737 * Update the disabled state, in case of changes in parent widget.
1741 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1742 this.setDisabled( this.disabled
);
1747 * A window is a container for elements that are in a child frame. They are used with
1748 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
1749 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
1750 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
1751 * the window manager will choose a sensible fallback.
1753 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
1754 * different processes are executed:
1756 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
1757 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
1760 * - {@link #getSetupProcess} method is called and its result executed
1761 * - {@link #getReadyProcess} method is called and its result executed
1763 * **opened**: The window is now open
1765 * **closing**: The closing stage begins when the window manager's
1766 * {@link OO.ui.WindowManager#closeWindow closeWindow}
1767 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
1769 * - {@link #getHoldProcess} method is called and its result executed
1770 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
1772 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
1773 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
1774 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
1775 * processing can complete. Always assume window processes are executed asynchronously.
1777 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
1779 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
1783 * @extends OO.ui.Element
1784 * @mixins OO.EventEmitter
1787 * @param {Object} [config] Configuration options
1788 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
1789 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
1791 OO
.ui
.Window
= function OoUiWindow( config
) {
1792 // Configuration initialization
1793 config
= config
|| {};
1795 // Parent constructor
1796 OO
.ui
.Window
.super.call( this, config
);
1798 // Mixin constructors
1799 OO
.EventEmitter
.call( this );
1802 this.manager
= null;
1803 this.size
= config
.size
|| this.constructor.static.size
;
1804 this.$frame
= $( '<div>' );
1805 this.$overlay
= $( '<div>' );
1806 this.$content
= $( '<div>' );
1809 this.$overlay
.addClass( 'oo-ui-window-overlay' );
1811 .addClass( 'oo-ui-window-content' )
1812 .attr( 'tabIndex', 0 );
1814 .addClass( 'oo-ui-window-frame' )
1815 .append( this.$content
);
1818 .addClass( 'oo-ui-window' )
1819 .append( this.$frame
, this.$overlay
);
1821 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
1822 // that reference properties not initialized at that time of parent class construction
1823 // TODO: Find a better way to handle post-constructor setup
1824 this.visible
= false;
1825 this.$element
.addClass( 'oo-ui-element-hidden' );
1830 OO
.inheritClass( OO
.ui
.Window
, OO
.ui
.Element
);
1831 OO
.mixinClass( OO
.ui
.Window
, OO
.EventEmitter
);
1833 /* Static Properties */
1836 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
1838 * The static size is used if no #size is configured during construction.
1842 * @property {string}
1844 OO
.ui
.Window
.static.size
= 'medium';
1849 * Handle mouse down events.
1852 * @param {jQuery.Event} e Mouse down event
1854 OO
.ui
.Window
.prototype.onMouseDown = function ( e
) {
1855 // Prevent clicking on the click-block from stealing focus
1856 if ( e
.target
=== this.$element
[ 0 ] ) {
1862 * Check if the window has been initialized.
1864 * Initialization occurs when a window is added to a manager.
1866 * @return {boolean} Window has been initialized
1868 OO
.ui
.Window
.prototype.isInitialized = function () {
1869 return !!this.manager
;
1873 * Check if the window is visible.
1875 * @return {boolean} Window is visible
1877 OO
.ui
.Window
.prototype.isVisible = function () {
1878 return this.visible
;
1882 * Check if the window is opening.
1884 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
1887 * @return {boolean} Window is opening
1889 OO
.ui
.Window
.prototype.isOpening = function () {
1890 return this.manager
.isOpening( this );
1894 * Check if the window is closing.
1896 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
1898 * @return {boolean} Window is closing
1900 OO
.ui
.Window
.prototype.isClosing = function () {
1901 return this.manager
.isClosing( this );
1905 * Check if the window is opened.
1907 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
1909 * @return {boolean} Window is opened
1911 OO
.ui
.Window
.prototype.isOpened = function () {
1912 return this.manager
.isOpened( this );
1916 * Get the window manager.
1918 * All windows must be attached to a window manager, which is used to open
1919 * and close the window and control its presentation.
1921 * @return {OO.ui.WindowManager} Manager of window
1923 OO
.ui
.Window
.prototype.getManager = function () {
1924 return this.manager
;
1928 * Get the symbolic name of the window size (e.g., `small` or `medium`).
1930 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
1932 OO
.ui
.Window
.prototype.getSize = function () {
1937 * Disable transitions on window's frame for the duration of the callback function, then enable them
1941 * @param {Function} callback Function to call while transitions are disabled
1943 OO
.ui
.Window
.prototype.withoutSizeTransitions = function ( callback
) {
1944 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1945 // Disable transitions first, otherwise we'll get values from when the window was animating.
1947 styleObj
= this.$frame
[ 0 ].style
;
1948 oldTransition
= styleObj
.transition
|| styleObj
.OTransition
|| styleObj
.MsTransition
||
1949 styleObj
.MozTransition
|| styleObj
.WebkitTransition
;
1950 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
1951 styleObj
.MozTransition
= styleObj
.WebkitTransition
= 'none';
1953 // Force reflow to make sure the style changes done inside callback really are not transitioned
1954 this.$frame
.height();
1955 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
1956 styleObj
.MozTransition
= styleObj
.WebkitTransition
= oldTransition
;
1960 * Get the height of the full window contents (i.e., the window head, body and foot together).
1962 * What consistitutes the head, body, and foot varies depending on the window type.
1963 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
1964 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
1965 * and special actions in the head, and dialog content in the body.
1967 * To get just the height of the dialog body, use the #getBodyHeight method.
1969 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
1971 OO
.ui
.Window
.prototype.getContentHeight = function () {
1974 bodyStyleObj
= this.$body
[ 0 ].style
,
1975 frameStyleObj
= this.$frame
[ 0 ].style
;
1977 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1978 // Disable transitions first, otherwise we'll get values from when the window was animating.
1979 this.withoutSizeTransitions( function () {
1980 var oldHeight
= frameStyleObj
.height
,
1981 oldPosition
= bodyStyleObj
.position
;
1982 frameStyleObj
.height
= '1px';
1983 // Force body to resize to new width
1984 bodyStyleObj
.position
= 'relative';
1985 bodyHeight
= win
.getBodyHeight();
1986 frameStyleObj
.height
= oldHeight
;
1987 bodyStyleObj
.position
= oldPosition
;
1991 // Add buffer for border
1992 ( this.$frame
.outerHeight() - this.$frame
.innerHeight() ) +
1993 // Use combined heights of children
1994 ( this.$head
.outerHeight( true ) + bodyHeight
+ this.$foot
.outerHeight( true ) )
1999 * Get the height of the window body.
2001 * To get the height of the full window contents (the window body, head, and foot together),
2002 * use #getContentHeight.
2004 * When this function is called, the window will temporarily have been resized
2005 * to height=1px, so .scrollHeight measurements can be taken accurately.
2007 * @return {number} Height of the window body in pixels
2009 OO
.ui
.Window
.prototype.getBodyHeight = function () {
2010 return this.$body
[ 0 ].scrollHeight
;
2014 * Get the directionality of the frame (right-to-left or left-to-right).
2016 * @return {string} Directionality: `'ltr'` or `'rtl'`
2018 OO
.ui
.Window
.prototype.getDir = function () {
2023 * Get the 'setup' process.
2025 * The setup process is used to set up a window for use in a particular context,
2026 * based on the `data` argument. This method is called during the opening phase of the window’s
2029 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2030 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2033 * To add window content that persists between openings, you may wish to use the #initialize method
2037 * @param {Object} [data] Window opening data
2038 * @return {OO.ui.Process} Setup process
2040 OO
.ui
.Window
.prototype.getSetupProcess = function () {
2041 return new OO
.ui
.Process();
2045 * Get the ‘ready’ process.
2047 * The ready process is used to ready a window for use in a particular
2048 * context, based on the `data` argument. This method is called during the opening phase of
2049 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2051 * Override this method to add additional steps to the ‘ready’ process the parent method
2052 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2053 * methods of OO.ui.Process.
2056 * @param {Object} [data] Window opening data
2057 * @return {OO.ui.Process} Ready process
2059 OO
.ui
.Window
.prototype.getReadyProcess = function () {
2060 return new OO
.ui
.Process();
2064 * Get the 'hold' process.
2066 * The hold proccess is used to keep a window from being used in a particular context,
2067 * based on the `data` argument. This method is called during the closing phase of the window’s
2070 * Override this method to add additional steps to the 'hold' process the parent method provides
2071 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2075 * @param {Object} [data] Window closing data
2076 * @return {OO.ui.Process} Hold process
2078 OO
.ui
.Window
.prototype.getHoldProcess = function () {
2079 return new OO
.ui
.Process();
2083 * Get the ‘teardown’ process.
2085 * The teardown process is used to teardown a window after use. During teardown,
2086 * user interactions within the window are conveyed and the window is closed, based on the `data`
2087 * argument. This method is called during the closing phase of the window’s lifecycle.
2089 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2090 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2094 * @param {Object} [data] Window closing data
2095 * @return {OO.ui.Process} Teardown process
2097 OO
.ui
.Window
.prototype.getTeardownProcess = function () {
2098 return new OO
.ui
.Process();
2102 * Set the window manager.
2104 * This will cause the window to initialize. Calling it more than once will cause an error.
2106 * @param {OO.ui.WindowManager} manager Manager for this window
2107 * @throws {Error} An error is thrown if the method is called more than once
2110 OO
.ui
.Window
.prototype.setManager = function ( manager
) {
2111 if ( this.manager
) {
2112 throw new Error( 'Cannot set window manager, window already has a manager' );
2115 this.manager
= manager
;
2122 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2124 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2128 OO
.ui
.Window
.prototype.setSize = function ( size
) {
2135 * Update the window size.
2137 * @throws {Error} An error is thrown if the window is not attached to a window manager
2140 OO
.ui
.Window
.prototype.updateSize = function () {
2141 if ( !this.manager
) {
2142 throw new Error( 'Cannot update window size, must be attached to a manager' );
2145 this.manager
.updateWindowSize( this );
2151 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2152 * when the window is opening. In general, setDimensions should not be called directly.
2154 * To set the size of the window, use the #setSize method.
2156 * @param {Object} dim CSS dimension properties
2157 * @param {string|number} [dim.width] Width
2158 * @param {string|number} [dim.minWidth] Minimum width
2159 * @param {string|number} [dim.maxWidth] Maximum width
2160 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2161 * @param {string|number} [dim.minWidth] Minimum height
2162 * @param {string|number} [dim.maxWidth] Maximum height
2165 OO
.ui
.Window
.prototype.setDimensions = function ( dim
) {
2168 styleObj
= this.$frame
[ 0 ].style
;
2170 // Calculate the height we need to set using the correct width
2171 if ( dim
.height
=== undefined ) {
2172 this.withoutSizeTransitions( function () {
2173 var oldWidth
= styleObj
.width
;
2174 win
.$frame
.css( 'width', dim
.width
|| '' );
2175 height
= win
.getContentHeight();
2176 styleObj
.width
= oldWidth
;
2179 height
= dim
.height
;
2183 width
: dim
.width
|| '',
2184 minWidth
: dim
.minWidth
|| '',
2185 maxWidth
: dim
.maxWidth
|| '',
2186 height
: height
|| '',
2187 minHeight
: dim
.minHeight
|| '',
2188 maxHeight
: dim
.maxHeight
|| ''
2195 * Initialize window contents.
2197 * Before the window is opened for the first time, #initialize is called so that content that
2198 * persists between openings can be added to the window.
2200 * To set up a window with new content each time the window opens, use #getSetupProcess.
2202 * @throws {Error} An error is thrown if the window is not attached to a window manager
2205 OO
.ui
.Window
.prototype.initialize = function () {
2206 if ( !this.manager
) {
2207 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2211 this.$head
= $( '<div>' );
2212 this.$body
= $( '<div>' );
2213 this.$foot
= $( '<div>' );
2214 this.dir
= OO
.ui
.Element
.static.getDir( this.$content
) || 'ltr';
2215 this.$document
= $( this.getElementDocument() );
2218 this.$element
.on( 'mousedown', this.onMouseDown
.bind( this ) );
2221 this.$head
.addClass( 'oo-ui-window-head' );
2222 this.$body
.addClass( 'oo-ui-window-body' );
2223 this.$foot
.addClass( 'oo-ui-window-foot' );
2224 this.$content
.append( this.$head
, this.$body
, this.$foot
);
2232 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2233 * method, which returns a promise resolved when the window is done opening.
2235 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2237 * @param {Object} [data] Window opening data
2238 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2239 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2240 * value is a new promise, which is resolved when the window begins closing.
2241 * @throws {Error} An error is thrown if the window is not attached to a window manager
2243 OO
.ui
.Window
.prototype.open = function ( data
) {
2244 if ( !this.manager
) {
2245 throw new Error( 'Cannot open window, must be attached to a manager' );
2248 return this.manager
.openWindow( this, data
);
2254 * This method is a wrapper around a call to the window
2255 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2256 * which returns a closing promise resolved when the window is done closing.
2258 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2259 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2260 * the window closes.
2262 * @param {Object} [data] Window closing data
2263 * @return {jQuery.Promise} Promise resolved when window is closed
2264 * @throws {Error} An error is thrown if the window is not attached to a window manager
2266 OO
.ui
.Window
.prototype.close = function ( data
) {
2267 if ( !this.manager
) {
2268 throw new Error( 'Cannot close window, must be attached to a manager' );
2271 return this.manager
.closeWindow( this, data
);
2277 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2280 * @param {Object} [data] Window opening data
2281 * @return {jQuery.Promise} Promise resolved when window is setup
2283 OO
.ui
.Window
.prototype.setup = function ( data
) {
2285 deferred
= $.Deferred();
2287 this.toggle( true );
2289 this.getSetupProcess( data
).execute().done( function () {
2290 // Force redraw by asking the browser to measure the elements' widths
2291 win
.$element
.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2292 win
.$content
.addClass( 'oo-ui-window-content-setup' ).width();
2296 return deferred
.promise();
2302 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2305 * @param {Object} [data] Window opening data
2306 * @return {jQuery.Promise} Promise resolved when window is ready
2308 OO
.ui
.Window
.prototype.ready = function ( data
) {
2310 deferred
= $.Deferred();
2312 this.$content
.focus();
2313 this.getReadyProcess( data
).execute().done( function () {
2314 // Force redraw by asking the browser to measure the elements' widths
2315 win
.$element
.addClass( 'oo-ui-window-ready' ).width();
2316 win
.$content
.addClass( 'oo-ui-window-content-ready' ).width();
2320 return deferred
.promise();
2326 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2329 * @param {Object} [data] Window closing data
2330 * @return {jQuery.Promise} Promise resolved when window is held
2332 OO
.ui
.Window
.prototype.hold = function ( data
) {
2334 deferred
= $.Deferred();
2336 this.getHoldProcess( data
).execute().done( function () {
2337 // Get the focused element within the window's content
2338 var $focus
= win
.$content
.find( OO
.ui
.Element
.static.getDocument( win
.$content
).activeElement
);
2340 // Blur the focused element
2341 if ( $focus
.length
) {
2345 // Force redraw by asking the browser to measure the elements' widths
2346 win
.$element
.removeClass( 'oo-ui-window-ready' ).width();
2347 win
.$content
.removeClass( 'oo-ui-window-content-ready' ).width();
2351 return deferred
.promise();
2357 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2360 * @param {Object} [data] Window closing data
2361 * @return {jQuery.Promise} Promise resolved when window is torn down
2363 OO
.ui
.Window
.prototype.teardown = function ( data
) {
2366 return this.getTeardownProcess( data
).execute()
2367 .done( function () {
2368 // Force redraw by asking the browser to measure the elements' widths
2369 win
.$element
.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2370 win
.$content
.removeClass( 'oo-ui-window-content-setup' ).width();
2371 win
.toggle( false );
2376 * The Dialog class serves as the base class for the other types of dialogs.
2377 * Unless extended to include controls, the rendered dialog box is a simple window
2378 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2379 * which opens, closes, and controls the presentation of the window. See the
2380 * [OOjs UI documentation on MediaWiki] [1] for more information.
2383 * // A simple dialog window.
2384 * function MyDialog( config ) {
2385 * MyDialog.super.call( this, config );
2387 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2388 * MyDialog.prototype.initialize = function () {
2389 * MyDialog.super.prototype.initialize.call( this );
2390 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2391 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2392 * this.$body.append( this.content.$element );
2394 * MyDialog.prototype.getBodyHeight = function () {
2395 * return this.content.$element.outerHeight( true );
2397 * var myDialog = new MyDialog( {
2400 * // Create and append a window manager, which opens and closes the window.
2401 * var windowManager = new OO.ui.WindowManager();
2402 * $( 'body' ).append( windowManager.$element );
2403 * windowManager.addWindows( [ myDialog ] );
2404 * // Open the window!
2405 * windowManager.openWindow( myDialog );
2407 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2411 * @extends OO.ui.Window
2412 * @mixins OO.ui.PendingElement
2415 * @param {Object} [config] Configuration options
2417 OO
.ui
.Dialog
= function OoUiDialog( config
) {
2418 // Parent constructor
2419 OO
.ui
.Dialog
.super.call( this, config
);
2421 // Mixin constructors
2422 OO
.ui
.PendingElement
.call( this );
2425 this.actions
= new OO
.ui
.ActionSet();
2426 this.attachedActions
= [];
2427 this.currentAction
= null;
2428 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
2431 this.actions
.connect( this, {
2432 click
: 'onActionClick',
2433 resize
: 'onActionResize',
2434 change
: 'onActionsChange'
2439 .addClass( 'oo-ui-dialog' )
2440 .attr( 'role', 'dialog' );
2445 OO
.inheritClass( OO
.ui
.Dialog
, OO
.ui
.Window
);
2446 OO
.mixinClass( OO
.ui
.Dialog
, OO
.ui
.PendingElement
);
2448 /* Static Properties */
2451 * Symbolic name of dialog.
2453 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2454 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2456 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2461 * @property {string}
2463 OO
.ui
.Dialog
.static.name
= '';
2468 * The title can be specified as a plaintext string, a {@link OO.ui.LabelElement Label} node, or a function
2469 * that will produce a Label node or string. The title can also be specified with data passed to the
2470 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2475 * @property {jQuery|string|Function}
2477 OO
.ui
.Dialog
.static.title
= '';
2480 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2482 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2483 * value will be overriden.
2485 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2489 * @property {Object[]}
2491 OO
.ui
.Dialog
.static.actions
= [];
2494 * Close the dialog when the 'Esc' key is pressed.
2499 * @property {boolean}
2501 OO
.ui
.Dialog
.static.escapable
= true;
2506 * Handle frame document key down events.
2509 * @param {jQuery.Event} e Key down event
2511 OO
.ui
.Dialog
.prototype.onDocumentKeyDown = function ( e
) {
2512 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
2515 e
.stopPropagation();
2520 * Handle action resized events.
2523 * @param {OO.ui.ActionWidget} action Action that was resized
2525 OO
.ui
.Dialog
.prototype.onActionResize = function () {
2526 // Override in subclass
2530 * Handle action click events.
2533 * @param {OO.ui.ActionWidget} action Action that was clicked
2535 OO
.ui
.Dialog
.prototype.onActionClick = function ( action
) {
2536 if ( !this.isPending() ) {
2537 this.executeAction( action
.getAction() );
2542 * Handle actions change event.
2546 OO
.ui
.Dialog
.prototype.onActionsChange = function () {
2547 this.detachActions();
2548 if ( !this.isClosing() ) {
2549 this.attachActions();
2554 * Get the set of actions used by the dialog.
2556 * @return {OO.ui.ActionSet}
2558 OO
.ui
.Dialog
.prototype.getActions = function () {
2559 return this.actions
;
2563 * Get a process for taking action.
2565 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2566 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2567 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2570 * @param {string} [action] Symbolic name of action
2571 * @return {OO.ui.Process} Action process
2573 OO
.ui
.Dialog
.prototype.getActionProcess = function ( action
) {
2574 return new OO
.ui
.Process()
2575 .next( function () {
2577 // An empty action always closes the dialog without data, which should always be
2578 // safe and make no changes
2587 * @param {Object} [data] Dialog opening data
2588 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2589 * the {@link #static-title static title}
2590 * @param {Object[]} [data.actions] List of configuration options for each
2591 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2593 OO
.ui
.Dialog
.prototype.getSetupProcess = function ( data
) {
2597 return OO
.ui
.Dialog
.super.prototype.getSetupProcess
.call( this, data
)
2598 .next( function () {
2599 var config
= this.constructor.static,
2600 actions
= data
.actions
!== undefined ? data
.actions
: config
.actions
;
2602 this.title
.setLabel(
2603 data
.title
!== undefined ? data
.title
: this.constructor.static.title
2605 this.actions
.add( this.getActionWidgets( actions
) );
2607 if ( this.constructor.static.escapable
) {
2608 this.$document
.on( 'keydown', this.onDocumentKeyDownHandler
);
2616 OO
.ui
.Dialog
.prototype.getTeardownProcess = function ( data
) {
2618 return OO
.ui
.Dialog
.super.prototype.getTeardownProcess
.call( this, data
)
2619 .first( function () {
2620 if ( this.constructor.static.escapable
) {
2621 this.$document
.off( 'keydown', this.onDocumentKeyDownHandler
);
2624 this.actions
.clear();
2625 this.currentAction
= null;
2632 OO
.ui
.Dialog
.prototype.initialize = function () {
2634 OO
.ui
.Dialog
.super.prototype.initialize
.call( this );
2637 this.title
= new OO
.ui
.LabelWidget();
2640 this.$content
.addClass( 'oo-ui-dialog-content' );
2641 this.setPendingElement( this.$head
);
2645 * Get action widgets from a list of configs
2647 * @param {Object[]} actions Action widget configs
2648 * @return {OO.ui.ActionWidget[]} Action widgets
2650 OO
.ui
.Dialog
.prototype.getActionWidgets = function ( actions
) {
2651 var i
, len
, widgets
= [];
2652 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
2654 new OO
.ui
.ActionWidget( actions
[ i
] )
2661 * Attach action actions.
2665 OO
.ui
.Dialog
.prototype.attachActions = function () {
2666 // Remember the list of potentially attached actions
2667 this.attachedActions
= this.actions
.get();
2671 * Detach action actions.
2676 OO
.ui
.Dialog
.prototype.detachActions = function () {
2679 // Detach all actions that may have been previously attached
2680 for ( i
= 0, len
= this.attachedActions
.length
; i
< len
; i
++ ) {
2681 this.attachedActions
[ i
].$element
.detach();
2683 this.attachedActions
= [];
2687 * Execute an action.
2689 * @param {string} action Symbolic name of action to execute
2690 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2692 OO
.ui
.Dialog
.prototype.executeAction = function ( action
) {
2694 this.currentAction
= action
;
2695 return this.getActionProcess( action
).execute()
2696 .always( this.popPending
.bind( this ) );
2700 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
2701 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
2702 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
2703 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
2704 * pertinent data and reused.
2706 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
2707 * `opened`, and `closing`, which represent the primary stages of the cycle:
2709 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
2710 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
2712 * - an `opening` event is emitted with an `opening` promise
2713 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
2714 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
2715 * window and its result executed
2716 * - a `setup` progress notification is emitted from the `opening` promise
2717 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
2718 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
2719 * window and its result executed
2720 * - a `ready` progress notification is emitted from the `opening` promise
2721 * - the `opening` promise is resolved with an `opened` promise
2723 * **Opened**: the window is now open.
2725 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
2726 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
2727 * to close the window.
2729 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
2730 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
2731 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
2732 * window and its result executed
2733 * - a `hold` progress notification is emitted from the `closing` promise
2734 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
2735 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
2736 * window and its result executed
2737 * - a `teardown` progress notification is emitted from the `closing` promise
2738 * - the `closing` promise is resolved. The window is now closed
2740 * See the [OOjs UI documentation on MediaWiki][1] for more information.
2742 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2745 * @extends OO.ui.Element
2746 * @mixins OO.EventEmitter
2749 * @param {Object} [config] Configuration options
2750 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
2751 * Note that window classes that are instantiated with a factory must have
2752 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
2753 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
2755 OO
.ui
.WindowManager
= function OoUiWindowManager( config
) {
2756 // Configuration initialization
2757 config
= config
|| {};
2759 // Parent constructor
2760 OO
.ui
.WindowManager
.super.call( this, config
);
2762 // Mixin constructors
2763 OO
.EventEmitter
.call( this );
2766 this.factory
= config
.factory
;
2767 this.modal
= config
.modal
=== undefined || !!config
.modal
;
2769 this.opening
= null;
2771 this.closing
= null;
2772 this.preparingToOpen
= null;
2773 this.preparingToClose
= null;
2774 this.currentWindow
= null;
2775 this.globalEvents
= false;
2776 this.$ariaHidden
= null;
2777 this.onWindowResizeTimeout
= null;
2778 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
2779 this.afterWindowResizeHandler
= this.afterWindowResize
.bind( this );
2783 .addClass( 'oo-ui-windowManager' )
2784 .toggleClass( 'oo-ui-windowManager-modal', this.modal
);
2789 OO
.inheritClass( OO
.ui
.WindowManager
, OO
.ui
.Element
);
2790 OO
.mixinClass( OO
.ui
.WindowManager
, OO
.EventEmitter
);
2795 * An 'opening' event is emitted when the window begins to be opened.
2798 * @param {OO.ui.Window} win Window that's being opened
2799 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
2800 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
2801 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
2802 * @param {Object} data Window opening data
2806 * A 'closing' event is emitted when the window begins to be closed.
2809 * @param {OO.ui.Window} win Window that's being closed
2810 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
2811 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
2812 * processes are complete. When the `closing` promise is resolved, the first argument of its value
2813 * is the closing data.
2814 * @param {Object} data Window closing data
2818 * A 'resize' event is emitted when a window is resized.
2821 * @param {OO.ui.Window} win Window that was resized
2824 /* Static Properties */
2827 * Map of the symbolic name of each window size and its CSS properties.
2831 * @property {Object}
2833 OO
.ui
.WindowManager
.static.sizes
= {
2847 // These can be non-numeric because they are never used in calculations
2854 * Symbolic name of the default window size.
2856 * The default size is used if the window's requested size is not recognized.
2860 * @property {string}
2862 OO
.ui
.WindowManager
.static.defaultSize
= 'medium';
2867 * Handle window resize events.
2870 * @param {jQuery.Event} e Window resize event
2872 OO
.ui
.WindowManager
.prototype.onWindowResize = function () {
2873 clearTimeout( this.onWindowResizeTimeout
);
2874 this.onWindowResizeTimeout
= setTimeout( this.afterWindowResizeHandler
, 200 );
2878 * Handle window resize events.
2881 * @param {jQuery.Event} e Window resize event
2883 OO
.ui
.WindowManager
.prototype.afterWindowResize = function () {
2884 if ( this.currentWindow
) {
2885 this.updateWindowSize( this.currentWindow
);
2890 * Check if window is opening.
2892 * @return {boolean} Window is opening
2894 OO
.ui
.WindowManager
.prototype.isOpening = function ( win
) {
2895 return win
=== this.currentWindow
&& !!this.opening
&& this.opening
.state() === 'pending';
2899 * Check if window is closing.
2901 * @return {boolean} Window is closing
2903 OO
.ui
.WindowManager
.prototype.isClosing = function ( win
) {
2904 return win
=== this.currentWindow
&& !!this.closing
&& this.closing
.state() === 'pending';
2908 * Check if window is opened.
2910 * @return {boolean} Window is opened
2912 OO
.ui
.WindowManager
.prototype.isOpened = function ( win
) {
2913 return win
=== this.currentWindow
&& !!this.opened
&& this.opened
.state() === 'pending';
2917 * Check if a window is being managed.
2919 * @param {OO.ui.Window} win Window to check
2920 * @return {boolean} Window is being managed
2922 OO
.ui
.WindowManager
.prototype.hasWindow = function ( win
) {
2925 for ( name
in this.windows
) {
2926 if ( this.windows
[ name
] === win
) {
2935 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
2937 * @param {OO.ui.Window} win Window being opened
2938 * @param {Object} [data] Window opening data
2939 * @return {number} Milliseconds to wait
2941 OO
.ui
.WindowManager
.prototype.getSetupDelay = function () {
2946 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
2948 * @param {OO.ui.Window} win Window being opened
2949 * @param {Object} [data] Window opening data
2950 * @return {number} Milliseconds to wait
2952 OO
.ui
.WindowManager
.prototype.getReadyDelay = function () {
2957 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
2959 * @param {OO.ui.Window} win Window being closed
2960 * @param {Object} [data] Window closing data
2961 * @return {number} Milliseconds to wait
2963 OO
.ui
.WindowManager
.prototype.getHoldDelay = function () {
2968 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
2969 * executing the ‘teardown’ process.
2971 * @param {OO.ui.Window} win Window being closed
2972 * @param {Object} [data] Window closing data
2973 * @return {number} Milliseconds to wait
2975 OO
.ui
.WindowManager
.prototype.getTeardownDelay = function () {
2976 return this.modal
? 250 : 0;
2980 * Get a window by its symbolic name.
2982 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
2983 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
2984 * for more information about using factories.
2985 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2987 * @param {string} name Symbolic name of the window
2988 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
2989 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
2990 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
2992 OO
.ui
.WindowManager
.prototype.getWindow = function ( name
) {
2993 var deferred
= $.Deferred(),
2994 win
= this.windows
[ name
];
2996 if ( !( win
instanceof OO
.ui
.Window
) ) {
2997 if ( this.factory
) {
2998 if ( !this.factory
.lookup( name
) ) {
2999 deferred
.reject( new OO
.ui
.Error(
3000 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3003 win
= this.factory
.create( name
);
3004 this.addWindows( [ win
] );
3005 deferred
.resolve( win
);
3008 deferred
.reject( new OO
.ui
.Error(
3009 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3013 deferred
.resolve( win
);
3016 return deferred
.promise();
3020 * Get current window.
3022 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3024 OO
.ui
.WindowManager
.prototype.getCurrentWindow = function () {
3025 return this.currentWindow
;
3031 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3032 * @param {Object} [data] Window opening data
3033 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3034 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3037 OO
.ui
.WindowManager
.prototype.openWindow = function ( win
, data
) {
3039 opening
= $.Deferred();
3041 // Argument handling
3042 if ( typeof win
=== 'string' ) {
3043 return this.getWindow( win
).then( function ( win
) {
3044 return manager
.openWindow( win
, data
);
3049 if ( !this.hasWindow( win
) ) {
3050 opening
.reject( new OO
.ui
.Error(
3051 'Cannot open window: window is not attached to manager'
3053 } else if ( this.preparingToOpen
|| this.opening
|| this.opened
) {
3054 opening
.reject( new OO
.ui
.Error(
3055 'Cannot open window: another window is opening or open'
3060 if ( opening
.state() !== 'rejected' ) {
3061 // If a window is currently closing, wait for it to complete
3062 this.preparingToOpen
= $.when( this.closing
);
3063 // Ensure handlers get called after preparingToOpen is set
3064 this.preparingToOpen
.done( function () {
3065 if ( manager
.modal
) {
3066 manager
.toggleGlobalEvents( true );
3067 manager
.toggleAriaIsolation( true );
3069 manager
.currentWindow
= win
;
3070 manager
.opening
= opening
;
3071 manager
.preparingToOpen
= null;
3072 manager
.emit( 'opening', win
, opening
, data
);
3073 setTimeout( function () {
3074 win
.setup( data
).then( function () {
3075 manager
.updateWindowSize( win
);
3076 manager
.opening
.notify( { state
: 'setup' } );
3077 setTimeout( function () {
3078 win
.ready( data
).then( function () {
3079 manager
.opening
.notify( { state
: 'ready' } );
3080 manager
.opening
= null;
3081 manager
.opened
= $.Deferred();
3082 opening
.resolve( manager
.opened
.promise(), data
);
3084 }, manager
.getReadyDelay() );
3086 }, manager
.getSetupDelay() );
3090 return opening
.promise();
3096 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3097 * @param {Object} [data] Window closing data
3098 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3099 * See {@link #event-closing 'closing' event} for more information about closing promises.
3100 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3103 OO
.ui
.WindowManager
.prototype.closeWindow = function ( win
, data
) {
3105 closing
= $.Deferred(),
3108 // Argument handling
3109 if ( typeof win
=== 'string' ) {
3110 win
= this.windows
[ win
];
3111 } else if ( !this.hasWindow( win
) ) {
3117 closing
.reject( new OO
.ui
.Error(
3118 'Cannot close window: window is not attached to manager'
3120 } else if ( win
!== this.currentWindow
) {
3121 closing
.reject( new OO
.ui
.Error(
3122 'Cannot close window: window already closed with different data'
3124 } else if ( this.preparingToClose
|| this.closing
) {
3125 closing
.reject( new OO
.ui
.Error(
3126 'Cannot close window: window already closing with different data'
3131 if ( closing
.state() !== 'rejected' ) {
3132 // If the window is currently opening, close it when it's done
3133 this.preparingToClose
= $.when( this.opening
);
3134 // Ensure handlers get called after preparingToClose is set
3135 this.preparingToClose
.done( function () {
3136 manager
.closing
= closing
;
3137 manager
.preparingToClose
= null;
3138 manager
.emit( 'closing', win
, closing
, data
);
3139 opened
= manager
.opened
;
3140 manager
.opened
= null;
3141 opened
.resolve( closing
.promise(), data
);
3142 setTimeout( function () {
3143 win
.hold( data
).then( function () {
3144 closing
.notify( { state
: 'hold' } );
3145 setTimeout( function () {
3146 win
.teardown( data
).then( function () {
3147 closing
.notify( { state
: 'teardown' } );
3148 if ( manager
.modal
) {
3149 manager
.toggleGlobalEvents( false );
3150 manager
.toggleAriaIsolation( false );
3152 manager
.closing
= null;
3153 manager
.currentWindow
= null;
3154 closing
.resolve( data
);
3156 }, manager
.getTeardownDelay() );
3158 }, manager
.getHoldDelay() );
3162 return closing
.promise();
3166 * Add windows to the window manager.
3168 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3169 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3170 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3172 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3173 * by reference, symbolic name, or explicitly defined symbolic names.
3174 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3175 * explicit nor a statically configured symbolic name.
3177 OO
.ui
.WindowManager
.prototype.addWindows = function ( windows
) {
3178 var i
, len
, win
, name
, list
;
3180 if ( Array
.isArray( windows
) ) {
3181 // Convert to map of windows by looking up symbolic names from static configuration
3183 for ( i
= 0, len
= windows
.length
; i
< len
; i
++ ) {
3184 name
= windows
[ i
].constructor.static.name
;
3185 if ( typeof name
!== 'string' ) {
3186 throw new Error( 'Cannot add window' );
3188 list
[ name
] = windows
[ i
];
3190 } else if ( OO
.isPlainObject( windows
) ) {
3195 for ( name
in list
) {
3197 this.windows
[ name
] = win
.toggle( false );
3198 this.$element
.append( win
.$element
);
3199 win
.setManager( this );
3204 * Remove the specified windows from the windows manager.
3206 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3207 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3208 * longer listens to events, use the #destroy method.
3210 * @param {string[]} names Symbolic names of windows to remove
3211 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3212 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3214 OO
.ui
.WindowManager
.prototype.removeWindows = function ( names
) {
3215 var i
, len
, win
, name
, cleanupWindow
,
3218 cleanup = function ( name
, win
) {
3219 delete manager
.windows
[ name
];
3220 win
.$element
.detach();
3223 for ( i
= 0, len
= names
.length
; i
< len
; i
++ ) {
3225 win
= this.windows
[ name
];
3227 throw new Error( 'Cannot remove window' );
3229 cleanupWindow
= cleanup
.bind( null, name
, win
);
3230 promises
.push( this.closeWindow( name
).then( cleanupWindow
, cleanupWindow
) );
3233 return $.when
.apply( $, promises
);
3237 * Remove all windows from the window manager.
3239 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3240 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3241 * To remove just a subset of windows, use the #removeWindows method.
3243 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3245 OO
.ui
.WindowManager
.prototype.clearWindows = function () {
3246 return this.removeWindows( Object
.keys( this.windows
) );
3250 * Set dialog size. In general, this method should not be called directly.
3252 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3256 OO
.ui
.WindowManager
.prototype.updateWindowSize = function ( win
) {
3257 // Bypass for non-current, and thus invisible, windows
3258 if ( win
!== this.currentWindow
) {
3262 var viewport
= OO
.ui
.Element
.static.getDimensions( win
.getElementWindow() ),
3263 sizes
= this.constructor.static.sizes
,
3264 size
= win
.getSize();
3266 if ( !sizes
[ size
] ) {
3267 size
= this.constructor.static.defaultSize
;
3269 if ( size
!== 'full' && viewport
.rect
.right
- viewport
.rect
.left
< sizes
[ size
].width
) {
3273 this.$element
.toggleClass( 'oo-ui-windowManager-fullscreen', size
=== 'full' );
3274 this.$element
.toggleClass( 'oo-ui-windowManager-floating', size
!== 'full' );
3275 win
.setDimensions( sizes
[ size
] );
3277 this.emit( 'resize', win
);
3283 * Bind or unbind global events for scrolling.
3286 * @param {boolean} [on] Bind global events
3289 OO
.ui
.WindowManager
.prototype.toggleGlobalEvents = function ( on
) {
3290 on
= on
=== undefined ? !!this.globalEvents
: !!on
;
3292 var scrollWidth
, bodyMargin
,
3293 $body
= $( this.getElementDocument().body
),
3294 // We could have multiple window managers open so only modify
3295 // the body css at the bottom of the stack
3296 stackDepth
= $body
.data( 'windowManagerGlobalEvents' ) || 0 ;
3299 if ( !this.globalEvents
) {
3300 $( this.getElementWindow() ).on( {
3301 // Start listening for top-level window dimension changes
3302 'orientationchange resize': this.onWindowResizeHandler
3304 if ( stackDepth
=== 0 ) {
3305 scrollWidth
= window
.innerWidth
- document
.documentElement
.clientWidth
;
3306 bodyMargin
= parseFloat( $body
.css( 'margin-right' ) ) || 0;
3309 'margin-right': bodyMargin
+ scrollWidth
3313 this.globalEvents
= true;
3315 } else if ( this.globalEvents
) {
3316 $( this.getElementWindow() ).off( {
3317 // Stop listening for top-level window dimension changes
3318 'orientationchange resize': this.onWindowResizeHandler
3321 if ( stackDepth
=== 0 ) {
3327 this.globalEvents
= false;
3329 $body
.data( 'windowManagerGlobalEvents', stackDepth
);
3335 * Toggle screen reader visibility of content other than the window manager.
3338 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3341 OO
.ui
.WindowManager
.prototype.toggleAriaIsolation = function ( isolate
) {
3342 isolate
= isolate
=== undefined ? !this.$ariaHidden
: !!isolate
;
3345 if ( !this.$ariaHidden
) {
3346 // Hide everything other than the window manager from screen readers
3347 this.$ariaHidden
= $( 'body' )
3349 .not( this.$element
.parentsUntil( 'body' ).last() )
3350 .attr( 'aria-hidden', '' );
3352 } else if ( this.$ariaHidden
) {
3353 // Restore screen reader visibility
3354 this.$ariaHidden
.removeAttr( 'aria-hidden' );
3355 this.$ariaHidden
= null;
3362 * Destroy the window manager.
3364 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3365 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3368 OO
.ui
.WindowManager
.prototype.destroy = function () {
3369 this.toggleGlobalEvents( false );
3370 this.toggleAriaIsolation( false );
3371 this.clearWindows();
3372 this.$element
.remove();
3376 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3377 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3378 * appearance and functionality of the error interface.
3380 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3381 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3382 * that initiated the failed process will be disabled.
3384 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3387 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3389 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3394 * @param {string|jQuery} message Description of error
3395 * @param {Object} [config] Configuration options
3396 * @cfg {boolean} [recoverable=true] Error is recoverable.
3397 * By default, errors are recoverable, and users can try the process again.
3398 * @cfg {boolean} [warning=false] Error is a warning.
3399 * If the error is a warning, the error interface will include a
3400 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3401 * is not triggered a second time if the user chooses to continue.
3403 OO
.ui
.Error
= function OoUiError( message
, config
) {
3404 // Allow passing positional parameters inside the config object
3405 if ( OO
.isPlainObject( message
) && config
=== undefined ) {
3407 message
= config
.message
;
3410 // Configuration initialization
3411 config
= config
|| {};
3414 this.message
= message
instanceof jQuery
? message
: String( message
);
3415 this.recoverable
= config
.recoverable
=== undefined || !!config
.recoverable
;
3416 this.warning
= !!config
.warning
;
3421 OO
.initClass( OO
.ui
.Error
);
3426 * Check if the error is recoverable.
3428 * If the error is recoverable, users are able to try the process again.
3430 * @return {boolean} Error is recoverable
3432 OO
.ui
.Error
.prototype.isRecoverable = function () {
3433 return this.recoverable
;
3437 * Check if the error is a warning.
3439 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3441 * @return {boolean} Error is warning
3443 OO
.ui
.Error
.prototype.isWarning = function () {
3444 return this.warning
;
3448 * Get error message as DOM nodes.
3450 * @return {jQuery} Error message in DOM nodes
3452 OO
.ui
.Error
.prototype.getMessage = function () {
3453 return this.message
instanceof jQuery
?
3454 this.message
.clone() :
3455 $( '<div>' ).text( this.message
).contents();
3459 * Get the error message text.
3461 * @return {string} Error message
3463 OO
.ui
.Error
.prototype.getMessageText = function () {
3464 return this.message
instanceof jQuery
? this.message
.text() : this.message
;
3468 * Wraps an HTML snippet for use with configuration values which default
3469 * to strings. This bypasses the default html-escaping done to string
3475 * @param {string} [content] HTML content
3477 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
3479 this.content
= content
;
3484 OO
.initClass( OO
.ui
.HtmlSnippet
);
3491 * @return {string} Unchanged HTML snippet.
3493 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
3494 return this.content
;
3498 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3501 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3502 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3503 * or stop if the promise is rejected.
3504 * - **function**: the process will execute the function. The process will stop if the function returns
3505 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3506 * will wait for that number of milliseconds before proceeding.
3508 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3509 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3510 * its remaining steps will not be performed.
3515 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3516 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3517 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3518 * a number or promise.
3519 * @return {Object} Step object, with `callback` and `context` properties
3521 OO
.ui
.Process = function ( step
, context
) {
3526 if ( step
!== undefined ) {
3527 this.next( step
, context
);
3533 OO
.initClass( OO
.ui
.Process
);
3538 * Start the process.
3540 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3541 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3542 * and any remaining steps are not performed.
3544 OO
.ui
.Process
.prototype.execute = function () {
3545 var i
, len
, promise
;
3548 * Continue execution.
3551 * @param {Array} step A function and the context it should be called in
3552 * @return {Function} Function that continues the process
3554 function proceed( step
) {
3555 return function () {
3556 // Execute step in the correct context
3558 result
= step
.callback
.call( step
.context
);
3560 if ( result
=== false ) {
3561 // Use rejected promise for boolean false results
3562 return $.Deferred().reject( [] ).promise();
3564 if ( typeof result
=== 'number' ) {
3566 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3568 // Use a delayed promise for numbers, expecting them to be in milliseconds
3569 deferred
= $.Deferred();
3570 setTimeout( deferred
.resolve
, result
);
3571 return deferred
.promise();
3573 if ( result
instanceof OO
.ui
.Error
) {
3574 // Use rejected promise for error
3575 return $.Deferred().reject( [ result
] ).promise();
3577 if ( Array
.isArray( result
) && result
.length
&& result
[ 0 ] instanceof OO
.ui
.Error
) {
3578 // Use rejected promise for list of errors
3579 return $.Deferred().reject( result
).promise();
3581 // Duck-type the object to see if it can produce a promise
3582 if ( result
&& $.isFunction( result
.promise
) ) {
3583 // Use a promise generated from the result
3584 return result
.promise();
3586 // Use resolved promise for other results
3587 return $.Deferred().resolve().promise();
3591 if ( this.steps
.length
) {
3592 // Generate a chain reaction of promises
3593 promise
= proceed( this.steps
[ 0 ] )();
3594 for ( i
= 1, len
= this.steps
.length
; i
< len
; i
++ ) {
3595 promise
= promise
.then( proceed( this.steps
[ i
] ) );
3598 promise
= $.Deferred().resolve().promise();
3605 * Create a process step.
3608 * @param {number|jQuery.Promise|Function} step
3610 * - Number of milliseconds to wait before proceeding
3611 * - Promise that must be resolved before proceeding
3612 * - Function to execute
3613 * - If the function returns a boolean false the process will stop
3614 * - If the function returns a promise, the process will continue to the next
3615 * step when the promise is resolved or stop if the promise is rejected
3616 * - If the function returns a number, the process will wait for that number of
3617 * milliseconds before proceeding
3618 * @param {Object} [context=null] Execution context of the function. The context is
3619 * ignored if the step is a number or promise.
3620 * @return {Object} Step object, with `callback` and `context` properties
3622 OO
.ui
.Process
.prototype.createStep = function ( step
, context
) {
3623 if ( typeof step
=== 'number' || $.isFunction( step
.promise
) ) {
3625 callback: function () {
3631 if ( $.isFunction( step
) ) {
3637 throw new Error( 'Cannot create process step: number, promise or function expected' );
3641 * Add step to the beginning of the process.
3643 * @inheritdoc #createStep
3644 * @return {OO.ui.Process} this
3647 OO
.ui
.Process
.prototype.first = function ( step
, context
) {
3648 this.steps
.unshift( this.createStep( step
, context
) );
3653 * Add step to the end of the process.
3655 * @inheritdoc #createStep
3656 * @return {OO.ui.Process} this
3659 OO
.ui
.Process
.prototype.next = function ( step
, context
) {
3660 this.steps
.push( this.createStep( step
, context
) );
3665 * Factory for tools.
3668 * @extends OO.Factory
3671 OO
.ui
.ToolFactory
= function OoUiToolFactory() {
3672 // Parent constructor
3673 OO
.ui
.ToolFactory
.super.call( this );
3678 OO
.inheritClass( OO
.ui
.ToolFactory
, OO
.Factory
);
3683 * Get tools from the factory
3685 * @param {Array} include Included tools
3686 * @param {Array} exclude Excluded tools
3687 * @param {Array} promote Promoted tools
3688 * @param {Array} demote Demoted tools
3689 * @return {string[]} List of tools
3691 OO
.ui
.ToolFactory
.prototype.getTools = function ( include
, exclude
, promote
, demote
) {
3692 var i
, len
, included
, promoted
, demoted
,
3696 // Collect included and not excluded tools
3697 included
= OO
.simpleArrayDifference( this.extract( include
), this.extract( exclude
) );
3700 promoted
= this.extract( promote
, used
);
3701 demoted
= this.extract( demote
, used
);
3704 for ( i
= 0, len
= included
.length
; i
< len
; i
++ ) {
3705 if ( !used
[ included
[ i
] ] ) {
3706 auto
.push( included
[ i
] );
3710 return promoted
.concat( auto
).concat( demoted
);
3714 * Get a flat list of names from a list of names or groups.
3716 * Tools can be specified in the following ways:
3718 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
3719 * - All tools in a group: `{ group: 'group-name' }`
3720 * - All tools: `'*'`
3723 * @param {Array|string} collection List of tools
3724 * @param {Object} [used] Object with names that should be skipped as properties; extracted
3725 * names will be added as properties
3726 * @return {string[]} List of extracted names
3728 OO
.ui
.ToolFactory
.prototype.extract = function ( collection
, used
) {
3729 var i
, len
, item
, name
, tool
,
3732 if ( collection
=== '*' ) {
3733 for ( name
in this.registry
) {
3734 tool
= this.registry
[ name
];
3736 // Only add tools by group name when auto-add is enabled
3737 tool
.static.autoAddToCatchall
&&
3738 // Exclude already used tools
3739 ( !used
|| !used
[ name
] )
3743 used
[ name
] = true;
3747 } else if ( Array
.isArray( collection
) ) {
3748 for ( i
= 0, len
= collection
.length
; i
< len
; i
++ ) {
3749 item
= collection
[ i
];
3750 // Allow plain strings as shorthand for named tools
3751 if ( typeof item
=== 'string' ) {
3752 item
= { name
: item
};
3754 if ( OO
.isPlainObject( item
) ) {
3756 for ( name
in this.registry
) {
3757 tool
= this.registry
[ name
];
3759 // Include tools with matching group
3760 tool
.static.group
=== item
.group
&&
3761 // Only add tools by group name when auto-add is enabled
3762 tool
.static.autoAddToGroup
&&
3763 // Exclude already used tools
3764 ( !used
|| !used
[ name
] )
3768 used
[ name
] = true;
3772 // Include tools with matching name and exclude already used tools
3773 } else if ( item
.name
&& ( !used
|| !used
[ item
.name
] ) ) {
3774 names
.push( item
.name
);
3776 used
[ item
.name
] = true;
3786 * Factory for tool groups.
3789 * @extends OO.Factory
3792 OO
.ui
.ToolGroupFactory
= function OoUiToolGroupFactory() {
3793 // Parent constructor
3794 OO
.Factory
.call( this );
3797 defaultClasses
= this.constructor.static.getDefaultClasses();
3799 // Register default toolgroups
3800 for ( i
= 0, l
= defaultClasses
.length
; i
< l
; i
++ ) {
3801 this.register( defaultClasses
[ i
] );
3807 OO
.inheritClass( OO
.ui
.ToolGroupFactory
, OO
.Factory
);
3809 /* Static Methods */
3812 * Get a default set of classes to be registered on construction
3814 * @return {Function[]} Default classes
3816 OO
.ui
.ToolGroupFactory
.static.getDefaultClasses = function () {
3819 OO
.ui
.ListToolGroup
,
3831 * @param {Object} [config] Configuration options
3833 OO
.ui
.Theme
= function OoUiTheme( config
) {
3834 // Configuration initialization
3835 config
= config
|| {};
3840 OO
.initClass( OO
.ui
.Theme
);
3845 * Get a list of classes to be applied to a widget.
3847 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
3848 * otherwise state transitions will not work properly.
3850 * @param {OO.ui.Element} element Element for which to get classes
3851 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3853 OO
.ui
.Theme
.prototype.getElementClasses = function ( /* element */ ) {
3854 return { on
: [], off
: [] };
3858 * Update CSS classes provided by the theme.
3860 * For elements with theme logic hooks, this should be called any time there's a state change.
3862 * @param {OO.ui.Element} element Element for which to update classes
3863 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3865 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
3866 var classes
= this.getElementClasses( element
);
3869 .removeClass( classes
.off
.join( ' ' ) )
3870 .addClass( classes
.on
.join( ' ' ) );
3874 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
3875 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
3876 * order in which users will navigate through the focusable elements via the "tab" key.
3879 * // TabIndexedElement is mixed into the ButtonWidget class
3880 * // to provide a tabIndex property.
3881 * var button1 = new OO.ui.ButtonWidget( {
3885 * var button2 = new OO.ui.ButtonWidget( {
3889 * var button3 = new OO.ui.ButtonWidget( {
3893 * var button4 = new OO.ui.ButtonWidget( {
3897 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
3903 * @param {Object} [config] Configuration options
3904 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
3905 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
3906 * functionality will be applied to it instead.
3907 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
3908 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
3909 * to remove the element from the tab-navigation flow.
3911 OO
.ui
.TabIndexedElement
= function OoUiTabIndexedElement( config
) {
3912 // Configuration initialization
3913 config
= $.extend( { tabIndex
: 0 }, config
);
3916 this.$tabIndexed
= null;
3917 this.tabIndex
= null;
3920 this.connect( this, { disable
: 'onDisable' } );
3923 this.setTabIndex( config
.tabIndex
);
3924 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
3929 OO
.initClass( OO
.ui
.TabIndexedElement
);
3934 * Set the element that should use the tabindex functionality.
3936 * This method is used to retarget a tabindex mixin so that its functionality applies
3937 * to the specified element. If an element is currently using the functionality, the mixin’s
3938 * effect on that element is removed before the new element is set up.
3940 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
3943 OO
.ui
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
3944 var tabIndex
= this.tabIndex
;
3945 // Remove attributes from old $tabIndexed
3946 this.setTabIndex( null );
3947 // Force update of new $tabIndexed
3948 this.$tabIndexed
= $tabIndexed
;
3949 this.tabIndex
= tabIndex
;
3950 return this.updateTabIndex();
3954 * Set the value of the tabindex.
3956 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
3959 OO
.ui
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
3960 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
3962 if ( this.tabIndex
!== tabIndex
) {
3963 this.tabIndex
= tabIndex
;
3964 this.updateTabIndex();
3971 * Update the `tabindex` attribute, in case of changes to tab index or
3977 OO
.ui
.TabIndexedElement
.prototype.updateTabIndex = function () {
3978 if ( this.$tabIndexed
) {
3979 if ( this.tabIndex
!== null ) {
3980 // Do not index over disabled elements
3981 this.$tabIndexed
.attr( {
3982 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
3983 // ChromeVox and NVDA do not seem to inherit this from parent elements
3984 'aria-disabled': this.isDisabled().toString()
3987 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
3994 * Handle disable events.
3997 * @param {boolean} disabled Element is disabled
3999 OO
.ui
.TabIndexedElement
.prototype.onDisable = function () {
4000 this.updateTabIndex();
4004 * Get the value of the tabindex.
4006 * @return {number|null} Tabindex value
4008 OO
.ui
.TabIndexedElement
.prototype.getTabIndex = function () {
4009 return this.tabIndex
;
4013 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4014 * interface element that can be configured with access keys for accessibility.
4015 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4017 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4022 * @param {Object} [config] Configuration options
4023 * @cfg {jQuery} [$button] The button element created by the class.
4024 * If this configuration is omitted, the button element will use a generated `<a>`.
4025 * @cfg {boolean} [framed=true] Render the button with a frame
4026 * @cfg {string} [accessKey] Button's access key
4028 OO
.ui
.ButtonElement
= function OoUiButtonElement( config
) {
4029 // Configuration initialization
4030 config
= config
|| {};
4033 this.$button
= null;
4035 this.accessKey
= null;
4036 this.active
= false;
4037 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
4038 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4039 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
4040 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
4041 this.onClickHandler
= this.onClick
.bind( this );
4042 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
4045 this.$element
.addClass( 'oo-ui-buttonElement' );
4046 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
4047 this.setAccessKey( config
.accessKey
);
4048 this.setButtonElement( config
.$button
|| $( '<a>' ) );
4053 OO
.initClass( OO
.ui
.ButtonElement
);
4055 /* Static Properties */
4058 * Cancel mouse down events.
4060 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4061 * Classes such as {@link OO.ui.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4062 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4067 * @property {boolean}
4069 OO
.ui
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
4074 * A 'click' event is emitted when the button element is clicked.
4082 * Set the button element.
4084 * This method is used to retarget a button mixin so that its functionality applies to
4085 * the specified button element instead of the one created by the class. If a button element
4086 * is already set, the method will remove the mixin’s effect on that element.
4088 * @param {jQuery} $button Element to use as button
4090 OO
.ui
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
4091 if ( this.$button
) {
4093 .removeClass( 'oo-ui-buttonElement-button' )
4094 .removeAttr( 'role accesskey' )
4096 mousedown
: this.onMouseDownHandler
,
4097 keydown
: this.onKeyDownHandler
,
4098 click
: this.onClickHandler
,
4099 keypress
: this.onKeyPressHandler
4103 this.$button
= $button
4104 .addClass( 'oo-ui-buttonElement-button' )
4105 .attr( { role
: 'button', accesskey
: this.accessKey
} )
4107 mousedown
: this.onMouseDownHandler
,
4108 keydown
: this.onKeyDownHandler
,
4109 click
: this.onClickHandler
,
4110 keypress
: this.onKeyPressHandler
4115 * Handles mouse down events.
4118 * @param {jQuery.Event} e Mouse down event
4120 OO
.ui
.ButtonElement
.prototype.onMouseDown = function ( e
) {
4121 if ( this.isDisabled() || e
.which
!== 1 ) {
4124 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4125 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4126 // reliably remove the pressed class
4127 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
4128 // Prevent change of focus unless specifically configured otherwise
4129 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
4135 * Handles mouse up events.
4138 * @param {jQuery.Event} e Mouse up event
4140 OO
.ui
.ButtonElement
.prototype.onMouseUp = function ( e
) {
4141 if ( this.isDisabled() || e
.which
!== 1 ) {
4144 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4145 // Stop listening for mouseup, since we only needed this once
4146 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
4150 * Handles mouse click events.
4153 * @param {jQuery.Event} e Mouse click event
4156 OO
.ui
.ButtonElement
.prototype.onClick = function ( e
) {
4157 if ( !this.isDisabled() && e
.which
=== 1 ) {
4158 this.emit( 'click' );
4164 * Handles key down events.
4167 * @param {jQuery.Event} e Key down event
4169 OO
.ui
.ButtonElement
.prototype.onKeyDown = function ( e
) {
4170 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4173 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4174 // Run the keyup handler no matter where the key is when the button is let go, so we can
4175 // reliably remove the pressed class
4176 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler
, true );
4180 * Handles key up events.
4183 * @param {jQuery.Event} e Key up event
4185 OO
.ui
.ButtonElement
.prototype.onKeyUp = function ( e
) {
4186 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4189 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4190 // Stop listening for keyup, since we only needed this once
4191 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler
, true );
4195 * Handles key press events.
4198 * @param {jQuery.Event} e Key press event
4201 OO
.ui
.ButtonElement
.prototype.onKeyPress = function ( e
) {
4202 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
4203 this.emit( 'click' );
4209 * Check if button has a frame.
4211 * @return {boolean} Button is framed
4213 OO
.ui
.ButtonElement
.prototype.isFramed = function () {
4218 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4220 * @param {boolean} [framed] Make button framed, omit to toggle
4223 OO
.ui
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
4224 framed
= framed
=== undefined ? !this.framed
: !!framed
;
4225 if ( framed
!== this.framed
) {
4226 this.framed
= framed
;
4228 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
4229 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
4230 this.updateThemeClasses();
4237 * Set the button's access key.
4239 * @param {string} accessKey Button's access key, use empty string to remove
4242 OO
.ui
.ButtonElement
.prototype.setAccessKey = function ( accessKey
) {
4243 accessKey
= typeof accessKey
=== 'string' && accessKey
.length
? accessKey
: null;
4245 if ( this.accessKey
!== accessKey
) {
4246 if ( this.$button
) {
4247 if ( accessKey
!== null ) {
4248 this.$button
.attr( 'accesskey', accessKey
);
4250 this.$button
.removeAttr( 'accesskey' );
4253 this.accessKey
= accessKey
;
4260 * Set the button to its 'active' state.
4262 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4263 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4264 * for other button types.
4266 * @param {boolean} [value] Make button active
4269 OO
.ui
.ButtonElement
.prototype.setActive = function ( value
) {
4270 this.$element
.toggleClass( 'oo-ui-buttonElement-active', !!value
);
4275 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4276 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4277 * items from the group is done through the interface the class provides.
4278 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4280 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4286 * @param {Object} [config] Configuration options
4287 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4288 * is omitted, the group element will use a generated `<div>`.
4290 OO
.ui
.GroupElement
= function OoUiGroupElement( config
) {
4291 // Configuration initialization
4292 config
= config
|| {};
4297 this.aggregateItemEvents
= {};
4300 this.setGroupElement( config
.$group
|| $( '<div>' ) );
4306 * Set the group element.
4308 * If an element is already set, items will be moved to the new element.
4310 * @param {jQuery} $group Element to use as group
4312 OO
.ui
.GroupElement
.prototype.setGroupElement = function ( $group
) {
4315 this.$group
= $group
;
4316 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4317 this.$group
.append( this.items
[ i
].$element
);
4322 * Check if a group contains no items.
4324 * @return {boolean} Group is empty
4326 OO
.ui
.GroupElement
.prototype.isEmpty = function () {
4327 return !this.items
.length
;
4331 * Get all items in the group.
4333 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4334 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4337 * @return {OO.ui.Element[]} An array of items.
4339 OO
.ui
.GroupElement
.prototype.getItems = function () {
4340 return this.items
.slice( 0 );
4344 * Get an item by its data.
4346 * Only the first item with matching data will be returned. To return all matching items,
4347 * use the #getItemsFromData method.
4349 * @param {Object} data Item data to search for
4350 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4352 OO
.ui
.GroupElement
.prototype.getItemFromData = function ( data
) {
4354 hash
= OO
.getHash( data
);
4356 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4357 item
= this.items
[ i
];
4358 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4367 * Get items by their data.
4369 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4371 * @param {Object} data Item data to search for
4372 * @return {OO.ui.Element[]} Items with equivalent data
4374 OO
.ui
.GroupElement
.prototype.getItemsFromData = function ( data
) {
4376 hash
= OO
.getHash( data
),
4379 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4380 item
= this.items
[ i
];
4381 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4390 * Aggregate the events emitted by the group.
4392 * When events are aggregated, the group will listen to all contained items for the event,
4393 * and then emit the event under a new name. The new event will contain an additional leading
4394 * parameter containing the item that emitted the original event. Other arguments emitted from
4395 * the original event are passed through.
4397 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4398 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4399 * A `null` value will remove aggregated events.
4401 * @throws {Error} An error is thrown if aggregation already exists.
4403 OO
.ui
.GroupElement
.prototype.aggregate = function ( events
) {
4404 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
4406 for ( itemEvent
in events
) {
4407 groupEvent
= events
[ itemEvent
];
4409 // Remove existing aggregated event
4410 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4411 // Don't allow duplicate aggregations
4413 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
4415 // Remove event aggregation from existing items
4416 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4417 item
= this.items
[ i
];
4418 if ( item
.connect
&& item
.disconnect
) {
4420 remove
[ itemEvent
] = [ 'emit', groupEvent
, item
];
4421 item
.disconnect( this, remove
);
4424 // Prevent future items from aggregating event
4425 delete this.aggregateItemEvents
[ itemEvent
];
4428 // Add new aggregate event
4430 // Make future items aggregate event
4431 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
4432 // Add event aggregation to existing items
4433 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4434 item
= this.items
[ i
];
4435 if ( item
.connect
&& item
.disconnect
) {
4437 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
4438 item
.connect( this, add
);
4446 * Add items to the group.
4448 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4449 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4451 * @param {OO.ui.Element[]} items An array of items to add to the group
4452 * @param {number} [index] Index of the insertion point
4455 OO
.ui
.GroupElement
.prototype.addItems = function ( items
, index
) {
4456 var i
, len
, item
, event
, events
, currentIndex
,
4459 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4462 // Check if item exists then remove it first, effectively "moving" it
4463 currentIndex
= $.inArray( item
, this.items
);
4464 if ( currentIndex
>= 0 ) {
4465 this.removeItems( [ item
] );
4466 // Adjust index to compensate for removal
4467 if ( currentIndex
< index
) {
4472 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
4474 for ( event
in this.aggregateItemEvents
) {
4475 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
4477 item
.connect( this, events
);
4479 item
.setElementGroup( this );
4480 itemElements
.push( item
.$element
.get( 0 ) );
4483 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
4484 this.$group
.append( itemElements
);
4485 this.items
.push
.apply( this.items
, items
);
4486 } else if ( index
=== 0 ) {
4487 this.$group
.prepend( itemElements
);
4488 this.items
.unshift
.apply( this.items
, items
);
4490 this.items
[ index
].$element
.before( itemElements
);
4491 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
4498 * Remove the specified items from a group.
4500 * Removed items are detached (not removed) from the DOM so that they may be reused.
4501 * To remove all items from a group, you may wish to use the #clearItems method instead.
4503 * @param {OO.ui.Element[]} items An array of items to remove
4506 OO
.ui
.GroupElement
.prototype.removeItems = function ( items
) {
4507 var i
, len
, item
, index
, remove
, itemEvent
;
4509 // Remove specific items
4510 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4512 index
= $.inArray( item
, this.items
);
4513 if ( index
!== -1 ) {
4515 item
.connect
&& item
.disconnect
&&
4516 !$.isEmptyObject( this.aggregateItemEvents
)
4519 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4520 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4522 item
.disconnect( this, remove
);
4524 item
.setElementGroup( null );
4525 this.items
.splice( index
, 1 );
4526 item
.$element
.detach();
4534 * Clear all items from the group.
4536 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4537 * To remove only a subset of items from a group, use the #removeItems method.
4541 OO
.ui
.GroupElement
.prototype.clearItems = function () {
4542 var i
, len
, item
, remove
, itemEvent
;
4545 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4546 item
= this.items
[ i
];
4548 item
.connect
&& item
.disconnect
&&
4549 !$.isEmptyObject( this.aggregateItemEvents
)
4552 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4553 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4555 item
.disconnect( this, remove
);
4557 item
.setElementGroup( null );
4558 item
.$element
.detach();
4566 * DraggableElement is a mixin class used to create elements that can be clicked
4567 * and dragged by a mouse to a new position within a group. This class must be used
4568 * in conjunction with OO.ui.DraggableGroupElement, which provides a container for
4569 * the draggable elements.
4576 OO
.ui
.DraggableElement
= function OoUiDraggableElement() {
4580 // Initialize and events
4582 .attr( 'draggable', true )
4583 .addClass( 'oo-ui-draggableElement' )
4585 dragstart
: this.onDragStart
.bind( this ),
4586 dragover
: this.onDragOver
.bind( this ),
4587 dragend
: this.onDragEnd
.bind( this ),
4588 drop
: this.onDrop
.bind( this )
4592 OO
.initClass( OO
.ui
.DraggableElement
);
4599 * A dragstart event is emitted when the user clicks and begins dragging an item.
4600 * @param {OO.ui.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4605 * A dragend event is emitted when the user drags an item and releases the mouse,
4606 * thus terminating the drag operation.
4611 * A drop event is emitted when the user drags an item and then releases the mouse button
4612 * over a valid target.
4615 /* Static Properties */
4618 * @inheritdoc OO.ui.ButtonElement
4620 OO
.ui
.DraggableElement
.static.cancelButtonMouseDownEvents
= false;
4625 * Respond to dragstart event.
4628 * @param {jQuery.Event} event jQuery event
4631 OO
.ui
.DraggableElement
.prototype.onDragStart = function ( e
) {
4632 var dataTransfer
= e
.originalEvent
.dataTransfer
;
4633 // Define drop effect
4634 dataTransfer
.dropEffect
= 'none';
4635 dataTransfer
.effectAllowed
= 'move';
4636 // We must set up a dataTransfer data property or Firefox seems to
4637 // ignore the fact the element is draggable.
4639 dataTransfer
.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4641 // The above is only for firefox. No need to set a catch clause
4642 // if it fails, move on.
4644 // Add dragging class
4645 this.$element
.addClass( 'oo-ui-draggableElement-dragging' );
4647 this.emit( 'dragstart', this );
4652 * Respond to dragend event.
4657 OO
.ui
.DraggableElement
.prototype.onDragEnd = function () {
4658 this.$element
.removeClass( 'oo-ui-draggableElement-dragging' );
4659 this.emit( 'dragend' );
4663 * Handle drop event.
4666 * @param {jQuery.Event} event jQuery event
4669 OO
.ui
.DraggableElement
.prototype.onDrop = function ( e
) {
4671 this.emit( 'drop', e
);
4675 * In order for drag/drop to work, the dragover event must
4676 * return false and stop propogation.
4680 OO
.ui
.DraggableElement
.prototype.onDragOver = function ( e
) {
4686 * Store it in the DOM so we can access from the widget drag event
4689 * @param {number} Item index
4691 OO
.ui
.DraggableElement
.prototype.setIndex = function ( index
) {
4692 if ( this.index
!== index
) {
4694 this.$element
.data( 'index', index
);
4702 * @return {number} Item index
4704 OO
.ui
.DraggableElement
.prototype.getIndex = function () {
4709 * DraggableGroupElement is a mixin class used to create a group element to
4710 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
4711 * The class is used with OO.ui.DraggableElement.
4715 * @mixins OO.ui.GroupElement
4718 * @param {Object} [config] Configuration options
4719 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
4720 * should match the layout of the items. Items displayed in a single row
4721 * or in several rows should use horizontal orientation. The vertical orientation should only be
4722 * used when the items are displayed in a single column. Defaults to 'vertical'
4724 OO
.ui
.DraggableGroupElement
= function OoUiDraggableGroupElement( config
) {
4725 // Configuration initialization
4726 config
= config
|| {};
4728 // Parent constructor
4729 OO
.ui
.GroupElement
.call( this, config
);
4732 this.orientation
= config
.orientation
|| 'vertical';
4733 this.dragItem
= null;
4734 this.itemDragOver
= null;
4736 this.sideInsertion
= '';
4740 dragstart
: 'itemDragStart',
4741 dragend
: 'itemDragEnd',
4744 this.connect( this, {
4745 itemDragStart
: 'onItemDragStart',
4746 itemDrop
: 'onItemDrop',
4747 itemDragEnd
: 'onItemDragEnd'
4750 dragover
: $.proxy( this.onDragOver
, this ),
4751 dragleave
: $.proxy( this.onDragLeave
, this )
4755 if ( Array
.isArray( config
.items
) ) {
4756 this.addItems( config
.items
);
4758 this.$placeholder
= $( '<div>' )
4759 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
4761 .addClass( 'oo-ui-draggableGroupElement' )
4762 .append( this.$status
)
4763 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation
=== 'horizontal' )
4764 .prepend( this.$placeholder
);
4768 OO
.mixinClass( OO
.ui
.DraggableGroupElement
, OO
.ui
.GroupElement
);
4773 * A 'reorder' event is emitted when the order of items in the group changes.
4776 * @param {OO.ui.DraggableElement} item Reordered item
4777 * @param {number} [newIndex] New index for the item
4783 * Respond to item drag start event
4786 * @param {OO.ui.DraggableElement} item Dragged item
4788 OO
.ui
.DraggableGroupElement
.prototype.onItemDragStart = function ( item
) {
4791 // Map the index of each object
4792 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4793 this.items
[ i
].setIndex( i
);
4796 if ( this.orientation
=== 'horizontal' ) {
4797 // Set the height of the indicator
4798 this.$placeholder
.css( {
4799 height
: item
.$element
.outerHeight(),
4803 // Set the width of the indicator
4804 this.$placeholder
.css( {
4806 width
: item
.$element
.outerWidth()
4809 this.setDragItem( item
);
4813 * Respond to item drag end event
4817 OO
.ui
.DraggableGroupElement
.prototype.onItemDragEnd = function () {
4818 this.unsetDragItem();
4823 * Handle drop event and switch the order of the items accordingly
4826 * @param {OO.ui.DraggableElement} item Dropped item
4829 OO
.ui
.DraggableGroupElement
.prototype.onItemDrop = function ( item
) {
4830 var toIndex
= item
.getIndex();
4831 // Check if the dropped item is from the current group
4832 // TODO: Figure out a way to configure a list of legally droppable
4833 // elements even if they are not yet in the list
4834 if ( this.getDragItem() ) {
4835 // If the insertion point is 'after', the insertion index
4836 // is shifted to the right (or to the left in RTL, hence 'after')
4837 if ( this.sideInsertion
=== 'after' ) {
4840 // Emit change event
4841 this.emit( 'reorder', this.getDragItem(), toIndex
);
4843 this.unsetDragItem();
4844 // Return false to prevent propogation
4849 * Handle dragleave event.
4853 OO
.ui
.DraggableGroupElement
.prototype.onDragLeave = function () {
4854 // This means the item was dragged outside the widget
4857 .addClass( 'oo-ui-element-hidden' );
4861 * Respond to dragover event
4864 * @param {jQuery.Event} event Event details
4866 OO
.ui
.DraggableGroupElement
.prototype.onDragOver = function ( e
) {
4867 var dragOverObj
, $optionWidget
, itemOffset
, itemMidpoint
, itemBoundingRect
,
4868 itemSize
, cssOutput
, dragPosition
, itemIndex
, itemPosition
,
4869 clientX
= e
.originalEvent
.clientX
,
4870 clientY
= e
.originalEvent
.clientY
;
4872 // Get the OptionWidget item we are dragging over
4873 dragOverObj
= this.getElementDocument().elementFromPoint( clientX
, clientY
);
4874 $optionWidget
= $( dragOverObj
).closest( '.oo-ui-draggableElement' );
4875 if ( $optionWidget
[ 0 ] ) {
4876 itemOffset
= $optionWidget
.offset();
4877 itemBoundingRect
= $optionWidget
[ 0 ].getBoundingClientRect();
4878 itemPosition
= $optionWidget
.position();
4879 itemIndex
= $optionWidget
.data( 'index' );
4884 this.isDragging() &&
4885 itemIndex
!== this.getDragItem().getIndex()
4887 if ( this.orientation
=== 'horizontal' ) {
4888 // Calculate where the mouse is relative to the item width
4889 itemSize
= itemBoundingRect
.width
;
4890 itemMidpoint
= itemBoundingRect
.left
+ itemSize
/ 2;
4891 dragPosition
= clientX
;
4892 // Which side of the item we hover over will dictate
4893 // where the placeholder will appear, on the left or
4896 left
: dragPosition
< itemMidpoint
? itemPosition
.left
: itemPosition
.left
+ itemSize
,
4897 top
: itemPosition
.top
4900 // Calculate where the mouse is relative to the item height
4901 itemSize
= itemBoundingRect
.height
;
4902 itemMidpoint
= itemBoundingRect
.top
+ itemSize
/ 2;
4903 dragPosition
= clientY
;
4904 // Which side of the item we hover over will dictate
4905 // where the placeholder will appear, on the top or
4908 top
: dragPosition
< itemMidpoint
? itemPosition
.top
: itemPosition
.top
+ itemSize
,
4909 left
: itemPosition
.left
4912 // Store whether we are before or after an item to rearrange
4913 // For horizontal layout, we need to account for RTL, as this is flipped
4914 if ( this.orientation
=== 'horizontal' && this.$element
.css( 'direction' ) === 'rtl' ) {
4915 this.sideInsertion
= dragPosition
< itemMidpoint
? 'after' : 'before';
4917 this.sideInsertion
= dragPosition
< itemMidpoint
? 'before' : 'after';
4919 // Add drop indicator between objects
4922 .removeClass( 'oo-ui-element-hidden' );
4924 // This means the item was dragged outside the widget
4927 .addClass( 'oo-ui-element-hidden' );
4934 * Set a dragged item
4936 * @param {OO.ui.DraggableElement} item Dragged item
4938 OO
.ui
.DraggableGroupElement
.prototype.setDragItem = function ( item
) {
4939 this.dragItem
= item
;
4943 * Unset the current dragged item
4945 OO
.ui
.DraggableGroupElement
.prototype.unsetDragItem = function () {
4946 this.dragItem
= null;
4947 this.itemDragOver
= null;
4948 this.$placeholder
.addClass( 'oo-ui-element-hidden' );
4949 this.sideInsertion
= '';
4953 * Get the item that is currently being dragged.
4955 * @return {OO.ui.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
4957 OO
.ui
.DraggableGroupElement
.prototype.getDragItem = function () {
4958 return this.dragItem
;
4962 * Check if an item in the group is currently being dragged.
4964 * @return {Boolean} Item is being dragged
4966 OO
.ui
.DraggableGroupElement
.prototype.isDragging = function () {
4967 return this.getDragItem() !== null;
4971 * IconElement is often mixed into other classes to generate an icon.
4972 * Icons are graphics, about the size of normal text. They are used to aid the user
4973 * in locating a control or to convey information in a space-efficient way. See the
4974 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
4975 * included in the library.
4977 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
4983 * @param {Object} [config] Configuration options
4984 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
4985 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
4986 * the icon element be set to an existing icon instead of the one generated by this class, set a
4987 * value using a jQuery selection. For example:
4989 * // Use a <div> tag instead of a <span>
4991 * // Use an existing icon element instead of the one generated by the class
4992 * $icon: this.$element
4993 * // Use an icon element from a child widget
4994 * $icon: this.childwidget.$element
4995 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
4996 * symbolic names. A map is used for i18n purposes and contains a `default` icon
4997 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
4998 * by the user's language.
5000 * Example of an i18n map:
5002 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5003 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5004 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5005 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5006 * text. The icon title is displayed when users move the mouse over the icon.
5008 OO
.ui
.IconElement
= function OoUiIconElement( config
) {
5009 // Configuration initialization
5010 config
= config
|| {};
5015 this.iconTitle
= null;
5018 this.setIcon( config
.icon
|| this.constructor.static.icon
);
5019 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
5020 this.setIconElement( config
.$icon
|| $( '<span>' ) );
5025 OO
.initClass( OO
.ui
.IconElement
);
5027 /* Static Properties */
5030 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5031 * for i18n purposes and contains a `default` icon name and additional names keyed by
5032 * language code. The `default` name is used when no icon is keyed by the user's language.
5034 * Example of an i18n map:
5036 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5038 * Note: the static property will be overridden if the #icon configuration is used.
5042 * @property {Object|string}
5044 OO
.ui
.IconElement
.static.icon
= null;
5047 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5048 * function that returns title text, or `null` for no title.
5050 * The static property will be overridden if the #iconTitle configuration is used.
5054 * @property {string|Function|null}
5056 OO
.ui
.IconElement
.static.iconTitle
= null;
5061 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5062 * applies to the specified icon element instead of the one created by the class. If an icon
5063 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5064 * and mixin methods will no longer affect the element.
5066 * @param {jQuery} $icon Element to use as icon
5068 OO
.ui
.IconElement
.prototype.setIconElement = function ( $icon
) {
5071 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
5072 .removeAttr( 'title' );
5076 .addClass( 'oo-ui-iconElement-icon' )
5077 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
5078 if ( this.iconTitle
!== null ) {
5079 this.$icon
.attr( 'title', this.iconTitle
);
5084 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5085 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5088 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5089 * by language code, or `null` to remove the icon.
5092 OO
.ui
.IconElement
.prototype.setIcon = function ( icon
) {
5093 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
5094 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
5096 if ( this.icon
!== icon
) {
5098 if ( this.icon
!== null ) {
5099 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
5101 if ( icon
!== null ) {
5102 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
5108 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
5109 this.updateThemeClasses();
5115 * Set the icon title. Use `null` to remove the title.
5117 * @param {string|Function|null} iconTitle A text string used as the icon title,
5118 * a function that returns title text, or `null` for no title.
5121 OO
.ui
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
5122 iconTitle
= typeof iconTitle
=== 'function' ||
5123 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
5124 OO
.ui
.resolveMsg( iconTitle
) : null;
5126 if ( this.iconTitle
!== iconTitle
) {
5127 this.iconTitle
= iconTitle
;
5129 if ( this.iconTitle
!== null ) {
5130 this.$icon
.attr( 'title', iconTitle
);
5132 this.$icon
.removeAttr( 'title' );
5141 * Get the symbolic name of the icon.
5143 * @return {string} Icon name
5145 OO
.ui
.IconElement
.prototype.getIcon = function () {
5150 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5152 * @return {string} Icon title text
5154 OO
.ui
.IconElement
.prototype.getIconTitle = function () {
5155 return this.iconTitle
;
5159 * IndicatorElement is often mixed into other classes to generate an indicator.
5160 * Indicators are small graphics that are generally used in two ways:
5162 * - To draw attention to the status of an item. For example, an indicator might be
5163 * used to show that an item in a list has errors that need to be resolved.
5164 * - To clarify the function of a control that acts in an exceptional way (a button
5165 * that opens a menu instead of performing an action directly, for example).
5167 * For a list of indicators included in the library, please see the
5168 * [OOjs UI documentation on MediaWiki] [1].
5170 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5176 * @param {Object} [config] Configuration options
5177 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5178 * configuration is omitted, the indicator element will use a generated `<span>`.
5179 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5180 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5182 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5183 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5184 * or a function that returns title text. The indicator title is displayed when users move
5185 * the mouse over the indicator.
5187 OO
.ui
.IndicatorElement
= function OoUiIndicatorElement( config
) {
5188 // Configuration initialization
5189 config
= config
|| {};
5192 this.$indicator
= null;
5193 this.indicator
= null;
5194 this.indicatorTitle
= null;
5197 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
5198 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
5199 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
5204 OO
.initClass( OO
.ui
.IndicatorElement
);
5206 /* Static Properties */
5209 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5210 * The static property will be overridden if the #indicator configuration is used.
5214 * @property {string|null}
5216 OO
.ui
.IndicatorElement
.static.indicator
= null;
5219 * A text string used as the indicator title, a function that returns title text, or `null`
5220 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5224 * @property {string|Function|null}
5226 OO
.ui
.IndicatorElement
.static.indicatorTitle
= null;
5231 * Set the indicator element.
5233 * If an element is already set, it will be cleaned up before setting up the new element.
5235 * @param {jQuery} $indicator Element to use as indicator
5237 OO
.ui
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
5238 if ( this.$indicator
) {
5240 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
5241 .removeAttr( 'title' );
5244 this.$indicator
= $indicator
5245 .addClass( 'oo-ui-indicatorElement-indicator' )
5246 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
5247 if ( this.indicatorTitle
!== null ) {
5248 this.$indicator
.attr( 'title', this.indicatorTitle
);
5253 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5255 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5258 OO
.ui
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
5259 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
5261 if ( this.indicator
!== indicator
) {
5262 if ( this.$indicator
) {
5263 if ( this.indicator
!== null ) {
5264 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
5266 if ( indicator
!== null ) {
5267 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
5270 this.indicator
= indicator
;
5273 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
5274 this.updateThemeClasses();
5280 * Set the indicator title.
5282 * The title is displayed when a user moves the mouse over the indicator.
5284 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5285 * `null` for no indicator title
5288 OO
.ui
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
5289 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
5290 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
5291 OO
.ui
.resolveMsg( indicatorTitle
) : null;
5293 if ( this.indicatorTitle
!== indicatorTitle
) {
5294 this.indicatorTitle
= indicatorTitle
;
5295 if ( this.$indicator
) {
5296 if ( this.indicatorTitle
!== null ) {
5297 this.$indicator
.attr( 'title', indicatorTitle
);
5299 this.$indicator
.removeAttr( 'title' );
5308 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5310 * @return {string} Symbolic name of indicator
5312 OO
.ui
.IndicatorElement
.prototype.getIndicator = function () {
5313 return this.indicator
;
5317 * Get the indicator title.
5319 * The title is displayed when a user moves the mouse over the indicator.
5321 * @return {string} Indicator title text
5323 OO
.ui
.IndicatorElement
.prototype.getIndicatorTitle = function () {
5324 return this.indicatorTitle
;
5328 * LabelElement is often mixed into other classes to generate a label, which
5329 * helps identify the function of an interface element.
5330 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5332 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5338 * @param {Object} [config] Configuration options
5339 * @cfg {jQuery} [$label] The label element created by the class. If this
5340 * configuration is omitted, the label element will use a generated `<span>`.
5341 * @cfg {jQuery|string|Function} [label] The label text. The label can be specified as a plaintext string,
5342 * a jQuery selection of elements, or a function that will produce a string in the future. See the
5343 * [OOjs UI documentation on MediaWiki] [2] for examples.
5344 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5345 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5346 * The label will be truncated to fit if necessary.
5348 OO
.ui
.LabelElement
= function OoUiLabelElement( config
) {
5349 // Configuration initialization
5350 config
= config
|| {};
5355 this.autoFitLabel
= config
.autoFitLabel
=== undefined || !!config
.autoFitLabel
;
5358 this.setLabel( config
.label
|| this.constructor.static.label
);
5359 this.setLabelElement( config
.$label
|| $( '<span>' ) );
5364 OO
.initClass( OO
.ui
.LabelElement
);
5369 * @event labelChange
5370 * @param {string} value
5373 /* Static Properties */
5376 * The label text. The label can be specified as a plaintext string, a function that will
5377 * produce a string in the future, or `null` for no label. The static value will
5378 * be overridden if a label is specified with the #label config option.
5382 * @property {string|Function|null}
5384 OO
.ui
.LabelElement
.static.label
= null;
5389 * Set the label element.
5391 * If an element is already set, it will be cleaned up before setting up the new element.
5393 * @param {jQuery} $label Element to use as label
5395 OO
.ui
.LabelElement
.prototype.setLabelElement = function ( $label
) {
5396 if ( this.$label
) {
5397 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
5400 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
5401 this.setLabelContent( this.label
);
5407 * An empty string will result in the label being hidden. A string containing only whitespace will
5408 * be converted to a single ` `.
5410 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5411 * text; or null for no label
5414 OO
.ui
.LabelElement
.prototype.setLabel = function ( label
) {
5415 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
5416 label
= ( ( typeof label
=== 'string' && label
.length
) || label
instanceof jQuery
|| label
instanceof OO
.ui
.HtmlSnippet
) ? label
: null;
5418 this.$element
.toggleClass( 'oo-ui-labelElement', !!label
);
5420 if ( this.label
!== label
) {
5421 if ( this.$label
) {
5422 this.setLabelContent( label
);
5425 this.emit( 'labelChange' );
5434 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5435 * text; or null for no label
5437 OO
.ui
.LabelElement
.prototype.getLabel = function () {
5446 OO
.ui
.LabelElement
.prototype.fitLabel = function () {
5447 if ( this.$label
&& this.$label
.autoEllipsis
&& this.autoFitLabel
) {
5448 this.$label
.autoEllipsis( { hasSpan
: false, tooltip
: true } );
5455 * Set the content of the label.
5457 * Do not call this method until after the label element has been set by #setLabelElement.
5460 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5461 * text; or null for no label
5463 OO
.ui
.LabelElement
.prototype.setLabelContent = function ( label
) {
5464 if ( typeof label
=== 'string' ) {
5465 if ( label
.match( /^\s*$/ ) ) {
5466 // Convert whitespace only string to a single non-breaking space
5467 this.$label
.html( ' ' );
5469 this.$label
.text( label
);
5471 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
5472 this.$label
.html( label
.toString() );
5473 } else if ( label
instanceof jQuery
) {
5474 this.$label
.empty().append( label
);
5476 this.$label
.empty();
5481 * LookupElement is a mixin that creates a {@link OO.ui.TextInputMenuSelectWidget menu} of suggested values for
5482 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5483 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5484 * from the lookup menu, that value becomes the value of the input field.
5486 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5487 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5488 * re-enable lookups.
5490 * See the [OOjs UI demos][1] for an example.
5492 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5498 * @param {Object} [config] Configuration options
5499 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5500 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5501 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5502 * By default, the lookup menu is not generated and displayed until the user begins to type.
5504 OO
.ui
.LookupElement
= function OoUiLookupElement( config
) {
5505 // Configuration initialization
5506 config
= config
|| {};
5509 this.$overlay
= config
.$overlay
|| this.$element
;
5510 this.lookupMenu
= new OO
.ui
.TextInputMenuSelectWidget( this, {
5513 $container
: config
.$container
5516 this.allowSuggestionsWhenEmpty
= config
.allowSuggestionsWhenEmpty
|| false;
5518 this.lookupCache
= {};
5519 this.lookupQuery
= null;
5520 this.lookupRequest
= null;
5521 this.lookupsDisabled
= false;
5522 this.lookupInputFocused
= false;
5526 focus
: this.onLookupInputFocus
.bind( this ),
5527 blur
: this.onLookupInputBlur
.bind( this ),
5528 mousedown
: this.onLookupInputMouseDown
.bind( this )
5530 this.connect( this, { change
: 'onLookupInputChange' } );
5531 this.lookupMenu
.connect( this, {
5532 toggle
: 'onLookupMenuToggle',
5533 choose
: 'onLookupMenuItemChoose'
5537 this.$element
.addClass( 'oo-ui-lookupElement' );
5538 this.lookupMenu
.$element
.addClass( 'oo-ui-lookupElement-menu' );
5539 this.$overlay
.append( this.lookupMenu
.$element
);
5545 * Handle input focus event.
5548 * @param {jQuery.Event} e Input focus event
5550 OO
.ui
.LookupElement
.prototype.onLookupInputFocus = function () {
5551 this.lookupInputFocused
= true;
5552 this.populateLookupMenu();
5556 * Handle input blur event.
5559 * @param {jQuery.Event} e Input blur event
5561 OO
.ui
.LookupElement
.prototype.onLookupInputBlur = function () {
5562 this.closeLookupMenu();
5563 this.lookupInputFocused
= false;
5567 * Handle input mouse down event.
5570 * @param {jQuery.Event} e Input mouse down event
5572 OO
.ui
.LookupElement
.prototype.onLookupInputMouseDown = function () {
5573 // Only open the menu if the input was already focused.
5574 // This way we allow the user to open the menu again after closing it with Esc
5575 // by clicking in the input. Opening (and populating) the menu when initially
5576 // clicking into the input is handled by the focus handler.
5577 if ( this.lookupInputFocused
&& !this.lookupMenu
.isVisible() ) {
5578 this.populateLookupMenu();
5583 * Handle input change event.
5586 * @param {string} value New input value
5588 OO
.ui
.LookupElement
.prototype.onLookupInputChange = function () {
5589 if ( this.lookupInputFocused
) {
5590 this.populateLookupMenu();
5595 * Handle the lookup menu being shown/hidden.
5598 * @param {boolean} visible Whether the lookup menu is now visible.
5600 OO
.ui
.LookupElement
.prototype.onLookupMenuToggle = function ( visible
) {
5602 // When the menu is hidden, abort any active request and clear the menu.
5603 // This has to be done here in addition to closeLookupMenu(), because
5604 // MenuSelectWidget will close itself when the user presses Esc.
5605 this.abortLookupRequest();
5606 this.lookupMenu
.clearItems();
5611 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5614 * @param {OO.ui.MenuOptionWidget} item Selected item
5616 OO
.ui
.LookupElement
.prototype.onLookupMenuItemChoose = function ( item
) {
5617 this.setValue( item
.getData() );
5624 * @return {OO.ui.TextInputMenuSelectWidget}
5626 OO
.ui
.LookupElement
.prototype.getLookupMenu = function () {
5627 return this.lookupMenu
;
5631 * Disable or re-enable lookups.
5633 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
5635 * @param {boolean} disabled Disable lookups
5637 OO
.ui
.LookupElement
.prototype.setLookupsDisabled = function ( disabled
) {
5638 this.lookupsDisabled
= !!disabled
;
5642 * Open the menu. If there are no entries in the menu, this does nothing.
5647 OO
.ui
.LookupElement
.prototype.openLookupMenu = function () {
5648 if ( !this.lookupMenu
.isEmpty() ) {
5649 this.lookupMenu
.toggle( true );
5655 * Close the menu, empty it, and abort any pending request.
5660 OO
.ui
.LookupElement
.prototype.closeLookupMenu = function () {
5661 this.lookupMenu
.toggle( false );
5662 this.abortLookupRequest();
5663 this.lookupMenu
.clearItems();
5668 * Request menu items based on the input's current value, and when they arrive,
5669 * populate the menu with these items and show the menu.
5671 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
5676 OO
.ui
.LookupElement
.prototype.populateLookupMenu = function () {
5678 value
= this.getValue();
5680 if ( this.lookupsDisabled
) {
5684 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
5685 if ( !this.allowSuggestionsWhenEmpty
&& value
=== '' ) {
5686 this.closeLookupMenu();
5687 // Skip population if there is already a request pending for the current value
5688 } else if ( value
!== this.lookupQuery
) {
5689 this.getLookupMenuItems()
5690 .done( function ( items
) {
5691 widget
.lookupMenu
.clearItems();
5692 if ( items
.length
) {
5696 widget
.initializeLookupMenuSelection();
5698 widget
.lookupMenu
.toggle( false );
5701 .fail( function () {
5702 widget
.lookupMenu
.clearItems();
5710 * Select and highlight the first selectable item in the menu.
5715 OO
.ui
.LookupElement
.prototype.initializeLookupMenuSelection = function () {
5716 if ( !this.lookupMenu
.getSelectedItem() ) {
5717 this.lookupMenu
.selectItem( this.lookupMenu
.getFirstSelectableItem() );
5719 this.lookupMenu
.highlightItem( this.lookupMenu
.getSelectedItem() );
5723 * Get lookup menu items for the current query.
5726 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
5727 * the done event. If the request was aborted to make way for a subsequent request, this promise
5728 * will not be rejected: it will remain pending forever.
5730 OO
.ui
.LookupElement
.prototype.getLookupMenuItems = function () {
5732 value
= this.getValue(),
5733 deferred
= $.Deferred(),
5736 this.abortLookupRequest();
5737 if ( Object
.prototype.hasOwnProperty
.call( this.lookupCache
, value
) ) {
5738 deferred
.resolve( this.getLookupMenuOptionsFromData( this.lookupCache
[ value
] ) );
5741 this.lookupQuery
= value
;
5742 ourRequest
= this.lookupRequest
= this.getLookupRequest();
5744 .always( function () {
5745 // We need to pop pending even if this is an old request, otherwise
5746 // the widget will remain pending forever.
5747 // TODO: this assumes that an aborted request will fail or succeed soon after
5748 // being aborted, or at least eventually. It would be nice if we could popPending()
5749 // at abort time, but only if we knew that we hadn't already called popPending()
5750 // for that request.
5751 widget
.popPending();
5753 .done( function ( response
) {
5754 // If this is an old request (and aborting it somehow caused it to still succeed),
5755 // ignore its success completely
5756 if ( ourRequest
=== widget
.lookupRequest
) {
5757 widget
.lookupQuery
= null;
5758 widget
.lookupRequest
= null;
5759 widget
.lookupCache
[ value
] = widget
.getLookupCacheDataFromResponse( response
);
5760 deferred
.resolve( widget
.getLookupMenuOptionsFromData( widget
.lookupCache
[ value
] ) );
5763 .fail( function () {
5764 // If this is an old request (or a request failing because it's being aborted),
5765 // ignore its failure completely
5766 if ( ourRequest
=== widget
.lookupRequest
) {
5767 widget
.lookupQuery
= null;
5768 widget
.lookupRequest
= null;
5773 return deferred
.promise();
5777 * Abort the currently pending lookup request, if any.
5781 OO
.ui
.LookupElement
.prototype.abortLookupRequest = function () {
5782 var oldRequest
= this.lookupRequest
;
5784 // First unset this.lookupRequest to the fail handler will notice
5785 // that the request is no longer current
5786 this.lookupRequest
= null;
5787 this.lookupQuery
= null;
5793 * Get a new request object of the current lookup query value.
5797 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
5799 OO
.ui
.LookupElement
.prototype.getLookupRequest = function () {
5800 // Stub, implemented in subclass
5805 * Pre-process data returned by the request from #getLookupRequest.
5807 * The return value of this function will be cached, and any further queries for the given value
5808 * will use the cache rather than doing API requests.
5812 * @param {Mixed} response Response from server
5813 * @return {Mixed} Cached result data
5815 OO
.ui
.LookupElement
.prototype.getLookupCacheDataFromResponse = function () {
5816 // Stub, implemented in subclass
5821 * Get a list of menu option widgets from the (possibly cached) data returned by
5822 * #getLookupCacheDataFromResponse.
5826 * @param {Mixed} data Cached result data, usually an array
5827 * @return {OO.ui.MenuOptionWidget[]} Menu items
5829 OO
.ui
.LookupElement
.prototype.getLookupMenuOptionsFromData = function () {
5830 // Stub, implemented in subclass
5835 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5836 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5837 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5838 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5844 * @param {Object} [config] Configuration options
5845 * @cfg {Object} [popup] Configuration to pass to popup
5846 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5848 OO
.ui
.PopupElement
= function OoUiPopupElement( config
) {
5849 // Configuration initialization
5850 config
= config
|| {};
5853 this.popup
= new OO
.ui
.PopupWidget( $.extend(
5854 { autoClose
: true },
5856 { $autoCloseIgnore
: this.$element
}
5865 * @return {OO.ui.PopupWidget} Popup widget
5867 OO
.ui
.PopupElement
.prototype.getPopup = function () {
5872 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
5873 * additional functionality to an element created by another class. The class provides
5874 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
5875 * which are used to customize the look and feel of a widget to better describe its
5876 * importance and functionality.
5878 * The library currently contains the following styling flags for general use:
5880 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
5881 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
5882 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
5884 * The flags affect the appearance of the buttons:
5887 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
5888 * var button1 = new OO.ui.ButtonWidget( {
5889 * label: 'Constructive',
5890 * flags: 'constructive'
5892 * var button2 = new OO.ui.ButtonWidget( {
5893 * label: 'Destructive',
5894 * flags: 'destructive'
5896 * var button3 = new OO.ui.ButtonWidget( {
5897 * label: 'Progressive',
5898 * flags: 'progressive'
5900 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
5902 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
5903 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
5905 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5911 * @param {Object} [config] Configuration options
5912 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
5913 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
5914 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5915 * @cfg {jQuery} [$flagged] The flagged element. By default,
5916 * the flagged functionality is applied to the element created by the class ($element).
5917 * If a different element is specified, the flagged functionality will be applied to it instead.
5919 OO
.ui
.FlaggedElement
= function OoUiFlaggedElement( config
) {
5920 // Configuration initialization
5921 config
= config
|| {};
5925 this.$flagged
= null;
5928 this.setFlags( config
.flags
);
5929 this.setFlaggedElement( config
.$flagged
|| this.$element
);
5936 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
5937 * parameter contains the name of each modified flag and indicates whether it was
5940 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
5941 * that the flag was added, `false` that the flag was removed.
5947 * Set the flagged element.
5949 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
5950 * If an element is already set, the method will remove the mixin’s effect on that element.
5952 * @param {jQuery} $flagged Element that should be flagged
5954 OO
.ui
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
5955 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
5956 return 'oo-ui-flaggedElement-' + flag
;
5959 if ( this.$flagged
) {
5960 this.$flagged
.removeClass( classNames
);
5963 this.$flagged
= $flagged
.addClass( classNames
);
5967 * Check if the specified flag is set.
5969 * @param {string} flag Name of flag
5970 * @return {boolean} The flag is set
5972 OO
.ui
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
5973 return flag
in this.flags
;
5977 * Get the names of all flags set.
5979 * @return {string[]} Flag names
5981 OO
.ui
.FlaggedElement
.prototype.getFlags = function () {
5982 return Object
.keys( this.flags
);
5991 OO
.ui
.FlaggedElement
.prototype.clearFlags = function () {
5992 var flag
, className
,
5995 classPrefix
= 'oo-ui-flaggedElement-';
5997 for ( flag
in this.flags
) {
5998 className
= classPrefix
+ flag
;
5999 changes
[ flag
] = false;
6000 delete this.flags
[ flag
];
6001 remove
.push( className
);
6004 if ( this.$flagged
) {
6005 this.$flagged
.removeClass( remove
.join( ' ' ) );
6008 this.updateThemeClasses();
6009 this.emit( 'flag', changes
);
6015 * Add one or more flags.
6017 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6018 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6019 * be added (`true`) or removed (`false`).
6023 OO
.ui
.FlaggedElement
.prototype.setFlags = function ( flags
) {
6024 var i
, len
, flag
, className
,
6028 classPrefix
= 'oo-ui-flaggedElement-';
6030 if ( typeof flags
=== 'string' ) {
6031 className
= classPrefix
+ flags
;
6033 if ( !this.flags
[ flags
] ) {
6034 this.flags
[ flags
] = true;
6035 add
.push( className
);
6037 } else if ( Array
.isArray( flags
) ) {
6038 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
6040 className
= classPrefix
+ flag
;
6042 if ( !this.flags
[ flag
] ) {
6043 changes
[ flag
] = true;
6044 this.flags
[ flag
] = true;
6045 add
.push( className
);
6048 } else if ( OO
.isPlainObject( flags
) ) {
6049 for ( flag
in flags
) {
6050 className
= classPrefix
+ flag
;
6051 if ( flags
[ flag
] ) {
6053 if ( !this.flags
[ flag
] ) {
6054 changes
[ flag
] = true;
6055 this.flags
[ flag
] = true;
6056 add
.push( className
);
6060 if ( this.flags
[ flag
] ) {
6061 changes
[ flag
] = false;
6062 delete this.flags
[ flag
];
6063 remove
.push( className
);
6069 if ( this.$flagged
) {
6071 .addClass( add
.join( ' ' ) )
6072 .removeClass( remove
.join( ' ' ) );
6075 this.updateThemeClasses();
6076 this.emit( 'flag', changes
);
6082 * TitledElement is mixed into other classes to provide a `title` attribute.
6083 * Titles are rendered by the browser and are made visible when the user moves
6084 * the mouse over the element. Titles are not visible on touch devices.
6087 * // TitledElement provides a 'title' attribute to the
6088 * // ButtonWidget class
6089 * var button = new OO.ui.ButtonWidget( {
6090 * label: 'Button with Title',
6091 * title: 'I am a button'
6093 * $( 'body' ).append( button.$element );
6099 * @param {Object} [config] Configuration options
6100 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6101 * If this config is omitted, the title functionality is applied to $element, the
6102 * element created by the class.
6103 * @cfg {string|Function} [title] The title text or a function that returns text. If
6104 * this config is omitted, the value of the {@link #static-title static title} property is used.
6106 OO
.ui
.TitledElement
= function OoUiTitledElement( config
) {
6107 // Configuration initialization
6108 config
= config
|| {};
6111 this.$titled
= null;
6115 this.setTitle( config
.title
|| this.constructor.static.title
);
6116 this.setTitledElement( config
.$titled
|| this.$element
);
6121 OO
.initClass( OO
.ui
.TitledElement
);
6123 /* Static Properties */
6126 * The title text, a function that returns text, or `null` for no title. The value of the static property
6127 * is overridden if the #title config option is used.
6131 * @property {string|Function|null}
6133 OO
.ui
.TitledElement
.static.title
= null;
6138 * Set the titled element.
6140 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6141 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6143 * @param {jQuery} $titled Element that should use the 'titled' functionality
6145 OO
.ui
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
6146 if ( this.$titled
) {
6147 this.$titled
.removeAttr( 'title' );
6150 this.$titled
= $titled
;
6152 this.$titled
.attr( 'title', this.title
);
6159 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6162 OO
.ui
.TitledElement
.prototype.setTitle = function ( title
) {
6163 title
= typeof title
=== 'string' ? OO
.ui
.resolveMsg( title
) : null;
6165 if ( this.title
!== title
) {
6166 if ( this.$titled
) {
6167 if ( title
!== null ) {
6168 this.$titled
.attr( 'title', title
);
6170 this.$titled
.removeAttr( 'title' );
6182 * @return {string} Title string
6184 OO
.ui
.TitledElement
.prototype.getTitle = function () {
6189 * Element that can be automatically clipped to visible boundaries.
6191 * Whenever the element's natural height changes, you have to call
6192 * #clip to make sure it's still clipping correctly.
6198 * @param {Object} [config] Configuration options
6199 * @cfg {jQuery} [$clippable] Nodes to clip, assigned to #$clippable, omit to use #$element
6201 OO
.ui
.ClippableElement
= function OoUiClippableElement( config
) {
6202 // Configuration initialization
6203 config
= config
|| {};
6206 this.$clippable
= null;
6207 this.clipping
= false;
6208 this.clippedHorizontally
= false;
6209 this.clippedVertically
= false;
6210 this.$clippableContainer
= null;
6211 this.$clippableScroller
= null;
6212 this.$clippableWindow
= null;
6213 this.idealWidth
= null;
6214 this.idealHeight
= null;
6215 this.onClippableContainerScrollHandler
= this.clip
.bind( this );
6216 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
6219 this.setClippableElement( config
.$clippable
|| this.$element
);
6225 * Set clippable element.
6227 * If an element is already set, it will be cleaned up before setting up the new element.
6229 * @param {jQuery} $clippable Element to make clippable
6231 OO
.ui
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
6232 if ( this.$clippable
) {
6233 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
6234 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6235 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6238 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
6245 * Do not turn clipping on until after the element is attached to the DOM and visible.
6247 * @param {boolean} [clipping] Enable clipping, omit to toggle
6250 OO
.ui
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
6251 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
6253 if ( this.clipping
!== clipping
) {
6254 this.clipping
= clipping
;
6256 this.$clippableContainer
= $( this.getClosestScrollableElementContainer() );
6257 // If the clippable container is the root, we have to listen to scroll events and check
6258 // jQuery.scrollTop on the window because of browser inconsistencies
6259 this.$clippableScroller
= this.$clippableContainer
.is( 'html, body' ) ?
6260 $( OO
.ui
.Element
.static.getWindow( this.$clippableContainer
) ) :
6261 this.$clippableContainer
;
6262 this.$clippableScroller
.on( 'scroll', this.onClippableContainerScrollHandler
);
6263 this.$clippableWindow
= $( this.getElementWindow() )
6264 .on( 'resize', this.onClippableWindowResizeHandler
);
6265 // Initial clip after visible
6268 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6269 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6271 this.$clippableContainer
= null;
6272 this.$clippableScroller
.off( 'scroll', this.onClippableContainerScrollHandler
);
6273 this.$clippableScroller
= null;
6274 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
6275 this.$clippableWindow
= null;
6283 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6285 * @return {boolean} Element will be clipped to the visible area
6287 OO
.ui
.ClippableElement
.prototype.isClipping = function () {
6288 return this.clipping
;
6292 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6294 * @return {boolean} Part of the element is being clipped
6296 OO
.ui
.ClippableElement
.prototype.isClipped = function () {
6297 return this.clippedHorizontally
|| this.clippedVertically
;
6301 * Check if the right of the element is being clipped by the nearest scrollable container.
6303 * @return {boolean} Part of the element is being clipped
6305 OO
.ui
.ClippableElement
.prototype.isClippedHorizontally = function () {
6306 return this.clippedHorizontally
;
6310 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6312 * @return {boolean} Part of the element is being clipped
6314 OO
.ui
.ClippableElement
.prototype.isClippedVertically = function () {
6315 return this.clippedVertically
;
6319 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6321 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6322 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6324 OO
.ui
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
6325 this.idealWidth
= width
;
6326 this.idealHeight
= height
;
6328 if ( !this.clipping
) {
6329 // Update dimensions
6330 this.$clippable
.css( { width
: width
, height
: height
} );
6332 // While clipping, idealWidth and idealHeight are not considered
6336 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6337 * the element's natural height changes.
6339 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6340 * overlapped by, the visible area of the nearest scrollable container.
6344 OO
.ui
.ClippableElement
.prototype.clip = function () {
6345 if ( !this.clipping
) {
6346 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
6350 var buffer
= 7, // Chosen by fair dice roll
6351 cOffset
= this.$clippable
.offset(),
6352 $container
= this.$clippableContainer
.is( 'html, body' ) ?
6353 this.$clippableWindow
: this.$clippableContainer
,
6354 ccOffset
= $container
.offset() || { top
: 0, left
: 0 },
6355 ccHeight
= $container
.innerHeight() - buffer
,
6356 ccWidth
= $container
.innerWidth() - buffer
,
6357 cHeight
= this.$clippable
.outerHeight() + buffer
,
6358 cWidth
= this.$clippable
.outerWidth() + buffer
,
6359 scrollTop
= this.$clippableScroller
.scrollTop(),
6360 scrollLeft
= this.$clippableScroller
.scrollLeft(),
6361 desiredWidth
= cOffset
.left
< 0 ?
6362 cWidth
+ cOffset
.left
:
6363 ( ccOffset
.left
+ scrollLeft
+ ccWidth
) - cOffset
.left
,
6364 desiredHeight
= cOffset
.top
< 0 ?
6365 cHeight
+ cOffset
.top
:
6366 ( ccOffset
.top
+ scrollTop
+ ccHeight
) - cOffset
.top
,
6367 naturalWidth
= this.$clippable
.prop( 'scrollWidth' ),
6368 naturalHeight
= this.$clippable
.prop( 'scrollHeight' ),
6369 clipWidth
= desiredWidth
< naturalWidth
,
6370 clipHeight
= desiredHeight
< naturalHeight
;
6373 this.$clippable
.css( { overflowX
: 'scroll', width
: desiredWidth
} );
6375 this.$clippable
.css( { width
: this.idealWidth
|| '', overflowX
: '' } );
6378 this.$clippable
.css( { overflowY
: 'scroll', height
: desiredHeight
} );
6380 this.$clippable
.css( { height
: this.idealHeight
|| '', overflowY
: '' } );
6383 // If we stopped clipping in at least one of the dimensions
6384 if ( !clipWidth
|| !clipHeight
) {
6385 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6388 this.clippedHorizontally
= clipWidth
;
6389 this.clippedVertically
= clipHeight
;
6395 * Generic toolbar tool.
6399 * @extends OO.ui.Widget
6400 * @mixins OO.ui.IconElement
6401 * @mixins OO.ui.FlaggedElement
6404 * @param {OO.ui.ToolGroup} toolGroup
6405 * @param {Object} [config] Configuration options
6406 * @cfg {string|Function} [title] Title text or a function that returns text
6408 OO
.ui
.Tool
= function OoUiTool( toolGroup
, config
) {
6409 // Allow passing positional parameters inside the config object
6410 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
6412 toolGroup
= config
.toolGroup
;
6415 // Configuration initialization
6416 config
= config
|| {};
6418 // Parent constructor
6419 OO
.ui
.Tool
.super.call( this, config
);
6421 // Mixin constructors
6422 OO
.ui
.IconElement
.call( this, config
);
6423 OO
.ui
.FlaggedElement
.call( this, config
);
6426 this.toolGroup
= toolGroup
;
6427 this.toolbar
= this.toolGroup
.getToolbar();
6428 this.active
= false;
6429 this.$title
= $( '<span>' );
6430 this.$accel
= $( '<span>' );
6431 this.$link
= $( '<a>' );
6435 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
6438 this.$title
.addClass( 'oo-ui-tool-title' );
6440 .addClass( 'oo-ui-tool-accel' )
6442 // This may need to be changed if the key names are ever localized,
6443 // but for now they are essentially written in English
6448 .addClass( 'oo-ui-tool-link' )
6449 .append( this.$icon
, this.$title
, this.$accel
)
6450 .prop( 'tabIndex', 0 )
6451 .attr( 'role', 'button' );
6453 .data( 'oo-ui-tool', this )
6455 'oo-ui-tool ' + 'oo-ui-tool-name-' +
6456 this.constructor.static.name
.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
6458 .append( this.$link
);
6459 this.setTitle( config
.title
|| this.constructor.static.title
);
6464 OO
.inheritClass( OO
.ui
.Tool
, OO
.ui
.Widget
);
6465 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.IconElement
);
6466 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.FlaggedElement
);
6474 /* Static Properties */
6480 OO
.ui
.Tool
.static.tagName
= 'span';
6483 * Symbolic name of tool.
6488 * @property {string}
6490 OO
.ui
.Tool
.static.name
= '';
6498 * @property {string}
6500 OO
.ui
.Tool
.static.group
= '';
6505 * Title is used as a tooltip when the tool is part of a bar tool group, or a label when the tool
6506 * is part of a list or menu tool group. If a trigger is associated with an action by the same name
6507 * as the tool, a description of its keyboard shortcut for the appropriate platform will be
6508 * appended to the title if the tool is part of a bar tool group.
6513 * @property {string|Function} Title text or a function that returns text
6515 OO
.ui
.Tool
.static.title
= '';
6518 * Tool can be automatically added to catch-all groups.
6522 * @property {boolean}
6524 OO
.ui
.Tool
.static.autoAddToCatchall
= true;
6527 * Tool can be automatically added to named groups.
6530 * @property {boolean}
6533 OO
.ui
.Tool
.static.autoAddToGroup
= true;
6536 * Check if this tool is compatible with given data.
6540 * @param {Mixed} data Data to check
6541 * @return {boolean} Tool can be used with data
6543 OO
.ui
.Tool
.static.isCompatibleWith = function () {
6550 * Handle the toolbar state being updated.
6552 * This is an abstract method that must be overridden in a concrete subclass.
6556 OO
.ui
.Tool
.prototype.onUpdateState = function () {
6558 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
6563 * Handle the tool being selected.
6565 * This is an abstract method that must be overridden in a concrete subclass.
6569 OO
.ui
.Tool
.prototype.onSelect = function () {
6571 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
6576 * Check if the button is active.
6578 * @return {boolean} Button is active
6580 OO
.ui
.Tool
.prototype.isActive = function () {
6585 * Make the button appear active or inactive.
6587 * @param {boolean} state Make button appear active
6589 OO
.ui
.Tool
.prototype.setActive = function ( state
) {
6590 this.active
= !!state
;
6591 if ( this.active
) {
6592 this.$element
.addClass( 'oo-ui-tool-active' );
6594 this.$element
.removeClass( 'oo-ui-tool-active' );
6599 * Get the tool title.
6601 * @param {string|Function} title Title text or a function that returns text
6604 OO
.ui
.Tool
.prototype.setTitle = function ( title
) {
6605 this.title
= OO
.ui
.resolveMsg( title
);
6611 * Get the tool title.
6613 * @return {string} Title text
6615 OO
.ui
.Tool
.prototype.getTitle = function () {
6620 * Get the tool's symbolic name.
6622 * @return {string} Symbolic name of tool
6624 OO
.ui
.Tool
.prototype.getName = function () {
6625 return this.constructor.static.name
;
6631 OO
.ui
.Tool
.prototype.updateTitle = function () {
6632 var titleTooltips
= this.toolGroup
.constructor.static.titleTooltips
,
6633 accelTooltips
= this.toolGroup
.constructor.static.accelTooltips
,
6634 accel
= this.toolbar
.getToolAccelerator( this.constructor.static.name
),
6637 this.$title
.text( this.title
);
6638 this.$accel
.text( accel
);
6640 if ( titleTooltips
&& typeof this.title
=== 'string' && this.title
.length
) {
6641 tooltipParts
.push( this.title
);
6643 if ( accelTooltips
&& typeof accel
=== 'string' && accel
.length
) {
6644 tooltipParts
.push( accel
);
6646 if ( tooltipParts
.length
) {
6647 this.$link
.attr( 'title', tooltipParts
.join( ' ' ) );
6649 this.$link
.removeAttr( 'title' );
6656 OO
.ui
.Tool
.prototype.destroy = function () {
6657 this.toolbar
.disconnect( this );
6658 this.$element
.remove();
6662 * Collection of tool groups.
6665 * // Basic OOjs UI toolbar example
6667 * // Create the toolbar
6668 * var toolFactory = new OO.ui.ToolFactory();
6669 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
6670 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
6672 * // We will be placing status text in this element when tools are used
6673 * var $area = $( '<p>' ).css( 'font-size', '0.8em' ).text( 'Toolbar example' );
6675 * // Define the tools that we're going to place in our toolbar
6677 * // Create a class inheriting from OO.ui.Tool
6678 * function PictureTool() {
6679 * PictureTool.super.apply( this, arguments );
6681 * OO.inheritClass( PictureTool, OO.ui.Tool );
6682 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
6683 * // of 'icon' and 'title' (displayed icon and text).
6684 * PictureTool.static.name = 'picture';
6685 * PictureTool.static.icon = 'picture';
6686 * PictureTool.static.title = 'Insert picture';
6687 * // Defines the action that will happen when this tool is selected (clicked).
6688 * PictureTool.prototype.onSelect = function () {
6689 * $area.text( 'Picture tool clicked!' );
6690 * this.setActive( false );
6692 * // The toolbar can be synchronized with the state of some external stuff, like a text
6693 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
6694 * // when the text cursor was inside bolded text). Here we simply disable this feature.
6695 * PictureTool.prototype.onUpdateState = function () {
6696 * this.setActive( false );
6698 * // Make this tool available in our toolFactory and thus our toolbar
6699 * toolFactory.register( PictureTool );
6701 * // Register two more tools, nothing interesting here
6702 * function SettingsTool() {
6703 * SettingsTool.super.apply( this, arguments );
6705 * OO.inheritClass( SettingsTool, OO.ui.Tool );
6706 * SettingsTool.static.name = 'settings';
6707 * SettingsTool.static.icon = 'settings';
6708 * SettingsTool.static.title = 'Change settings';
6709 * SettingsTool.prototype.onSelect = function () {
6710 * $area.text( 'Settings tool clicked!' );
6711 * this.setActive( false );
6713 * SettingsTool.prototype.onUpdateState = function () {
6714 * this.setActive( false );
6716 * toolFactory.register( SettingsTool );
6718 * // Register two more tools, nothing interesting here
6719 * function StuffTool() {
6720 * StuffTool.super.apply( this, arguments );
6722 * OO.inheritClass( StuffTool, OO.ui.Tool );
6723 * StuffTool.static.name = 'stuff';
6724 * StuffTool.static.icon = 'ellipsis';
6725 * StuffTool.static.title = 'More stuff';
6726 * StuffTool.prototype.onSelect = function () {
6727 * $area.text( 'More stuff tool clicked!' );
6728 * this.setActive( false );
6730 * StuffTool.prototype.onUpdateState = function () {
6731 * this.setActive( false );
6733 * toolFactory.register( StuffTool );
6735 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
6736 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
6737 * function HelpTool( toolGroup, config ) {
6738 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
6743 * this.popup.$body.append( '<p>I am helpful!</p>' );
6745 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
6746 * HelpTool.static.name = 'help';
6747 * HelpTool.static.icon = 'help';
6748 * HelpTool.static.title = 'Help';
6749 * toolFactory.register( HelpTool );
6751 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
6752 * // used once (but not all defined tools must be used).
6755 * // 'bar' tool groups display tools' icons only, side-by-side.
6757 * include: [ 'picture', 'help' ]
6760 * // 'list' tool groups display both the titles and icons, in a dropdown list.
6762 * indicator: 'down',
6764 * include: [ 'settings', 'stuff' ]
6766 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
6767 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here.
6770 * // Create some UI around the toolbar and place it in the document
6771 * var frame = new OO.ui.PanelLayout( {
6775 * var contentFrame = new OO.ui.PanelLayout( {
6779 * frame.$element.append(
6781 * contentFrame.$element.append( $area )
6783 * $( 'body' ).append( frame.$element );
6785 * // Here is where the toolbar is actually built. This must be done after inserting it into the
6787 * toolbar.initialize();
6788 * toolbar.emit( 'updateState' );
6791 * @extends OO.ui.Element
6792 * @mixins OO.EventEmitter
6793 * @mixins OO.ui.GroupElement
6796 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
6797 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating tool groups
6798 * @param {Object} [config] Configuration options
6799 * @cfg {boolean} [actions] Add an actions section opposite to the tools
6800 * @cfg {boolean} [shadow] Add a shadow below the toolbar
6802 OO
.ui
.Toolbar
= function OoUiToolbar( toolFactory
, toolGroupFactory
, config
) {
6803 // Allow passing positional parameters inside the config object
6804 if ( OO
.isPlainObject( toolFactory
) && config
=== undefined ) {
6805 config
= toolFactory
;
6806 toolFactory
= config
.toolFactory
;
6807 toolGroupFactory
= config
.toolGroupFactory
;
6810 // Configuration initialization
6811 config
= config
|| {};
6813 // Parent constructor
6814 OO
.ui
.Toolbar
.super.call( this, config
);
6816 // Mixin constructors
6817 OO
.EventEmitter
.call( this );
6818 OO
.ui
.GroupElement
.call( this, config
);
6821 this.toolFactory
= toolFactory
;
6822 this.toolGroupFactory
= toolGroupFactory
;
6825 this.$bar
= $( '<div>' );
6826 this.$actions
= $( '<div>' );
6827 this.initialized
= false;
6828 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
6832 .add( this.$bar
).add( this.$group
).add( this.$actions
)
6833 .on( 'mousedown', this.onPointerDown
.bind( this ) );
6836 this.$group
.addClass( 'oo-ui-toolbar-tools' );
6837 if ( config
.actions
) {
6838 this.$bar
.append( this.$actions
.addClass( 'oo-ui-toolbar-actions' ) );
6841 .addClass( 'oo-ui-toolbar-bar' )
6842 .append( this.$group
, '<div style="clear:both"></div>' );
6843 if ( config
.shadow
) {
6844 this.$bar
.append( '<div class="oo-ui-toolbar-shadow"></div>' );
6846 this.$element
.addClass( 'oo-ui-toolbar' ).append( this.$bar
);
6851 OO
.inheritClass( OO
.ui
.Toolbar
, OO
.ui
.Element
);
6852 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.EventEmitter
);
6853 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.ui
.GroupElement
);
6858 * Get the tool factory.
6860 * @return {OO.ui.ToolFactory} Tool factory
6862 OO
.ui
.Toolbar
.prototype.getToolFactory = function () {
6863 return this.toolFactory
;
6867 * Get the tool group factory.
6869 * @return {OO.Factory} Tool group factory
6871 OO
.ui
.Toolbar
.prototype.getToolGroupFactory = function () {
6872 return this.toolGroupFactory
;
6876 * Handles mouse down events.
6878 * @param {jQuery.Event} e Mouse down event
6880 OO
.ui
.Toolbar
.prototype.onPointerDown = function ( e
) {
6881 var $closestWidgetToEvent
= $( e
.target
).closest( '.oo-ui-widget' ),
6882 $closestWidgetToToolbar
= this.$element
.closest( '.oo-ui-widget' );
6883 if ( !$closestWidgetToEvent
.length
|| $closestWidgetToEvent
[ 0 ] === $closestWidgetToToolbar
[ 0 ] ) {
6889 * Handle window resize event.
6892 * @param {jQuery.Event} e Window resize event
6894 OO
.ui
.Toolbar
.prototype.onWindowResize = function () {
6895 this.$element
.toggleClass(
6896 'oo-ui-toolbar-narrow',
6897 this.$bar
.width() <= this.narrowThreshold
6902 * Sets up handles and preloads required information for the toolbar to work.
6903 * This must be called after it is attached to a visible document and before doing anything else.
6905 OO
.ui
.Toolbar
.prototype.initialize = function () {
6906 this.initialized
= true;
6907 this.narrowThreshold
= this.$group
.width() + this.$actions
.width();
6908 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
6909 this.onWindowResize();
6915 * Tools can be specified in the following ways:
6917 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6918 * - All tools in a group: `{ group: 'group-name' }`
6919 * - All tools: `'*'` - Using this will make the group a list with a "More" label by default
6921 * @param {Object.<string,Array>} groups List of tool group configurations
6922 * @param {Array|string} [groups.include] Tools to include
6923 * @param {Array|string} [groups.exclude] Tools to exclude
6924 * @param {Array|string} [groups.promote] Tools to promote to the beginning
6925 * @param {Array|string} [groups.demote] Tools to demote to the end
6927 OO
.ui
.Toolbar
.prototype.setup = function ( groups
) {
6928 var i
, len
, type
, group
,
6930 defaultType
= 'bar';
6932 // Cleanup previous groups
6935 // Build out new groups
6936 for ( i
= 0, len
= groups
.length
; i
< len
; i
++ ) {
6937 group
= groups
[ i
];
6938 if ( group
.include
=== '*' ) {
6939 // Apply defaults to catch-all groups
6940 if ( group
.type
=== undefined ) {
6941 group
.type
= 'list';
6943 if ( group
.label
=== undefined ) {
6944 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
6947 // Check type has been registered
6948 type
= this.getToolGroupFactory().lookup( group
.type
) ? group
.type
: defaultType
;
6950 this.getToolGroupFactory().create( type
, this, group
)
6953 this.addItems( items
);
6957 * Remove all tools and groups from the toolbar.
6959 OO
.ui
.Toolbar
.prototype.reset = function () {
6964 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6965 this.items
[ i
].destroy();
6971 * Destroys toolbar, removing event handlers and DOM elements.
6973 * Call this whenever you are done using a toolbar.
6975 OO
.ui
.Toolbar
.prototype.destroy = function () {
6976 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
6978 this.$element
.remove();
6982 * Check if tool has not been used yet.
6984 * @param {string} name Symbolic name of tool
6985 * @return {boolean} Tool is available
6987 OO
.ui
.Toolbar
.prototype.isToolAvailable = function ( name
) {
6988 return !this.tools
[ name
];
6992 * Prevent tool from being used again.
6994 * @param {OO.ui.Tool} tool Tool to reserve
6996 OO
.ui
.Toolbar
.prototype.reserveTool = function ( tool
) {
6997 this.tools
[ tool
.getName() ] = tool
;
7001 * Allow tool to be used again.
7003 * @param {OO.ui.Tool} tool Tool to release
7005 OO
.ui
.Toolbar
.prototype.releaseTool = function ( tool
) {
7006 delete this.tools
[ tool
.getName() ];
7010 * Get accelerator label for tool.
7012 * This is a stub that should be overridden to provide access to accelerator information.
7014 * @param {string} name Symbolic name of tool
7015 * @return {string|undefined} Tool accelerator label if available
7017 OO
.ui
.Toolbar
.prototype.getToolAccelerator = function () {
7022 * Collection of tools.
7024 * Tools can be specified in the following ways:
7026 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
7027 * - All tools in a group: `{ group: 'group-name' }`
7028 * - All tools: `'*'`
7032 * @extends OO.ui.Widget
7033 * @mixins OO.ui.GroupElement
7036 * @param {OO.ui.Toolbar} toolbar
7037 * @param {Object} [config] Configuration options
7038 * @cfg {Array|string} [include=[]] List of tools to include
7039 * @cfg {Array|string} [exclude=[]] List of tools to exclude
7040 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning
7041 * @cfg {Array|string} [demote=[]] List of tools to demote to the end
7043 OO
.ui
.ToolGroup
= function OoUiToolGroup( toolbar
, config
) {
7044 // Allow passing positional parameters inside the config object
7045 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
7047 toolbar
= config
.toolbar
;
7050 // Configuration initialization
7051 config
= config
|| {};
7053 // Parent constructor
7054 OO
.ui
.ToolGroup
.super.call( this, config
);
7056 // Mixin constructors
7057 OO
.ui
.GroupElement
.call( this, config
);
7060 this.toolbar
= toolbar
;
7062 this.pressed
= null;
7063 this.autoDisabled
= false;
7064 this.include
= config
.include
|| [];
7065 this.exclude
= config
.exclude
|| [];
7066 this.promote
= config
.promote
|| [];
7067 this.demote
= config
.demote
|| [];
7068 this.onCapturedMouseUpHandler
= this.onCapturedMouseUp
.bind( this );
7072 mousedown
: this.onPointerDown
.bind( this ),
7073 mouseup
: this.onPointerUp
.bind( this ),
7074 mouseover
: this.onMouseOver
.bind( this ),
7075 mouseout
: this.onMouseOut
.bind( this )
7077 this.toolbar
.getToolFactory().connect( this, { register
: 'onToolFactoryRegister' } );
7078 this.aggregate( { disable
: 'itemDisable' } );
7079 this.connect( this, { itemDisable
: 'updateDisabled' } );
7082 this.$group
.addClass( 'oo-ui-toolGroup-tools' );
7084 .addClass( 'oo-ui-toolGroup' )
7085 .append( this.$group
);
7091 OO
.inheritClass( OO
.ui
.ToolGroup
, OO
.ui
.Widget
);
7092 OO
.mixinClass( OO
.ui
.ToolGroup
, OO
.ui
.GroupElement
);
7100 /* Static Properties */
7103 * Show labels in tooltips.
7107 * @property {boolean}
7109 OO
.ui
.ToolGroup
.static.titleTooltips
= false;
7112 * Show acceleration labels in tooltips.
7116 * @property {boolean}
7118 OO
.ui
.ToolGroup
.static.accelTooltips
= false;
7121 * Automatically disable the toolgroup when all tools are disabled
7125 * @property {boolean}
7127 OO
.ui
.ToolGroup
.static.autoDisable
= true;
7134 OO
.ui
.ToolGroup
.prototype.isDisabled = function () {
7135 return this.autoDisabled
|| OO
.ui
.ToolGroup
.super.prototype.isDisabled
.apply( this, arguments
);
7141 OO
.ui
.ToolGroup
.prototype.updateDisabled = function () {
7142 var i
, item
, allDisabled
= true;
7144 if ( this.constructor.static.autoDisable
) {
7145 for ( i
= this.items
.length
- 1; i
>= 0; i
-- ) {
7146 item
= this.items
[ i
];
7147 if ( !item
.isDisabled() ) {
7148 allDisabled
= false;
7152 this.autoDisabled
= allDisabled
;
7154 OO
.ui
.ToolGroup
.super.prototype.updateDisabled
.apply( this, arguments
);
7158 * Handle mouse down events.
7160 * @param {jQuery.Event} e Mouse down event
7162 OO
.ui
.ToolGroup
.prototype.onPointerDown = function ( e
) {
7163 if ( !this.isDisabled() && e
.which
=== 1 ) {
7164 this.pressed
= this.getTargetTool( e
);
7165 if ( this.pressed
) {
7166 this.pressed
.setActive( true );
7167 this.getElementDocument().addEventListener(
7168 'mouseup', this.onCapturedMouseUpHandler
, true
7176 * Handle captured mouse up events.
7178 * @param {Event} e Mouse up event
7180 OO
.ui
.ToolGroup
.prototype.onCapturedMouseUp = function ( e
) {
7181 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseUpHandler
, true );
7182 // onPointerUp may be called a second time, depending on where the mouse is when the button is
7183 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
7184 this.onPointerUp( e
);
7188 * Handle mouse up events.
7190 * @param {jQuery.Event} e Mouse up event
7192 OO
.ui
.ToolGroup
.prototype.onPointerUp = function ( e
) {
7193 var tool
= this.getTargetTool( e
);
7195 if ( !this.isDisabled() && e
.which
=== 1 && this.pressed
&& this.pressed
=== tool
) {
7196 this.pressed
.onSelect();
7199 this.pressed
= null;
7204 * Handle mouse over events.
7206 * @param {jQuery.Event} e Mouse over event
7208 OO
.ui
.ToolGroup
.prototype.onMouseOver = function ( e
) {
7209 var tool
= this.getTargetTool( e
);
7211 if ( this.pressed
&& this.pressed
=== tool
) {
7212 this.pressed
.setActive( true );
7217 * Handle mouse out events.
7219 * @param {jQuery.Event} e Mouse out event
7221 OO
.ui
.ToolGroup
.prototype.onMouseOut = function ( e
) {
7222 var tool
= this.getTargetTool( e
);
7224 if ( this.pressed
&& this.pressed
=== tool
) {
7225 this.pressed
.setActive( false );
7230 * Get the closest tool to a jQuery.Event.
7232 * Only tool links are considered, which prevents other elements in the tool such as popups from
7233 * triggering tool group interactions.
7236 * @param {jQuery.Event} e
7237 * @return {OO.ui.Tool|null} Tool, `null` if none was found
7239 OO
.ui
.ToolGroup
.prototype.getTargetTool = function ( e
) {
7241 $item
= $( e
.target
).closest( '.oo-ui-tool-link' );
7243 if ( $item
.length
) {
7244 tool
= $item
.parent().data( 'oo-ui-tool' );
7247 return tool
&& !tool
.isDisabled() ? tool
: null;
7251 * Handle tool registry register events.
7253 * If a tool is registered after the group is created, we must repopulate the list to account for:
7255 * - a tool being added that may be included
7256 * - a tool already included being overridden
7258 * @param {string} name Symbolic name of tool
7260 OO
.ui
.ToolGroup
.prototype.onToolFactoryRegister = function () {
7265 * Get the toolbar this group is in.
7267 * @return {OO.ui.Toolbar} Toolbar of group
7269 OO
.ui
.ToolGroup
.prototype.getToolbar = function () {
7270 return this.toolbar
;
7274 * Add and remove tools based on configuration.
7276 OO
.ui
.ToolGroup
.prototype.populate = function () {
7277 var i
, len
, name
, tool
,
7278 toolFactory
= this.toolbar
.getToolFactory(),
7282 list
= this.toolbar
.getToolFactory().getTools(
7283 this.include
, this.exclude
, this.promote
, this.demote
7286 // Build a list of needed tools
7287 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
7291 toolFactory
.lookup( name
) &&
7292 // Tool is available or is already in this group
7293 ( this.toolbar
.isToolAvailable( name
) || this.tools
[ name
] )
7295 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
7296 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
7297 this.toolbar
.tools
[ name
] = true;
7298 tool
= this.tools
[ name
];
7300 // Auto-initialize tools on first use
7301 this.tools
[ name
] = tool
= toolFactory
.create( name
, this );
7304 this.toolbar
.reserveTool( tool
);
7306 names
[ name
] = true;
7309 // Remove tools that are no longer needed
7310 for ( name
in this.tools
) {
7311 if ( !names
[ name
] ) {
7312 this.tools
[ name
].destroy();
7313 this.toolbar
.releaseTool( this.tools
[ name
] );
7314 remove
.push( this.tools
[ name
] );
7315 delete this.tools
[ name
];
7318 if ( remove
.length
) {
7319 this.removeItems( remove
);
7321 // Update emptiness state
7323 this.$element
.removeClass( 'oo-ui-toolGroup-empty' );
7325 this.$element
.addClass( 'oo-ui-toolGroup-empty' );
7327 // Re-add tools (moving existing ones to new locations)
7328 this.addItems( add
);
7329 // Disabled state may depend on items
7330 this.updateDisabled();
7334 * Destroy tool group.
7336 OO
.ui
.ToolGroup
.prototype.destroy = function () {
7340 this.toolbar
.getToolFactory().disconnect( this );
7341 for ( name
in this.tools
) {
7342 this.toolbar
.releaseTool( this.tools
[ name
] );
7343 this.tools
[ name
].disconnect( this ).destroy();
7344 delete this.tools
[ name
];
7346 this.$element
.remove();
7350 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
7351 * consists of a header that contains the dialog title, a body with the message, and a footer that
7352 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
7353 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
7355 * There are two basic types of message dialogs, confirmation and alert:
7357 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
7358 * more details about the consequences.
7359 * - **alert**: the dialog title describes which event occurred and the message provides more information
7360 * about why the event occurred.
7362 * The MessageDialog class specifies two actions: ‘accept’, the primary
7363 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
7364 * passing along the selected action.
7366 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
7369 * // Example: Creating and opening a message dialog window.
7370 * var messageDialog = new OO.ui.MessageDialog();
7372 * // Create and append a window manager.
7373 * var windowManager = new OO.ui.WindowManager();
7374 * $( 'body' ).append( windowManager.$element );
7375 * windowManager.addWindows( [ messageDialog ] );
7376 * // Open the window.
7377 * windowManager.openWindow( messageDialog, {
7378 * title: 'Basic message dialog',
7379 * message: 'This is the message'
7382 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
7385 * @extends OO.ui.Dialog
7388 * @param {Object} [config] Configuration options
7390 OO
.ui
.MessageDialog
= function OoUiMessageDialog( config
) {
7391 // Parent constructor
7392 OO
.ui
.MessageDialog
.super.call( this, config
);
7395 this.verticalActionLayout
= null;
7398 this.$element
.addClass( 'oo-ui-messageDialog' );
7403 OO
.inheritClass( OO
.ui
.MessageDialog
, OO
.ui
.Dialog
);
7405 /* Static Properties */
7407 OO
.ui
.MessageDialog
.static.name
= 'message';
7409 OO
.ui
.MessageDialog
.static.size
= 'small';
7411 OO
.ui
.MessageDialog
.static.verbose
= false;
7416 * The title of a confirmation dialog describes what a progressive action will do. The
7417 * title of an alert dialog describes which event occurred.
7421 * @property {jQuery|string|Function|null}
7423 OO
.ui
.MessageDialog
.static.title
= null;
7426 * The message displayed in the dialog body.
7428 * A confirmation message describes the consequences of a progressive action. An alert
7429 * message describes why an event occurred.
7433 * @property {jQuery|string|Function|null}
7435 OO
.ui
.MessageDialog
.static.message
= null;
7437 OO
.ui
.MessageDialog
.static.actions
= [
7438 { action
: 'accept', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-accept' ), flags
: 'primary' },
7439 { action
: 'reject', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-reject' ), flags
: 'safe' }
7447 OO
.ui
.MessageDialog
.prototype.setManager = function ( manager
) {
7448 OO
.ui
.MessageDialog
.super.prototype.setManager
.call( this, manager
);
7451 this.manager
.connect( this, {
7461 OO
.ui
.MessageDialog
.prototype.onActionResize = function ( action
) {
7463 return OO
.ui
.MessageDialog
.super.prototype.onActionResize
.call( this, action
);
7467 * Handle window resized events.
7471 OO
.ui
.MessageDialog
.prototype.onResize = function () {
7473 dialog
.fitActions();
7474 // Wait for CSS transition to finish and do it again :(
7475 setTimeout( function () {
7476 dialog
.fitActions();
7481 * Toggle action layout between vertical and horizontal.
7485 * @param {boolean} [value] Layout actions vertically, omit to toggle
7488 OO
.ui
.MessageDialog
.prototype.toggleVerticalActionLayout = function ( value
) {
7489 value
= value
=== undefined ? !this.verticalActionLayout
: !!value
;
7491 if ( value
!== this.verticalActionLayout
) {
7492 this.verticalActionLayout
= value
;
7494 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value
)
7495 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value
);
7504 OO
.ui
.MessageDialog
.prototype.getActionProcess = function ( action
) {
7506 return new OO
.ui
.Process( function () {
7507 this.close( { action
: action
} );
7510 return OO
.ui
.MessageDialog
.super.prototype.getActionProcess
.call( this, action
);
7516 * @param {Object} [data] Dialog opening data
7517 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
7518 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
7519 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
7520 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
7523 OO
.ui
.MessageDialog
.prototype.getSetupProcess = function ( data
) {
7527 return OO
.ui
.MessageDialog
.super.prototype.getSetupProcess
.call( this, data
)
7528 .next( function () {
7529 this.title
.setLabel(
7530 data
.title
!== undefined ? data
.title
: this.constructor.static.title
7532 this.message
.setLabel(
7533 data
.message
!== undefined ? data
.message
: this.constructor.static.message
7535 this.message
.$element
.toggleClass(
7536 'oo-ui-messageDialog-message-verbose',
7537 data
.verbose
!== undefined ? data
.verbose
: this.constructor.static.verbose
7545 OO
.ui
.MessageDialog
.prototype.getBodyHeight = function () {
7546 var bodyHeight
, oldOverflow
,
7547 $scrollable
= this.container
.$element
;
7549 oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
7550 $scrollable
[ 0 ].style
.overflow
= 'hidden';
7552 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
7554 bodyHeight
= this.text
.$element
.outerHeight( true );
7555 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
7563 OO
.ui
.MessageDialog
.prototype.setDimensions = function ( dim
) {
7564 var $scrollable
= this.container
.$element
;
7565 OO
.ui
.MessageDialog
.super.prototype.setDimensions
.call( this, dim
);
7567 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
7568 // Need to do it after transition completes (250ms), add 50ms just in case.
7569 setTimeout( function () {
7570 var oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
7571 $scrollable
[ 0 ].style
.overflow
= 'hidden';
7573 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
7575 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
7584 OO
.ui
.MessageDialog
.prototype.initialize = function () {
7586 OO
.ui
.MessageDialog
.super.prototype.initialize
.call( this );
7589 this.$actions
= $( '<div>' );
7590 this.container
= new OO
.ui
.PanelLayout( {
7591 scrollable
: true, classes
: [ 'oo-ui-messageDialog-container' ]
7593 this.text
= new OO
.ui
.PanelLayout( {
7594 padded
: true, expanded
: false, classes
: [ 'oo-ui-messageDialog-text' ]
7596 this.message
= new OO
.ui
.LabelWidget( {
7597 classes
: [ 'oo-ui-messageDialog-message' ]
7601 this.title
.$element
.addClass( 'oo-ui-messageDialog-title' );
7602 this.$content
.addClass( 'oo-ui-messageDialog-content' );
7603 this.container
.$element
.append( this.text
.$element
);
7604 this.text
.$element
.append( this.title
.$element
, this.message
.$element
);
7605 this.$body
.append( this.container
.$element
);
7606 this.$actions
.addClass( 'oo-ui-messageDialog-actions' );
7607 this.$foot
.append( this.$actions
);
7613 OO
.ui
.MessageDialog
.prototype.attachActions = function () {
7614 var i
, len
, other
, special
, others
;
7617 OO
.ui
.MessageDialog
.super.prototype.attachActions
.call( this );
7619 special
= this.actions
.getSpecial();
7620 others
= this.actions
.getOthers();
7621 if ( special
.safe
) {
7622 this.$actions
.append( special
.safe
.$element
);
7623 special
.safe
.toggleFramed( false );
7625 if ( others
.length
) {
7626 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
7627 other
= others
[ i
];
7628 this.$actions
.append( other
.$element
);
7629 other
.toggleFramed( false );
7632 if ( special
.primary
) {
7633 this.$actions
.append( special
.primary
.$element
);
7634 special
.primary
.toggleFramed( false );
7637 if ( !this.isOpening() ) {
7638 // If the dialog is currently opening, this will be called automatically soon.
7639 // This also calls #fitActions.
7645 * Fit action actions into columns or rows.
7647 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
7651 OO
.ui
.MessageDialog
.prototype.fitActions = function () {
7653 previous
= this.verticalActionLayout
,
7654 actions
= this.actions
.get();
7657 this.toggleVerticalActionLayout( false );
7658 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
7659 action
= actions
[ i
];
7660 if ( action
.$element
.innerWidth() < action
.$label
.outerWidth( true ) ) {
7661 this.toggleVerticalActionLayout( true );
7666 // Move the body out of the way of the foot
7667 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
7669 if ( this.verticalActionLayout
!== previous
) {
7670 // We changed the layout, window height might need to be updated.
7676 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
7677 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
7678 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
7679 * relevant. The ProcessDialog class is always extended and customized with the actions and content
7680 * required for each process.
7682 * The process dialog box consists of a header that visually represents the ‘working’ state of long
7683 * processes with an animation. The header contains the dialog title as well as
7684 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
7685 * a ‘primary’ action on the right (e.g., ‘Done’).
7687 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
7688 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
7691 * // Example: Creating and opening a process dialog window.
7692 * function MyProcessDialog( config ) {
7693 * MyProcessDialog.super.call( this, config );
7695 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
7697 * MyProcessDialog.static.title = 'Process dialog';
7698 * MyProcessDialog.static.actions = [
7699 * { action: 'save', label: 'Done', flags: 'primary' },
7700 * { label: 'Cancel', flags: 'safe' }
7703 * MyProcessDialog.prototype.initialize = function () {
7704 * MyProcessDialog.super.prototype.initialize.apply( this, arguments );
7705 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
7706 * 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>' );
7707 * this.$body.append( this.content.$element );
7709 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
7710 * var dialog = this;
7712 * return new OO.ui.Process( function () {
7713 * dialog.close( { action: action } );
7716 * return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
7719 * var windowManager = new OO.ui.WindowManager();
7720 * $( 'body' ).append( windowManager.$element );
7722 * var dialog = new MyProcessDialog();
7723 * windowManager.addWindows( [ dialog ] );
7724 * windowManager.openWindow( dialog );
7726 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
7730 * @extends OO.ui.Dialog
7733 * @param {Object} [config] Configuration options
7735 OO
.ui
.ProcessDialog
= function OoUiProcessDialog( config
) {
7736 // Parent constructor
7737 OO
.ui
.ProcessDialog
.super.call( this, config
);
7740 this.$element
.addClass( 'oo-ui-processDialog' );
7745 OO
.inheritClass( OO
.ui
.ProcessDialog
, OO
.ui
.Dialog
);
7750 * Handle dismiss button click events.
7756 OO
.ui
.ProcessDialog
.prototype.onDismissErrorButtonClick = function () {
7761 * Handle retry button click events.
7763 * Hides errors and then tries again.
7767 OO
.ui
.ProcessDialog
.prototype.onRetryButtonClick = function () {
7769 this.executeAction( this.currentAction
);
7775 OO
.ui
.ProcessDialog
.prototype.onActionResize = function ( action
) {
7776 if ( this.actions
.isSpecial( action
) ) {
7779 return OO
.ui
.ProcessDialog
.super.prototype.onActionResize
.call( this, action
);
7785 OO
.ui
.ProcessDialog
.prototype.initialize = function () {
7787 OO
.ui
.ProcessDialog
.super.prototype.initialize
.call( this );
7790 this.$navigation
= $( '<div>' );
7791 this.$location
= $( '<div>' );
7792 this.$safeActions
= $( '<div>' );
7793 this.$primaryActions
= $( '<div>' );
7794 this.$otherActions
= $( '<div>' );
7795 this.dismissButton
= new OO
.ui
.ButtonWidget( {
7796 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' )
7798 this.retryButton
= new OO
.ui
.ButtonWidget();
7799 this.$errors
= $( '<div>' );
7800 this.$errorsTitle
= $( '<div>' );
7803 this.dismissButton
.connect( this, { click
: 'onDismissErrorButtonClick' } );
7804 this.retryButton
.connect( this, { click
: 'onRetryButtonClick' } );
7807 this.title
.$element
.addClass( 'oo-ui-processDialog-title' );
7809 .append( this.title
.$element
)
7810 .addClass( 'oo-ui-processDialog-location' );
7811 this.$safeActions
.addClass( 'oo-ui-processDialog-actions-safe' );
7812 this.$primaryActions
.addClass( 'oo-ui-processDialog-actions-primary' );
7813 this.$otherActions
.addClass( 'oo-ui-processDialog-actions-other' );
7815 .addClass( 'oo-ui-processDialog-errors-title' )
7816 .text( OO
.ui
.msg( 'ooui-dialog-process-error' ) );
7818 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
7819 .append( this.$errorsTitle
, this.dismissButton
.$element
, this.retryButton
.$element
);
7821 .addClass( 'oo-ui-processDialog-content' )
7822 .append( this.$errors
);
7824 .addClass( 'oo-ui-processDialog-navigation' )
7825 .append( this.$safeActions
, this.$location
, this.$primaryActions
);
7826 this.$head
.append( this.$navigation
);
7827 this.$foot
.append( this.$otherActions
);
7833 OO
.ui
.ProcessDialog
.prototype.getActionWidgets = function ( actions
) {
7834 var i
, len
, widgets
= [];
7835 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
7837 new OO
.ui
.ActionWidget( $.extend( { framed
: true }, actions
[ i
] ) )
7846 OO
.ui
.ProcessDialog
.prototype.attachActions = function () {
7847 var i
, len
, other
, special
, others
;
7850 OO
.ui
.ProcessDialog
.super.prototype.attachActions
.call( this );
7852 special
= this.actions
.getSpecial();
7853 others
= this.actions
.getOthers();
7854 if ( special
.primary
) {
7855 this.$primaryActions
.append( special
.primary
.$element
);
7857 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
7858 other
= others
[ i
];
7859 this.$otherActions
.append( other
.$element
);
7861 if ( special
.safe
) {
7862 this.$safeActions
.append( special
.safe
.$element
);
7866 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
7872 OO
.ui
.ProcessDialog
.prototype.executeAction = function ( action
) {
7874 return OO
.ui
.ProcessDialog
.super.prototype.executeAction
.call( this, action
)
7875 .fail( function ( errors
) {
7876 process
.showErrors( errors
|| [] );
7881 * Fit label between actions.
7886 OO
.ui
.ProcessDialog
.prototype.fitLabel = function () {
7887 var width
= Math
.max(
7888 this.$safeActions
.is( ':visible' ) ? this.$safeActions
.width() : 0,
7889 this.$primaryActions
.is( ':visible' ) ? this.$primaryActions
.width() : 0
7891 this.$location
.css( { paddingLeft
: width
, paddingRight
: width
} );
7897 * Handle errors that occurred during accept or reject processes.
7900 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
7902 OO
.ui
.ProcessDialog
.prototype.showErrors = function ( errors
) {
7903 var i
, len
, $item
, actions
,
7909 if ( errors
instanceof OO
.ui
.Error
) {
7910 errors
= [ errors
];
7913 for ( i
= 0, len
= errors
.length
; i
< len
; i
++ ) {
7914 if ( !errors
[ i
].isRecoverable() ) {
7915 recoverable
= false;
7917 if ( errors
[ i
].isWarning() ) {
7920 $item
= $( '<div>' )
7921 .addClass( 'oo-ui-processDialog-error' )
7922 .append( errors
[ i
].getMessage() );
7923 items
.push( $item
[ 0 ] );
7925 this.$errorItems
= $( items
);
7926 if ( recoverable
) {
7927 abilities
[this.currentAction
] = true;
7928 // Copy the flags from the first matching action
7929 actions
= this.actions
.get( { actions
: this.currentAction
} );
7930 if ( actions
.length
) {
7931 this.retryButton
.clearFlags().setFlags( actions
[0].getFlags() );
7934 abilities
[this.currentAction
] = false;
7935 this.actions
.setAbilities( abilities
);
7938 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-continue' ) );
7940 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-retry' ) );
7942 this.retryButton
.toggle( recoverable
);
7943 this.$errorsTitle
.after( this.$errorItems
);
7944 this.$errors
.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
7952 OO
.ui
.ProcessDialog
.prototype.hideErrors = function () {
7953 this.$errors
.addClass( 'oo-ui-element-hidden' );
7954 if ( this.$errorItems
) {
7955 this.$errorItems
.remove();
7956 this.$errorItems
= null;
7963 OO
.ui
.ProcessDialog
.prototype.getTeardownProcess = function ( data
) {
7965 return OO
.ui
.ProcessDialog
.super.prototype.getTeardownProcess
.call( this, data
)
7966 .first( function () {
7967 // Make sure to hide errors
7973 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
7974 * which is a widget that is specified by reference before any optional configuration settings.
7976 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
7978 * - **left**: The label is placed before the field-widget and aligned with the left margin.
7979 * A left-alignment is used for forms with many fields.
7980 * - **right**: The label is placed before the field-widget and aligned to the right margin.
7981 * A right-alignment is used for long but familiar forms which users tab through,
7982 * verifying the current field with a quick glance at the label.
7983 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
7984 * that users fill out from top to bottom.
7985 * - **inline**: The label is placed after the field-widget and aligned to the left.
7986 * An inline-alignment is best used with checkboxes or radio buttons.
7988 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
7989 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
7991 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
7993 * @extends OO.ui.Layout
7994 * @mixins OO.ui.LabelElement
7997 * @param {OO.ui.Widget} fieldWidget Field widget
7998 * @param {Object} [config] Configuration options
7999 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8000 * @cfg {string} [help] Help text. When help text is specified, a help icon will appear
8001 * in the upper-right corner of the rendered field.
8003 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
8004 // Allow passing positional parameters inside the config object
8005 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
8006 config
= fieldWidget
;
8007 fieldWidget
= config
.fieldWidget
;
8010 var hasInputWidget
= fieldWidget
instanceof OO
.ui
.InputWidget
;
8012 // Configuration initialization
8013 config
= $.extend( { align
: 'left' }, config
);
8015 // Parent constructor
8016 OO
.ui
.FieldLayout
.super.call( this, config
);
8018 // Mixin constructors
8019 OO
.ui
.LabelElement
.call( this, config
);
8022 this.fieldWidget
= fieldWidget
;
8023 this.$field
= $( '<div>' );
8024 this.$body
= $( '<' + ( hasInputWidget
? 'label' : 'div' ) + '>' );
8026 if ( config
.help
) {
8027 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
8028 classes
: [ 'oo-ui-fieldLayout-help' ],
8033 this.popupButtonWidget
.getPopup().$body
.append(
8035 .text( config
.help
)
8036 .addClass( 'oo-ui-fieldLayout-help-content' )
8038 this.$help
= this.popupButtonWidget
.$element
;
8040 this.$help
= $( [] );
8044 if ( hasInputWidget
) {
8045 this.$label
.on( 'click', this.onLabelClick
.bind( this ) );
8047 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
8051 .addClass( 'oo-ui-fieldLayout' )
8052 .append( this.$help
, this.$body
);
8053 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
8055 .addClass( 'oo-ui-fieldLayout-field' )
8056 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget
.isDisabled() )
8057 .append( this.fieldWidget
.$element
);
8059 this.setAlignment( config
.align
);
8064 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
8065 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.LabelElement
);
8070 * Handle field disable events.
8073 * @param {boolean} value Field is disabled
8075 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
8076 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
8080 * Handle label mouse click events.
8083 * @param {jQuery.Event} e Mouse click event
8085 OO
.ui
.FieldLayout
.prototype.onLabelClick = function () {
8086 this.fieldWidget
.simulateLabelClick();
8091 * Get the widget contained by the field.
8093 * @return {OO.ui.Widget} Field widget
8095 OO
.ui
.FieldLayout
.prototype.getField = function () {
8096 return this.fieldWidget
;
8100 * Set the field alignment mode.
8103 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
8106 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
8107 if ( value
!== this.align
) {
8108 // Default to 'left'
8109 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
8113 if ( value
=== 'inline' ) {
8114 this.$body
.append( this.$field
, this.$label
);
8116 this.$body
.append( this.$label
, this.$field
);
8118 // Set classes. The following classes can be used here:
8119 // * oo-ui-fieldLayout-align-left
8120 // * oo-ui-fieldLayout-align-right
8121 // * oo-ui-fieldLayout-align-top
8122 // * oo-ui-fieldLayout-align-inline
8124 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
8126 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
8134 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
8135 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
8136 * is required and is specified before any optional configuration settings.
8138 * Labels can be aligned in one of four ways:
8140 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8141 * A left-alignment is used for forms with many fields.
8142 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8143 * A right-alignment is used for long but familiar forms which users tab through,
8144 * verifying the current field with a quick glance at the label.
8145 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8146 * that users fill out from top to bottom.
8147 * - **inline**: The label is placed after the field-widget and aligned to the left.
8148 * An inline-alignment is best used with checkboxes or radio buttons.
8150 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
8151 * text is specified.
8154 * // Example of an ActionFieldLayout
8155 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
8156 * new OO.ui.TextInputWidget( {
8157 * placeholder: 'Field widget'
8159 * new OO.ui.ButtonWidget( {
8163 * label: 'An ActionFieldLayout. This label is aligned top',
8165 * help: 'This is help text'
8169 * $( 'body' ).append( actionFieldLayout.$element );
8173 * @extends OO.ui.FieldLayout
8176 * @param {OO.ui.Widget} fieldWidget Field widget
8177 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
8178 * @param {Object} [config] Configuration options
8179 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8180 * @cfg {string} [help] Help text. When help text is specified, a help icon will appear in the
8181 * upper-right corner of the rendered field.
8183 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
8184 // Allow passing positional parameters inside the config object
8185 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
8186 config
= fieldWidget
;
8187 fieldWidget
= config
.fieldWidget
;
8188 buttonWidget
= config
.buttonWidget
;
8191 // Configuration initialization
8192 config
= $.extend( { align
: 'left' }, config
);
8194 // Parent constructor
8195 OO
.ui
.ActionFieldLayout
.super.call( this, fieldWidget
, config
);
8198 this.fieldWidget
= fieldWidget
;
8199 this.buttonWidget
= buttonWidget
;
8200 this.$button
= $( '<div>' )
8201 .addClass( 'oo-ui-actionFieldLayout-button' )
8202 .append( this.buttonWidget
.$element
);
8203 this.$input
= $( '<div>' )
8204 .addClass( 'oo-ui-actionFieldLayout-input' )
8205 .append( this.fieldWidget
.$element
);
8207 .addClass( 'oo-ui-actionFieldLayout' )
8208 .append( this.$input
, this.$button
);
8213 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
8216 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
8217 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
8218 * configured with a label as well. For more information and examples,
8219 * please see the [OOjs UI documentation on MediaWiki][1].
8222 * // Example of a fieldset layout
8223 * var input1 = new OO.ui.TextInputWidget( {
8224 * placeholder: 'A text input field'
8227 * var input2 = new OO.ui.TextInputWidget( {
8228 * placeholder: 'A text input field'
8231 * var fieldset = new OO.ui.FieldsetLayout( {
8232 * label: 'Example of a fieldset layout'
8235 * fieldset.addItems( [
8236 * new OO.ui.FieldLayout( input1, {
8237 * label: 'Field One'
8239 * new OO.ui.FieldLayout( input2, {
8240 * label: 'Field Two'
8243 * $( 'body' ).append( fieldset.$element );
8245 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8248 * @extends OO.ui.Layout
8249 * @mixins OO.ui.IconElement
8250 * @mixins OO.ui.LabelElement
8251 * @mixins OO.ui.GroupElement
8254 * @param {Object} [config] Configuration options
8255 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
8257 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
8258 // Configuration initialization
8259 config
= config
|| {};
8261 // Parent constructor
8262 OO
.ui
.FieldsetLayout
.super.call( this, config
);
8264 // Mixin constructors
8265 OO
.ui
.IconElement
.call( this, config
);
8266 OO
.ui
.LabelElement
.call( this, config
);
8267 OO
.ui
.GroupElement
.call( this, config
);
8269 if ( config
.help
) {
8270 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
8271 classes
: [ 'oo-ui-fieldsetLayout-help' ],
8276 this.popupButtonWidget
.getPopup().$body
.append(
8278 .text( config
.help
)
8279 .addClass( 'oo-ui-fieldsetLayout-help-content' )
8281 this.$help
= this.popupButtonWidget
.$element
;
8283 this.$help
= $( [] );
8288 .addClass( 'oo-ui-fieldsetLayout' )
8289 .prepend( this.$help
, this.$icon
, this.$label
, this.$group
);
8290 if ( Array
.isArray( config
.items
) ) {
8291 this.addItems( config
.items
);
8297 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
8298 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.IconElement
);
8299 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.LabelElement
);
8300 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.GroupElement
);
8303 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
8304 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
8305 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
8306 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
8308 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
8309 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
8310 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
8311 * some fancier controls. Some controls have both regular and InputWidget variants, for example
8312 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
8313 * often have simplified APIs to match the capabilities of HTML forms.
8314 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
8316 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
8317 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8320 * // Example of a form layout that wraps a fieldset layout
8321 * var input1 = new OO.ui.TextInputWidget( {
8322 * placeholder: 'Username'
8324 * var input2 = new OO.ui.TextInputWidget( {
8325 * placeholder: 'Password',
8328 * var submit = new OO.ui.ButtonInputWidget( {
8332 * var fieldset = new OO.ui.FieldsetLayout( {
8333 * label: 'A form layout'
8335 * fieldset.addItems( [
8336 * new OO.ui.FieldLayout( input1, {
8337 * label: 'Username',
8340 * new OO.ui.FieldLayout( input2, {
8341 * label: 'Password',
8344 * new OO.ui.FieldLayout( submit )
8346 * var form = new OO.ui.FormLayout( {
8347 * items: [ fieldset ],
8348 * action: '/api/formhandler',
8351 * $( 'body' ).append( form.$element );
8354 * @extends OO.ui.Layout
8355 * @mixins OO.ui.GroupElement
8358 * @param {Object} [config] Configuration options
8359 * @cfg {string} [method] HTML form `method` attribute
8360 * @cfg {string} [action] HTML form `action` attribute
8361 * @cfg {string} [enctype] HTML form `enctype` attribute
8362 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
8364 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
8365 // Configuration initialization
8366 config
= config
|| {};
8368 // Parent constructor
8369 OO
.ui
.FormLayout
.super.call( this, config
);
8371 // Mixin constructors
8372 OO
.ui
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
8375 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
8379 .addClass( 'oo-ui-formLayout' )
8381 method
: config
.method
,
8382 action
: config
.action
,
8383 enctype
: config
.enctype
8385 if ( Array
.isArray( config
.items
) ) {
8386 this.addItems( config
.items
);
8392 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
8393 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.GroupElement
);
8398 * A 'submit' event is emitted when the form is submitted.
8403 /* Static Properties */
8405 OO
.ui
.FormLayout
.static.tagName
= 'form';
8410 * Handle form submit events.
8413 * @param {jQuery.Event} e Submit event
8416 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
8417 this.emit( 'submit' );
8422 * 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)
8423 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
8426 * var menuLayout = new OO.ui.MenuLayout( {
8429 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
8430 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
8431 * select = new OO.ui.SelectWidget( {
8433 * new OO.ui.OptionWidget( {
8437 * new OO.ui.OptionWidget( {
8441 * new OO.ui.OptionWidget( {
8445 * new OO.ui.OptionWidget( {
8450 * } ).on( 'select', function ( item ) {
8451 * menuLayout.setMenuPosition( item.getData() );
8454 * menuLayout.$menu.append(
8455 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
8457 * menuLayout.$content.append(
8458 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
8460 * $( 'body' ).append( menuLayout.$element );
8462 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
8463 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
8464 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
8467 * .oo-ui-menuLayout-menu {
8471 * .oo-ui-menuLayout-content {
8479 * @extends OO.ui.Layout
8482 * @param {Object} [config] Configuration options
8483 * @cfg {boolean} [showMenu=true] Show menu
8484 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
8486 OO
.ui
.MenuLayout
= function OoUiMenuLayout( config
) {
8487 // Configuration initialization
8488 config
= $.extend( {
8490 menuPosition
: 'before'
8493 // Parent constructor
8494 OO
.ui
.MenuLayout
.super.call( this, config
);
8499 * @property {jQuery}
8501 this.$menu
= $( '<div>' );
8505 * @property {jQuery}
8507 this.$content
= $( '<div>' );
8511 .addClass( 'oo-ui-menuLayout-menu' );
8512 this.$content
.addClass( 'oo-ui-menuLayout-content' );
8514 .addClass( 'oo-ui-menuLayout' )
8515 .append( this.$content
, this.$menu
);
8516 this.setMenuPosition( config
.menuPosition
);
8517 this.toggleMenu( config
.showMenu
);
8522 OO
.inheritClass( OO
.ui
.MenuLayout
, OO
.ui
.Layout
);
8529 * @param {boolean} showMenu Show menu, omit to toggle
8532 OO
.ui
.MenuLayout
.prototype.toggleMenu = function ( showMenu
) {
8533 showMenu
= showMenu
=== undefined ? !this.showMenu
: !!showMenu
;
8535 if ( this.showMenu
!== showMenu
) {
8536 this.showMenu
= showMenu
;
8538 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu
)
8539 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu
);
8546 * Check if menu is visible
8548 * @return {boolean} Menu is visible
8550 OO
.ui
.MenuLayout
.prototype.isMenuVisible = function () {
8551 return this.showMenu
;
8555 * Set menu position.
8557 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
8558 * @throws {Error} If position value is not supported
8561 OO
.ui
.MenuLayout
.prototype.setMenuPosition = function ( position
) {
8562 this.$element
.removeClass( 'oo-ui-menuLayout-' + this.menuPosition
);
8563 this.menuPosition
= position
;
8564 this.$element
.addClass( 'oo-ui-menuLayout-' + position
);
8570 * Get menu position.
8572 * @return {string} Menu position
8574 OO
.ui
.MenuLayout
.prototype.getMenuPosition = function () {
8575 return this.menuPosition
;
8579 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
8580 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
8581 * through the pages and select which one to display. By default, only one page is
8582 * displayed at a time and the outline is hidden. When a user navigates to a new page,
8583 * the booklet layout automatically focuses on the first focusable element, unless the
8584 * default setting is changed. Optionally, booklets can be configured to show
8585 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
8588 * // Example of a BookletLayout that contains two PageLayouts.
8590 * function PageOneLayout( name, config ) {
8591 * PageOneLayout.super.call( this, name, config );
8592 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
8594 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
8595 * PageOneLayout.prototype.setupOutlineItem = function () {
8596 * this.outlineItem.setLabel( 'Page One' );
8599 * function PageTwoLayout( name, config ) {
8600 * PageTwoLayout.super.call( this, name, config );
8601 * this.$element.append( '<p>Second page</p>' );
8603 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
8604 * PageTwoLayout.prototype.setupOutlineItem = function () {
8605 * this.outlineItem.setLabel( 'Page Two' );
8608 * var page1 = new PageOneLayout( 'one' ),
8609 * page2 = new PageTwoLayout( 'two' );
8611 * var booklet = new OO.ui.BookletLayout( {
8615 * booklet.addPages ( [ page1, page2 ] );
8616 * $( 'body' ).append( booklet.$element );
8619 * @extends OO.ui.MenuLayout
8622 * @param {Object} [config] Configuration options
8623 * @cfg {boolean} [continuous=false] Show all pages, one after another
8624 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
8625 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
8626 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
8628 OO
.ui
.BookletLayout
= function OoUiBookletLayout( config
) {
8629 // Configuration initialization
8630 config
= config
|| {};
8632 // Parent constructor
8633 OO
.ui
.BookletLayout
.super.call( this, config
);
8636 this.currentPageName
= null;
8638 this.ignoreFocus
= false;
8639 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
8640 this.$content
.append( this.stackLayout
.$element
);
8641 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
8642 this.outlineVisible
= false;
8643 this.outlined
= !!config
.outlined
;
8644 if ( this.outlined
) {
8645 this.editable
= !!config
.editable
;
8646 this.outlineControlsWidget
= null;
8647 this.outlineSelectWidget
= new OO
.ui
.OutlineSelectWidget();
8648 this.outlinePanel
= new OO
.ui
.PanelLayout( { scrollable
: true } );
8649 this.$menu
.append( this.outlinePanel
.$element
);
8650 this.outlineVisible
= true;
8651 if ( this.editable
) {
8652 this.outlineControlsWidget
= new OO
.ui
.OutlineControlsWidget(
8653 this.outlineSelectWidget
8657 this.toggleMenu( this.outlined
);
8660 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
8661 if ( this.outlined
) {
8662 this.outlineSelectWidget
.connect( this, { select
: 'onOutlineSelectWidgetSelect' } );
8664 if ( this.autoFocus
) {
8665 // Event 'focus' does not bubble, but 'focusin' does
8666 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
8670 this.$element
.addClass( 'oo-ui-bookletLayout' );
8671 this.stackLayout
.$element
.addClass( 'oo-ui-bookletLayout-stackLayout' );
8672 if ( this.outlined
) {
8673 this.outlinePanel
.$element
8674 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
8675 .append( this.outlineSelectWidget
.$element
);
8676 if ( this.editable
) {
8677 this.outlinePanel
.$element
8678 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
8679 .append( this.outlineControlsWidget
.$element
);
8686 OO
.inheritClass( OO
.ui
.BookletLayout
, OO
.ui
.MenuLayout
);
8691 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
8693 * @param {OO.ui.PageLayout} page Current page
8697 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
8700 * @param {OO.ui.PageLayout[]} page Added pages
8701 * @param {number} index Index pages were added at
8705 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
8706 * {@link #removePages removed} from the booklet.
8709 * @param {OO.ui.PageLayout[]} pages Removed pages
8715 * Handle stack layout focus.
8718 * @param {jQuery.Event} e Focusin event
8720 OO
.ui
.BookletLayout
.prototype.onStackLayoutFocus = function ( e
) {
8723 // Find the page that an element was focused within
8724 $target
= $( e
.target
).closest( '.oo-ui-pageLayout' );
8725 for ( name
in this.pages
) {
8726 // Check for page match, exclude current page to find only page changes
8727 if ( this.pages
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentPageName
) {
8728 this.setPage( name
);
8735 * Handle stack layout set events.
8738 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
8740 OO
.ui
.BookletLayout
.prototype.onStackLayoutSet = function ( page
) {
8743 page
.scrollElementIntoView( { complete: function () {
8744 if ( layout
.autoFocus
) {
8752 * Focus the first input in the current page.
8754 * If no page is selected, the first selectable page will be selected.
8755 * If the focus is already in an element on the current page, nothing will happen.
8756 * @param {number} [itemIndex] A specific item to focus on
8758 OO
.ui
.BookletLayout
.prototype.focus = function ( itemIndex
) {
8760 items
= this.stackLayout
.getItems();
8762 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
8763 page
= items
[ itemIndex
];
8765 page
= this.stackLayout
.getCurrentItem();
8768 if ( !page
&& this.outlined
) {
8769 this.selectFirstSelectablePage();
8770 page
= this.stackLayout
.getCurrentItem();
8775 // Only change the focus if is not already in the current page
8776 if ( !page
.$element
.find( ':focus' ).length
) {
8777 $input
= page
.$element
.find( ':input:first' );
8778 if ( $input
.length
) {
8779 $input
[ 0 ].focus();
8785 * Find the first focusable input in the booklet layout and focus
8788 OO
.ui
.BookletLayout
.prototype.focusFirstFocusable = function () {
8791 items
= this.stackLayout
.getItems(),
8792 checkAndFocus = function () {
8793 if ( OO
.ui
.isFocusableElement( $( this ) ) ) {
8800 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
8804 // Find all potentially focusable elements in the item
8805 // and check if they are focusable
8807 .find( 'input, select, textarea, button, object' )
8808 /* jshint loopfunc:true */
8809 .each( checkAndFocus
);
8814 * Handle outline widget select events.
8817 * @param {OO.ui.OptionWidget|null} item Selected item
8819 OO
.ui
.BookletLayout
.prototype.onOutlineSelectWidgetSelect = function ( item
) {
8821 this.setPage( item
.getData() );
8826 * Check if booklet has an outline.
8828 * @return {boolean} Booklet has an outline
8830 OO
.ui
.BookletLayout
.prototype.isOutlined = function () {
8831 return this.outlined
;
8835 * Check if booklet has editing controls.
8837 * @return {boolean} Booklet is editable
8839 OO
.ui
.BookletLayout
.prototype.isEditable = function () {
8840 return this.editable
;
8844 * Check if booklet has a visible outline.
8846 * @return {boolean} Outline is visible
8848 OO
.ui
.BookletLayout
.prototype.isOutlineVisible = function () {
8849 return this.outlined
&& this.outlineVisible
;
8853 * Hide or show the outline.
8855 * @param {boolean} [show] Show outline, omit to invert current state
8858 OO
.ui
.BookletLayout
.prototype.toggleOutline = function ( show
) {
8859 if ( this.outlined
) {
8860 show
= show
=== undefined ? !this.outlineVisible
: !!show
;
8861 this.outlineVisible
= show
;
8862 this.toggleMenu( show
);
8869 * Get the page closest to the specified page.
8871 * @param {OO.ui.PageLayout} page Page to use as a reference point
8872 * @return {OO.ui.PageLayout|null} Page closest to the specified page
8874 OO
.ui
.BookletLayout
.prototype.getClosestPage = function ( page
) {
8875 var next
, prev
, level
,
8876 pages
= this.stackLayout
.getItems(),
8877 index
= $.inArray( page
, pages
);
8879 if ( index
!== -1 ) {
8880 next
= pages
[ index
+ 1 ];
8881 prev
= pages
[ index
- 1 ];
8882 // Prefer adjacent pages at the same level
8883 if ( this.outlined
) {
8884 level
= this.outlineSelectWidget
.getItemFromData( page
.getName() ).getLevel();
8887 level
=== this.outlineSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
8893 level
=== this.outlineSelectWidget
.getItemFromData( next
.getName() ).getLevel()
8899 return prev
|| next
|| null;
8903 * Get the outline widget.
8905 * If the booklet is not outlined, the method will return `null`.
8907 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
8909 OO
.ui
.BookletLayout
.prototype.getOutline = function () {
8910 return this.outlineSelectWidget
;
8914 * Get the outline controls widget.
8916 * If the outline is not editable, the method will return `null`.
8918 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
8920 OO
.ui
.BookletLayout
.prototype.getOutlineControls = function () {
8921 return this.outlineControlsWidget
;
8925 * Get a page by its symbolic name.
8927 * @param {string} name Symbolic name of page
8928 * @return {OO.ui.PageLayout|undefined} Page, if found
8930 OO
.ui
.BookletLayout
.prototype.getPage = function ( name
) {
8931 return this.pages
[ name
];
8935 * Get the current page.
8937 * @return {OO.ui.PageLayout|undefined} Current page, if found
8939 OO
.ui
.BookletLayout
.prototype.getCurrentPage = function () {
8940 var name
= this.getCurrentPageName();
8941 return name
? this.getPage( name
) : undefined;
8945 * Get the symbolic name of the current page.
8947 * @return {string|null} Symbolic name of the current page
8949 OO
.ui
.BookletLayout
.prototype.getCurrentPageName = function () {
8950 return this.currentPageName
;
8954 * Add pages to the booklet layout
8956 * When pages are added with the same names as existing pages, the existing pages will be
8957 * automatically removed before the new pages are added.
8959 * @param {OO.ui.PageLayout[]} pages Pages to add
8960 * @param {number} index Index of the insertion point
8964 OO
.ui
.BookletLayout
.prototype.addPages = function ( pages
, index
) {
8965 var i
, len
, name
, page
, item
, currentIndex
,
8966 stackLayoutPages
= this.stackLayout
.getItems(),
8970 // Remove pages with same names
8971 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
8973 name
= page
.getName();
8975 if ( Object
.prototype.hasOwnProperty
.call( this.pages
, name
) ) {
8976 // Correct the insertion index
8977 currentIndex
= $.inArray( this.pages
[ name
], stackLayoutPages
);
8978 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
8981 remove
.push( this.pages
[ name
] );
8984 if ( remove
.length
) {
8985 this.removePages( remove
);
8989 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
8991 name
= page
.getName();
8992 this.pages
[ page
.getName() ] = page
;
8993 if ( this.outlined
) {
8994 item
= new OO
.ui
.OutlineOptionWidget( { data
: name
} );
8995 page
.setOutlineItem( item
);
9000 if ( this.outlined
&& items
.length
) {
9001 this.outlineSelectWidget
.addItems( items
, index
);
9002 this.selectFirstSelectablePage();
9004 this.stackLayout
.addItems( pages
, index
);
9005 this.emit( 'add', pages
, index
);
9011 * Remove the specified pages from the booklet layout.
9013 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
9015 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
9019 OO
.ui
.BookletLayout
.prototype.removePages = function ( pages
) {
9020 var i
, len
, name
, page
,
9023 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9025 name
= page
.getName();
9026 delete this.pages
[ name
];
9027 if ( this.outlined
) {
9028 items
.push( this.outlineSelectWidget
.getItemFromData( name
) );
9029 page
.setOutlineItem( null );
9032 if ( this.outlined
&& items
.length
) {
9033 this.outlineSelectWidget
.removeItems( items
);
9034 this.selectFirstSelectablePage();
9036 this.stackLayout
.removeItems( pages
);
9037 this.emit( 'remove', pages
);
9043 * Clear all pages from the booklet layout.
9045 * To remove only a subset of pages from the booklet, use the #removePages method.
9050 OO
.ui
.BookletLayout
.prototype.clearPages = function () {
9052 pages
= this.stackLayout
.getItems();
9055 this.currentPageName
= null;
9056 if ( this.outlined
) {
9057 this.outlineSelectWidget
.clearItems();
9058 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9059 pages
[ i
].setOutlineItem( null );
9062 this.stackLayout
.clearItems();
9064 this.emit( 'remove', pages
);
9070 * Set the current page by symbolic name.
9073 * @param {string} name Symbolic name of page
9075 OO
.ui
.BookletLayout
.prototype.setPage = function ( name
) {
9078 page
= this.pages
[ name
];
9080 if ( name
!== this.currentPageName
) {
9081 if ( this.outlined
) {
9082 selectedItem
= this.outlineSelectWidget
.getSelectedItem();
9083 if ( selectedItem
&& selectedItem
.getData() !== name
) {
9084 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getItemFromData( name
) );
9088 if ( this.currentPageName
&& this.pages
[ this.currentPageName
] ) {
9089 this.pages
[ this.currentPageName
].setActive( false );
9090 // Blur anything focused if the next page doesn't have anything focusable - this
9091 // is not needed if the next page has something focusable because once it is focused
9092 // this blur happens automatically
9093 if ( this.autoFocus
&& !page
.$element
.find( ':input' ).length
) {
9094 $focused
= this.pages
[ this.currentPageName
].$element
.find( ':focus' );
9095 if ( $focused
.length
) {
9096 $focused
[ 0 ].blur();
9100 this.currentPageName
= name
;
9101 this.stackLayout
.setItem( page
);
9102 page
.setActive( true );
9103 this.emit( 'set', page
);
9109 * Select the first selectable page.
9113 OO
.ui
.BookletLayout
.prototype.selectFirstSelectablePage = function () {
9114 if ( !this.outlineSelectWidget
.getSelectedItem() ) {
9115 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getFirstSelectableItem() );
9122 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
9123 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
9126 * // Example of a panel layout
9127 * var panel = new OO.ui.PanelLayout( {
9131 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
9133 * $( 'body' ).append( panel.$element );
9136 * @extends OO.ui.Layout
9139 * @param {Object} [config] Configuration options
9140 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
9141 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
9142 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
9143 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
9145 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
9146 // Configuration initialization
9147 config
= $.extend( {
9154 // Parent constructor
9155 OO
.ui
.PanelLayout
.super.call( this, config
);
9158 this.$element
.addClass( 'oo-ui-panelLayout' );
9159 if ( config
.scrollable
) {
9160 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
9162 if ( config
.padded
) {
9163 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
9165 if ( config
.expanded
) {
9166 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
9168 if ( config
.framed
) {
9169 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
9175 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
9178 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
9179 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
9180 * rather extended to include the required content and functionality.
9182 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
9183 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
9184 * {@link OO.ui.BookletLayout BookletLayout} for an example.
9187 * @extends OO.ui.PanelLayout
9190 * @param {string} name Unique symbolic name of page
9191 * @param {Object} [config] Configuration options
9193 OO
.ui
.PageLayout
= function OoUiPageLayout( name
, config
) {
9194 // Allow passing positional parameters inside the config object
9195 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
9200 // Configuration initialization
9201 config
= $.extend( { scrollable
: true }, config
);
9203 // Parent constructor
9204 OO
.ui
.PageLayout
.super.call( this, config
);
9208 this.outlineItem
= null;
9209 this.active
= false;
9212 this.$element
.addClass( 'oo-ui-pageLayout' );
9217 OO
.inheritClass( OO
.ui
.PageLayout
, OO
.ui
.PanelLayout
);
9222 * An 'active' event is emitted when the page becomes active. Pages become active when they are
9223 * shown in a booklet layout that is configured to display only one page at a time.
9226 * @param {boolean} active Page is active
9232 * Get the symbolic name of the page.
9234 * @return {string} Symbolic name of page
9236 OO
.ui
.PageLayout
.prototype.getName = function () {
9241 * Check if page is active.
9243 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
9244 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
9246 * @return {boolean} Page is active
9248 OO
.ui
.PageLayout
.prototype.isActive = function () {
9255 * The outline item allows users to access the page from the booklet's outline
9256 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
9258 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
9260 OO
.ui
.PageLayout
.prototype.getOutlineItem = function () {
9261 return this.outlineItem
;
9265 * Set or unset the outline item.
9267 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
9268 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
9269 * level), use #setupOutlineItem instead of this method.
9271 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
9274 OO
.ui
.PageLayout
.prototype.setOutlineItem = function ( outlineItem
) {
9275 this.outlineItem
= outlineItem
|| null;
9276 if ( outlineItem
) {
9277 this.setupOutlineItem();
9283 * Set up the outline item.
9285 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
9286 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
9287 * the #setOutlineItem method instead.
9289 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
9292 OO
.ui
.PageLayout
.prototype.setupOutlineItem = function () {
9297 * Set the page to its 'active' state.
9299 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
9300 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
9301 * context, setting the active state on a page does nothing.
9303 * @param {boolean} value Page is active
9306 OO
.ui
.PageLayout
.prototype.setActive = function ( active
) {
9309 if ( active
!== this.active
) {
9310 this.active
= active
;
9311 this.$element
.toggleClass( 'oo-ui-pageLayout-active', active
);
9312 this.emit( 'active', this.active
);
9317 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
9318 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
9319 * by setting the #continuous option to 'true'.
9322 * // A stack layout with two panels, configured to be displayed continously
9323 * var myStack = new OO.ui.StackLayout( {
9325 * new OO.ui.PanelLayout( {
9326 * $content: $( '<p>Panel One</p>' ),
9330 * new OO.ui.PanelLayout( {
9331 * $content: $( '<p>Panel Two</p>' ),
9338 * $( 'body' ).append( myStack.$element );
9341 * @extends OO.ui.PanelLayout
9342 * @mixins OO.ui.GroupElement
9345 * @param {Object} [config] Configuration options
9346 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
9347 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
9349 OO
.ui
.StackLayout
= function OoUiStackLayout( config
) {
9350 // Configuration initialization
9351 config
= $.extend( { scrollable
: true }, config
);
9353 // Parent constructor
9354 OO
.ui
.StackLayout
.super.call( this, config
);
9356 // Mixin constructors
9357 OO
.ui
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
9360 this.currentItem
= null;
9361 this.continuous
= !!config
.continuous
;
9364 this.$element
.addClass( 'oo-ui-stackLayout' );
9365 if ( this.continuous
) {
9366 this.$element
.addClass( 'oo-ui-stackLayout-continuous' );
9368 if ( Array
.isArray( config
.items
) ) {
9369 this.addItems( config
.items
);
9375 OO
.inheritClass( OO
.ui
.StackLayout
, OO
.ui
.PanelLayout
);
9376 OO
.mixinClass( OO
.ui
.StackLayout
, OO
.ui
.GroupElement
);
9381 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
9382 * {@link #clearItems cleared} or {@link #setItem displayed}.
9385 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
9391 * Get the current panel.
9393 * @return {OO.ui.Layout|null}
9395 OO
.ui
.StackLayout
.prototype.getCurrentItem = function () {
9396 return this.currentItem
;
9400 * Unset the current item.
9403 * @param {OO.ui.StackLayout} layout
9406 OO
.ui
.StackLayout
.prototype.unsetCurrentItem = function () {
9407 var prevItem
= this.currentItem
;
9408 if ( prevItem
=== null ) {
9412 this.currentItem
= null;
9413 this.emit( 'set', null );
9417 * Add panel layouts to the stack layout.
9419 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
9420 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
9423 * @param {OO.ui.Layout[]} items Panels to add
9424 * @param {number} [index] Index of the insertion point
9427 OO
.ui
.StackLayout
.prototype.addItems = function ( items
, index
) {
9428 // Update the visibility
9429 this.updateHiddenState( items
, this.currentItem
);
9432 OO
.ui
.GroupElement
.prototype.addItems
.call( this, items
, index
);
9434 if ( !this.currentItem
&& items
.length
) {
9435 this.setItem( items
[ 0 ] );
9442 * Remove the specified panels from the stack layout.
9444 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
9445 * you may wish to use the #clearItems method instead.
9447 * @param {OO.ui.Layout[]} items Panels to remove
9451 OO
.ui
.StackLayout
.prototype.removeItems = function ( items
) {
9453 OO
.ui
.GroupElement
.prototype.removeItems
.call( this, items
);
9455 if ( $.inArray( this.currentItem
, items
) !== -1 ) {
9456 if ( this.items
.length
) {
9457 this.setItem( this.items
[ 0 ] );
9459 this.unsetCurrentItem();
9467 * Clear all panels from the stack layout.
9469 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
9470 * a subset of panels, use the #removeItems method.
9475 OO
.ui
.StackLayout
.prototype.clearItems = function () {
9476 this.unsetCurrentItem();
9477 OO
.ui
.GroupElement
.prototype.clearItems
.call( this );
9483 * Show the specified panel.
9485 * If another panel is currently displayed, it will be hidden.
9487 * @param {OO.ui.Layout} item Panel to show
9491 OO
.ui
.StackLayout
.prototype.setItem = function ( item
) {
9492 if ( item
!== this.currentItem
) {
9493 this.updateHiddenState( this.items
, item
);
9495 if ( $.inArray( item
, this.items
) !== -1 ) {
9496 this.currentItem
= item
;
9497 this.emit( 'set', item
);
9499 this.unsetCurrentItem();
9507 * Update the visibility of all items in case of non-continuous view.
9509 * Ensure all items are hidden except for the selected one.
9510 * This method does nothing when the stack is continuous.
9513 * @param {OO.ui.Layout[]} items Item list iterate over
9514 * @param {OO.ui.Layout} [selectedItem] Selected item to show
9516 OO
.ui
.StackLayout
.prototype.updateHiddenState = function ( items
, selectedItem
) {
9519 if ( !this.continuous
) {
9520 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
9521 if ( !selectedItem
|| selectedItem
!== items
[ i
] ) {
9522 items
[ i
].$element
.addClass( 'oo-ui-element-hidden' );
9525 if ( selectedItem
) {
9526 selectedItem
.$element
.removeClass( 'oo-ui-element-hidden' );
9532 * Horizontal bar layout of tools as icon buttons.
9535 * @extends OO.ui.ToolGroup
9538 * @param {OO.ui.Toolbar} toolbar
9539 * @param {Object} [config] Configuration options
9541 OO
.ui
.BarToolGroup
= function OoUiBarToolGroup( toolbar
, config
) {
9542 // Allow passing positional parameters inside the config object
9543 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
9545 toolbar
= config
.toolbar
;
9548 // Parent constructor
9549 OO
.ui
.BarToolGroup
.super.call( this, toolbar
, config
);
9552 this.$element
.addClass( 'oo-ui-barToolGroup' );
9557 OO
.inheritClass( OO
.ui
.BarToolGroup
, OO
.ui
.ToolGroup
);
9559 /* Static Properties */
9561 OO
.ui
.BarToolGroup
.static.titleTooltips
= true;
9563 OO
.ui
.BarToolGroup
.static.accelTooltips
= true;
9565 OO
.ui
.BarToolGroup
.static.name
= 'bar';
9568 * Popup list of tools with an icon and optional label.
9572 * @extends OO.ui.ToolGroup
9573 * @mixins OO.ui.IconElement
9574 * @mixins OO.ui.IndicatorElement
9575 * @mixins OO.ui.LabelElement
9576 * @mixins OO.ui.TitledElement
9577 * @mixins OO.ui.ClippableElement
9580 * @param {OO.ui.Toolbar} toolbar
9581 * @param {Object} [config] Configuration options
9582 * @cfg {string} [header] Text to display at the top of the pop-up
9584 OO
.ui
.PopupToolGroup
= function OoUiPopupToolGroup( toolbar
, config
) {
9585 // Allow passing positional parameters inside the config object
9586 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
9588 toolbar
= config
.toolbar
;
9591 // Configuration initialization
9592 config
= config
|| {};
9594 // Parent constructor
9595 OO
.ui
.PopupToolGroup
.super.call( this, toolbar
, config
);
9597 // Mixin constructors
9598 OO
.ui
.IconElement
.call( this, config
);
9599 OO
.ui
.IndicatorElement
.call( this, config
);
9600 OO
.ui
.LabelElement
.call( this, config
);
9601 OO
.ui
.TitledElement
.call( this, config
);
9602 OO
.ui
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
9605 this.active
= false;
9606 this.dragging
= false;
9607 this.onBlurHandler
= this.onBlur
.bind( this );
9608 this.$handle
= $( '<span>' );
9612 mousedown
: this.onHandlePointerDown
.bind( this ),
9613 mouseup
: this.onHandlePointerUp
.bind( this )
9618 .addClass( 'oo-ui-popupToolGroup-handle' )
9619 .append( this.$icon
, this.$label
, this.$indicator
);
9620 // If the pop-up should have a header, add it to the top of the toolGroup.
9621 // Note: If this feature is useful for other widgets, we could abstract it into an
9622 // OO.ui.HeaderedElement mixin constructor.
9623 if ( config
.header
!== undefined ) {
9625 .prepend( $( '<span>' )
9626 .addClass( 'oo-ui-popupToolGroup-header' )
9627 .text( config
.header
)
9631 .addClass( 'oo-ui-popupToolGroup' )
9632 .prepend( this.$handle
);
9637 OO
.inheritClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ToolGroup
);
9638 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.IconElement
);
9639 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.IndicatorElement
);
9640 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.LabelElement
);
9641 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.TitledElement
);
9642 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ClippableElement
);
9644 /* Static Properties */
9651 OO
.ui
.PopupToolGroup
.prototype.setDisabled = function () {
9653 OO
.ui
.PopupToolGroup
.super.prototype.setDisabled
.apply( this, arguments
);
9655 if ( this.isDisabled() && this.isElementAttached() ) {
9656 this.setActive( false );
9661 * Handle focus being lost.
9663 * The event is actually generated from a mouseup, so it is not a normal blur event object.
9665 * @param {jQuery.Event} e Mouse up event
9667 OO
.ui
.PopupToolGroup
.prototype.onBlur = function ( e
) {
9668 // Only deactivate when clicking outside the dropdown element
9669 if ( $( e
.target
).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element
[ 0 ] ) {
9670 this.setActive( false );
9677 OO
.ui
.PopupToolGroup
.prototype.onPointerUp = function ( e
) {
9678 // Only close toolgroup when a tool was actually selected
9679 if ( !this.isDisabled() && e
.which
=== 1 && this.pressed
&& this.pressed
=== this.getTargetTool( e
) ) {
9680 this.setActive( false );
9682 return OO
.ui
.PopupToolGroup
.super.prototype.onPointerUp
.call( this, e
);
9686 * Handle mouse up events.
9688 * @param {jQuery.Event} e Mouse up event
9690 OO
.ui
.PopupToolGroup
.prototype.onHandlePointerUp = function () {
9695 * Handle mouse down events.
9697 * @param {jQuery.Event} e Mouse down event
9699 OO
.ui
.PopupToolGroup
.prototype.onHandlePointerDown = function ( e
) {
9700 if ( !this.isDisabled() && e
.which
=== 1 ) {
9701 this.setActive( !this.active
);
9707 * Switch into active mode.
9709 * When active, mouseup events anywhere in the document will trigger deactivation.
9711 OO
.ui
.PopupToolGroup
.prototype.setActive = function ( value
) {
9713 if ( this.active
!== value
) {
9714 this.active
= value
;
9716 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler
, true );
9718 // Try anchoring the popup to the left first
9719 this.$element
.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
9720 this.toggleClipping( true );
9721 if ( this.isClippedHorizontally() ) {
9722 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
9723 this.toggleClipping( false );
9725 .removeClass( 'oo-ui-popupToolGroup-left' )
9726 .addClass( 'oo-ui-popupToolGroup-right' );
9727 this.toggleClipping( true );
9730 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler
, true );
9731 this.$element
.removeClass(
9732 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
9734 this.toggleClipping( false );
9740 * Drop down list layout of tools as labeled icon buttons.
9742 * This layout allows some tools to be collapsible, controlled by a "More" / "Fewer" option at the
9743 * bottom of the main list. These are not automatically positioned at the bottom of the list; you
9744 * may want to use the 'promote' and 'demote' configuration options to achieve this.
9747 * @extends OO.ui.PopupToolGroup
9750 * @param {OO.ui.Toolbar} toolbar
9751 * @param {Object} [config] Configuration options
9752 * @cfg {Array} [allowCollapse] List of tools that can be collapsed. Remaining tools will be always
9754 * @cfg {Array} [forceExpand] List of tools that *may not* be collapsed. All remaining tools will be
9755 * allowed to be collapsed.
9756 * @cfg {boolean} [expanded=false] Whether the collapsible tools are expanded by default
9758 OO
.ui
.ListToolGroup
= function OoUiListToolGroup( toolbar
, config
) {
9759 // Allow passing positional parameters inside the config object
9760 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
9762 toolbar
= config
.toolbar
;
9765 // Configuration initialization
9766 config
= config
|| {};
9768 // Properties (must be set before parent constructor, which calls #populate)
9769 this.allowCollapse
= config
.allowCollapse
;
9770 this.forceExpand
= config
.forceExpand
;
9771 this.expanded
= config
.expanded
!== undefined ? config
.expanded
: false;
9772 this.collapsibleTools
= [];
9774 // Parent constructor
9775 OO
.ui
.ListToolGroup
.super.call( this, toolbar
, config
);
9778 this.$element
.addClass( 'oo-ui-listToolGroup' );
9783 OO
.inheritClass( OO
.ui
.ListToolGroup
, OO
.ui
.PopupToolGroup
);
9785 /* Static Properties */
9787 OO
.ui
.ListToolGroup
.static.accelTooltips
= true;
9789 OO
.ui
.ListToolGroup
.static.name
= 'list';
9796 OO
.ui
.ListToolGroup
.prototype.populate = function () {
9797 var i
, len
, allowCollapse
= [];
9799 OO
.ui
.ListToolGroup
.super.prototype.populate
.call( this );
9801 // Update the list of collapsible tools
9802 if ( this.allowCollapse
!== undefined ) {
9803 allowCollapse
= this.allowCollapse
;
9804 } else if ( this.forceExpand
!== undefined ) {
9805 allowCollapse
= OO
.simpleArrayDifference( Object
.keys( this.tools
), this.forceExpand
);
9808 this.collapsibleTools
= [];
9809 for ( i
= 0, len
= allowCollapse
.length
; i
< len
; i
++ ) {
9810 if ( this.tools
[ allowCollapse
[ i
] ] !== undefined ) {
9811 this.collapsibleTools
.push( this.tools
[ allowCollapse
[ i
] ] );
9815 // Keep at the end, even when tools are added
9816 this.$group
.append( this.getExpandCollapseTool().$element
);
9818 this.getExpandCollapseTool().toggle( this.collapsibleTools
.length
!== 0 );
9819 this.updateCollapsibleState();
9822 OO
.ui
.ListToolGroup
.prototype.getExpandCollapseTool = function () {
9823 if ( this.expandCollapseTool
=== undefined ) {
9824 var ExpandCollapseTool = function () {
9825 ExpandCollapseTool
.super.apply( this, arguments
);
9828 OO
.inheritClass( ExpandCollapseTool
, OO
.ui
.Tool
);
9830 ExpandCollapseTool
.prototype.onSelect = function () {
9831 this.toolGroup
.expanded
= !this.toolGroup
.expanded
;
9832 this.toolGroup
.updateCollapsibleState();
9833 this.setActive( false );
9835 ExpandCollapseTool
.prototype.onUpdateState = function () {
9836 // Do nothing. Tool interface requires an implementation of this function.
9839 ExpandCollapseTool
.static.name
= 'more-fewer';
9841 this.expandCollapseTool
= new ExpandCollapseTool( this );
9843 return this.expandCollapseTool
;
9849 OO
.ui
.ListToolGroup
.prototype.onPointerUp = function ( e
) {
9850 var ret
= OO
.ui
.ListToolGroup
.super.prototype.onPointerUp
.call( this, e
);
9852 // Do not close the popup when the user wants to show more/fewer tools
9853 if ( $( e
.target
).closest( '.oo-ui-tool-name-more-fewer' ).length
) {
9854 // Prevent the popup list from being hidden
9855 this.setActive( true );
9861 OO
.ui
.ListToolGroup
.prototype.updateCollapsibleState = function () {
9864 this.getExpandCollapseTool()
9865 .setIcon( this.expanded
? 'collapse' : 'expand' )
9866 .setTitle( OO
.ui
.msg( this.expanded
? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
9868 for ( i
= 0, len
= this.collapsibleTools
.length
; i
< len
; i
++ ) {
9869 this.collapsibleTools
[ i
].toggle( this.expanded
);
9874 * Drop down menu layout of tools as selectable menu items.
9877 * @extends OO.ui.PopupToolGroup
9880 * @param {OO.ui.Toolbar} toolbar
9881 * @param {Object} [config] Configuration options
9883 OO
.ui
.MenuToolGroup
= function OoUiMenuToolGroup( toolbar
, config
) {
9884 // Allow passing positional parameters inside the config object
9885 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
9887 toolbar
= config
.toolbar
;
9890 // Configuration initialization
9891 config
= config
|| {};
9893 // Parent constructor
9894 OO
.ui
.MenuToolGroup
.super.call( this, toolbar
, config
);
9897 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
9900 this.$element
.addClass( 'oo-ui-menuToolGroup' );
9905 OO
.inheritClass( OO
.ui
.MenuToolGroup
, OO
.ui
.PopupToolGroup
);
9907 /* Static Properties */
9909 OO
.ui
.MenuToolGroup
.static.accelTooltips
= true;
9911 OO
.ui
.MenuToolGroup
.static.name
= 'menu';
9916 * Handle the toolbar state being updated.
9918 * When the state changes, the title of each active item in the menu will be joined together and
9919 * used as a label for the group. The label will be empty if none of the items are active.
9921 OO
.ui
.MenuToolGroup
.prototype.onUpdateState = function () {
9925 for ( name
in this.tools
) {
9926 if ( this.tools
[ name
].isActive() ) {
9927 labelTexts
.push( this.tools
[ name
].getTitle() );
9931 this.setLabel( labelTexts
.join( ', ' ) || ' ' );
9935 * Tool that shows a popup when selected.
9939 * @extends OO.ui.Tool
9940 * @mixins OO.ui.PopupElement
9943 * @param {OO.ui.ToolGroup} toolGroup
9944 * @param {Object} [config] Configuration options
9946 OO
.ui
.PopupTool
= function OoUiPopupTool( toolGroup
, config
) {
9947 // Allow passing positional parameters inside the config object
9948 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
9950 toolGroup
= config
.toolGroup
;
9953 // Parent constructor
9954 OO
.ui
.PopupTool
.super.call( this, toolGroup
, config
);
9956 // Mixin constructors
9957 OO
.ui
.PopupElement
.call( this, config
);
9961 .addClass( 'oo-ui-popupTool' )
9962 .append( this.popup
.$element
);
9967 OO
.inheritClass( OO
.ui
.PopupTool
, OO
.ui
.Tool
);
9968 OO
.mixinClass( OO
.ui
.PopupTool
, OO
.ui
.PopupElement
);
9973 * Handle the tool being selected.
9977 OO
.ui
.PopupTool
.prototype.onSelect = function () {
9978 if ( !this.isDisabled() ) {
9979 this.popup
.toggle();
9981 this.setActive( false );
9986 * Handle the toolbar state being updated.
9990 OO
.ui
.PopupTool
.prototype.onUpdateState = function () {
9991 this.setActive( false );
9995 * Tool that has a tool group inside. This is a bad workaround for the lack of proper hierarchical
9996 * menus in toolbars (T74159).
10000 * @extends OO.ui.Tool
10003 * @param {OO.ui.ToolGroup} toolGroup
10004 * @param {Object} [config] Configuration options
10006 OO
.ui
.ToolGroupTool
= function OoUiToolGroupTool( toolGroup
, config
) {
10007 // Allow passing positional parameters inside the config object
10008 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
10009 config
= toolGroup
;
10010 toolGroup
= config
.toolGroup
;
10013 // Parent constructor
10014 OO
.ui
.ToolGroupTool
.super.call( this, toolGroup
, config
);
10017 this.innerToolGroup
= this.createGroup( this.constructor.static.groupConfig
);
10020 this.$link
.remove();
10022 .addClass( 'oo-ui-toolGroupTool' )
10023 .append( this.innerToolGroup
.$element
);
10028 OO
.inheritClass( OO
.ui
.ToolGroupTool
, OO
.ui
.Tool
);
10030 /* Static Properties */
10033 * Tool group configuration. See OO.ui.Toolbar#setup for the accepted values.
10035 * @property {Object.<string,Array>}
10037 OO
.ui
.ToolGroupTool
.static.groupConfig
= {};
10042 * Handle the tool being selected.
10046 OO
.ui
.ToolGroupTool
.prototype.onSelect = function () {
10047 this.innerToolGroup
.setActive( !this.innerToolGroup
.active
);
10052 * Handle the toolbar state being updated.
10056 OO
.ui
.ToolGroupTool
.prototype.onUpdateState = function () {
10057 this.setActive( false );
10061 * Build a OO.ui.ToolGroup from the configuration.
10063 * @param {Object.<string,Array>} group Tool group configuration. See OO.ui.Toolbar#setup for the
10065 * @return {OO.ui.ListToolGroup}
10067 OO
.ui
.ToolGroupTool
.prototype.createGroup = function ( group
) {
10068 if ( group
.include
=== '*' ) {
10069 // Apply defaults to catch-all groups
10070 if ( group
.label
=== undefined ) {
10071 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
10075 return this.toolbar
.getToolGroupFactory().create( 'list', this.toolbar
, group
);
10079 * Mixin for OO.ui.Widget subclasses to provide OO.ui.GroupElement.
10081 * Use together with OO.ui.ItemWidget to make disabled state inheritable.
10086 * @extends OO.ui.GroupElement
10089 * @param {Object} [config] Configuration options
10091 OO
.ui
.GroupWidget
= function OoUiGroupWidget( config
) {
10092 // Parent constructor
10093 OO
.ui
.GroupWidget
.super.call( this, config
);
10098 OO
.inheritClass( OO
.ui
.GroupWidget
, OO
.ui
.GroupElement
);
10103 * Set the disabled state of the widget.
10105 * This will also update the disabled state of child widgets.
10107 * @param {boolean} disabled Disable widget
10110 OO
.ui
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
10114 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
10115 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
10117 // During construction, #setDisabled is called before the OO.ui.GroupElement constructor
10118 if ( this.items
) {
10119 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
10120 this.items
[ i
].updateDisabled();
10128 * Mixin for widgets used as items in widgets that inherit OO.ui.GroupWidget.
10130 * Item widgets have a reference to a OO.ui.GroupWidget while they are attached to the group. This
10131 * allows bidirectional communication.
10133 * Use together with OO.ui.GroupWidget to make disabled state inheritable.
10141 OO
.ui
.ItemWidget
= function OoUiItemWidget() {
10148 * Check if widget is disabled.
10150 * Checks parent if present, making disabled state inheritable.
10152 * @return {boolean} Widget is disabled
10154 OO
.ui
.ItemWidget
.prototype.isDisabled = function () {
10155 return this.disabled
||
10156 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
10160 * Set group element is in.
10162 * @param {OO.ui.GroupElement|null} group Group element, null if none
10165 OO
.ui
.ItemWidget
.prototype.setElementGroup = function ( group
) {
10167 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
10168 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
10170 // Initialize item disabled states
10171 this.updateDisabled();
10177 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
10178 * Controls include moving items up and down, removing items, and adding different kinds of items.
10179 * ####Currently, this class is only used by {@link OO.ui.BookletLayout BookletLayouts}.####
10182 * @extends OO.ui.Widget
10183 * @mixins OO.ui.GroupElement
10184 * @mixins OO.ui.IconElement
10187 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
10188 * @param {Object} [config] Configuration options
10189 * @cfg {Object} [abilities] List of abilties
10190 * @cfg {boolean} [abilities.move=true] Allow moving movable items
10191 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
10193 OO
.ui
.OutlineControlsWidget
= function OoUiOutlineControlsWidget( outline
, config
) {
10194 // Allow passing positional parameters inside the config object
10195 if ( OO
.isPlainObject( outline
) && config
=== undefined ) {
10197 outline
= config
.outline
;
10200 // Configuration initialization
10201 config
= $.extend( { icon
: 'add' }, config
);
10203 // Parent constructor
10204 OO
.ui
.OutlineControlsWidget
.super.call( this, config
);
10206 // Mixin constructors
10207 OO
.ui
.GroupElement
.call( this, config
);
10208 OO
.ui
.IconElement
.call( this, config
);
10211 this.outline
= outline
;
10212 this.$movers
= $( '<div>' );
10213 this.upButton
= new OO
.ui
.ButtonWidget( {
10216 title
: OO
.ui
.msg( 'ooui-outline-control-move-up' )
10218 this.downButton
= new OO
.ui
.ButtonWidget( {
10221 title
: OO
.ui
.msg( 'ooui-outline-control-move-down' )
10223 this.removeButton
= new OO
.ui
.ButtonWidget( {
10226 title
: OO
.ui
.msg( 'ooui-outline-control-remove' )
10228 this.abilities
= { move: true, remove
: true };
10231 outline
.connect( this, {
10232 select
: 'onOutlineChange',
10233 add
: 'onOutlineChange',
10234 remove
: 'onOutlineChange'
10236 this.upButton
.connect( this, { click
: [ 'emit', 'move', -1 ] } );
10237 this.downButton
.connect( this, { click
: [ 'emit', 'move', 1 ] } );
10238 this.removeButton
.connect( this, { click
: [ 'emit', 'remove' ] } );
10241 this.$element
.addClass( 'oo-ui-outlineControlsWidget' );
10242 this.$group
.addClass( 'oo-ui-outlineControlsWidget-items' );
10244 .addClass( 'oo-ui-outlineControlsWidget-movers' )
10245 .append( this.removeButton
.$element
, this.upButton
.$element
, this.downButton
.$element
);
10246 this.$element
.append( this.$icon
, this.$group
, this.$movers
);
10247 this.setAbilities( config
.abilities
|| {} );
10252 OO
.inheritClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.Widget
);
10253 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.GroupElement
);
10254 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.IconElement
);
10260 * @param {number} places Number of places to move
10272 * @param {Object} abilities List of abilties
10273 * @param {boolean} [abilities.move] Allow moving movable items
10274 * @param {boolean} [abilities.remove] Allow removing removable items
10276 OO
.ui
.OutlineControlsWidget
.prototype.setAbilities = function ( abilities
) {
10279 for ( ability
in this.abilities
) {
10280 if ( abilities
[ability
] !== undefined ) {
10281 this.abilities
[ability
] = !!abilities
[ability
];
10285 this.onOutlineChange();
10291 * Handle outline change events.
10293 OO
.ui
.OutlineControlsWidget
.prototype.onOutlineChange = function () {
10294 var i
, len
, firstMovable
, lastMovable
,
10295 items
= this.outline
.getItems(),
10296 selectedItem
= this.outline
.getSelectedItem(),
10297 movable
= this.abilities
.move && selectedItem
&& selectedItem
.isMovable(),
10298 removable
= this.abilities
.remove
&& selectedItem
&& selectedItem
.isRemovable();
10302 len
= items
.length
;
10303 while ( ++i
< len
) {
10304 if ( items
[ i
].isMovable() ) {
10305 firstMovable
= items
[ i
];
10311 if ( items
[ i
].isMovable() ) {
10312 lastMovable
= items
[ i
];
10317 this.upButton
.setDisabled( !movable
|| selectedItem
=== firstMovable
);
10318 this.downButton
.setDisabled( !movable
|| selectedItem
=== lastMovable
);
10319 this.removeButton
.setDisabled( !removable
);
10323 * ToggleWidget implements basic behavior of widgets with an on/off state.
10324 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
10328 * @extends OO.ui.Widget
10331 * @param {Object} [config] Configuration options
10332 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
10333 * By default, the toggle is in the 'off' state.
10335 OO
.ui
.ToggleWidget
= function OoUiToggleWidget( config
) {
10336 // Configuration initialization
10337 config
= config
|| {};
10339 // Parent constructor
10340 OO
.ui
.ToggleWidget
.super.call( this, config
);
10346 this.$element
.addClass( 'oo-ui-toggleWidget' );
10347 this.setValue( !!config
.value
);
10352 OO
.inheritClass( OO
.ui
.ToggleWidget
, OO
.ui
.Widget
);
10359 * A change event is emitted when the on/off state of the toggle changes.
10361 * @param {boolean} value Value representing the new state of the toggle
10367 * Get the value representing the toggle’s state.
10369 * @return {boolean} The on/off state of the toggle
10371 OO
.ui
.ToggleWidget
.prototype.getValue = function () {
10376 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
10378 * @param {boolean} value The state of the toggle
10382 OO
.ui
.ToggleWidget
.prototype.setValue = function ( value
) {
10384 if ( this.value
!== value
) {
10385 this.value
= value
;
10386 this.emit( 'change', value
);
10387 this.$element
.toggleClass( 'oo-ui-toggleWidget-on', value
);
10388 this.$element
.toggleClass( 'oo-ui-toggleWidget-off', !value
);
10389 this.$element
.attr( 'aria-checked', value
.toString() );
10395 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
10396 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
10397 * removed, and cleared from the group.
10400 * // Example: A ButtonGroupWidget with two buttons
10401 * var button1 = new OO.ui.PopupButtonWidget( {
10402 * label: 'Select a category',
10405 * $content: $( '<p>List of categories...</p>' ),
10410 * var button2 = new OO.ui.ButtonWidget( {
10411 * label: 'Add item'
10413 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
10414 * items: [button1, button2]
10416 * $( 'body' ).append( buttonGroup.$element );
10419 * @extends OO.ui.Widget
10420 * @mixins OO.ui.GroupElement
10423 * @param {Object} [config] Configuration options
10424 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
10426 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
10427 // Configuration initialization
10428 config
= config
|| {};
10430 // Parent constructor
10431 OO
.ui
.ButtonGroupWidget
.super.call( this, config
);
10433 // Mixin constructors
10434 OO
.ui
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
10437 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
10438 if ( Array
.isArray( config
.items
) ) {
10439 this.addItems( config
.items
);
10445 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
10446 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.GroupElement
);
10449 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
10450 * feels, and functionality can be customized via the class’s configuration options
10451 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
10454 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
10457 * // A button widget
10458 * var button = new OO.ui.ButtonWidget( {
10459 * label: 'Button with Icon',
10461 * iconTitle: 'Remove'
10463 * $( 'body' ).append( button.$element );
10465 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
10468 * @extends OO.ui.Widget
10469 * @mixins OO.ui.ButtonElement
10470 * @mixins OO.ui.IconElement
10471 * @mixins OO.ui.IndicatorElement
10472 * @mixins OO.ui.LabelElement
10473 * @mixins OO.ui.TitledElement
10474 * @mixins OO.ui.FlaggedElement
10475 * @mixins OO.ui.TabIndexedElement
10478 * @param {Object} [config] Configuration options
10479 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
10480 * @cfg {string} [target] The frame or window in which to open the hyperlink.
10481 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
10483 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
10484 // Configuration initialization
10485 config
= config
|| {};
10487 // Parent constructor
10488 OO
.ui
.ButtonWidget
.super.call( this, config
);
10490 // Mixin constructors
10491 OO
.ui
.ButtonElement
.call( this, config
);
10492 OO
.ui
.IconElement
.call( this, config
);
10493 OO
.ui
.IndicatorElement
.call( this, config
);
10494 OO
.ui
.LabelElement
.call( this, config
);
10495 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
10496 OO
.ui
.FlaggedElement
.call( this, config
);
10497 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
10501 this.target
= null;
10502 this.noFollow
= false;
10505 this.connect( this, { disable
: 'onDisable' } );
10508 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
10510 .addClass( 'oo-ui-buttonWidget' )
10511 .append( this.$button
);
10512 this.setHref( config
.href
);
10513 this.setTarget( config
.target
);
10514 this.setNoFollow( config
.noFollow
);
10519 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
10520 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.ButtonElement
);
10521 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.IconElement
);
10522 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.IndicatorElement
);
10523 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.LabelElement
);
10524 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.TitledElement
);
10525 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.FlaggedElement
);
10526 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.TabIndexedElement
);
10533 OO
.ui
.ButtonWidget
.prototype.onMouseDown = function ( e
) {
10534 if ( !this.isDisabled() ) {
10535 // Remove the tab-index while the button is down to prevent the button from stealing focus
10536 this.$button
.removeAttr( 'tabindex' );
10539 return OO
.ui
.ButtonElement
.prototype.onMouseDown
.call( this, e
);
10545 OO
.ui
.ButtonWidget
.prototype.onMouseUp = function ( e
) {
10546 if ( !this.isDisabled() ) {
10547 // Restore the tab-index after the button is up to restore the button's accessibility
10548 this.$button
.attr( 'tabindex', this.tabIndex
);
10551 return OO
.ui
.ButtonElement
.prototype.onMouseUp
.call( this, e
);
10557 OO
.ui
.ButtonWidget
.prototype.onClick = function ( e
) {
10558 var ret
= OO
.ui
.ButtonElement
.prototype.onClick
.call( this, e
);
10568 OO
.ui
.ButtonWidget
.prototype.onKeyPress = function ( e
) {
10569 var ret
= OO
.ui
.ButtonElement
.prototype.onKeyPress
.call( this, e
);
10577 * Get hyperlink location.
10579 * @return {string} Hyperlink location
10581 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
10586 * Get hyperlink target.
10588 * @return {string} Hyperlink target
10590 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
10591 return this.target
;
10595 * Get search engine traversal hint.
10597 * @return {boolean} Whether search engines should avoid traversing this hyperlink
10599 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
10600 return this.noFollow
;
10604 * Set hyperlink location.
10606 * @param {string|null} href Hyperlink location, null to remove
10608 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
10609 href
= typeof href
=== 'string' ? href
: null;
10611 if ( href
!== this.href
) {
10620 * Update the `href` attribute, in case of changes to href or
10626 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
10627 if ( this.href
!== null && !this.isDisabled() ) {
10628 this.$button
.attr( 'href', this.href
);
10630 this.$button
.removeAttr( 'href' );
10637 * Handle disable events.
10640 * @param {boolean} disabled Element is disabled
10642 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
10647 * Set hyperlink target.
10649 * @param {string|null} target Hyperlink target, null to remove
10651 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
10652 target
= typeof target
=== 'string' ? target
: null;
10654 if ( target
!== this.target
) {
10655 this.target
= target
;
10656 if ( target
!== null ) {
10657 this.$button
.attr( 'target', target
);
10659 this.$button
.removeAttr( 'target' );
10667 * Set search engine traversal hint.
10669 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
10671 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
10672 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
10674 if ( noFollow
!== this.noFollow
) {
10675 this.noFollow
= noFollow
;
10677 this.$button
.attr( 'rel', 'nofollow' );
10679 this.$button
.removeAttr( 'rel' );
10687 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
10688 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
10691 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
10692 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
10695 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
10698 * @extends OO.ui.ButtonWidget
10699 * @mixins OO.ui.PendingElement
10702 * @param {Object} [config] Configuration options
10703 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
10704 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
10705 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
10706 * for more information about setting modes.
10707 * @cfg {boolean} [framed=false] Render the action button with a frame
10709 OO
.ui
.ActionWidget
= function OoUiActionWidget( config
) {
10710 // Configuration initialization
10711 config
= $.extend( { framed
: false }, config
);
10713 // Parent constructor
10714 OO
.ui
.ActionWidget
.super.call( this, config
);
10716 // Mixin constructors
10717 OO
.ui
.PendingElement
.call( this, config
);
10720 this.action
= config
.action
|| '';
10721 this.modes
= config
.modes
|| [];
10726 this.$element
.addClass( 'oo-ui-actionWidget' );
10731 OO
.inheritClass( OO
.ui
.ActionWidget
, OO
.ui
.ButtonWidget
);
10732 OO
.mixinClass( OO
.ui
.ActionWidget
, OO
.ui
.PendingElement
);
10737 * A resize event is emitted when the size of the widget changes.
10745 * Check if the action is configured to be available in the specified `mode`.
10747 * @param {string} mode Name of mode
10748 * @return {boolean} The action is configured with the mode
10750 OO
.ui
.ActionWidget
.prototype.hasMode = function ( mode
) {
10751 return this.modes
.indexOf( mode
) !== -1;
10755 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
10759 OO
.ui
.ActionWidget
.prototype.getAction = function () {
10760 return this.action
;
10764 * Get the symbolic name of the mode or modes for which the action is configured to be available.
10766 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
10767 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
10770 * @return {string[]}
10772 OO
.ui
.ActionWidget
.prototype.getModes = function () {
10773 return this.modes
.slice();
10777 * Emit a resize event if the size has changed.
10782 OO
.ui
.ActionWidget
.prototype.propagateResize = function () {
10785 if ( this.isElementAttached() ) {
10786 width
= this.$element
.width();
10787 height
= this.$element
.height();
10789 if ( width
!== this.width
|| height
!== this.height
) {
10790 this.width
= width
;
10791 this.height
= height
;
10792 this.emit( 'resize' );
10802 OO
.ui
.ActionWidget
.prototype.setIcon = function () {
10804 OO
.ui
.IconElement
.prototype.setIcon
.apply( this, arguments
);
10805 this.propagateResize();
10813 OO
.ui
.ActionWidget
.prototype.setLabel = function () {
10815 OO
.ui
.LabelElement
.prototype.setLabel
.apply( this, arguments
);
10816 this.propagateResize();
10824 OO
.ui
.ActionWidget
.prototype.setFlags = function () {
10826 OO
.ui
.FlaggedElement
.prototype.setFlags
.apply( this, arguments
);
10827 this.propagateResize();
10835 OO
.ui
.ActionWidget
.prototype.clearFlags = function () {
10837 OO
.ui
.FlaggedElement
.prototype.clearFlags
.apply( this, arguments
);
10838 this.propagateResize();
10844 * Toggle the visibility of the action button.
10846 * @param {boolean} [show] Show button, omit to toggle visibility
10849 OO
.ui
.ActionWidget
.prototype.toggle = function () {
10851 OO
.ui
.ActionWidget
.super.prototype.toggle
.apply( this, arguments
);
10852 this.propagateResize();
10858 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
10859 * which is used to display additional information or options.
10862 * // Example of a popup button.
10863 * var popupButton = new OO.ui.PopupButtonWidget( {
10864 * label: 'Popup button with options',
10867 * $content: $( '<p>Additional options here.</p>' ),
10872 * // Append the button to the DOM.
10873 * $( 'body' ).append( popupButton.$element );
10876 * @extends OO.ui.ButtonWidget
10877 * @mixins OO.ui.PopupElement
10880 * @param {Object} [config] Configuration options
10882 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
10883 // Parent constructor
10884 OO
.ui
.PopupButtonWidget
.super.call( this, config
);
10886 // Mixin constructors
10887 OO
.ui
.PopupElement
.call( this, config
);
10890 this.connect( this, { click
: 'onAction' } );
10894 .addClass( 'oo-ui-popupButtonWidget' )
10895 .attr( 'aria-haspopup', 'true' )
10896 .append( this.popup
.$element
);
10901 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
10902 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.PopupElement
);
10907 * Handle the button action being triggered.
10911 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
10912 this.popup
.toggle();
10916 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
10917 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
10918 * configured with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators},
10919 * {@link OO.ui.TitledElement titles}, {@link OO.ui.FlaggedElement styling flags},
10920 * and {@link OO.ui.LabelElement labels}. Please see
10921 * the [OOjs UI documentation][1] on MediaWiki for more information.
10924 * // Toggle buttons in the 'off' and 'on' state.
10925 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
10926 * label: 'Toggle Button off'
10928 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
10929 * label: 'Toggle Button on',
10932 * // Append the buttons to the DOM.
10933 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
10935 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
10938 * @extends OO.ui.ToggleWidget
10939 * @mixins OO.ui.ButtonElement
10940 * @mixins OO.ui.IconElement
10941 * @mixins OO.ui.IndicatorElement
10942 * @mixins OO.ui.LabelElement
10943 * @mixins OO.ui.TitledElement
10944 * @mixins OO.ui.FlaggedElement
10945 * @mixins OO.ui.TabIndexedElement
10948 * @param {Object} [config] Configuration options
10949 * @cfg {boolean} [value=false] The toggle button’s initial on/off
10950 * state. By default, the button is in the 'off' state.
10952 OO
.ui
.ToggleButtonWidget
= function OoUiToggleButtonWidget( config
) {
10953 // Configuration initialization
10954 config
= config
|| {};
10956 // Parent constructor
10957 OO
.ui
.ToggleButtonWidget
.super.call( this, config
);
10959 // Mixin constructors
10960 OO
.ui
.ButtonElement
.call( this, config
);
10961 OO
.ui
.IconElement
.call( this, config
);
10962 OO
.ui
.IndicatorElement
.call( this, config
);
10963 OO
.ui
.LabelElement
.call( this, config
);
10964 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
10965 OO
.ui
.FlaggedElement
.call( this, config
);
10966 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
10969 this.connect( this, { click
: 'onAction' } );
10972 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
10974 .addClass( 'oo-ui-toggleButtonWidget' )
10975 .append( this.$button
);
10980 OO
.inheritClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ToggleWidget
);
10981 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ButtonElement
);
10982 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.IconElement
);
10983 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.IndicatorElement
);
10984 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.LabelElement
);
10985 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.TitledElement
);
10986 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.FlaggedElement
);
10987 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.TabIndexedElement
);
10992 * Handle the button action being triggered.
10996 OO
.ui
.ToggleButtonWidget
.prototype.onAction = function () {
10997 this.setValue( !this.value
);
11003 OO
.ui
.ToggleButtonWidget
.prototype.setValue = function ( value
) {
11005 if ( value
!== this.value
) {
11006 // Might be called from parent constructor before ButtonElement constructor
11007 if ( this.$button
) {
11008 this.$button
.attr( 'aria-pressed', value
.toString() );
11010 this.setActive( value
);
11014 OO
.ui
.ToggleButtonWidget
.super.prototype.setValue
.call( this, value
);
11022 OO
.ui
.ToggleButtonWidget
.prototype.setButtonElement = function ( $button
) {
11023 if ( this.$button
) {
11024 this.$button
.removeAttr( 'aria-pressed' );
11026 OO
.ui
.ButtonElement
.prototype.setButtonElement
.call( this, $button
);
11027 this.$button
.attr( 'aria-pressed', this.value
.toString() );
11031 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
11032 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
11033 * users can interact with it.
11036 * // Example: A DropdownWidget with a menu that contains three options
11037 * var dropDown = new OO.ui.DropdownWidget( {
11038 * label: 'Dropdown menu: Select a menu option',
11041 * new OO.ui.MenuOptionWidget( {
11045 * new OO.ui.MenuOptionWidget( {
11049 * new OO.ui.MenuOptionWidget( {
11057 * $( 'body' ).append( dropDown.$element );
11059 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
11061 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
11064 * @extends OO.ui.Widget
11065 * @mixins OO.ui.IconElement
11066 * @mixins OO.ui.IndicatorElement
11067 * @mixins OO.ui.LabelElement
11068 * @mixins OO.ui.TitledElement
11069 * @mixins OO.ui.TabIndexedElement
11072 * @param {Object} [config] Configuration options
11073 * @cfg {Object} [menu] Configuration options to pass to menu widget
11075 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
11076 // Configuration initialization
11077 config
= $.extend( { indicator
: 'down' }, config
);
11079 // Parent constructor
11080 OO
.ui
.DropdownWidget
.super.call( this, config
);
11082 // Properties (must be set before TabIndexedElement constructor call)
11083 this.$handle
= this.$( '<span>' );
11085 // Mixin constructors
11086 OO
.ui
.IconElement
.call( this, config
);
11087 OO
.ui
.IndicatorElement
.call( this, config
);
11088 OO
.ui
.LabelElement
.call( this, config
);
11089 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
11090 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
11093 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend( { widget
: this }, config
.menu
) );
11097 click
: this.onClick
.bind( this ),
11098 keypress
: this.onKeyPress
.bind( this )
11100 this.menu
.connect( this, { select
: 'onMenuSelect' } );
11104 .addClass( 'oo-ui-dropdownWidget-handle' )
11105 .append( this.$icon
, this.$label
, this.$indicator
);
11107 .addClass( 'oo-ui-dropdownWidget' )
11108 .append( this.$handle
, this.menu
.$element
);
11113 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
11114 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.IconElement
);
11115 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.IndicatorElement
);
11116 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.LabelElement
);
11117 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.TitledElement
);
11118 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.TabIndexedElement
);
11125 * @return {OO.ui.MenuSelectWidget} Menu of widget
11127 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
11132 * Handles menu select events.
11135 * @param {OO.ui.MenuOptionWidget} item Selected menu item
11137 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
11144 selectedLabel
= item
.getLabel();
11146 // If the label is a DOM element, clone it, because setLabel will append() it
11147 if ( selectedLabel
instanceof jQuery
) {
11148 selectedLabel
= selectedLabel
.clone();
11151 this.setLabel( selectedLabel
);
11155 * Handle mouse click events.
11158 * @param {jQuery.Event} e Mouse click event
11160 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
11161 if ( !this.isDisabled() && e
.which
=== 1 ) {
11162 this.menu
.toggle();
11168 * Handle key press events.
11171 * @param {jQuery.Event} e Key press event
11173 OO
.ui
.DropdownWidget
.prototype.onKeyPress = function ( e
) {
11174 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
11175 this.menu
.toggle();
11181 * IconWidget is a generic widget for {@link OO.ui.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
11182 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
11183 * for a list of icons included in the library.
11186 * // An icon widget with a label
11187 * var myIcon = new OO.ui.IconWidget( {
11189 * iconTitle: 'Help'
11191 * // Create a label.
11192 * var iconLabel = new OO.ui.LabelWidget( {
11195 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
11197 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
11200 * @extends OO.ui.Widget
11201 * @mixins OO.ui.IconElement
11202 * @mixins OO.ui.TitledElement
11203 * @mixins OO.ui.FlaggedElement
11206 * @param {Object} [config] Configuration options
11208 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
11209 // Configuration initialization
11210 config
= config
|| {};
11212 // Parent constructor
11213 OO
.ui
.IconWidget
.super.call( this, config
);
11215 // Mixin constructors
11216 OO
.ui
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
11217 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
11218 OO
.ui
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
11221 this.$element
.addClass( 'oo-ui-iconWidget' );
11226 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
11227 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.IconElement
);
11228 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.TitledElement
);
11229 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.FlaggedElement
);
11231 /* Static Properties */
11233 OO
.ui
.IconWidget
.static.tagName
= 'span';
11236 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
11237 * attention to the status of an item or to clarify the function of a control. For a list of
11238 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
11241 * // Example of an indicator widget
11242 * var indicator1 = new OO.ui.IndicatorWidget( {
11243 * indicator: 'alert'
11246 * // Create a fieldset layout to add a label
11247 * var fieldset = new OO.ui.FieldsetLayout();
11248 * fieldset.addItems( [
11249 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
11251 * $( 'body' ).append( fieldset.$element );
11253 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
11256 * @extends OO.ui.Widget
11257 * @mixins OO.ui.IndicatorElement
11258 * @mixins OO.ui.TitledElement
11261 * @param {Object} [config] Configuration options
11263 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
11264 // Configuration initialization
11265 config
= config
|| {};
11267 // Parent constructor
11268 OO
.ui
.IndicatorWidget
.super.call( this, config
);
11270 // Mixin constructors
11271 OO
.ui
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
11272 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
11275 this.$element
.addClass( 'oo-ui-indicatorWidget' );
11280 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
11281 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.IndicatorElement
);
11282 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.TitledElement
);
11284 /* Static Properties */
11286 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
11289 * InputWidget is the base class for all input widgets, which
11290 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
11291 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
11292 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
11294 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11298 * @extends OO.ui.Widget
11299 * @mixins OO.ui.FlaggedElement
11300 * @mixins OO.ui.TabIndexedElement
11303 * @param {Object} [config] Configuration options
11304 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
11305 * @cfg {string} [value=''] The value of the input.
11306 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
11307 * before it is accepted.
11309 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
11310 // Configuration initialization
11311 config
= config
|| {};
11313 // Parent constructor
11314 OO
.ui
.InputWidget
.super.call( this, config
);
11317 this.$input
= this.getInputElement( config
);
11319 this.inputFilter
= config
.inputFilter
;
11321 // Mixin constructors
11322 OO
.ui
.FlaggedElement
.call( this, config
);
11323 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
11326 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
11330 .attr( 'name', config
.name
)
11331 .prop( 'disabled', this.isDisabled() );
11332 this.$element
.addClass( 'oo-ui-inputWidget' ).append( this.$input
, $( '<span>' ) );
11333 this.setValue( config
.value
);
11338 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
11339 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.FlaggedElement
);
11340 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.TabIndexedElement
);
11347 * A change event is emitted when the value of the input changes.
11349 * @param {string} value
11355 * Get input element.
11357 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
11358 * different circumstances. The element must have a `value` property (like form elements).
11361 * @param {Object} config Configuration options
11362 * @return {jQuery} Input element
11364 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
11365 return $( '<input>' );
11369 * Handle potentially value-changing events.
11372 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
11374 OO
.ui
.InputWidget
.prototype.onEdit = function () {
11376 if ( !this.isDisabled() ) {
11377 // Allow the stack to clear so the value will be updated
11378 setTimeout( function () {
11379 widget
.setValue( widget
.$input
.val() );
11385 * Get the value of the input.
11387 * @return {string} Input value
11389 OO
.ui
.InputWidget
.prototype.getValue = function () {
11390 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
11391 // it, and we won't know unless they're kind enough to trigger a 'change' event.
11392 var value
= this.$input
.val();
11393 if ( this.value
!== value
) {
11394 this.setValue( value
);
11400 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
11402 * @param {boolean} isRTL
11403 * Direction is right-to-left
11405 OO
.ui
.InputWidget
.prototype.setRTL = function ( isRTL
) {
11406 this.$input
.prop( 'dir', isRTL
? 'rtl' : 'ltr' );
11410 * Set the value of the input.
11412 * @param {string} value New value
11416 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
11417 value
= this.cleanUpValue( value
);
11418 // Update the DOM if it has changed. Note that with cleanUpValue, it
11419 // is possible for the DOM value to change without this.value changing.
11420 if ( this.$input
.val() !== value
) {
11421 this.$input
.val( value
);
11423 if ( this.value
!== value
) {
11424 this.value
= value
;
11425 this.emit( 'change', this.value
);
11431 * Clean up incoming value.
11433 * Ensures value is a string, and converts undefined and null to empty string.
11436 * @param {string} value Original value
11437 * @return {string} Cleaned up value
11439 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
11440 if ( value
=== undefined || value
=== null ) {
11442 } else if ( this.inputFilter
) {
11443 return this.inputFilter( String( value
) );
11445 return String( value
);
11450 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
11451 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
11454 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
11455 if ( !this.isDisabled() ) {
11456 if ( this.$input
.is( ':checkbox, :radio' ) ) {
11457 this.$input
.click();
11459 if ( this.$input
.is( ':input' ) ) {
11460 this.$input
[ 0 ].focus();
11468 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
11469 OO
.ui
.InputWidget
.super.prototype.setDisabled
.call( this, state
);
11470 if ( this.$input
) {
11471 this.$input
.prop( 'disabled', this.isDisabled() );
11481 OO
.ui
.InputWidget
.prototype.focus = function () {
11482 this.$input
[ 0 ].focus();
11491 OO
.ui
.InputWidget
.prototype.blur = function () {
11492 this.$input
[ 0 ].blur();
11497 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
11498 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
11499 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
11500 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
11501 * [OOjs UI documentation on MediaWiki] [1] for more information.
11504 * // A ButtonInputWidget rendered as an HTML button, the default.
11505 * var button = new OO.ui.ButtonInputWidget( {
11506 * label: 'Input button',
11510 * $( 'body' ).append( button.$element );
11512 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
11515 * @extends OO.ui.InputWidget
11516 * @mixins OO.ui.ButtonElement
11517 * @mixins OO.ui.IconElement
11518 * @mixins OO.ui.IndicatorElement
11519 * @mixins OO.ui.LabelElement
11520 * @mixins OO.ui.TitledElement
11523 * @param {Object} [config] Configuration options
11524 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
11525 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
11526 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
11527 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
11528 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
11530 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
11531 // Configuration initialization
11532 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
11534 // Properties (must be set before parent constructor, which calls #setValue)
11535 this.useInputTag
= config
.useInputTag
;
11537 // Parent constructor
11538 OO
.ui
.ButtonInputWidget
.super.call( this, config
);
11540 // Mixin constructors
11541 OO
.ui
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
11542 OO
.ui
.IconElement
.call( this, config
);
11543 OO
.ui
.IndicatorElement
.call( this, config
);
11544 OO
.ui
.LabelElement
.call( this, config
);
11545 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
11548 if ( !config
.useInputTag
) {
11549 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
11551 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
11556 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
11557 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.ButtonElement
);
11558 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.IconElement
);
11559 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.IndicatorElement
);
11560 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.LabelElement
);
11561 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.TitledElement
);
11569 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
11570 var html
= '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + config
.type
+ '">';
11577 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
11579 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
11580 * text, or `null` for no label
11583 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
11584 OO
.ui
.LabelElement
.prototype.setLabel
.call( this, label
);
11586 if ( this.useInputTag
) {
11587 if ( typeof label
=== 'function' ) {
11588 label
= OO
.ui
.resolveMsg( label
);
11590 if ( label
instanceof jQuery
) {
11591 label
= label
.text();
11596 this.$input
.val( label
);
11603 * Set the value of the input.
11605 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
11606 * they do not support {@link #value values}.
11608 * @param {string} value New value
11611 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
11612 if ( !this.useInputTag
) {
11613 OO
.ui
.ButtonInputWidget
.super.prototype.setValue
.call( this, value
);
11619 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
11620 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
11621 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
11622 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
11624 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
11627 * // An example of selected, unselected, and disabled checkbox inputs
11628 * var checkbox1=new OO.ui.CheckboxInputWidget( {
11632 * var checkbox2=new OO.ui.CheckboxInputWidget( {
11635 * var checkbox3=new OO.ui.CheckboxInputWidget( {
11639 * // Create a fieldset layout with fields for each checkbox.
11640 * var fieldset = new OO.ui.FieldsetLayout( {
11641 * label: 'Checkboxes'
11643 * fieldset.addItems( [
11644 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
11645 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
11646 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
11648 * $( 'body' ).append( fieldset.$element );
11650 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11653 * @extends OO.ui.InputWidget
11656 * @param {Object} [config] Configuration options
11657 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
11659 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
11660 // Configuration initialization
11661 config
= config
|| {};
11663 // Parent constructor
11664 OO
.ui
.CheckboxInputWidget
.super.call( this, config
);
11667 this.$element
.addClass( 'oo-ui-checkboxInputWidget' );
11668 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
11673 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
11681 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
11682 return $( '<input type="checkbox" />' );
11688 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
11690 if ( !this.isDisabled() ) {
11691 // Allow the stack to clear so the value will be updated
11692 setTimeout( function () {
11693 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
11699 * Set selection state of this checkbox.
11701 * @param {boolean} state `true` for selected
11704 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
11706 if ( this.selected
!== state
) {
11707 this.selected
= state
;
11708 this.$input
.prop( 'checked', this.selected
);
11709 this.emit( 'change', this.selected
);
11715 * Check if this checkbox is selected.
11717 * @return {boolean} Checkbox is selected
11719 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
11720 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
11721 // it, and we won't know unless they're kind enough to trigger a 'change' event.
11722 var selected
= this.$input
.prop( 'checked' );
11723 if ( this.selected
!== selected
) {
11724 this.setSelected( selected
);
11726 return this.selected
;
11730 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
11731 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
11732 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
11733 * more information about input widgets.
11736 * // Example: A DropdownInputWidget with three options
11737 * var dropDown = new OO.ui.DropdownInputWidget( {
11738 * label: 'Dropdown menu: Select a menu option',
11740 * { data: 'a', label: 'First' } ,
11741 * { data: 'b', label: 'Second'} ,
11742 * { data: 'c', label: 'Third' }
11745 * $( 'body' ).append( dropDown.$element );
11747 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11750 * @extends OO.ui.InputWidget
11753 * @param {Object} [config] Configuration options
11754 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11756 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
11757 // Configuration initialization
11758 config
= config
|| {};
11760 // Properties (must be done before parent constructor which calls #setDisabled)
11761 this.dropdownWidget
= new OO
.ui
.DropdownWidget();
11763 // Parent constructor
11764 OO
.ui
.DropdownInputWidget
.super.call( this, config
);
11767 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
11770 this.setOptions( config
.options
|| [] );
11772 .addClass( 'oo-ui-dropdownInputWidget' )
11773 .append( this.dropdownWidget
.$element
);
11778 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
11786 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
11787 return $( '<input type="hidden">' );
11791 * Handles menu select events.
11794 * @param {OO.ui.MenuOptionWidget} item Selected menu item
11796 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
11797 this.setValue( item
.getData() );
11803 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
11804 var item
= this.dropdownWidget
.getMenu().getItemFromData( value
);
11806 this.dropdownWidget
.getMenu().selectItem( item
);
11808 OO
.ui
.DropdownInputWidget
.super.prototype.setValue
.call( this, value
);
11815 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
11816 this.dropdownWidget
.setDisabled( state
);
11817 OO
.ui
.DropdownInputWidget
.super.prototype.setDisabled
.call( this, state
);
11822 * Set the options available for this input.
11824 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11827 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
11828 var value
= this.getValue();
11830 // Rebuild the dropdown menu
11831 this.dropdownWidget
.getMenu()
11833 .addItems( options
.map( function ( opt
) {
11834 return new OO
.ui
.MenuOptionWidget( {
11836 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
11840 // Restore the previous value, or reset to something sensible
11841 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
11842 // Previous value is still available, ensure consistency with the dropdown
11843 this.setValue( value
);
11845 // No longer valid, reset
11846 if ( options
.length
) {
11847 this.setValue( options
[ 0 ].data
);
11857 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
11858 this.dropdownWidget
.getMenu().toggle( true );
11865 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
11866 this.dropdownWidget
.getMenu().toggle( false );
11871 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
11872 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
11873 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
11874 * please see the [OOjs UI documentation on MediaWiki][1].
11876 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
11879 * // An example of selected, unselected, and disabled radio inputs
11880 * var radio1 = new OO.ui.RadioInputWidget( {
11884 * var radio2 = new OO.ui.RadioInputWidget( {
11887 * var radio3 = new OO.ui.RadioInputWidget( {
11891 * // Create a fieldset layout with fields for each radio button.
11892 * var fieldset = new OO.ui.FieldsetLayout( {
11893 * label: 'Radio inputs'
11895 * fieldset.addItems( [
11896 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
11897 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
11898 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
11900 * $( 'body' ).append( fieldset.$element );
11902 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11905 * @extends OO.ui.InputWidget
11908 * @param {Object} [config] Configuration options
11909 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
11911 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
11912 // Configuration initialization
11913 config
= config
|| {};
11915 // Parent constructor
11916 OO
.ui
.RadioInputWidget
.super.call( this, config
);
11919 this.$element
.addClass( 'oo-ui-radioInputWidget' );
11920 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
11925 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
11933 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
11934 return $( '<input type="radio" />' );
11940 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
11941 // RadioInputWidget doesn't track its state.
11945 * Set selection state of this radio button.
11947 * @param {boolean} state `true` for selected
11950 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
11951 // RadioInputWidget doesn't track its state.
11952 this.$input
.prop( 'checked', state
);
11957 * Check if this radio button is selected.
11959 * @return {boolean} Radio is selected
11961 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
11962 return this.$input
.prop( 'checked' );
11966 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
11967 * size of the field as well as its presentation. In addition, these widgets can be configured
11968 * with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators}, an optional
11969 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
11970 * which modifies incoming values rather than validating them.
11971 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
11973 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
11976 * // Example of a text input widget
11977 * var textInput = new OO.ui.TextInputWidget( {
11978 * value: 'Text input'
11980 * $( 'body' ).append( textInput.$element );
11982 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11985 * @extends OO.ui.InputWidget
11986 * @mixins OO.ui.IconElement
11987 * @mixins OO.ui.IndicatorElement
11988 * @mixins OO.ui.PendingElement
11989 * @mixins OO.ui.LabelElement
11992 * @param {Object} [config] Configuration options
11993 * @cfg {string} [type='text'] The value of the HTML `type` attribute
11994 * @cfg {string} [placeholder] Placeholder text
11995 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
11996 * instruct the browser to focus this widget.
11997 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
11998 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
11999 * @cfg {boolean} [multiline=false] Allow multiple lines of text
12000 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
12001 * Use the #maxRows config to specify a maximum number of displayed rows.
12002 * @cfg {boolean} [maxRows=10] Maximum number of rows to display when #autosize is set to true.
12003 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
12004 * the value or placeholder text: `'before'` or `'after'`
12005 * @cfg {boolean} [required=false] Mark the field as required
12006 * @cfg {RegExp|string} [validate] Validation pattern, either a regular expression or the
12007 * symbolic name of a pattern defined by the class: 'non-empty' (the value cannot be an empty string)
12008 * or 'integer' (the value must contain only numbers).
12010 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
12011 // Configuration initialization
12012 config
= $.extend( {
12014 labelPosition
: 'after',
12018 // Parent constructor
12019 OO
.ui
.TextInputWidget
.super.call( this, config
);
12021 // Mixin constructors
12022 OO
.ui
.IconElement
.call( this, config
);
12023 OO
.ui
.IndicatorElement
.call( this, config
);
12024 OO
.ui
.PendingElement
.call( this, config
);
12025 OO
.ui
.LabelElement
.call( this, config
);
12028 this.readOnly
= false;
12029 this.multiline
= !!config
.multiline
;
12030 this.autosize
= !!config
.autosize
;
12031 this.maxRows
= config
.maxRows
;
12032 this.validate
= null;
12034 // Clone for resizing
12035 if ( this.autosize
) {
12036 this.$clone
= this.$input
12038 .insertAfter( this.$input
)
12039 .attr( 'aria-hidden', 'true' )
12040 .addClass( 'oo-ui-element-hidden' );
12043 this.setValidation( config
.validate
);
12044 this.setLabelPosition( config
.labelPosition
);
12048 keypress
: this.onKeyPress
.bind( this ),
12049 blur
: this.setValidityFlag
.bind( this )
12052 focus
: this.onElementAttach
.bind( this )
12054 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
12055 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
12056 this.on( 'labelChange', this.updatePosition
.bind( this ) );
12060 .addClass( 'oo-ui-textInputWidget' )
12061 .append( this.$icon
, this.$indicator
);
12062 this.setReadOnly( !!config
.readOnly
);
12063 if ( config
.placeholder
) {
12064 this.$input
.attr( 'placeholder', config
.placeholder
);
12066 if ( config
.maxLength
!== undefined ) {
12067 this.$input
.attr( 'maxlength', config
.maxLength
);
12069 if ( config
.autofocus
) {
12070 this.$input
.attr( 'autofocus', 'autofocus' );
12072 if ( config
.required
) {
12073 this.$input
.attr( 'required', 'true' );
12075 if ( this.label
|| config
.autosize
) {
12076 this.installParentChangeDetector();
12082 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
12083 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.IconElement
);
12084 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.IndicatorElement
);
12085 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.PendingElement
);
12086 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.LabelElement
);
12088 /* Static properties */
12090 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
12098 * An `enter` event is emitted when the user presses 'enter' inside the text box.
12100 * Not emitted if the input is multiline.
12108 * Handle icon mouse down events.
12111 * @param {jQuery.Event} e Mouse down event
12114 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
12115 if ( e
.which
=== 1 ) {
12116 this.$input
[ 0 ].focus();
12122 * Handle indicator mouse down events.
12125 * @param {jQuery.Event} e Mouse down event
12128 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
12129 if ( e
.which
=== 1 ) {
12130 this.$input
[ 0 ].focus();
12136 * Handle key press events.
12139 * @param {jQuery.Event} e Key press event
12140 * @fires enter If enter key is pressed and input is not multiline
12142 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
12143 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
12144 this.emit( 'enter', e
);
12149 * Handle element attach events.
12152 * @param {jQuery.Event} e Element attach event
12154 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
12155 // Any previously calculated size is now probably invalid if we reattached elsewhere
12156 this.valCache
= null;
12158 this.positionLabel();
12164 OO
.ui
.TextInputWidget
.prototype.onEdit = function () {
12168 return OO
.ui
.TextInputWidget
.super.prototype.onEdit
.call( this );
12174 OO
.ui
.TextInputWidget
.prototype.setValue = function ( value
) {
12176 OO
.ui
.TextInputWidget
.super.prototype.setValue
.call( this, value
);
12178 this.setValidityFlag();
12184 * Check if the input is {@link #readOnly read-only}.
12186 * @return {boolean}
12188 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
12189 return this.readOnly
;
12193 * Set the {@link #readOnly read-only} state of the input.
12195 * @param {boolean} state Make input read-only
12198 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
12199 this.readOnly
= !!state
;
12200 this.$input
.prop( 'readOnly', this.readOnly
);
12205 * Support function for making #onElementAttach work across browsers.
12207 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
12208 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
12210 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
12211 * first time that the element gets attached to the documented.
12213 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
12214 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
12215 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
12218 if ( MutationObserver
) {
12219 // The new way. If only it wasn't so ugly.
12221 if ( this.$element
.closest( 'html' ).length
) {
12222 // Widget is attached already, do nothing. This breaks the functionality of this function when
12223 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
12224 // would require observation of the whole document, which would hurt performance of other,
12225 // more important code.
12229 // Find topmost node in the tree
12230 topmostNode
= this.$element
[0];
12231 while ( topmostNode
.parentNode
) {
12232 topmostNode
= topmostNode
.parentNode
;
12235 // We have no way to detect the $element being attached somewhere without observing the entire
12236 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
12237 // parent node of $element, and instead detect when $element is removed from it (and thus
12238 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
12239 // doesn't get attached, we end up back here and create the parent.
12241 mutationObserver
= new MutationObserver( function ( mutations
) {
12242 var i
, j
, removedNodes
;
12243 for ( i
= 0; i
< mutations
.length
; i
++ ) {
12244 removedNodes
= mutations
[ i
].removedNodes
;
12245 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
12246 if ( removedNodes
[ j
] === topmostNode
) {
12247 setTimeout( onRemove
, 0 );
12254 onRemove = function () {
12255 // If the node was attached somewhere else, report it
12256 if ( widget
.$element
.closest( 'html' ).length
) {
12257 widget
.onElementAttach();
12259 mutationObserver
.disconnect();
12260 widget
.installParentChangeDetector();
12263 // Create a fake parent and observe it
12264 fakeParentNode
= $( '<div>' ).append( this.$element
)[0];
12265 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
12267 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
12268 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
12269 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
12274 * Automatically adjust the size of the text input.
12276 * This only affects #multiline inputs that are {@link #autosize autosized}.
12280 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
12281 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
, idealHeight
;
12283 if ( this.multiline
&& this.autosize
&& this.$input
.val() !== this.valCache
) {
12285 .val( this.$input
.val() )
12286 .attr( 'rows', '' )
12287 // Set inline height property to 0 to measure scroll height
12288 .css( 'height', 0 );
12290 this.$clone
.removeClass( 'oo-ui-element-hidden' );
12292 this.valCache
= this.$input
.val();
12294 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
12296 // Remove inline height property to measure natural heights
12297 this.$clone
.css( 'height', '' );
12298 innerHeight
= this.$clone
.innerHeight();
12299 outerHeight
= this.$clone
.outerHeight();
12301 // Measure max rows height
12303 .attr( 'rows', this.maxRows
)
12304 .css( 'height', 'auto' )
12306 maxInnerHeight
= this.$clone
.innerHeight();
12308 // Difference between reported innerHeight and scrollHeight with no scrollbars present
12309 // Equals 1 on Blink-based browsers and 0 everywhere else
12310 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
12311 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
12313 this.$clone
.addClass( 'oo-ui-element-hidden' );
12315 // Only apply inline height when expansion beyond natural height is needed
12316 if ( idealHeight
> innerHeight
) {
12317 // Use the difference between the inner and outer height as a buffer
12318 this.$input
.css( 'height', idealHeight
+ ( outerHeight
- innerHeight
) );
12320 this.$input
.css( 'height', '' );
12330 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
12331 return config
.multiline
? $( '<textarea>' ) : $( '<input type="' + config
.type
+ '" />' );
12335 * Check if the input supports multiple lines.
12337 * @return {boolean}
12339 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
12340 return !!this.multiline
;
12344 * Check if the input automatically adjusts its size.
12346 * @return {boolean}
12348 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
12349 return !!this.autosize
;
12353 * Select the entire text of the input.
12357 OO
.ui
.TextInputWidget
.prototype.select = function () {
12358 this.$input
.select();
12363 * Set the validation pattern.
12365 * The validation pattern is either a regular expression or the symbolic name of a pattern
12366 * defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
12367 * value must contain only numbers).
12369 * @param {RegExp|string|null} validate Regular expression or the symbolic name of a
12370 * pattern (either ‘integer’ or ‘non-empty’) defined by the class.
12372 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
12373 if ( validate
instanceof RegExp
) {
12374 this.validate
= validate
;
12376 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
12381 * Sets the 'invalid' flag appropriately.
12383 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function () {
12385 this.isValid().done( function ( valid
) {
12386 widget
.setFlags( { invalid
: !valid
} );
12391 * Check if a value is valid.
12393 * This method returns a promise that resolves with a boolean `true` if the current value is
12394 * considered valid according to the supplied {@link #validate validation pattern}.
12396 * @return {jQuery.Deferred} A promise that resolves to a boolean `true` if the value is valid.
12398 OO
.ui
.TextInputWidget
.prototype.isValid = function () {
12399 return $.Deferred().resolve( !!this.getValue().match( this.validate
) ).promise();
12403 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
12405 * @param {string} labelPosition Label position, 'before' or 'after'
12408 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
12409 this.labelPosition
= labelPosition
;
12410 this.updatePosition();
12415 * Deprecated alias of #setLabelPosition
12417 * @deprecated Use setLabelPosition instead.
12419 OO
.ui
.TextInputWidget
.prototype.setPosition
=
12420 OO
.ui
.TextInputWidget
.prototype.setLabelPosition
;
12423 * Update the position of the inline label.
12425 * This method is called by #setLabelPosition, and can also be called on its own if
12426 * something causes the label to be mispositioned.
12431 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
12432 var after
= this.labelPosition
=== 'after';
12435 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
12436 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
12438 if ( this.label
) {
12439 this.positionLabel();
12446 * Position the label by setting the correct padding on the input.
12451 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
12452 // Clear old values
12454 // Clear old values if present
12456 'padding-right': '',
12460 if ( this.label
) {
12461 this.$element
.append( this.$label
);
12463 this.$label
.detach();
12467 var after
= this.labelPosition
=== 'after',
12468 rtl
= this.$element
.css( 'direction' ) === 'rtl',
12469 property
= after
=== rtl
? 'padding-left' : 'padding-right';
12471 this.$input
.css( property
, this.$label
.outerWidth( true ) );
12477 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
12478 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
12479 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
12481 * - by typing a value in the text input field. If the value exactly matches the value of a menu
12482 * option, that option will appear to be selected.
12483 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
12486 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
12489 * // Example: A ComboBoxWidget.
12490 * var comboBox = new OO.ui.ComboBoxWidget( {
12491 * label: 'ComboBoxWidget',
12492 * input: { value: 'Option One' },
12495 * new OO.ui.MenuOptionWidget( {
12496 * data: 'Option 1',
12497 * label: 'Option One'
12499 * new OO.ui.MenuOptionWidget( {
12500 * data: 'Option 2',
12501 * label: 'Option Two'
12503 * new OO.ui.MenuOptionWidget( {
12504 * data: 'Option 3',
12505 * label: 'Option Three'
12507 * new OO.ui.MenuOptionWidget( {
12508 * data: 'Option 4',
12509 * label: 'Option Four'
12511 * new OO.ui.MenuOptionWidget( {
12512 * data: 'Option 5',
12513 * label: 'Option Five'
12518 * $( 'body' ).append( comboBox.$element );
12520 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12523 * @extends OO.ui.Widget
12524 * @mixins OO.ui.TabIndexedElement
12527 * @param {Object} [config] Configuration options
12528 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
12529 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
12530 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
12531 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
12532 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
12534 OO
.ui
.ComboBoxWidget
= function OoUiComboBoxWidget( config
) {
12535 // Configuration initialization
12536 config
= config
|| {};
12538 // Parent constructor
12539 OO
.ui
.ComboBoxWidget
.super.call( this, config
);
12541 // Properties (must be set before TabIndexedElement constructor call)
12542 this.$indicator
= this.$( '<span>' );
12544 // Mixin constructors
12545 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
12548 this.$overlay
= config
.$overlay
|| this.$element
;
12549 this.input
= new OO
.ui
.TextInputWidget( $.extend(
12552 $indicator
: this.$indicator
,
12553 disabled
: this.isDisabled()
12557 this.input
.$input
.eq( 0 ).attr( {
12559 'aria-autocomplete': 'list'
12561 this.menu
= new OO
.ui
.TextInputMenuSelectWidget( this.input
, $.extend(
12565 disabled
: this.isDisabled()
12571 this.$indicator
.on( {
12572 click
: this.onClick
.bind( this ),
12573 keypress
: this.onKeyPress
.bind( this )
12575 this.input
.connect( this, {
12576 change
: 'onInputChange',
12577 enter
: 'onInputEnter'
12579 this.menu
.connect( this, {
12580 choose
: 'onMenuChoose',
12581 add
: 'onMenuItemsChange',
12582 remove
: 'onMenuItemsChange'
12586 this.$element
.addClass( 'oo-ui-comboBoxWidget' ).append( this.input
.$element
);
12587 this.$overlay
.append( this.menu
.$element
);
12588 this.onMenuItemsChange();
12593 OO
.inheritClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.Widget
);
12594 OO
.mixinClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.TabIndexedElement
);
12599 * Get the combobox's menu.
12600 * @return {OO.ui.TextInputMenuSelectWidget} Menu widget
12602 OO
.ui
.ComboBoxWidget
.prototype.getMenu = function () {
12607 * Handle input change events.
12610 * @param {string} value New value
12612 OO
.ui
.ComboBoxWidget
.prototype.onInputChange = function ( value
) {
12613 var match
= this.menu
.getItemFromData( value
);
12615 this.menu
.selectItem( match
);
12616 if ( this.menu
.getHighlightedItem() ) {
12617 this.menu
.highlightItem( match
);
12620 if ( !this.isDisabled() ) {
12621 this.menu
.toggle( true );
12626 * Handle mouse click events.
12630 * @param {jQuery.Event} e Mouse click event
12632 OO
.ui
.ComboBoxWidget
.prototype.onClick = function ( e
) {
12633 if ( !this.isDisabled() && e
.which
=== 1 ) {
12634 this.menu
.toggle();
12635 this.input
.$input
[ 0 ].focus();
12641 * Handle key press events.
12645 * @param {jQuery.Event} e Key press event
12647 OO
.ui
.ComboBoxWidget
.prototype.onKeyPress = function ( e
) {
12648 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
12649 this.menu
.toggle();
12650 this.input
.$input
[ 0 ].focus();
12656 * Handle input enter events.
12660 OO
.ui
.ComboBoxWidget
.prototype.onInputEnter = function () {
12661 if ( !this.isDisabled() ) {
12662 this.menu
.toggle( false );
12667 * Handle menu choose events.
12670 * @param {OO.ui.OptionWidget} item Chosen item
12672 OO
.ui
.ComboBoxWidget
.prototype.onMenuChoose = function ( item
) {
12673 this.input
.setValue( item
.getData() );
12677 * Handle menu item change events.
12681 OO
.ui
.ComboBoxWidget
.prototype.onMenuItemsChange = function () {
12682 var match
= this.menu
.getItemFromData( this.input
.getValue() );
12683 this.menu
.selectItem( match
);
12684 if ( this.menu
.getHighlightedItem() ) {
12685 this.menu
.highlightItem( match
);
12687 this.$element
.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu
.isEmpty() );
12693 OO
.ui
.ComboBoxWidget
.prototype.setDisabled = function ( disabled
) {
12695 OO
.ui
.ComboBoxWidget
.super.prototype.setDisabled
.call( this, disabled
);
12697 if ( this.input
) {
12698 this.input
.setDisabled( this.isDisabled() );
12701 this.menu
.setDisabled( this.isDisabled() );
12708 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
12709 * be configured with a `label` option that is set to a string, a label node, or a function:
12711 * - String: a plaintext string
12712 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
12713 * label that includes a link or special styling, such as a gray color or additional graphical elements.
12714 * - Function: a function that will produce a string in the future. Functions are used
12715 * in cases where the value of the label is not currently defined.
12717 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
12718 * will come into focus when the label is clicked.
12721 * // Examples of LabelWidgets
12722 * var label1 = new OO.ui.LabelWidget( {
12723 * label: 'plaintext label'
12725 * var label2 = new OO.ui.LabelWidget( {
12726 * label: $( '<a href="default.html">jQuery label</a>' )
12728 * // Create a fieldset layout with fields for each example
12729 * var fieldset = new OO.ui.FieldsetLayout();
12730 * fieldset.addItems( [
12731 * new OO.ui.FieldLayout( label1 ),
12732 * new OO.ui.FieldLayout( label2 )
12734 * $( 'body' ).append( fieldset.$element );
12738 * @extends OO.ui.Widget
12739 * @mixins OO.ui.LabelElement
12742 * @param {Object} [config] Configuration options
12743 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
12744 * Clicking the label will focus the specified input field.
12746 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
12747 // Configuration initialization
12748 config
= config
|| {};
12750 // Parent constructor
12751 OO
.ui
.LabelWidget
.super.call( this, config
);
12753 // Mixin constructors
12754 OO
.ui
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
12755 OO
.ui
.TitledElement
.call( this, config
);
12758 this.input
= config
.input
;
12761 if ( this.input
instanceof OO
.ui
.InputWidget
) {
12762 this.$element
.on( 'click', this.onClick
.bind( this ) );
12766 this.$element
.addClass( 'oo-ui-labelWidget' );
12771 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
12772 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.LabelElement
);
12773 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.TitledElement
);
12775 /* Static Properties */
12777 OO
.ui
.LabelWidget
.static.tagName
= 'span';
12782 * Handles label mouse click events.
12785 * @param {jQuery.Event} e Mouse click event
12787 OO
.ui
.LabelWidget
.prototype.onClick = function () {
12788 this.input
.simulateLabelClick();
12793 * OptionWidgets are special elements that can be selected and configured with data. The
12794 * data is often unique for each option, but it does not have to be. OptionWidgets are used
12795 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
12796 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
12798 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
12801 * @extends OO.ui.Widget
12802 * @mixins OO.ui.LabelElement
12803 * @mixins OO.ui.FlaggedElement
12806 * @param {Object} [config] Configuration options
12808 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
12809 // Configuration initialization
12810 config
= config
|| {};
12812 // Parent constructor
12813 OO
.ui
.OptionWidget
.super.call( this, config
);
12815 // Mixin constructors
12816 OO
.ui
.ItemWidget
.call( this );
12817 OO
.ui
.LabelElement
.call( this, config
);
12818 OO
.ui
.FlaggedElement
.call( this, config
);
12821 this.selected
= false;
12822 this.highlighted
= false;
12823 this.pressed
= false;
12827 .data( 'oo-ui-optionWidget', this )
12828 .attr( 'role', 'option' )
12829 .addClass( 'oo-ui-optionWidget' )
12830 .append( this.$label
);
12835 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
12836 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.ItemWidget
);
12837 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.LabelElement
);
12838 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.FlaggedElement
);
12840 /* Static Properties */
12842 OO
.ui
.OptionWidget
.static.selectable
= true;
12844 OO
.ui
.OptionWidget
.static.highlightable
= true;
12846 OO
.ui
.OptionWidget
.static.pressable
= true;
12848 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
12853 * Check if the option can be selected.
12855 * @return {boolean} Item is selectable
12857 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
12858 return this.constructor.static.selectable
&& !this.isDisabled();
12862 * Check if the option can be highlighted. A highlight indicates that the option
12863 * may be selected when a user presses enter or clicks. Disabled items cannot
12866 * @return {boolean} Item is highlightable
12868 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
12869 return this.constructor.static.highlightable
&& !this.isDisabled();
12873 * Check if the option can be pressed. The pressed state occurs when a user mouses
12874 * down on an item, but has not yet let go of the mouse.
12876 * @return {boolean} Item is pressable
12878 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
12879 return this.constructor.static.pressable
&& !this.isDisabled();
12883 * Check if the option is selected.
12885 * @return {boolean} Item is selected
12887 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
12888 return this.selected
;
12892 * Check if the option is highlighted. A highlight indicates that the
12893 * item may be selected when a user presses enter or clicks.
12895 * @return {boolean} Item is highlighted
12897 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
12898 return this.highlighted
;
12902 * Check if the option is pressed. The pressed state occurs when a user mouses
12903 * down on an item, but has not yet let go of the mouse. The item may appear
12904 * selected, but it will not be selected until the user releases the mouse.
12906 * @return {boolean} Item is pressed
12908 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
12909 return this.pressed
;
12913 * Set the option’s selected state. In general, all modifications to the selection
12914 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
12915 * method instead of this method.
12917 * @param {boolean} [state=false] Select option
12920 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
12921 if ( this.constructor.static.selectable
) {
12922 this.selected
= !!state
;
12924 .toggleClass( 'oo-ui-optionWidget-selected', state
)
12925 .attr( 'aria-selected', state
.toString() );
12926 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
12927 this.scrollElementIntoView();
12929 this.updateThemeClasses();
12935 * Set the option’s highlighted state. In general, all programmatic
12936 * modifications to the highlight should be handled by the
12937 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
12938 * method instead of this method.
12940 * @param {boolean} [state=false] Highlight option
12943 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
12944 if ( this.constructor.static.highlightable
) {
12945 this.highlighted
= !!state
;
12946 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
12947 this.updateThemeClasses();
12953 * Set the option’s pressed state. In general, all
12954 * programmatic modifications to the pressed state should be handled by the
12955 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
12956 * method instead of this method.
12958 * @param {boolean} [state=false] Press option
12961 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
12962 if ( this.constructor.static.pressable
) {
12963 this.pressed
= !!state
;
12964 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
12965 this.updateThemeClasses();
12971 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
12972 * with an {@link OO.ui.IconElement icon} and/or {@link OO.ui.IndicatorElement indicator}.
12973 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
12974 * options. For more information about options and selects, please see the
12975 * [OOjs UI documentation on MediaWiki][1].
12978 * // Decorated options in a select widget
12979 * var select = new OO.ui.SelectWidget( {
12981 * new OO.ui.DecoratedOptionWidget( {
12983 * label: 'Option with icon',
12986 * new OO.ui.DecoratedOptionWidget( {
12988 * label: 'Option with indicator',
12989 * indicator: 'next'
12993 * $( 'body' ).append( select.$element );
12995 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
12998 * @extends OO.ui.OptionWidget
12999 * @mixins OO.ui.IconElement
13000 * @mixins OO.ui.IndicatorElement
13003 * @param {Object} [config] Configuration options
13005 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
13006 // Parent constructor
13007 OO
.ui
.DecoratedOptionWidget
.super.call( this, config
);
13009 // Mixin constructors
13010 OO
.ui
.IconElement
.call( this, config
);
13011 OO
.ui
.IndicatorElement
.call( this, config
);
13015 .addClass( 'oo-ui-decoratedOptionWidget' )
13016 .prepend( this.$icon
)
13017 .append( this.$indicator
);
13022 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
13023 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.IconElement
);
13024 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.IndicatorElement
);
13027 * ButtonOptionWidget is a special type of {@link OO.ui.ButtonElement button element} that
13028 * can be selected and configured with data. The class is
13029 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
13030 * [OOjs UI documentation on MediaWiki] [1] for more information.
13032 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
13035 * @extends OO.ui.DecoratedOptionWidget
13036 * @mixins OO.ui.ButtonElement
13037 * @mixins OO.ui.TabIndexedElement
13040 * @param {Object} [config] Configuration options
13042 OO
.ui
.ButtonOptionWidget
= function OoUiButtonOptionWidget( config
) {
13043 // Configuration initialization
13044 config
= $.extend( { tabIndex
: -1 }, config
);
13046 // Parent constructor
13047 OO
.ui
.ButtonOptionWidget
.super.call( this, config
);
13049 // Mixin constructors
13050 OO
.ui
.ButtonElement
.call( this, config
);
13051 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
13054 this.$element
.addClass( 'oo-ui-buttonOptionWidget' );
13055 this.$button
.append( this.$element
.contents() );
13056 this.$element
.append( this.$button
);
13061 OO
.inheritClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
13062 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.ButtonElement
);
13063 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.TabIndexedElement
);
13065 /* Static Properties */
13067 // Allow button mouse down events to pass through so they can be handled by the parent select widget
13068 OO
.ui
.ButtonOptionWidget
.static.cancelButtonMouseDownEvents
= false;
13070 OO
.ui
.ButtonOptionWidget
.static.highlightable
= false;
13077 OO
.ui
.ButtonOptionWidget
.prototype.setSelected = function ( state
) {
13078 OO
.ui
.ButtonOptionWidget
.super.prototype.setSelected
.call( this, state
);
13080 if ( this.constructor.static.selectable
) {
13081 this.setActive( state
);
13088 * RadioOptionWidget is an option widget that looks like a radio button.
13089 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
13090 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
13092 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
13095 * @extends OO.ui.OptionWidget
13098 * @param {Object} [config] Configuration options
13100 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
13101 // Configuration initialization
13102 config
= config
|| {};
13104 // Properties (must be done before parent constructor which calls #setDisabled)
13105 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
13107 // Parent constructor
13108 OO
.ui
.RadioOptionWidget
.super.call( this, config
);
13112 .addClass( 'oo-ui-radioOptionWidget' )
13113 .prepend( this.radio
.$element
);
13118 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
13120 /* Static Properties */
13122 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
13124 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
13126 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
13128 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
13135 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
13136 OO
.ui
.RadioOptionWidget
.super.prototype.setSelected
.call( this, state
);
13138 this.radio
.setSelected( state
);
13146 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
13147 OO
.ui
.RadioOptionWidget
.super.prototype.setDisabled
.call( this, disabled
);
13149 this.radio
.setDisabled( this.isDisabled() );
13155 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
13156 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
13157 * the [OOjs UI documentation on MediaWiki] [1] for more information.
13159 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13162 * @extends OO.ui.DecoratedOptionWidget
13165 * @param {Object} [config] Configuration options
13167 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
13168 // Configuration initialization
13169 config
= $.extend( { icon
: 'check' }, config
);
13171 // Parent constructor
13172 OO
.ui
.MenuOptionWidget
.super.call( this, config
);
13176 .attr( 'role', 'menuitem' )
13177 .addClass( 'oo-ui-menuOptionWidget' );
13182 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
13184 /* Static Properties */
13186 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
13189 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
13190 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
13193 * var myDropdown = new OO.ui.DropdownWidget( {
13196 * new OO.ui.MenuSectionOptionWidget( {
13199 * new OO.ui.MenuOptionWidget( {
13201 * label: 'Welsh Corgi'
13203 * new OO.ui.MenuOptionWidget( {
13205 * label: 'Standard Poodle'
13207 * new OO.ui.MenuSectionOptionWidget( {
13210 * new OO.ui.MenuOptionWidget( {
13217 * $( 'body' ).append( myDropdown.$element );
13221 * @extends OO.ui.DecoratedOptionWidget
13224 * @param {Object} [config] Configuration options
13226 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
13227 // Parent constructor
13228 OO
.ui
.MenuSectionOptionWidget
.super.call( this, config
);
13231 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
13236 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
13238 /* Static Properties */
13240 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
13242 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
13245 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
13247 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
13248 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
13252 * @extends OO.ui.DecoratedOptionWidget
13255 * @param {Object} [config] Configuration options
13256 * @cfg {number} [level] Indentation level
13257 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
13259 OO
.ui
.OutlineOptionWidget
= function OoUiOutlineOptionWidget( config
) {
13260 // Configuration initialization
13261 config
= config
|| {};
13263 // Parent constructor
13264 OO
.ui
.OutlineOptionWidget
.super.call( this, config
);
13268 this.movable
= !!config
.movable
;
13269 this.removable
= !!config
.removable
;
13272 this.$element
.addClass( 'oo-ui-outlineOptionWidget' );
13273 this.setLevel( config
.level
);
13278 OO
.inheritClass( OO
.ui
.OutlineOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
13280 /* Static Properties */
13282 OO
.ui
.OutlineOptionWidget
.static.highlightable
= false;
13284 OO
.ui
.OutlineOptionWidget
.static.scrollIntoViewOnSelect
= true;
13286 OO
.ui
.OutlineOptionWidget
.static.levelClass
= 'oo-ui-outlineOptionWidget-level-';
13288 OO
.ui
.OutlineOptionWidget
.static.levels
= 3;
13293 * Check if item is movable.
13295 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13297 * @return {boolean} Item is movable
13299 OO
.ui
.OutlineOptionWidget
.prototype.isMovable = function () {
13300 return this.movable
;
13304 * Check if item is removable.
13306 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13308 * @return {boolean} Item is removable
13310 OO
.ui
.OutlineOptionWidget
.prototype.isRemovable = function () {
13311 return this.removable
;
13315 * Get indentation level.
13317 * @return {number} Indentation level
13319 OO
.ui
.OutlineOptionWidget
.prototype.getLevel = function () {
13326 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13328 * @param {boolean} movable Item is movable
13331 OO
.ui
.OutlineOptionWidget
.prototype.setMovable = function ( movable
) {
13332 this.movable
= !!movable
;
13333 this.updateThemeClasses();
13338 * Set removability.
13340 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13342 * @param {boolean} movable Item is removable
13345 OO
.ui
.OutlineOptionWidget
.prototype.setRemovable = function ( removable
) {
13346 this.removable
= !!removable
;
13347 this.updateThemeClasses();
13352 * Set indentation level.
13354 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
13357 OO
.ui
.OutlineOptionWidget
.prototype.setLevel = function ( level
) {
13358 var levels
= this.constructor.static.levels
,
13359 levelClass
= this.constructor.static.levelClass
,
13362 this.level
= level
? Math
.max( 0, Math
.min( levels
- 1, level
) ) : 0;
13364 if ( this.level
=== i
) {
13365 this.$element
.addClass( levelClass
+ i
);
13367 this.$element
.removeClass( levelClass
+ i
);
13370 this.updateThemeClasses();
13376 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
13377 * By default, each popup has an anchor that points toward its origin.
13378 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
13381 * // A popup widget.
13382 * var popup = new OO.ui.PopupWidget( {
13383 * $content: $( '<p>Hi there!</p>' ),
13388 * $( 'body' ).append( popup.$element );
13389 * // To display the popup, toggle the visibility to 'true'.
13390 * popup.toggle( true );
13392 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
13395 * @extends OO.ui.Widget
13396 * @mixins OO.ui.LabelElement
13399 * @param {Object} [config] Configuration options
13400 * @cfg {number} [width=320] Width of popup in pixels
13401 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
13402 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
13403 * @cfg {string} [align='center'] Alignment of the popup: `center`, `left`, or `right`.
13404 * If the popup is right-aligned, the right edge of the popup is aligned to the anchor.
13405 * For left-aligned popups, the left edge is aligned to the anchor.
13406 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
13407 * See the [OOjs UI docs on MediaWiki][3] for an example.
13408 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
13409 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
13410 * @cfg {jQuery} [$content] Content to append to the popup's body
13411 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
13412 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
13413 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
13415 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
13416 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
13418 * @cfg {boolean} [padded] Add padding to the popup's body
13420 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
13421 // Configuration initialization
13422 config
= config
|| {};
13424 // Parent constructor
13425 OO
.ui
.PopupWidget
.super.call( this, config
);
13427 // Properties (must be set before ClippableElement constructor call)
13428 this.$body
= $( '<div>' );
13430 // Mixin constructors
13431 OO
.ui
.LabelElement
.call( this, config
);
13432 OO
.ui
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$body
} ) );
13435 this.$popup
= $( '<div>' );
13436 this.$head
= $( '<div>' );
13437 this.$anchor
= $( '<div>' );
13438 // If undefined, will be computed lazily in updateDimensions()
13439 this.$container
= config
.$container
;
13440 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
13441 this.autoClose
= !!config
.autoClose
;
13442 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
13443 this.transitionTimeout
= null;
13444 this.anchor
= null;
13445 this.width
= config
.width
!== undefined ? config
.width
: 320;
13446 this.height
= config
.height
!== undefined ? config
.height
: null;
13447 this.align
= config
.align
|| 'center';
13448 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
13449 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
13450 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
13453 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
13456 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
13457 this.$body
.addClass( 'oo-ui-popupWidget-body' );
13458 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
13460 .addClass( 'oo-ui-popupWidget-head' )
13461 .append( this.$label
, this.closeButton
.$element
);
13462 if ( !config
.head
) {
13463 this.$head
.addClass( 'oo-ui-element-hidden' );
13466 .addClass( 'oo-ui-popupWidget-popup' )
13467 .append( this.$head
, this.$body
);
13469 .addClass( 'oo-ui-popupWidget' )
13470 .append( this.$popup
, this.$anchor
);
13471 // Move content, which was added to #$element by OO.ui.Widget, to the body
13472 if ( config
.$content
instanceof jQuery
) {
13473 this.$body
.append( config
.$content
);
13475 if ( config
.padded
) {
13476 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
13479 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
13480 // that reference properties not initialized at that time of parent class construction
13481 // TODO: Find a better way to handle post-constructor setup
13482 this.visible
= false;
13483 this.$element
.addClass( 'oo-ui-element-hidden' );
13488 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
13489 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.LabelElement
);
13490 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.ClippableElement
);
13495 * Handles mouse down events.
13498 * @param {MouseEvent} e Mouse down event
13500 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
13502 this.isVisible() &&
13503 !$.contains( this.$element
[ 0 ], e
.target
) &&
13504 ( !this.$autoCloseIgnore
|| !this.$autoCloseIgnore
.has( e
.target
).length
)
13506 this.toggle( false );
13511 * Bind mouse down listener.
13515 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
13516 // Capture clicks outside popup
13517 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler
, true );
13521 * Handles close button click events.
13525 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
13526 if ( this.isVisible() ) {
13527 this.toggle( false );
13532 * Unbind mouse down listener.
13536 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
13537 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler
, true );
13541 * Handles key down events.
13544 * @param {KeyboardEvent} e Key down event
13546 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
13548 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
13551 this.toggle( false );
13552 e
.preventDefault();
13553 e
.stopPropagation();
13558 * Bind key down listener.
13562 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
13563 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
13567 * Unbind key down listener.
13571 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
13572 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
13576 * Show, hide, or toggle the visibility of the anchor.
13578 * @param {boolean} [show] Show anchor, omit to toggle
13580 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
13581 show
= show
=== undefined ? !this.anchored
: !!show
;
13583 if ( this.anchored
!== show
) {
13585 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
13587 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
13589 this.anchored
= show
;
13594 * Check if the anchor is visible.
13596 * @return {boolean} Anchor is visible
13598 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
13599 return this.anchor
;
13605 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
13606 show
= show
=== undefined ? !this.isVisible() : !!show
;
13608 var change
= show
!== this.isVisible();
13611 OO
.ui
.PopupWidget
.super.prototype.toggle
.call( this, show
);
13615 if ( this.autoClose
) {
13616 this.bindMouseDownListener();
13617 this.bindKeyDownListener();
13619 this.updateDimensions();
13620 this.toggleClipping( true );
13622 this.toggleClipping( false );
13623 if ( this.autoClose
) {
13624 this.unbindMouseDownListener();
13625 this.unbindKeyDownListener();
13634 * Set the size of the popup.
13636 * Changing the size may also change the popup's position depending on the alignment.
13638 * @param {number} width Width in pixels
13639 * @param {number} height Height in pixels
13640 * @param {boolean} [transition=false] Use a smooth transition
13643 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
13644 this.width
= width
;
13645 this.height
= height
!== undefined ? height
: null;
13646 if ( this.isVisible() ) {
13647 this.updateDimensions( transition
);
13652 * Update the size and position.
13654 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
13655 * be called automatically.
13657 * @param {boolean} [transition=false] Use a smooth transition
13660 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
13661 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
13662 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
13665 if ( !this.$container
) {
13666 // Lazy-initialize $container if not specified in constructor
13667 this.$container
= $( this.getClosestScrollableElementContainer() );
13670 // Set height and width before measuring things, since it might cause our measurements
13671 // to change (e.g. due to scrollbars appearing or disappearing)
13674 height
: this.height
!== null ? this.height
: 'auto'
13677 // Compute initial popupOffset based on alignment
13678 popupOffset
= this.width
* ( { left
: 0, center
: -0.5, right
: -1 } )[ this.align
];
13680 // Figure out if this will cause the popup to go beyond the edge of the container
13681 originOffset
= this.$element
.offset().left
;
13682 containerLeft
= this.$container
.offset().left
;
13683 containerWidth
= this.$container
.innerWidth();
13684 containerRight
= containerLeft
+ containerWidth
;
13685 popupLeft
= popupOffset
- this.containerPadding
;
13686 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
13687 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
13688 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
13690 // Adjust offset to make the popup not go beyond the edge, if needed
13691 if ( overlapRight
< 0 ) {
13692 popupOffset
+= overlapRight
;
13693 } else if ( overlapLeft
< 0 ) {
13694 popupOffset
-= overlapLeft
;
13697 // Adjust offset to avoid anchor being rendered too close to the edge
13698 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
13699 // TODO: Find a measurement that works for CSS anchors and image anchors
13700 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
13701 if ( popupOffset
+ this.width
< anchorWidth
) {
13702 popupOffset
= anchorWidth
- this.width
;
13703 } else if ( -popupOffset
< anchorWidth
) {
13704 popupOffset
= -anchorWidth
;
13707 // Prevent transition from being interrupted
13708 clearTimeout( this.transitionTimeout
);
13709 if ( transition
) {
13710 // Enable transition
13711 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
13714 // Position body relative to anchor
13715 this.$popup
.css( 'margin-left', popupOffset
);
13717 if ( transition
) {
13718 // Prevent transitioning after transition is complete
13719 this.transitionTimeout
= setTimeout( function () {
13720 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
13723 // Prevent transitioning immediately
13724 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
13727 // Reevaluate clipping state since we've relocated and resized the popup
13734 * Progress bars visually display the status of an operation, such as a download,
13735 * and can be either determinate or indeterminate:
13737 * - **determinate** process bars show the percent of an operation that is complete.
13739 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
13740 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
13741 * not use percentages.
13743 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
13746 * // Examples of determinate and indeterminate progress bars.
13747 * var progressBar1 = new OO.ui.ProgressBarWidget( {
13750 * var progressBar2 = new OO.ui.ProgressBarWidget();
13752 * // Create a FieldsetLayout to layout progress bars
13753 * var fieldset = new OO.ui.FieldsetLayout;
13754 * fieldset.addItems( [
13755 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
13756 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
13758 * $( 'body' ).append( fieldset.$element );
13761 * @extends OO.ui.Widget
13764 * @param {Object} [config] Configuration options
13765 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
13766 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
13767 * By default, the progress bar is indeterminate.
13769 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
13770 // Configuration initialization
13771 config
= config
|| {};
13773 // Parent constructor
13774 OO
.ui
.ProgressBarWidget
.super.call( this, config
);
13777 this.$bar
= $( '<div>' );
13778 this.progress
= null;
13781 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
13782 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
13785 role
: 'progressbar',
13786 'aria-valuemin': 0,
13787 'aria-valuemax': 100
13789 .addClass( 'oo-ui-progressBarWidget' )
13790 .append( this.$bar
);
13795 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
13797 /* Static Properties */
13799 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
13804 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
13806 * @return {number|boolean} Progress percent
13808 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
13809 return this.progress
;
13813 * Set the percent of the process completed or `false` for an indeterminate process.
13815 * @param {number|boolean} progress Progress percent or `false` for indeterminate
13817 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
13818 this.progress
= progress
;
13820 if ( progress
!== false ) {
13821 this.$bar
.css( 'width', this.progress
+ '%' );
13822 this.$element
.attr( 'aria-valuenow', this.progress
);
13824 this.$bar
.css( 'width', '' );
13825 this.$element
.removeAttr( 'aria-valuenow' );
13827 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress
);
13831 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
13832 * and a {@link OO.ui.TextInputMenuSelectWidget menu} of search results, which is displayed beneath the query
13833 * field. Unlike {@link OO.ui.LookupElement lookup menus}, search result menus are always visible to the user.
13834 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
13835 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
13837 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
13838 * the [OOjs UI demos][1] for an example.
13840 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
13843 * @extends OO.ui.Widget
13846 * @param {Object} [config] Configuration options
13847 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
13848 * @cfg {string} [value] Initial query value
13850 OO
.ui
.SearchWidget
= function OoUiSearchWidget( config
) {
13851 // Configuration initialization
13852 config
= config
|| {};
13854 // Parent constructor
13855 OO
.ui
.SearchWidget
.super.call( this, config
);
13858 this.query
= new OO
.ui
.TextInputWidget( {
13860 placeholder
: config
.placeholder
,
13861 value
: config
.value
13863 this.results
= new OO
.ui
.SelectWidget();
13864 this.$query
= $( '<div>' );
13865 this.$results
= $( '<div>' );
13868 this.query
.connect( this, {
13869 change
: 'onQueryChange',
13870 enter
: 'onQueryEnter'
13872 this.results
.connect( this, {
13873 highlight
: 'onResultsHighlight',
13874 select
: 'onResultsSelect'
13876 this.query
.$input
.on( 'keydown', this.onQueryKeydown
.bind( this ) );
13880 .addClass( 'oo-ui-searchWidget-query' )
13881 .append( this.query
.$element
);
13883 .addClass( 'oo-ui-searchWidget-results' )
13884 .append( this.results
.$element
);
13886 .addClass( 'oo-ui-searchWidget' )
13887 .append( this.$results
, this.$query
);
13892 OO
.inheritClass( OO
.ui
.SearchWidget
, OO
.ui
.Widget
);
13897 * A 'highlight' event is emitted when an item is highlighted. The highlight indicates which
13898 * item will be selected. When a user mouses over a menu item, it is highlighted. If a search
13899 * string is typed into the query field instead, the first menu item that matches the query
13900 * will be highlighted.
13903 * @deprecated Connect straight to getResults() events instead
13904 * @param {Object|null} item Item data or null if no item is highlighted
13908 * A 'select' event is emitted when an item is selected. A menu item is selected when it is clicked,
13909 * or when a user types a search query, a menu result is highlighted, and the user presses enter.
13912 * @deprecated Connect straight to getResults() events instead
13913 * @param {Object|null} item Item data or null if no item is selected
13919 * Handle query key down events.
13922 * @param {jQuery.Event} e Key down event
13924 OO
.ui
.SearchWidget
.prototype.onQueryKeydown = function ( e
) {
13925 var highlightedItem
, nextItem
,
13926 dir
= e
.which
=== OO
.ui
.Keys
.DOWN
? 1 : ( e
.which
=== OO
.ui
.Keys
.UP
? -1 : 0 );
13929 highlightedItem
= this.results
.getHighlightedItem();
13930 if ( !highlightedItem
) {
13931 highlightedItem
= this.results
.getSelectedItem();
13933 nextItem
= this.results
.getRelativeSelectableItem( highlightedItem
, dir
);
13934 this.results
.highlightItem( nextItem
);
13935 nextItem
.scrollElementIntoView();
13940 * Handle select widget select events.
13942 * Clears existing results. Subclasses should repopulate items according to new query.
13945 * @param {string} value New value
13947 OO
.ui
.SearchWidget
.prototype.onQueryChange = function () {
13949 this.results
.clearItems();
13953 * Handle select widget enter key events.
13955 * Selects highlighted item.
13958 * @param {string} value New value
13960 OO
.ui
.SearchWidget
.prototype.onQueryEnter = function () {
13962 this.results
.selectItem( this.results
.getHighlightedItem() );
13966 * Handle select widget highlight events.
13969 * @deprecated Connect straight to getResults() events instead
13970 * @param {OO.ui.OptionWidget} item Highlighted item
13973 OO
.ui
.SearchWidget
.prototype.onResultsHighlight = function ( item
) {
13974 this.emit( 'highlight', item
? item
.getData() : null );
13978 * Handle select widget select events.
13981 * @deprecated Connect straight to getResults() events instead
13982 * @param {OO.ui.OptionWidget} item Selected item
13985 OO
.ui
.SearchWidget
.prototype.onResultsSelect = function ( item
) {
13986 this.emit( 'select', item
? item
.getData() : null );
13990 * Get the query input.
13992 * @return {OO.ui.TextInputWidget} Query input
13994 OO
.ui
.SearchWidget
.prototype.getQuery = function () {
13999 * Get the search results menu.
14001 * @return {OO.ui.SelectWidget} Menu of search results
14003 OO
.ui
.SearchWidget
.prototype.getResults = function () {
14004 return this.results
;
14008 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
14009 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
14010 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
14013 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
14014 * information, please see the [OOjs UI documentation on MediaWiki][1].
14017 * // Example of a select widget with three options
14018 * var select = new OO.ui.SelectWidget( {
14020 * new OO.ui.OptionWidget( {
14022 * label: 'Option One',
14024 * new OO.ui.OptionWidget( {
14026 * label: 'Option Two',
14028 * new OO.ui.OptionWidget( {
14030 * label: 'Option Three',
14034 * $( 'body' ).append( select.$element );
14036 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14039 * @extends OO.ui.Widget
14040 * @mixins OO.ui.GroupElement
14043 * @param {Object} [config] Configuration options
14044 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
14045 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
14046 * the [OOjs UI documentation on MediaWiki] [2] for examples.
14047 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14049 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
14050 // Configuration initialization
14051 config
= config
|| {};
14053 // Parent constructor
14054 OO
.ui
.SelectWidget
.super.call( this, config
);
14056 // Mixin constructors
14057 OO
.ui
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
14060 this.pressed
= false;
14061 this.selecting
= null;
14062 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
14063 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
14064 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
14067 this.$element
.on( {
14068 mousedown
: this.onMouseDown
.bind( this ),
14069 mouseover
: this.onMouseOver
.bind( this ),
14070 mouseleave
: this.onMouseLeave
.bind( this )
14075 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
14076 .attr( 'role', 'listbox' );
14077 if ( Array
.isArray( config
.items
) ) {
14078 this.addItems( config
.items
);
14084 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
14086 // Need to mixin base class as well
14087 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.GroupElement
);
14088 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.GroupWidget
);
14095 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
14097 * @param {OO.ui.OptionWidget|null} item Highlighted item
14103 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
14104 * pressed state of an option.
14106 * @param {OO.ui.OptionWidget|null} item Pressed item
14112 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
14114 * @param {OO.ui.OptionWidget|null} item Selected item
14119 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
14120 * @param {OO.ui.OptionWidget} item Chosen item
14126 * An `add` event is emitted when options are added to the select with the #addItems method.
14128 * @param {OO.ui.OptionWidget[]} items Added items
14129 * @param {number} index Index of insertion point
14135 * A `remove` event is emitted when options are removed from the select with the #clearItems
14136 * or #removeItems methods.
14138 * @param {OO.ui.OptionWidget[]} items Removed items
14144 * Handle mouse down events.
14147 * @param {jQuery.Event} e Mouse down event
14149 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
14152 if ( !this.isDisabled() && e
.which
=== 1 ) {
14153 this.togglePressed( true );
14154 item
= this.getTargetItem( e
);
14155 if ( item
&& item
.isSelectable() ) {
14156 this.pressItem( item
);
14157 this.selecting
= item
;
14158 this.getElementDocument().addEventListener(
14160 this.onMouseUpHandler
,
14163 this.getElementDocument().addEventListener(
14165 this.onMouseMoveHandler
,
14174 * Handle mouse up events.
14177 * @param {jQuery.Event} e Mouse up event
14179 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
14182 this.togglePressed( false );
14183 if ( !this.selecting
) {
14184 item
= this.getTargetItem( e
);
14185 if ( item
&& item
.isSelectable() ) {
14186 this.selecting
= item
;
14189 if ( !this.isDisabled() && e
.which
=== 1 && this.selecting
) {
14190 this.pressItem( null );
14191 this.chooseItem( this.selecting
);
14192 this.selecting
= null;
14195 this.getElementDocument().removeEventListener(
14197 this.onMouseUpHandler
,
14200 this.getElementDocument().removeEventListener(
14202 this.onMouseMoveHandler
,
14210 * Handle mouse move events.
14213 * @param {jQuery.Event} e Mouse move event
14215 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
14218 if ( !this.isDisabled() && this.pressed
) {
14219 item
= this.getTargetItem( e
);
14220 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
14221 this.pressItem( item
);
14222 this.selecting
= item
;
14229 * Handle mouse over events.
14232 * @param {jQuery.Event} e Mouse over event
14234 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
14237 if ( !this.isDisabled() ) {
14238 item
= this.getTargetItem( e
);
14239 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
14245 * Handle mouse leave events.
14248 * @param {jQuery.Event} e Mouse over event
14250 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
14251 if ( !this.isDisabled() ) {
14252 this.highlightItem( null );
14258 * Handle key down events.
14261 * @param {jQuery.Event} e Key down event
14263 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
14266 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
14268 if ( !this.isDisabled() && this.isVisible() ) {
14269 switch ( e
.keyCode
) {
14270 case OO
.ui
.Keys
.ENTER
:
14271 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
14272 // Was only highlighted, now let's select it. No-op if already selected.
14273 this.chooseItem( currentItem
);
14277 case OO
.ui
.Keys
.UP
:
14278 case OO
.ui
.Keys
.LEFT
:
14279 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
14282 case OO
.ui
.Keys
.DOWN
:
14283 case OO
.ui
.Keys
.RIGHT
:
14284 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
14287 case OO
.ui
.Keys
.ESCAPE
:
14288 case OO
.ui
.Keys
.TAB
:
14289 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
14290 currentItem
.setHighlighted( false );
14292 this.unbindKeyDownListener();
14293 // Don't prevent tabbing away / defocusing
14299 if ( nextItem
.constructor.static.highlightable
) {
14300 this.highlightItem( nextItem
);
14302 this.chooseItem( nextItem
);
14304 nextItem
.scrollElementIntoView();
14308 // Can't just return false, because e is not always a jQuery event
14309 e
.preventDefault();
14310 e
.stopPropagation();
14316 * Bind key down listener.
14320 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
14321 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler
, true );
14325 * Unbind key down listener.
14329 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
14330 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler
, true );
14334 * Get the closest item to a jQuery.Event.
14337 * @param {jQuery.Event} e
14338 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
14340 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
14341 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
14345 * Get selected item.
14347 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
14349 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
14352 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14353 if ( this.items
[ i
].isSelected() ) {
14354 return this.items
[ i
];
14361 * Get highlighted item.
14363 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
14365 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
14368 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14369 if ( this.items
[ i
].isHighlighted() ) {
14370 return this.items
[ i
];
14377 * Toggle pressed state.
14379 * Press is a state that occurs when a user mouses down on an item, but
14380 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
14381 * until the user releases the mouse.
14383 * @param {boolean} pressed An option is being pressed
14385 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
14386 if ( pressed
=== undefined ) {
14387 pressed
= !this.pressed
;
14389 if ( pressed
!== this.pressed
) {
14391 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
14392 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
14393 this.pressed
= pressed
;
14398 * Highlight an option. If the `item` param is omitted, no options will be highlighted
14399 * and any existing highlight will be removed. The highlight is mutually exclusive.
14401 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
14405 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
14406 var i
, len
, highlighted
,
14409 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14410 highlighted
= this.items
[ i
] === item
;
14411 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
14412 this.items
[ i
].setHighlighted( highlighted
);
14417 this.emit( 'highlight', item
);
14424 * Programmatically select an option by its reference. If the `item` parameter is omitted,
14425 * all options will be deselected.
14427 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
14431 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
14432 var i
, len
, selected
,
14435 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14436 selected
= this.items
[ i
] === item
;
14437 if ( this.items
[ i
].isSelected() !== selected
) {
14438 this.items
[ i
].setSelected( selected
);
14443 this.emit( 'select', item
);
14452 * Press is a state that occurs when a user mouses down on an item, but has not
14453 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
14454 * releases the mouse.
14456 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
14460 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
14461 var i
, len
, pressed
,
14464 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14465 pressed
= this.items
[ i
] === item
;
14466 if ( this.items
[ i
].isPressed() !== pressed
) {
14467 this.items
[ i
].setPressed( pressed
);
14472 this.emit( 'press', item
);
14481 * Note that ‘choose’ should never be modified programmatically. A user can choose
14482 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
14483 * use the #selectItem method.
14485 * This method is identical to #selectItem, but may vary in subclasses that take additional action
14486 * when users choose an item with the keyboard or mouse.
14488 * @param {OO.ui.OptionWidget} item Item to choose
14492 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
14493 this.selectItem( item
);
14494 this.emit( 'choose', item
);
14500 * Get an option by its position relative to the specified item (or to the start of the option array,
14501 * if item is `null`). The direction in which to search through the option array is specified with a
14502 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
14503 * `null` if there are no options in the array.
14505 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
14506 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
14507 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
14509 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
) {
14510 var currentIndex
, nextIndex
, i
,
14511 increase
= direction
> 0 ? 1 : -1,
14512 len
= this.items
.length
;
14514 if ( item
instanceof OO
.ui
.OptionWidget
) {
14515 currentIndex
= $.inArray( item
, this.items
);
14516 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
14518 // If no item is selected and moving forward, start at the beginning.
14519 // If moving backward, start at the end.
14520 nextIndex
= direction
> 0 ? 0 : len
- 1;
14523 for ( i
= 0; i
< len
; i
++ ) {
14524 item
= this.items
[ nextIndex
];
14525 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
14528 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
14534 * Get the next selectable item or `null` if there are no selectable items.
14535 * Disabled options and menu-section markers and breaks are not selectable.
14537 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
14539 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
14542 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14543 item
= this.items
[ i
];
14544 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
14553 * Add an array of options to the select. Optionally, an index number can be used to
14554 * specify an insertion point.
14556 * @param {OO.ui.OptionWidget[]} items Items to add
14557 * @param {number} [index] Index to insert items after
14561 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
14563 OO
.ui
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
14565 // Always provide an index, even if it was omitted
14566 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
14572 * Remove the specified array of options from the select. Options will be detached
14573 * from the DOM, not removed, so they can be reused later. To remove all options from
14574 * the select, you may wish to use the #clearItems method instead.
14576 * @param {OO.ui.OptionWidget[]} items Items to remove
14580 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
14583 // Deselect items being removed
14584 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
14586 if ( item
.isSelected() ) {
14587 this.selectItem( null );
14592 OO
.ui
.GroupWidget
.prototype.removeItems
.call( this, items
);
14594 this.emit( 'remove', items
);
14600 * Clear all options from the select. Options will be detached from the DOM, not removed,
14601 * so that they can be reused later. To remove a subset of options from the select, use
14602 * the #removeItems method.
14607 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
14608 var items
= this.items
.slice();
14611 OO
.ui
.GroupWidget
.prototype.clearItems
.call( this );
14614 this.selectItem( null );
14616 this.emit( 'remove', items
);
14622 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
14623 * button options and is used together with
14624 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
14625 * highlighting, choosing, and selecting mutually exclusive options. Please see
14626 * the [OOjs UI documentation on MediaWiki] [1] for more information.
14629 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
14630 * var option1 = new OO.ui.ButtonOptionWidget( {
14632 * label: 'Option 1',
14633 * title: 'Button option 1'
14636 * var option2 = new OO.ui.ButtonOptionWidget( {
14638 * label: 'Option 2',
14639 * title: 'Button option 2'
14642 * var option3 = new OO.ui.ButtonOptionWidget( {
14644 * label: 'Option 3',
14645 * title: 'Button option 3'
14648 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
14649 * items: [ option1, option2, option3 ]
14651 * $( 'body' ).append( buttonSelect.$element );
14653 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14656 * @extends OO.ui.SelectWidget
14657 * @mixins OO.ui.TabIndexedElement
14660 * @param {Object} [config] Configuration options
14662 OO
.ui
.ButtonSelectWidget
= function OoUiButtonSelectWidget( config
) {
14663 // Parent constructor
14664 OO
.ui
.ButtonSelectWidget
.super.call( this, config
);
14666 // Mixin constructors
14667 OO
.ui
.TabIndexedElement
.call( this, config
);
14670 this.$element
.on( {
14671 focus
: this.bindKeyDownListener
.bind( this ),
14672 blur
: this.unbindKeyDownListener
.bind( this )
14676 this.$element
.addClass( 'oo-ui-buttonSelectWidget' );
14681 OO
.inheritClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.SelectWidget
);
14682 OO
.mixinClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.TabIndexedElement
);
14685 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
14686 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
14687 * an interface for adding, removing and selecting options.
14688 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
14691 * // A RadioSelectWidget with RadioOptions.
14692 * var option1 = new OO.ui.RadioOptionWidget( {
14694 * label: 'Selected radio option'
14697 * var option2 = new OO.ui.RadioOptionWidget( {
14699 * label: 'Unselected radio option'
14702 * var radioSelect=new OO.ui.RadioSelectWidget( {
14703 * items: [ option1, option2 ]
14706 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
14707 * radioSelect.selectItem( option1 );
14709 * $( 'body' ).append( radioSelect.$element );
14711 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14715 * @extends OO.ui.SelectWidget
14716 * @mixins OO.ui.TabIndexedElement
14719 * @param {Object} [config] Configuration options
14721 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
14722 // Parent constructor
14723 OO
.ui
.RadioSelectWidget
.super.call( this, config
);
14725 // Mixin constructors
14726 OO
.ui
.TabIndexedElement
.call( this, config
);
14729 this.$element
.on( {
14730 focus
: this.bindKeyDownListener
.bind( this ),
14731 blur
: this.unbindKeyDownListener
.bind( this )
14735 this.$element
.addClass( 'oo-ui-radioSelectWidget' );
14740 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
14741 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.TabIndexedElement
);
14744 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
14745 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
14746 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
14747 * and {@link OO.ui.LookupElement LookupElement} for examples of widgets that contain menus.
14748 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
14749 * and customized to be opened, closed, and displayed as needed.
14751 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
14752 * mouse outside the menu.
14754 * Menus also have support for keyboard interaction:
14756 * - Enter/Return key: choose and select a menu option
14757 * - Up-arrow key: highlight the previous menu option
14758 * - Down-arrow key: highlight the next menu option
14759 * - Esc key: hide the menu
14761 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
14762 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14765 * @extends OO.ui.SelectWidget
14766 * @mixins OO.ui.ClippableElement
14769 * @param {Object} [config] Configuration options
14770 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
14771 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
14772 * and {@link OO.ui.LookupElement LookupElement}
14773 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu’s active state. If the user clicks the mouse
14774 * anywhere on the page outside of this widget, the menu is hidden.
14775 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
14777 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
14778 // Configuration initialization
14779 config
= config
|| {};
14781 // Parent constructor
14782 OO
.ui
.MenuSelectWidget
.super.call( this, config
);
14784 // Mixin constructors
14785 OO
.ui
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
14788 this.newItems
= null;
14789 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
14790 this.$input
= config
.input
? config
.input
.$input
: null;
14791 this.$widget
= config
.widget
? config
.widget
.$element
: null;
14792 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
14796 .addClass( 'oo-ui-menuSelectWidget' )
14797 .attr( 'role', 'menu' );
14799 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
14800 // that reference properties not initialized at that time of parent class construction
14801 // TODO: Find a better way to handle post-constructor setup
14802 this.visible
= false;
14803 this.$element
.addClass( 'oo-ui-element-hidden' );
14808 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
14809 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.ClippableElement
);
14814 * Handles document mouse down events.
14817 * @param {jQuery.Event} e Key down event
14819 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
14821 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
14822 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
14824 this.toggle( false );
14831 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
14832 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
14834 if ( !this.isDisabled() && this.isVisible() ) {
14835 switch ( e
.keyCode
) {
14836 case OO
.ui
.Keys
.LEFT
:
14837 case OO
.ui
.Keys
.RIGHT
:
14838 // Do nothing if a text field is associated, arrow keys will be handled natively
14839 if ( !this.$input
) {
14840 OO
.ui
.MenuSelectWidget
.super.prototype.onKeyDown
.call( this, e
);
14843 case OO
.ui
.Keys
.ESCAPE
:
14844 case OO
.ui
.Keys
.TAB
:
14845 if ( currentItem
) {
14846 currentItem
.setHighlighted( false );
14848 this.toggle( false );
14849 // Don't prevent tabbing away, prevent defocusing
14850 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
14851 e
.preventDefault();
14852 e
.stopPropagation();
14856 OO
.ui
.MenuSelectWidget
.super.prototype.onKeyDown
.call( this, e
);
14865 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
14866 if ( this.$input
) {
14867 this.$input
.on( 'keydown', this.onKeyDownHandler
);
14869 OO
.ui
.MenuSelectWidget
.super.prototype.bindKeyDownListener
.call( this );
14876 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
14877 if ( this.$input
) {
14878 this.$input
.off( 'keydown', this.onKeyDownHandler
);
14880 OO
.ui
.MenuSelectWidget
.super.prototype.unbindKeyDownListener
.call( this );
14887 * When a user chooses an item, the menu is closed.
14889 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
14890 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
14891 * @param {OO.ui.OptionWidget} item Item to choose
14894 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
14895 OO
.ui
.MenuSelectWidget
.super.prototype.chooseItem
.call( this, item
);
14896 this.toggle( false );
14903 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
14907 OO
.ui
.MenuSelectWidget
.super.prototype.addItems
.call( this, items
, index
);
14910 if ( !this.newItems
) {
14911 this.newItems
= [];
14914 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
14916 if ( this.isVisible() ) {
14917 // Defer fitting label until item has been attached
14920 this.newItems
.push( item
);
14924 // Reevaluate clipping
14933 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
14935 OO
.ui
.MenuSelectWidget
.super.prototype.removeItems
.call( this, items
);
14937 // Reevaluate clipping
14946 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
14948 OO
.ui
.MenuSelectWidget
.super.prototype.clearItems
.call( this );
14950 // Reevaluate clipping
14959 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
14960 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
14963 change
= visible
!== this.isVisible();
14966 OO
.ui
.MenuSelectWidget
.super.prototype.toggle
.call( this, visible
);
14970 this.bindKeyDownListener();
14972 if ( this.newItems
&& this.newItems
.length
) {
14973 for ( i
= 0, len
= this.newItems
.length
; i
< len
; i
++ ) {
14974 this.newItems
[ i
].fitLabel();
14976 this.newItems
= null;
14978 this.toggleClipping( true );
14981 if ( this.autoHide
) {
14982 this.getElementDocument().addEventListener(
14983 'mousedown', this.onDocumentMouseDownHandler
, true
14987 this.unbindKeyDownListener();
14988 this.getElementDocument().removeEventListener(
14989 'mousedown', this.onDocumentMouseDownHandler
, true
14991 this.toggleClipping( false );
14999 * TextInputMenuSelectWidget is a menu that is specially designed to be positioned beneath
15000 * a {@link OO.ui.TextInputWidget text input} field. The menu's position is automatically
15001 * calculated and maintained when the menu is toggled or the window is resized.
15002 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
15005 * @extends OO.ui.MenuSelectWidget
15008 * @param {OO.ui.TextInputWidget} inputWidget Text input widget to provide menu for
15009 * @param {Object} [config] Configuration options
15010 * @cfg {jQuery} [$container=input.$element] Element to render menu under
15012 OO
.ui
.TextInputMenuSelectWidget
= function OoUiTextInputMenuSelectWidget( inputWidget
, config
) {
15013 // Allow passing positional parameters inside the config object
15014 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
15015 config
= inputWidget
;
15016 inputWidget
= config
.inputWidget
;
15019 // Configuration initialization
15020 config
= config
|| {};
15022 // Parent constructor
15023 OO
.ui
.TextInputMenuSelectWidget
.super.call( this, config
);
15026 this.inputWidget
= inputWidget
;
15027 this.$container
= config
.$container
|| this.inputWidget
.$element
;
15028 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
15031 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
15036 OO
.inheritClass( OO
.ui
.TextInputMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
15041 * Handle window resize event.
15044 * @param {jQuery.Event} e Window resize event
15046 OO
.ui
.TextInputMenuSelectWidget
.prototype.onWindowResize = function () {
15053 OO
.ui
.TextInputMenuSelectWidget
.prototype.toggle = function ( visible
) {
15054 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
15056 var change
= visible
!== this.isVisible();
15058 if ( change
&& visible
) {
15059 // Make sure the width is set before the parent method runs.
15060 // After this we have to call this.position(); again to actually
15061 // position ourselves correctly.
15066 OO
.ui
.TextInputMenuSelectWidget
.super.prototype.toggle
.call( this, visible
);
15069 if ( this.isVisible() ) {
15071 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
15073 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
15081 * Position the menu.
15086 OO
.ui
.TextInputMenuSelectWidget
.prototype.position = function () {
15087 var $container
= this.$container
,
15088 pos
= OO
.ui
.Element
.static.getRelativePosition( $container
, this.$element
.offsetParent() );
15090 // Position under input
15091 pos
.top
+= $container
.height();
15092 this.$element
.css( pos
);
15095 this.setIdealSize( $container
.width() );
15096 // We updated the position, so re-evaluate the clipping state
15103 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
15104 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
15106 * ####Currently, this class is only used by {@link OO.ui.BookletLayout BookletLayouts}.####
15109 * @extends OO.ui.SelectWidget
15110 * @mixins OO.ui.TabIndexedElement
15113 * @param {Object} [config] Configuration options
15115 OO
.ui
.OutlineSelectWidget
= function OoUiOutlineSelectWidget( config
) {
15116 // Parent constructor
15117 OO
.ui
.OutlineSelectWidget
.super.call( this, config
);
15119 // Mixin constructors
15120 OO
.ui
.TabIndexedElement
.call( this, config
);
15123 this.$element
.on( {
15124 focus
: this.bindKeyDownListener
.bind( this ),
15125 blur
: this.unbindKeyDownListener
.bind( this )
15129 this.$element
.addClass( 'oo-ui-outlineSelectWidget' );
15134 OO
.inheritClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.SelectWidget
);
15135 OO
.mixinClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.TabIndexedElement
);
15138 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
15139 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
15140 * visually by a slider in the leftmost position.
15143 * // Toggle switches in the 'off' and 'on' position.
15144 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
15145 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
15149 * // Create a FieldsetLayout to layout and label switches
15150 * var fieldset = new OO.ui.FieldsetLayout( {
15151 * label: 'Toggle switches'
15153 * fieldset.addItems( [
15154 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
15155 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
15157 * $( 'body' ).append( fieldset.$element );
15160 * @extends OO.ui.ToggleWidget
15161 * @mixins OO.ui.TabIndexedElement
15164 * @param {Object} [config] Configuration options
15165 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
15166 * By default, the toggle switch is in the 'off' position.
15168 OO
.ui
.ToggleSwitchWidget
= function OoUiToggleSwitchWidget( config
) {
15169 // Parent constructor
15170 OO
.ui
.ToggleSwitchWidget
.super.call( this, config
);
15172 // Mixin constructors
15173 OO
.ui
.TabIndexedElement
.call( this, config
);
15176 this.dragging
= false;
15177 this.dragStart
= null;
15178 this.sliding
= false;
15179 this.$glow
= $( '<span>' );
15180 this.$grip
= $( '<span>' );
15183 this.$element
.on( {
15184 click
: this.onClick
.bind( this ),
15185 keypress
: this.onKeyPress
.bind( this )
15189 this.$glow
.addClass( 'oo-ui-toggleSwitchWidget-glow' );
15190 this.$grip
.addClass( 'oo-ui-toggleSwitchWidget-grip' );
15192 .addClass( 'oo-ui-toggleSwitchWidget' )
15193 .attr( 'role', 'checkbox' )
15194 .append( this.$glow
, this.$grip
);
15199 OO
.inheritClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.ToggleWidget
);
15200 OO
.mixinClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.TabIndexedElement
);
15205 * Handle mouse click events.
15208 * @param {jQuery.Event} e Mouse click event
15210 OO
.ui
.ToggleSwitchWidget
.prototype.onClick = function ( e
) {
15211 if ( !this.isDisabled() && e
.which
=== 1 ) {
15212 this.setValue( !this.value
);
15218 * Handle key press events.
15221 * @param {jQuery.Event} e Key press event
15223 OO
.ui
.ToggleSwitchWidget
.prototype.onKeyPress = function ( e
) {
15224 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
15225 this.setValue( !this.value
);