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-27T17:17:10Z
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
6402 * @mixins OO.ui.TabIndexedElement
6405 * @param {OO.ui.ToolGroup} toolGroup
6406 * @param {Object} [config] Configuration options
6407 * @cfg {string|Function} [title] Title text or a function that returns text
6409 OO
.ui
.Tool
= function OoUiTool( toolGroup
, config
) {
6410 // Allow passing positional parameters inside the config object
6411 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
6413 toolGroup
= config
.toolGroup
;
6416 // Configuration initialization
6417 config
= config
|| {};
6419 // Parent constructor
6420 OO
.ui
.Tool
.super.call( this, config
);
6423 this.toolGroup
= toolGroup
;
6424 this.toolbar
= this.toolGroup
.getToolbar();
6425 this.active
= false;
6426 this.$title
= $( '<span>' );
6427 this.$accel
= $( '<span>' );
6428 this.$link
= $( '<a>' );
6431 // Mixin constructors
6432 OO
.ui
.IconElement
.call( this, config
);
6433 OO
.ui
.FlaggedElement
.call( this, config
);
6434 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$link
} ) );
6437 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
6440 this.$title
.addClass( 'oo-ui-tool-title' );
6442 .addClass( 'oo-ui-tool-accel' )
6444 // This may need to be changed if the key names are ever localized,
6445 // but for now they are essentially written in English
6450 .addClass( 'oo-ui-tool-link' )
6451 .append( this.$icon
, this.$title
, this.$accel
)
6452 .attr( 'role', 'button' );
6454 .data( 'oo-ui-tool', this )
6456 'oo-ui-tool ' + 'oo-ui-tool-name-' +
6457 this.constructor.static.name
.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
6459 .append( this.$link
);
6460 this.setTitle( config
.title
|| this.constructor.static.title
);
6465 OO
.inheritClass( OO
.ui
.Tool
, OO
.ui
.Widget
);
6466 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.IconElement
);
6467 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.FlaggedElement
);
6468 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.TabIndexedElement
);
6476 /* Static Properties */
6482 OO
.ui
.Tool
.static.tagName
= 'span';
6485 * Symbolic name of tool.
6490 * @property {string}
6492 OO
.ui
.Tool
.static.name
= '';
6500 * @property {string}
6502 OO
.ui
.Tool
.static.group
= '';
6507 * Title is used as a tooltip when the tool is part of a bar tool group, or a label when the tool
6508 * is part of a list or menu tool group. If a trigger is associated with an action by the same name
6509 * as the tool, a description of its keyboard shortcut for the appropriate platform will be
6510 * appended to the title if the tool is part of a bar tool group.
6515 * @property {string|Function} Title text or a function that returns text
6517 OO
.ui
.Tool
.static.title
= '';
6520 * Tool can be automatically added to catch-all groups.
6524 * @property {boolean}
6526 OO
.ui
.Tool
.static.autoAddToCatchall
= true;
6529 * Tool can be automatically added to named groups.
6532 * @property {boolean}
6535 OO
.ui
.Tool
.static.autoAddToGroup
= true;
6538 * Check if this tool is compatible with given data.
6542 * @param {Mixed} data Data to check
6543 * @return {boolean} Tool can be used with data
6545 OO
.ui
.Tool
.static.isCompatibleWith = function () {
6552 * Handle the toolbar state being updated.
6554 * This is an abstract method that must be overridden in a concrete subclass.
6558 OO
.ui
.Tool
.prototype.onUpdateState = function () {
6560 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
6565 * Handle the tool being selected.
6567 * This is an abstract method that must be overridden in a concrete subclass.
6571 OO
.ui
.Tool
.prototype.onSelect = function () {
6573 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
6578 * Check if the button is active.
6580 * @return {boolean} Button is active
6582 OO
.ui
.Tool
.prototype.isActive = function () {
6587 * Make the button appear active or inactive.
6589 * @param {boolean} state Make button appear active
6591 OO
.ui
.Tool
.prototype.setActive = function ( state
) {
6592 this.active
= !!state
;
6593 if ( this.active
) {
6594 this.$element
.addClass( 'oo-ui-tool-active' );
6596 this.$element
.removeClass( 'oo-ui-tool-active' );
6601 * Get the tool title.
6603 * @param {string|Function} title Title text or a function that returns text
6606 OO
.ui
.Tool
.prototype.setTitle = function ( title
) {
6607 this.title
= OO
.ui
.resolveMsg( title
);
6613 * Get the tool title.
6615 * @return {string} Title text
6617 OO
.ui
.Tool
.prototype.getTitle = function () {
6622 * Get the tool's symbolic name.
6624 * @return {string} Symbolic name of tool
6626 OO
.ui
.Tool
.prototype.getName = function () {
6627 return this.constructor.static.name
;
6633 OO
.ui
.Tool
.prototype.updateTitle = function () {
6634 var titleTooltips
= this.toolGroup
.constructor.static.titleTooltips
,
6635 accelTooltips
= this.toolGroup
.constructor.static.accelTooltips
,
6636 accel
= this.toolbar
.getToolAccelerator( this.constructor.static.name
),
6639 this.$title
.text( this.title
);
6640 this.$accel
.text( accel
);
6642 if ( titleTooltips
&& typeof this.title
=== 'string' && this.title
.length
) {
6643 tooltipParts
.push( this.title
);
6645 if ( accelTooltips
&& typeof accel
=== 'string' && accel
.length
) {
6646 tooltipParts
.push( accel
);
6648 if ( tooltipParts
.length
) {
6649 this.$link
.attr( 'title', tooltipParts
.join( ' ' ) );
6651 this.$link
.removeAttr( 'title' );
6658 OO
.ui
.Tool
.prototype.destroy = function () {
6659 this.toolbar
.disconnect( this );
6660 this.$element
.remove();
6664 * Collection of tool groups.
6667 * // Basic OOjs UI toolbar example
6669 * // Create the toolbar
6670 * var toolFactory = new OO.ui.ToolFactory();
6671 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
6672 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
6674 * // We will be placing status text in this element when tools are used
6675 * var $area = $( '<p>' ).css( 'font-size', '0.8em' ).text( 'Toolbar example' );
6677 * // Define the tools that we're going to place in our toolbar
6679 * // Create a class inheriting from OO.ui.Tool
6680 * function PictureTool() {
6681 * PictureTool.super.apply( this, arguments );
6683 * OO.inheritClass( PictureTool, OO.ui.Tool );
6684 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
6685 * // of 'icon' and 'title' (displayed icon and text).
6686 * PictureTool.static.name = 'picture';
6687 * PictureTool.static.icon = 'picture';
6688 * PictureTool.static.title = 'Insert picture';
6689 * // Defines the action that will happen when this tool is selected (clicked).
6690 * PictureTool.prototype.onSelect = function () {
6691 * $area.text( 'Picture tool clicked!' );
6692 * this.setActive( false );
6694 * // The toolbar can be synchronized with the state of some external stuff, like a text
6695 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
6696 * // when the text cursor was inside bolded text). Here we simply disable this feature.
6697 * PictureTool.prototype.onUpdateState = function () {
6698 * this.setActive( false );
6700 * // Make this tool available in our toolFactory and thus our toolbar
6701 * toolFactory.register( PictureTool );
6703 * // Register two more tools, nothing interesting here
6704 * function SettingsTool() {
6705 * SettingsTool.super.apply( this, arguments );
6707 * OO.inheritClass( SettingsTool, OO.ui.Tool );
6708 * SettingsTool.static.name = 'settings';
6709 * SettingsTool.static.icon = 'settings';
6710 * SettingsTool.static.title = 'Change settings';
6711 * SettingsTool.prototype.onSelect = function () {
6712 * $area.text( 'Settings tool clicked!' );
6713 * this.setActive( false );
6715 * SettingsTool.prototype.onUpdateState = function () {
6716 * this.setActive( false );
6718 * toolFactory.register( SettingsTool );
6720 * // Register two more tools, nothing interesting here
6721 * function StuffTool() {
6722 * StuffTool.super.apply( this, arguments );
6724 * OO.inheritClass( StuffTool, OO.ui.Tool );
6725 * StuffTool.static.name = 'stuff';
6726 * StuffTool.static.icon = 'ellipsis';
6727 * StuffTool.static.title = 'More stuff';
6728 * StuffTool.prototype.onSelect = function () {
6729 * $area.text( 'More stuff tool clicked!' );
6730 * this.setActive( false );
6732 * StuffTool.prototype.onUpdateState = function () {
6733 * this.setActive( false );
6735 * toolFactory.register( StuffTool );
6737 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
6738 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
6739 * function HelpTool( toolGroup, config ) {
6740 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
6745 * this.popup.$body.append( '<p>I am helpful!</p>' );
6747 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
6748 * HelpTool.static.name = 'help';
6749 * HelpTool.static.icon = 'help';
6750 * HelpTool.static.title = 'Help';
6751 * toolFactory.register( HelpTool );
6753 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
6754 * // used once (but not all defined tools must be used).
6757 * // 'bar' tool groups display tools' icons only, side-by-side.
6759 * include: [ 'picture', 'help' ]
6762 * // 'list' tool groups display both the titles and icons, in a dropdown list.
6764 * indicator: 'down',
6766 * include: [ 'settings', 'stuff' ]
6768 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
6769 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here.
6772 * // Create some UI around the toolbar and place it in the document
6773 * var frame = new OO.ui.PanelLayout( {
6777 * var contentFrame = new OO.ui.PanelLayout( {
6781 * frame.$element.append(
6783 * contentFrame.$element.append( $area )
6785 * $( 'body' ).append( frame.$element );
6787 * // Here is where the toolbar is actually built. This must be done after inserting it into the
6789 * toolbar.initialize();
6790 * toolbar.emit( 'updateState' );
6793 * @extends OO.ui.Element
6794 * @mixins OO.EventEmitter
6795 * @mixins OO.ui.GroupElement
6798 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
6799 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating tool groups
6800 * @param {Object} [config] Configuration options
6801 * @cfg {boolean} [actions] Add an actions section opposite to the tools
6802 * @cfg {boolean} [shadow] Add a shadow below the toolbar
6804 OO
.ui
.Toolbar
= function OoUiToolbar( toolFactory
, toolGroupFactory
, config
) {
6805 // Allow passing positional parameters inside the config object
6806 if ( OO
.isPlainObject( toolFactory
) && config
=== undefined ) {
6807 config
= toolFactory
;
6808 toolFactory
= config
.toolFactory
;
6809 toolGroupFactory
= config
.toolGroupFactory
;
6812 // Configuration initialization
6813 config
= config
|| {};
6815 // Parent constructor
6816 OO
.ui
.Toolbar
.super.call( this, config
);
6818 // Mixin constructors
6819 OO
.EventEmitter
.call( this );
6820 OO
.ui
.GroupElement
.call( this, config
);
6823 this.toolFactory
= toolFactory
;
6824 this.toolGroupFactory
= toolGroupFactory
;
6827 this.$bar
= $( '<div>' );
6828 this.$actions
= $( '<div>' );
6829 this.initialized
= false;
6830 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
6834 .add( this.$bar
).add( this.$group
).add( this.$actions
)
6835 .on( 'mousedown keydown', this.onPointerDown
.bind( this ) );
6838 this.$group
.addClass( 'oo-ui-toolbar-tools' );
6839 if ( config
.actions
) {
6840 this.$bar
.append( this.$actions
.addClass( 'oo-ui-toolbar-actions' ) );
6843 .addClass( 'oo-ui-toolbar-bar' )
6844 .append( this.$group
, '<div style="clear:both"></div>' );
6845 if ( config
.shadow
) {
6846 this.$bar
.append( '<div class="oo-ui-toolbar-shadow"></div>' );
6848 this.$element
.addClass( 'oo-ui-toolbar' ).append( this.$bar
);
6853 OO
.inheritClass( OO
.ui
.Toolbar
, OO
.ui
.Element
);
6854 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.EventEmitter
);
6855 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.ui
.GroupElement
);
6860 * Get the tool factory.
6862 * @return {OO.ui.ToolFactory} Tool factory
6864 OO
.ui
.Toolbar
.prototype.getToolFactory = function () {
6865 return this.toolFactory
;
6869 * Get the tool group factory.
6871 * @return {OO.Factory} Tool group factory
6873 OO
.ui
.Toolbar
.prototype.getToolGroupFactory = function () {
6874 return this.toolGroupFactory
;
6878 * Handles mouse down events.
6880 * @param {jQuery.Event} e Mouse down event
6882 OO
.ui
.Toolbar
.prototype.onPointerDown = function ( e
) {
6883 var $closestWidgetToEvent
= $( e
.target
).closest( '.oo-ui-widget' ),
6884 $closestWidgetToToolbar
= this.$element
.closest( '.oo-ui-widget' );
6885 if ( !$closestWidgetToEvent
.length
|| $closestWidgetToEvent
[ 0 ] === $closestWidgetToToolbar
[ 0 ] ) {
6891 * Handle window resize event.
6894 * @param {jQuery.Event} e Window resize event
6896 OO
.ui
.Toolbar
.prototype.onWindowResize = function () {
6897 this.$element
.toggleClass(
6898 'oo-ui-toolbar-narrow',
6899 this.$bar
.width() <= this.narrowThreshold
6904 * Sets up handles and preloads required information for the toolbar to work.
6905 * This must be called after it is attached to a visible document and before doing anything else.
6907 OO
.ui
.Toolbar
.prototype.initialize = function () {
6908 this.initialized
= true;
6909 this.narrowThreshold
= this.$group
.width() + this.$actions
.width();
6910 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
6911 this.onWindowResize();
6917 * Tools can be specified in the following ways:
6919 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6920 * - All tools in a group: `{ group: 'group-name' }`
6921 * - All tools: `'*'` - Using this will make the group a list with a "More" label by default
6923 * @param {Object.<string,Array>} groups List of tool group configurations
6924 * @param {Array|string} [groups.include] Tools to include
6925 * @param {Array|string} [groups.exclude] Tools to exclude
6926 * @param {Array|string} [groups.promote] Tools to promote to the beginning
6927 * @param {Array|string} [groups.demote] Tools to demote to the end
6929 OO
.ui
.Toolbar
.prototype.setup = function ( groups
) {
6930 var i
, len
, type
, group
,
6932 defaultType
= 'bar';
6934 // Cleanup previous groups
6937 // Build out new groups
6938 for ( i
= 0, len
= groups
.length
; i
< len
; i
++ ) {
6939 group
= groups
[ i
];
6940 if ( group
.include
=== '*' ) {
6941 // Apply defaults to catch-all groups
6942 if ( group
.type
=== undefined ) {
6943 group
.type
= 'list';
6945 if ( group
.label
=== undefined ) {
6946 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
6949 // Check type has been registered
6950 type
= this.getToolGroupFactory().lookup( group
.type
) ? group
.type
: defaultType
;
6952 this.getToolGroupFactory().create( type
, this, group
)
6955 this.addItems( items
);
6959 * Remove all tools and groups from the toolbar.
6961 OO
.ui
.Toolbar
.prototype.reset = function () {
6966 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6967 this.items
[ i
].destroy();
6973 * Destroys toolbar, removing event handlers and DOM elements.
6975 * Call this whenever you are done using a toolbar.
6977 OO
.ui
.Toolbar
.prototype.destroy = function () {
6978 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
6980 this.$element
.remove();
6984 * Check if tool has not been used yet.
6986 * @param {string} name Symbolic name of tool
6987 * @return {boolean} Tool is available
6989 OO
.ui
.Toolbar
.prototype.isToolAvailable = function ( name
) {
6990 return !this.tools
[ name
];
6994 * Prevent tool from being used again.
6996 * @param {OO.ui.Tool} tool Tool to reserve
6998 OO
.ui
.Toolbar
.prototype.reserveTool = function ( tool
) {
6999 this.tools
[ tool
.getName() ] = tool
;
7003 * Allow tool to be used again.
7005 * @param {OO.ui.Tool} tool Tool to release
7007 OO
.ui
.Toolbar
.prototype.releaseTool = function ( tool
) {
7008 delete this.tools
[ tool
.getName() ];
7012 * Get accelerator label for tool.
7014 * This is a stub that should be overridden to provide access to accelerator information.
7016 * @param {string} name Symbolic name of tool
7017 * @return {string|undefined} Tool accelerator label if available
7019 OO
.ui
.Toolbar
.prototype.getToolAccelerator = function () {
7024 * Collection of tools.
7026 * Tools can be specified in the following ways:
7028 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
7029 * - All tools in a group: `{ group: 'group-name' }`
7030 * - All tools: `'*'`
7034 * @extends OO.ui.Widget
7035 * @mixins OO.ui.GroupElement
7038 * @param {OO.ui.Toolbar} toolbar
7039 * @param {Object} [config] Configuration options
7040 * @cfg {Array|string} [include=[]] List of tools to include
7041 * @cfg {Array|string} [exclude=[]] List of tools to exclude
7042 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning
7043 * @cfg {Array|string} [demote=[]] List of tools to demote to the end
7045 OO
.ui
.ToolGroup
= function OoUiToolGroup( toolbar
, config
) {
7046 // Allow passing positional parameters inside the config object
7047 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
7049 toolbar
= config
.toolbar
;
7052 // Configuration initialization
7053 config
= config
|| {};
7055 // Parent constructor
7056 OO
.ui
.ToolGroup
.super.call( this, config
);
7058 // Mixin constructors
7059 OO
.ui
.GroupElement
.call( this, config
);
7062 this.toolbar
= toolbar
;
7064 this.pressed
= null;
7065 this.autoDisabled
= false;
7066 this.include
= config
.include
|| [];
7067 this.exclude
= config
.exclude
|| [];
7068 this.promote
= config
.promote
|| [];
7069 this.demote
= config
.demote
|| [];
7070 this.onCapturedMouseKeyUpHandler
= this.onCapturedMouseKeyUp
.bind( this );
7074 mousedown
: this.onMouseKeyDown
.bind( this ),
7075 mouseup
: this.onMouseKeyUp
.bind( this ),
7076 keydown
: this.onMouseKeyDown
.bind( this ),
7077 keyup
: this.onMouseKeyUp
.bind( this ),
7078 focus
: this.onMouseOverFocus
.bind( this ),
7079 blur
: this.onMouseOutBlur
.bind( this ),
7080 mouseover
: this.onMouseOverFocus
.bind( this ),
7081 mouseout
: this.onMouseOutBlur
.bind( this )
7083 this.toolbar
.getToolFactory().connect( this, { register
: 'onToolFactoryRegister' } );
7084 this.aggregate( { disable
: 'itemDisable' } );
7085 this.connect( this, { itemDisable
: 'updateDisabled' } );
7088 this.$group
.addClass( 'oo-ui-toolGroup-tools' );
7090 .addClass( 'oo-ui-toolGroup' )
7091 .append( this.$group
);
7097 OO
.inheritClass( OO
.ui
.ToolGroup
, OO
.ui
.Widget
);
7098 OO
.mixinClass( OO
.ui
.ToolGroup
, OO
.ui
.GroupElement
);
7106 /* Static Properties */
7109 * Show labels in tooltips.
7113 * @property {boolean}
7115 OO
.ui
.ToolGroup
.static.titleTooltips
= false;
7118 * Show acceleration labels in tooltips.
7122 * @property {boolean}
7124 OO
.ui
.ToolGroup
.static.accelTooltips
= false;
7127 * Automatically disable the toolgroup when all tools are disabled
7131 * @property {boolean}
7133 OO
.ui
.ToolGroup
.static.autoDisable
= true;
7140 OO
.ui
.ToolGroup
.prototype.isDisabled = function () {
7141 return this.autoDisabled
|| OO
.ui
.ToolGroup
.super.prototype.isDisabled
.apply( this, arguments
);
7147 OO
.ui
.ToolGroup
.prototype.updateDisabled = function () {
7148 var i
, item
, allDisabled
= true;
7150 if ( this.constructor.static.autoDisable
) {
7151 for ( i
= this.items
.length
- 1; i
>= 0; i
-- ) {
7152 item
= this.items
[ i
];
7153 if ( !item
.isDisabled() ) {
7154 allDisabled
= false;
7158 this.autoDisabled
= allDisabled
;
7160 OO
.ui
.ToolGroup
.super.prototype.updateDisabled
.apply( this, arguments
);
7164 * Handle mouse down and key down events.
7166 * @param {jQuery.Event} e Mouse down or key down event
7168 OO
.ui
.ToolGroup
.prototype.onMouseKeyDown = function ( e
) {
7170 !this.isDisabled() &&
7171 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
7173 this.pressed
= this.getTargetTool( e
);
7174 if ( this.pressed
) {
7175 this.pressed
.setActive( true );
7176 this.getElementDocument().addEventListener( 'mouseup', this.onCapturedMouseKeyUpHandler
, true );
7177 this.getElementDocument().addEventListener( 'keyup', this.onCapturedMouseKeyUpHandler
, true );
7184 * Handle captured mouse up and key up events.
7186 * @param {Event} e Mouse up or key up event
7188 OO
.ui
.ToolGroup
.prototype.onCapturedMouseKeyUp = function ( e
) {
7189 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseKeyUpHandler
, true );
7190 this.getElementDocument().removeEventListener( 'keyup', this.onCapturedMouseKeyUpHandler
, true );
7191 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
7192 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
7193 this.onMouseKeyUp( e
);
7197 * Handle mouse up and key up events.
7199 * @param {jQuery.Event} e Mouse up or key up event
7201 OO
.ui
.ToolGroup
.prototype.onMouseKeyUp = function ( e
) {
7202 var tool
= this.getTargetTool( e
);
7205 !this.isDisabled() && this.pressed
&& this.pressed
=== tool
&&
7206 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
7208 this.pressed
.onSelect();
7209 this.pressed
= null;
7213 this.pressed
= null;
7217 * Handle mouse over and focus events.
7219 * @param {jQuery.Event} e Mouse over or focus event
7221 OO
.ui
.ToolGroup
.prototype.onMouseOverFocus = function ( e
) {
7222 var tool
= this.getTargetTool( e
);
7224 if ( this.pressed
&& this.pressed
=== tool
) {
7225 this.pressed
.setActive( true );
7230 * Handle mouse out and blur events.
7232 * @param {jQuery.Event} e Mouse out or blur event
7234 OO
.ui
.ToolGroup
.prototype.onMouseOutBlur = function ( e
) {
7235 var tool
= this.getTargetTool( e
);
7237 if ( this.pressed
&& this.pressed
=== tool
) {
7238 this.pressed
.setActive( false );
7243 * Get the closest tool to a jQuery.Event.
7245 * Only tool links are considered, which prevents other elements in the tool such as popups from
7246 * triggering tool group interactions.
7249 * @param {jQuery.Event} e
7250 * @return {OO.ui.Tool|null} Tool, `null` if none was found
7252 OO
.ui
.ToolGroup
.prototype.getTargetTool = function ( e
) {
7254 $item
= $( e
.target
).closest( '.oo-ui-tool-link' );
7256 if ( $item
.length
) {
7257 tool
= $item
.parent().data( 'oo-ui-tool' );
7260 return tool
&& !tool
.isDisabled() ? tool
: null;
7264 * Handle tool registry register events.
7266 * If a tool is registered after the group is created, we must repopulate the list to account for:
7268 * - a tool being added that may be included
7269 * - a tool already included being overridden
7271 * @param {string} name Symbolic name of tool
7273 OO
.ui
.ToolGroup
.prototype.onToolFactoryRegister = function () {
7278 * Get the toolbar this group is in.
7280 * @return {OO.ui.Toolbar} Toolbar of group
7282 OO
.ui
.ToolGroup
.prototype.getToolbar = function () {
7283 return this.toolbar
;
7287 * Add and remove tools based on configuration.
7289 OO
.ui
.ToolGroup
.prototype.populate = function () {
7290 var i
, len
, name
, tool
,
7291 toolFactory
= this.toolbar
.getToolFactory(),
7295 list
= this.toolbar
.getToolFactory().getTools(
7296 this.include
, this.exclude
, this.promote
, this.demote
7299 // Build a list of needed tools
7300 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
7304 toolFactory
.lookup( name
) &&
7305 // Tool is available or is already in this group
7306 ( this.toolbar
.isToolAvailable( name
) || this.tools
[ name
] )
7308 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
7309 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
7310 this.toolbar
.tools
[ name
] = true;
7311 tool
= this.tools
[ name
];
7313 // Auto-initialize tools on first use
7314 this.tools
[ name
] = tool
= toolFactory
.create( name
, this );
7317 this.toolbar
.reserveTool( tool
);
7319 names
[ name
] = true;
7322 // Remove tools that are no longer needed
7323 for ( name
in this.tools
) {
7324 if ( !names
[ name
] ) {
7325 this.tools
[ name
].destroy();
7326 this.toolbar
.releaseTool( this.tools
[ name
] );
7327 remove
.push( this.tools
[ name
] );
7328 delete this.tools
[ name
];
7331 if ( remove
.length
) {
7332 this.removeItems( remove
);
7334 // Update emptiness state
7336 this.$element
.removeClass( 'oo-ui-toolGroup-empty' );
7338 this.$element
.addClass( 'oo-ui-toolGroup-empty' );
7340 // Re-add tools (moving existing ones to new locations)
7341 this.addItems( add
);
7342 // Disabled state may depend on items
7343 this.updateDisabled();
7347 * Destroy tool group.
7349 OO
.ui
.ToolGroup
.prototype.destroy = function () {
7353 this.toolbar
.getToolFactory().disconnect( this );
7354 for ( name
in this.tools
) {
7355 this.toolbar
.releaseTool( this.tools
[ name
] );
7356 this.tools
[ name
].disconnect( this ).destroy();
7357 delete this.tools
[ name
];
7359 this.$element
.remove();
7363 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
7364 * consists of a header that contains the dialog title, a body with the message, and a footer that
7365 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
7366 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
7368 * There are two basic types of message dialogs, confirmation and alert:
7370 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
7371 * more details about the consequences.
7372 * - **alert**: the dialog title describes which event occurred and the message provides more information
7373 * about why the event occurred.
7375 * The MessageDialog class specifies two actions: ‘accept’, the primary
7376 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
7377 * passing along the selected action.
7379 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
7382 * // Example: Creating and opening a message dialog window.
7383 * var messageDialog = new OO.ui.MessageDialog();
7385 * // Create and append a window manager.
7386 * var windowManager = new OO.ui.WindowManager();
7387 * $( 'body' ).append( windowManager.$element );
7388 * windowManager.addWindows( [ messageDialog ] );
7389 * // Open the window.
7390 * windowManager.openWindow( messageDialog, {
7391 * title: 'Basic message dialog',
7392 * message: 'This is the message'
7395 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
7398 * @extends OO.ui.Dialog
7401 * @param {Object} [config] Configuration options
7403 OO
.ui
.MessageDialog
= function OoUiMessageDialog( config
) {
7404 // Parent constructor
7405 OO
.ui
.MessageDialog
.super.call( this, config
);
7408 this.verticalActionLayout
= null;
7411 this.$element
.addClass( 'oo-ui-messageDialog' );
7416 OO
.inheritClass( OO
.ui
.MessageDialog
, OO
.ui
.Dialog
);
7418 /* Static Properties */
7420 OO
.ui
.MessageDialog
.static.name
= 'message';
7422 OO
.ui
.MessageDialog
.static.size
= 'small';
7424 OO
.ui
.MessageDialog
.static.verbose
= false;
7429 * The title of a confirmation dialog describes what a progressive action will do. The
7430 * title of an alert dialog describes which event occurred.
7434 * @property {jQuery|string|Function|null}
7436 OO
.ui
.MessageDialog
.static.title
= null;
7439 * The message displayed in the dialog body.
7441 * A confirmation message describes the consequences of a progressive action. An alert
7442 * message describes why an event occurred.
7446 * @property {jQuery|string|Function|null}
7448 OO
.ui
.MessageDialog
.static.message
= null;
7450 OO
.ui
.MessageDialog
.static.actions
= [
7451 { action
: 'accept', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-accept' ), flags
: 'primary' },
7452 { action
: 'reject', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-reject' ), flags
: 'safe' }
7460 OO
.ui
.MessageDialog
.prototype.setManager = function ( manager
) {
7461 OO
.ui
.MessageDialog
.super.prototype.setManager
.call( this, manager
);
7464 this.manager
.connect( this, {
7474 OO
.ui
.MessageDialog
.prototype.onActionResize = function ( action
) {
7476 return OO
.ui
.MessageDialog
.super.prototype.onActionResize
.call( this, action
);
7480 * Handle window resized events.
7484 OO
.ui
.MessageDialog
.prototype.onResize = function () {
7486 dialog
.fitActions();
7487 // Wait for CSS transition to finish and do it again :(
7488 setTimeout( function () {
7489 dialog
.fitActions();
7494 * Toggle action layout between vertical and horizontal.
7498 * @param {boolean} [value] Layout actions vertically, omit to toggle
7501 OO
.ui
.MessageDialog
.prototype.toggleVerticalActionLayout = function ( value
) {
7502 value
= value
=== undefined ? !this.verticalActionLayout
: !!value
;
7504 if ( value
!== this.verticalActionLayout
) {
7505 this.verticalActionLayout
= value
;
7507 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value
)
7508 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value
);
7517 OO
.ui
.MessageDialog
.prototype.getActionProcess = function ( action
) {
7519 return new OO
.ui
.Process( function () {
7520 this.close( { action
: action
} );
7523 return OO
.ui
.MessageDialog
.super.prototype.getActionProcess
.call( this, action
);
7529 * @param {Object} [data] Dialog opening data
7530 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
7531 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
7532 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
7533 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
7536 OO
.ui
.MessageDialog
.prototype.getSetupProcess = function ( data
) {
7540 return OO
.ui
.MessageDialog
.super.prototype.getSetupProcess
.call( this, data
)
7541 .next( function () {
7542 this.title
.setLabel(
7543 data
.title
!== undefined ? data
.title
: this.constructor.static.title
7545 this.message
.setLabel(
7546 data
.message
!== undefined ? data
.message
: this.constructor.static.message
7548 this.message
.$element
.toggleClass(
7549 'oo-ui-messageDialog-message-verbose',
7550 data
.verbose
!== undefined ? data
.verbose
: this.constructor.static.verbose
7558 OO
.ui
.MessageDialog
.prototype.getBodyHeight = function () {
7559 var bodyHeight
, oldOverflow
,
7560 $scrollable
= this.container
.$element
;
7562 oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
7563 $scrollable
[ 0 ].style
.overflow
= 'hidden';
7565 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
7567 bodyHeight
= this.text
.$element
.outerHeight( true );
7568 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
7576 OO
.ui
.MessageDialog
.prototype.setDimensions = function ( dim
) {
7577 var $scrollable
= this.container
.$element
;
7578 OO
.ui
.MessageDialog
.super.prototype.setDimensions
.call( this, dim
);
7580 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
7581 // Need to do it after transition completes (250ms), add 50ms just in case.
7582 setTimeout( function () {
7583 var oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
7584 $scrollable
[ 0 ].style
.overflow
= 'hidden';
7586 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
7588 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
7597 OO
.ui
.MessageDialog
.prototype.initialize = function () {
7599 OO
.ui
.MessageDialog
.super.prototype.initialize
.call( this );
7602 this.$actions
= $( '<div>' );
7603 this.container
= new OO
.ui
.PanelLayout( {
7604 scrollable
: true, classes
: [ 'oo-ui-messageDialog-container' ]
7606 this.text
= new OO
.ui
.PanelLayout( {
7607 padded
: true, expanded
: false, classes
: [ 'oo-ui-messageDialog-text' ]
7609 this.message
= new OO
.ui
.LabelWidget( {
7610 classes
: [ 'oo-ui-messageDialog-message' ]
7614 this.title
.$element
.addClass( 'oo-ui-messageDialog-title' );
7615 this.$content
.addClass( 'oo-ui-messageDialog-content' );
7616 this.container
.$element
.append( this.text
.$element
);
7617 this.text
.$element
.append( this.title
.$element
, this.message
.$element
);
7618 this.$body
.append( this.container
.$element
);
7619 this.$actions
.addClass( 'oo-ui-messageDialog-actions' );
7620 this.$foot
.append( this.$actions
);
7626 OO
.ui
.MessageDialog
.prototype.attachActions = function () {
7627 var i
, len
, other
, special
, others
;
7630 OO
.ui
.MessageDialog
.super.prototype.attachActions
.call( this );
7632 special
= this.actions
.getSpecial();
7633 others
= this.actions
.getOthers();
7634 if ( special
.safe
) {
7635 this.$actions
.append( special
.safe
.$element
);
7636 special
.safe
.toggleFramed( false );
7638 if ( others
.length
) {
7639 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
7640 other
= others
[ i
];
7641 this.$actions
.append( other
.$element
);
7642 other
.toggleFramed( false );
7645 if ( special
.primary
) {
7646 this.$actions
.append( special
.primary
.$element
);
7647 special
.primary
.toggleFramed( false );
7650 if ( !this.isOpening() ) {
7651 // If the dialog is currently opening, this will be called automatically soon.
7652 // This also calls #fitActions.
7658 * Fit action actions into columns or rows.
7660 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
7664 OO
.ui
.MessageDialog
.prototype.fitActions = function () {
7666 previous
= this.verticalActionLayout
,
7667 actions
= this.actions
.get();
7670 this.toggleVerticalActionLayout( false );
7671 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
7672 action
= actions
[ i
];
7673 if ( action
.$element
.innerWidth() < action
.$label
.outerWidth( true ) ) {
7674 this.toggleVerticalActionLayout( true );
7679 // Move the body out of the way of the foot
7680 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
7682 if ( this.verticalActionLayout
!== previous
) {
7683 // We changed the layout, window height might need to be updated.
7689 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
7690 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
7691 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
7692 * relevant. The ProcessDialog class is always extended and customized with the actions and content
7693 * required for each process.
7695 * The process dialog box consists of a header that visually represents the ‘working’ state of long
7696 * processes with an animation. The header contains the dialog title as well as
7697 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
7698 * a ‘primary’ action on the right (e.g., ‘Done’).
7700 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
7701 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
7704 * // Example: Creating and opening a process dialog window.
7705 * function MyProcessDialog( config ) {
7706 * MyProcessDialog.super.call( this, config );
7708 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
7710 * MyProcessDialog.static.title = 'Process dialog';
7711 * MyProcessDialog.static.actions = [
7712 * { action: 'save', label: 'Done', flags: 'primary' },
7713 * { label: 'Cancel', flags: 'safe' }
7716 * MyProcessDialog.prototype.initialize = function () {
7717 * MyProcessDialog.super.prototype.initialize.apply( this, arguments );
7718 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
7719 * 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>' );
7720 * this.$body.append( this.content.$element );
7722 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
7723 * var dialog = this;
7725 * return new OO.ui.Process( function () {
7726 * dialog.close( { action: action } );
7729 * return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
7732 * var windowManager = new OO.ui.WindowManager();
7733 * $( 'body' ).append( windowManager.$element );
7735 * var dialog = new MyProcessDialog();
7736 * windowManager.addWindows( [ dialog ] );
7737 * windowManager.openWindow( dialog );
7739 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
7743 * @extends OO.ui.Dialog
7746 * @param {Object} [config] Configuration options
7748 OO
.ui
.ProcessDialog
= function OoUiProcessDialog( config
) {
7749 // Parent constructor
7750 OO
.ui
.ProcessDialog
.super.call( this, config
);
7753 this.$element
.addClass( 'oo-ui-processDialog' );
7758 OO
.inheritClass( OO
.ui
.ProcessDialog
, OO
.ui
.Dialog
);
7763 * Handle dismiss button click events.
7769 OO
.ui
.ProcessDialog
.prototype.onDismissErrorButtonClick = function () {
7774 * Handle retry button click events.
7776 * Hides errors and then tries again.
7780 OO
.ui
.ProcessDialog
.prototype.onRetryButtonClick = function () {
7782 this.executeAction( this.currentAction
);
7788 OO
.ui
.ProcessDialog
.prototype.onActionResize = function ( action
) {
7789 if ( this.actions
.isSpecial( action
) ) {
7792 return OO
.ui
.ProcessDialog
.super.prototype.onActionResize
.call( this, action
);
7798 OO
.ui
.ProcessDialog
.prototype.initialize = function () {
7800 OO
.ui
.ProcessDialog
.super.prototype.initialize
.call( this );
7803 this.$navigation
= $( '<div>' );
7804 this.$location
= $( '<div>' );
7805 this.$safeActions
= $( '<div>' );
7806 this.$primaryActions
= $( '<div>' );
7807 this.$otherActions
= $( '<div>' );
7808 this.dismissButton
= new OO
.ui
.ButtonWidget( {
7809 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' )
7811 this.retryButton
= new OO
.ui
.ButtonWidget();
7812 this.$errors
= $( '<div>' );
7813 this.$errorsTitle
= $( '<div>' );
7816 this.dismissButton
.connect( this, { click
: 'onDismissErrorButtonClick' } );
7817 this.retryButton
.connect( this, { click
: 'onRetryButtonClick' } );
7820 this.title
.$element
.addClass( 'oo-ui-processDialog-title' );
7822 .append( this.title
.$element
)
7823 .addClass( 'oo-ui-processDialog-location' );
7824 this.$safeActions
.addClass( 'oo-ui-processDialog-actions-safe' );
7825 this.$primaryActions
.addClass( 'oo-ui-processDialog-actions-primary' );
7826 this.$otherActions
.addClass( 'oo-ui-processDialog-actions-other' );
7828 .addClass( 'oo-ui-processDialog-errors-title' )
7829 .text( OO
.ui
.msg( 'ooui-dialog-process-error' ) );
7831 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
7832 .append( this.$errorsTitle
, this.dismissButton
.$element
, this.retryButton
.$element
);
7834 .addClass( 'oo-ui-processDialog-content' )
7835 .append( this.$errors
);
7837 .addClass( 'oo-ui-processDialog-navigation' )
7838 .append( this.$safeActions
, this.$location
, this.$primaryActions
);
7839 this.$head
.append( this.$navigation
);
7840 this.$foot
.append( this.$otherActions
);
7846 OO
.ui
.ProcessDialog
.prototype.getActionWidgets = function ( actions
) {
7847 var i
, len
, widgets
= [];
7848 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
7850 new OO
.ui
.ActionWidget( $.extend( { framed
: true }, actions
[ i
] ) )
7859 OO
.ui
.ProcessDialog
.prototype.attachActions = function () {
7860 var i
, len
, other
, special
, others
;
7863 OO
.ui
.ProcessDialog
.super.prototype.attachActions
.call( this );
7865 special
= this.actions
.getSpecial();
7866 others
= this.actions
.getOthers();
7867 if ( special
.primary
) {
7868 this.$primaryActions
.append( special
.primary
.$element
);
7870 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
7871 other
= others
[ i
];
7872 this.$otherActions
.append( other
.$element
);
7874 if ( special
.safe
) {
7875 this.$safeActions
.append( special
.safe
.$element
);
7879 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
7885 OO
.ui
.ProcessDialog
.prototype.executeAction = function ( action
) {
7887 return OO
.ui
.ProcessDialog
.super.prototype.executeAction
.call( this, action
)
7888 .fail( function ( errors
) {
7889 process
.showErrors( errors
|| [] );
7894 * Fit label between actions.
7899 OO
.ui
.ProcessDialog
.prototype.fitLabel = function () {
7900 var width
= Math
.max(
7901 this.$safeActions
.is( ':visible' ) ? this.$safeActions
.width() : 0,
7902 this.$primaryActions
.is( ':visible' ) ? this.$primaryActions
.width() : 0
7904 this.$location
.css( { paddingLeft
: width
, paddingRight
: width
} );
7910 * Handle errors that occurred during accept or reject processes.
7913 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
7915 OO
.ui
.ProcessDialog
.prototype.showErrors = function ( errors
) {
7916 var i
, len
, $item
, actions
,
7922 if ( errors
instanceof OO
.ui
.Error
) {
7923 errors
= [ errors
];
7926 for ( i
= 0, len
= errors
.length
; i
< len
; i
++ ) {
7927 if ( !errors
[ i
].isRecoverable() ) {
7928 recoverable
= false;
7930 if ( errors
[ i
].isWarning() ) {
7933 $item
= $( '<div>' )
7934 .addClass( 'oo-ui-processDialog-error' )
7935 .append( errors
[ i
].getMessage() );
7936 items
.push( $item
[ 0 ] );
7938 this.$errorItems
= $( items
);
7939 if ( recoverable
) {
7940 abilities
[this.currentAction
] = true;
7941 // Copy the flags from the first matching action
7942 actions
= this.actions
.get( { actions
: this.currentAction
} );
7943 if ( actions
.length
) {
7944 this.retryButton
.clearFlags().setFlags( actions
[0].getFlags() );
7947 abilities
[this.currentAction
] = false;
7948 this.actions
.setAbilities( abilities
);
7951 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-continue' ) );
7953 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-retry' ) );
7955 this.retryButton
.toggle( recoverable
);
7956 this.$errorsTitle
.after( this.$errorItems
);
7957 this.$errors
.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
7965 OO
.ui
.ProcessDialog
.prototype.hideErrors = function () {
7966 this.$errors
.addClass( 'oo-ui-element-hidden' );
7967 if ( this.$errorItems
) {
7968 this.$errorItems
.remove();
7969 this.$errorItems
= null;
7976 OO
.ui
.ProcessDialog
.prototype.getTeardownProcess = function ( data
) {
7978 return OO
.ui
.ProcessDialog
.super.prototype.getTeardownProcess
.call( this, data
)
7979 .first( function () {
7980 // Make sure to hide errors
7986 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
7987 * which is a widget that is specified by reference before any optional configuration settings.
7989 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
7991 * - **left**: The label is placed before the field-widget and aligned with the left margin.
7992 * A left-alignment is used for forms with many fields.
7993 * - **right**: The label is placed before the field-widget and aligned to the right margin.
7994 * A right-alignment is used for long but familiar forms which users tab through,
7995 * verifying the current field with a quick glance at the label.
7996 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
7997 * that users fill out from top to bottom.
7998 * - **inline**: The label is placed after the field-widget and aligned to the left.
7999 * An inline-alignment is best used with checkboxes or radio buttons.
8001 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
8002 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
8004 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8006 * @extends OO.ui.Layout
8007 * @mixins OO.ui.LabelElement
8010 * @param {OO.ui.Widget} fieldWidget Field widget
8011 * @param {Object} [config] Configuration options
8012 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8013 * @cfg {string} [help] Help text. When help text is specified, a help icon will appear
8014 * in the upper-right corner of the rendered field.
8016 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
8017 // Allow passing positional parameters inside the config object
8018 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
8019 config
= fieldWidget
;
8020 fieldWidget
= config
.fieldWidget
;
8023 var hasInputWidget
= fieldWidget
instanceof OO
.ui
.InputWidget
;
8025 // Configuration initialization
8026 config
= $.extend( { align
: 'left' }, config
);
8028 // Parent constructor
8029 OO
.ui
.FieldLayout
.super.call( this, config
);
8031 // Mixin constructors
8032 OO
.ui
.LabelElement
.call( this, config
);
8035 this.fieldWidget
= fieldWidget
;
8036 this.$field
= $( '<div>' );
8037 this.$body
= $( '<' + ( hasInputWidget
? 'label' : 'div' ) + '>' );
8039 if ( config
.help
) {
8040 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
8041 classes
: [ 'oo-ui-fieldLayout-help' ],
8046 this.popupButtonWidget
.getPopup().$body
.append(
8048 .text( config
.help
)
8049 .addClass( 'oo-ui-fieldLayout-help-content' )
8051 this.$help
= this.popupButtonWidget
.$element
;
8053 this.$help
= $( [] );
8057 if ( hasInputWidget
) {
8058 this.$label
.on( 'click', this.onLabelClick
.bind( this ) );
8060 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
8064 .addClass( 'oo-ui-fieldLayout' )
8065 .append( this.$help
, this.$body
);
8066 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
8068 .addClass( 'oo-ui-fieldLayout-field' )
8069 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget
.isDisabled() )
8070 .append( this.fieldWidget
.$element
);
8072 this.setAlignment( config
.align
);
8077 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
8078 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.LabelElement
);
8083 * Handle field disable events.
8086 * @param {boolean} value Field is disabled
8088 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
8089 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
8093 * Handle label mouse click events.
8096 * @param {jQuery.Event} e Mouse click event
8098 OO
.ui
.FieldLayout
.prototype.onLabelClick = function () {
8099 this.fieldWidget
.simulateLabelClick();
8104 * Get the widget contained by the field.
8106 * @return {OO.ui.Widget} Field widget
8108 OO
.ui
.FieldLayout
.prototype.getField = function () {
8109 return this.fieldWidget
;
8113 * Set the field alignment mode.
8116 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
8119 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
8120 if ( value
!== this.align
) {
8121 // Default to 'left'
8122 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
8126 if ( value
=== 'inline' ) {
8127 this.$body
.append( this.$field
, this.$label
);
8129 this.$body
.append( this.$label
, this.$field
);
8131 // Set classes. The following classes can be used here:
8132 // * oo-ui-fieldLayout-align-left
8133 // * oo-ui-fieldLayout-align-right
8134 // * oo-ui-fieldLayout-align-top
8135 // * oo-ui-fieldLayout-align-inline
8137 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
8139 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
8147 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
8148 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
8149 * is required and is specified before any optional configuration settings.
8151 * Labels can be aligned in one of four ways:
8153 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8154 * A left-alignment is used for forms with many fields.
8155 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8156 * A right-alignment is used for long but familiar forms which users tab through,
8157 * verifying the current field with a quick glance at the label.
8158 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8159 * that users fill out from top to bottom.
8160 * - **inline**: The label is placed after the field-widget and aligned to the left.
8161 * An inline-alignment is best used with checkboxes or radio buttons.
8163 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
8164 * text is specified.
8167 * // Example of an ActionFieldLayout
8168 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
8169 * new OO.ui.TextInputWidget( {
8170 * placeholder: 'Field widget'
8172 * new OO.ui.ButtonWidget( {
8176 * label: 'An ActionFieldLayout. This label is aligned top',
8178 * help: 'This is help text'
8182 * $( 'body' ).append( actionFieldLayout.$element );
8186 * @extends OO.ui.FieldLayout
8189 * @param {OO.ui.Widget} fieldWidget Field widget
8190 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
8191 * @param {Object} [config] Configuration options
8192 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8193 * @cfg {string} [help] Help text. When help text is specified, a help icon will appear in the
8194 * upper-right corner of the rendered field.
8196 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
8197 // Allow passing positional parameters inside the config object
8198 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
8199 config
= fieldWidget
;
8200 fieldWidget
= config
.fieldWidget
;
8201 buttonWidget
= config
.buttonWidget
;
8204 // Configuration initialization
8205 config
= $.extend( { align
: 'left' }, config
);
8207 // Parent constructor
8208 OO
.ui
.ActionFieldLayout
.super.call( this, fieldWidget
, config
);
8211 this.fieldWidget
= fieldWidget
;
8212 this.buttonWidget
= buttonWidget
;
8213 this.$button
= $( '<div>' )
8214 .addClass( 'oo-ui-actionFieldLayout-button' )
8215 .append( this.buttonWidget
.$element
);
8216 this.$input
= $( '<div>' )
8217 .addClass( 'oo-ui-actionFieldLayout-input' )
8218 .append( this.fieldWidget
.$element
);
8220 .addClass( 'oo-ui-actionFieldLayout' )
8221 .append( this.$input
, this.$button
);
8226 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
8229 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
8230 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
8231 * configured with a label as well. For more information and examples,
8232 * please see the [OOjs UI documentation on MediaWiki][1].
8235 * // Example of a fieldset layout
8236 * var input1 = new OO.ui.TextInputWidget( {
8237 * placeholder: 'A text input field'
8240 * var input2 = new OO.ui.TextInputWidget( {
8241 * placeholder: 'A text input field'
8244 * var fieldset = new OO.ui.FieldsetLayout( {
8245 * label: 'Example of a fieldset layout'
8248 * fieldset.addItems( [
8249 * new OO.ui.FieldLayout( input1, {
8250 * label: 'Field One'
8252 * new OO.ui.FieldLayout( input2, {
8253 * label: 'Field Two'
8256 * $( 'body' ).append( fieldset.$element );
8258 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8261 * @extends OO.ui.Layout
8262 * @mixins OO.ui.IconElement
8263 * @mixins OO.ui.LabelElement
8264 * @mixins OO.ui.GroupElement
8267 * @param {Object} [config] Configuration options
8268 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
8270 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
8271 // Configuration initialization
8272 config
= config
|| {};
8274 // Parent constructor
8275 OO
.ui
.FieldsetLayout
.super.call( this, config
);
8277 // Mixin constructors
8278 OO
.ui
.IconElement
.call( this, config
);
8279 OO
.ui
.LabelElement
.call( this, config
);
8280 OO
.ui
.GroupElement
.call( this, config
);
8282 if ( config
.help
) {
8283 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
8284 classes
: [ 'oo-ui-fieldsetLayout-help' ],
8289 this.popupButtonWidget
.getPopup().$body
.append(
8291 .text( config
.help
)
8292 .addClass( 'oo-ui-fieldsetLayout-help-content' )
8294 this.$help
= this.popupButtonWidget
.$element
;
8296 this.$help
= $( [] );
8301 .addClass( 'oo-ui-fieldsetLayout' )
8302 .prepend( this.$help
, this.$icon
, this.$label
, this.$group
);
8303 if ( Array
.isArray( config
.items
) ) {
8304 this.addItems( config
.items
);
8310 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
8311 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.IconElement
);
8312 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.LabelElement
);
8313 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.GroupElement
);
8316 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
8317 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
8318 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
8319 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
8321 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
8322 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
8323 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
8324 * some fancier controls. Some controls have both regular and InputWidget variants, for example
8325 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
8326 * often have simplified APIs to match the capabilities of HTML forms.
8327 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
8329 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
8330 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8333 * // Example of a form layout that wraps a fieldset layout
8334 * var input1 = new OO.ui.TextInputWidget( {
8335 * placeholder: 'Username'
8337 * var input2 = new OO.ui.TextInputWidget( {
8338 * placeholder: 'Password',
8341 * var submit = new OO.ui.ButtonInputWidget( {
8345 * var fieldset = new OO.ui.FieldsetLayout( {
8346 * label: 'A form layout'
8348 * fieldset.addItems( [
8349 * new OO.ui.FieldLayout( input1, {
8350 * label: 'Username',
8353 * new OO.ui.FieldLayout( input2, {
8354 * label: 'Password',
8357 * new OO.ui.FieldLayout( submit )
8359 * var form = new OO.ui.FormLayout( {
8360 * items: [ fieldset ],
8361 * action: '/api/formhandler',
8364 * $( 'body' ).append( form.$element );
8367 * @extends OO.ui.Layout
8368 * @mixins OO.ui.GroupElement
8371 * @param {Object} [config] Configuration options
8372 * @cfg {string} [method] HTML form `method` attribute
8373 * @cfg {string} [action] HTML form `action` attribute
8374 * @cfg {string} [enctype] HTML form `enctype` attribute
8375 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
8377 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
8378 // Configuration initialization
8379 config
= config
|| {};
8381 // Parent constructor
8382 OO
.ui
.FormLayout
.super.call( this, config
);
8384 // Mixin constructors
8385 OO
.ui
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
8388 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
8392 .addClass( 'oo-ui-formLayout' )
8394 method
: config
.method
,
8395 action
: config
.action
,
8396 enctype
: config
.enctype
8398 if ( Array
.isArray( config
.items
) ) {
8399 this.addItems( config
.items
);
8405 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
8406 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.GroupElement
);
8411 * A 'submit' event is emitted when the form is submitted.
8416 /* Static Properties */
8418 OO
.ui
.FormLayout
.static.tagName
= 'form';
8423 * Handle form submit events.
8426 * @param {jQuery.Event} e Submit event
8429 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
8430 this.emit( 'submit' );
8435 * 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)
8436 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
8439 * var menuLayout = new OO.ui.MenuLayout( {
8442 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
8443 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
8444 * select = new OO.ui.SelectWidget( {
8446 * new OO.ui.OptionWidget( {
8450 * new OO.ui.OptionWidget( {
8454 * new OO.ui.OptionWidget( {
8458 * new OO.ui.OptionWidget( {
8463 * } ).on( 'select', function ( item ) {
8464 * menuLayout.setMenuPosition( item.getData() );
8467 * menuLayout.$menu.append(
8468 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
8470 * menuLayout.$content.append(
8471 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
8473 * $( 'body' ).append( menuLayout.$element );
8475 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
8476 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
8477 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
8480 * .oo-ui-menuLayout-menu {
8484 * .oo-ui-menuLayout-content {
8492 * @extends OO.ui.Layout
8495 * @param {Object} [config] Configuration options
8496 * @cfg {boolean} [showMenu=true] Show menu
8497 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
8499 OO
.ui
.MenuLayout
= function OoUiMenuLayout( config
) {
8500 // Configuration initialization
8501 config
= $.extend( {
8503 menuPosition
: 'before'
8506 // Parent constructor
8507 OO
.ui
.MenuLayout
.super.call( this, config
);
8512 * @property {jQuery}
8514 this.$menu
= $( '<div>' );
8518 * @property {jQuery}
8520 this.$content
= $( '<div>' );
8524 .addClass( 'oo-ui-menuLayout-menu' );
8525 this.$content
.addClass( 'oo-ui-menuLayout-content' );
8527 .addClass( 'oo-ui-menuLayout' )
8528 .append( this.$content
, this.$menu
);
8529 this.setMenuPosition( config
.menuPosition
);
8530 this.toggleMenu( config
.showMenu
);
8535 OO
.inheritClass( OO
.ui
.MenuLayout
, OO
.ui
.Layout
);
8542 * @param {boolean} showMenu Show menu, omit to toggle
8545 OO
.ui
.MenuLayout
.prototype.toggleMenu = function ( showMenu
) {
8546 showMenu
= showMenu
=== undefined ? !this.showMenu
: !!showMenu
;
8548 if ( this.showMenu
!== showMenu
) {
8549 this.showMenu
= showMenu
;
8551 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu
)
8552 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu
);
8559 * Check if menu is visible
8561 * @return {boolean} Menu is visible
8563 OO
.ui
.MenuLayout
.prototype.isMenuVisible = function () {
8564 return this.showMenu
;
8568 * Set menu position.
8570 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
8571 * @throws {Error} If position value is not supported
8574 OO
.ui
.MenuLayout
.prototype.setMenuPosition = function ( position
) {
8575 this.$element
.removeClass( 'oo-ui-menuLayout-' + this.menuPosition
);
8576 this.menuPosition
= position
;
8577 this.$element
.addClass( 'oo-ui-menuLayout-' + position
);
8583 * Get menu position.
8585 * @return {string} Menu position
8587 OO
.ui
.MenuLayout
.prototype.getMenuPosition = function () {
8588 return this.menuPosition
;
8592 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
8593 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
8594 * through the pages and select which one to display. By default, only one page is
8595 * displayed at a time and the outline is hidden. When a user navigates to a new page,
8596 * the booklet layout automatically focuses on the first focusable element, unless the
8597 * default setting is changed. Optionally, booklets can be configured to show
8598 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
8601 * // Example of a BookletLayout that contains two PageLayouts.
8603 * function PageOneLayout( name, config ) {
8604 * PageOneLayout.super.call( this, name, config );
8605 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
8607 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
8608 * PageOneLayout.prototype.setupOutlineItem = function () {
8609 * this.outlineItem.setLabel( 'Page One' );
8612 * function PageTwoLayout( name, config ) {
8613 * PageTwoLayout.super.call( this, name, config );
8614 * this.$element.append( '<p>Second page</p>' );
8616 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
8617 * PageTwoLayout.prototype.setupOutlineItem = function () {
8618 * this.outlineItem.setLabel( 'Page Two' );
8621 * var page1 = new PageOneLayout( 'one' ),
8622 * page2 = new PageTwoLayout( 'two' );
8624 * var booklet = new OO.ui.BookletLayout( {
8628 * booklet.addPages ( [ page1, page2 ] );
8629 * $( 'body' ).append( booklet.$element );
8632 * @extends OO.ui.MenuLayout
8635 * @param {Object} [config] Configuration options
8636 * @cfg {boolean} [continuous=false] Show all pages, one after another
8637 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
8638 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
8639 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
8641 OO
.ui
.BookletLayout
= function OoUiBookletLayout( config
) {
8642 // Configuration initialization
8643 config
= config
|| {};
8645 // Parent constructor
8646 OO
.ui
.BookletLayout
.super.call( this, config
);
8649 this.currentPageName
= null;
8651 this.ignoreFocus
= false;
8652 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
8653 this.$content
.append( this.stackLayout
.$element
);
8654 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
8655 this.outlineVisible
= false;
8656 this.outlined
= !!config
.outlined
;
8657 if ( this.outlined
) {
8658 this.editable
= !!config
.editable
;
8659 this.outlineControlsWidget
= null;
8660 this.outlineSelectWidget
= new OO
.ui
.OutlineSelectWidget();
8661 this.outlinePanel
= new OO
.ui
.PanelLayout( { scrollable
: true } );
8662 this.$menu
.append( this.outlinePanel
.$element
);
8663 this.outlineVisible
= true;
8664 if ( this.editable
) {
8665 this.outlineControlsWidget
= new OO
.ui
.OutlineControlsWidget(
8666 this.outlineSelectWidget
8670 this.toggleMenu( this.outlined
);
8673 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
8674 if ( this.outlined
) {
8675 this.outlineSelectWidget
.connect( this, { select
: 'onOutlineSelectWidgetSelect' } );
8677 if ( this.autoFocus
) {
8678 // Event 'focus' does not bubble, but 'focusin' does
8679 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
8683 this.$element
.addClass( 'oo-ui-bookletLayout' );
8684 this.stackLayout
.$element
.addClass( 'oo-ui-bookletLayout-stackLayout' );
8685 if ( this.outlined
) {
8686 this.outlinePanel
.$element
8687 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
8688 .append( this.outlineSelectWidget
.$element
);
8689 if ( this.editable
) {
8690 this.outlinePanel
.$element
8691 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
8692 .append( this.outlineControlsWidget
.$element
);
8699 OO
.inheritClass( OO
.ui
.BookletLayout
, OO
.ui
.MenuLayout
);
8704 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
8706 * @param {OO.ui.PageLayout} page Current page
8710 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
8713 * @param {OO.ui.PageLayout[]} page Added pages
8714 * @param {number} index Index pages were added at
8718 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
8719 * {@link #removePages removed} from the booklet.
8722 * @param {OO.ui.PageLayout[]} pages Removed pages
8728 * Handle stack layout focus.
8731 * @param {jQuery.Event} e Focusin event
8733 OO
.ui
.BookletLayout
.prototype.onStackLayoutFocus = function ( e
) {
8736 // Find the page that an element was focused within
8737 $target
= $( e
.target
).closest( '.oo-ui-pageLayout' );
8738 for ( name
in this.pages
) {
8739 // Check for page match, exclude current page to find only page changes
8740 if ( this.pages
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentPageName
) {
8741 this.setPage( name
);
8748 * Handle stack layout set events.
8751 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
8753 OO
.ui
.BookletLayout
.prototype.onStackLayoutSet = function ( page
) {
8756 page
.scrollElementIntoView( { complete: function () {
8757 if ( layout
.autoFocus
) {
8765 * Focus the first input in the current page.
8767 * If no page is selected, the first selectable page will be selected.
8768 * If the focus is already in an element on the current page, nothing will happen.
8769 * @param {number} [itemIndex] A specific item to focus on
8771 OO
.ui
.BookletLayout
.prototype.focus = function ( itemIndex
) {
8773 items
= this.stackLayout
.getItems();
8775 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
8776 page
= items
[ itemIndex
];
8778 page
= this.stackLayout
.getCurrentItem();
8781 if ( !page
&& this.outlined
) {
8782 this.selectFirstSelectablePage();
8783 page
= this.stackLayout
.getCurrentItem();
8788 // Only change the focus if is not already in the current page
8789 if ( !page
.$element
.find( ':focus' ).length
) {
8790 $input
= page
.$element
.find( ':input:first' );
8791 if ( $input
.length
) {
8792 $input
[ 0 ].focus();
8798 * Find the first focusable input in the booklet layout and focus
8801 OO
.ui
.BookletLayout
.prototype.focusFirstFocusable = function () {
8804 items
= this.stackLayout
.getItems(),
8805 checkAndFocus = function () {
8806 if ( OO
.ui
.isFocusableElement( $( this ) ) ) {
8813 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
8817 // Find all potentially focusable elements in the item
8818 // and check if they are focusable
8820 .find( 'input, select, textarea, button, object' )
8821 /* jshint loopfunc:true */
8822 .each( checkAndFocus
);
8827 * Handle outline widget select events.
8830 * @param {OO.ui.OptionWidget|null} item Selected item
8832 OO
.ui
.BookletLayout
.prototype.onOutlineSelectWidgetSelect = function ( item
) {
8834 this.setPage( item
.getData() );
8839 * Check if booklet has an outline.
8841 * @return {boolean} Booklet has an outline
8843 OO
.ui
.BookletLayout
.prototype.isOutlined = function () {
8844 return this.outlined
;
8848 * Check if booklet has editing controls.
8850 * @return {boolean} Booklet is editable
8852 OO
.ui
.BookletLayout
.prototype.isEditable = function () {
8853 return this.editable
;
8857 * Check if booklet has a visible outline.
8859 * @return {boolean} Outline is visible
8861 OO
.ui
.BookletLayout
.prototype.isOutlineVisible = function () {
8862 return this.outlined
&& this.outlineVisible
;
8866 * Hide or show the outline.
8868 * @param {boolean} [show] Show outline, omit to invert current state
8871 OO
.ui
.BookletLayout
.prototype.toggleOutline = function ( show
) {
8872 if ( this.outlined
) {
8873 show
= show
=== undefined ? !this.outlineVisible
: !!show
;
8874 this.outlineVisible
= show
;
8875 this.toggleMenu( show
);
8882 * Get the page closest to the specified page.
8884 * @param {OO.ui.PageLayout} page Page to use as a reference point
8885 * @return {OO.ui.PageLayout|null} Page closest to the specified page
8887 OO
.ui
.BookletLayout
.prototype.getClosestPage = function ( page
) {
8888 var next
, prev
, level
,
8889 pages
= this.stackLayout
.getItems(),
8890 index
= $.inArray( page
, pages
);
8892 if ( index
!== -1 ) {
8893 next
= pages
[ index
+ 1 ];
8894 prev
= pages
[ index
- 1 ];
8895 // Prefer adjacent pages at the same level
8896 if ( this.outlined
) {
8897 level
= this.outlineSelectWidget
.getItemFromData( page
.getName() ).getLevel();
8900 level
=== this.outlineSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
8906 level
=== this.outlineSelectWidget
.getItemFromData( next
.getName() ).getLevel()
8912 return prev
|| next
|| null;
8916 * Get the outline widget.
8918 * If the booklet is not outlined, the method will return `null`.
8920 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
8922 OO
.ui
.BookletLayout
.prototype.getOutline = function () {
8923 return this.outlineSelectWidget
;
8927 * Get the outline controls widget.
8929 * If the outline is not editable, the method will return `null`.
8931 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
8933 OO
.ui
.BookletLayout
.prototype.getOutlineControls = function () {
8934 return this.outlineControlsWidget
;
8938 * Get a page by its symbolic name.
8940 * @param {string} name Symbolic name of page
8941 * @return {OO.ui.PageLayout|undefined} Page, if found
8943 OO
.ui
.BookletLayout
.prototype.getPage = function ( name
) {
8944 return this.pages
[ name
];
8948 * Get the current page.
8950 * @return {OO.ui.PageLayout|undefined} Current page, if found
8952 OO
.ui
.BookletLayout
.prototype.getCurrentPage = function () {
8953 var name
= this.getCurrentPageName();
8954 return name
? this.getPage( name
) : undefined;
8958 * Get the symbolic name of the current page.
8960 * @return {string|null} Symbolic name of the current page
8962 OO
.ui
.BookletLayout
.prototype.getCurrentPageName = function () {
8963 return this.currentPageName
;
8967 * Add pages to the booklet layout
8969 * When pages are added with the same names as existing pages, the existing pages will be
8970 * automatically removed before the new pages are added.
8972 * @param {OO.ui.PageLayout[]} pages Pages to add
8973 * @param {number} index Index of the insertion point
8977 OO
.ui
.BookletLayout
.prototype.addPages = function ( pages
, index
) {
8978 var i
, len
, name
, page
, item
, currentIndex
,
8979 stackLayoutPages
= this.stackLayout
.getItems(),
8983 // Remove pages with same names
8984 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
8986 name
= page
.getName();
8988 if ( Object
.prototype.hasOwnProperty
.call( this.pages
, name
) ) {
8989 // Correct the insertion index
8990 currentIndex
= $.inArray( this.pages
[ name
], stackLayoutPages
);
8991 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
8994 remove
.push( this.pages
[ name
] );
8997 if ( remove
.length
) {
8998 this.removePages( remove
);
9002 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9004 name
= page
.getName();
9005 this.pages
[ page
.getName() ] = page
;
9006 if ( this.outlined
) {
9007 item
= new OO
.ui
.OutlineOptionWidget( { data
: name
} );
9008 page
.setOutlineItem( item
);
9013 if ( this.outlined
&& items
.length
) {
9014 this.outlineSelectWidget
.addItems( items
, index
);
9015 this.selectFirstSelectablePage();
9017 this.stackLayout
.addItems( pages
, index
);
9018 this.emit( 'add', pages
, index
);
9024 * Remove the specified pages from the booklet layout.
9026 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
9028 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
9032 OO
.ui
.BookletLayout
.prototype.removePages = function ( pages
) {
9033 var i
, len
, name
, page
,
9036 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9038 name
= page
.getName();
9039 delete this.pages
[ name
];
9040 if ( this.outlined
) {
9041 items
.push( this.outlineSelectWidget
.getItemFromData( name
) );
9042 page
.setOutlineItem( null );
9045 if ( this.outlined
&& items
.length
) {
9046 this.outlineSelectWidget
.removeItems( items
);
9047 this.selectFirstSelectablePage();
9049 this.stackLayout
.removeItems( pages
);
9050 this.emit( 'remove', pages
);
9056 * Clear all pages from the booklet layout.
9058 * To remove only a subset of pages from the booklet, use the #removePages method.
9063 OO
.ui
.BookletLayout
.prototype.clearPages = function () {
9065 pages
= this.stackLayout
.getItems();
9068 this.currentPageName
= null;
9069 if ( this.outlined
) {
9070 this.outlineSelectWidget
.clearItems();
9071 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9072 pages
[ i
].setOutlineItem( null );
9075 this.stackLayout
.clearItems();
9077 this.emit( 'remove', pages
);
9083 * Set the current page by symbolic name.
9086 * @param {string} name Symbolic name of page
9088 OO
.ui
.BookletLayout
.prototype.setPage = function ( name
) {
9091 page
= this.pages
[ name
];
9093 if ( name
!== this.currentPageName
) {
9094 if ( this.outlined
) {
9095 selectedItem
= this.outlineSelectWidget
.getSelectedItem();
9096 if ( selectedItem
&& selectedItem
.getData() !== name
) {
9097 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getItemFromData( name
) );
9101 if ( this.currentPageName
&& this.pages
[ this.currentPageName
] ) {
9102 this.pages
[ this.currentPageName
].setActive( false );
9103 // Blur anything focused if the next page doesn't have anything focusable - this
9104 // is not needed if the next page has something focusable because once it is focused
9105 // this blur happens automatically
9106 if ( this.autoFocus
&& !page
.$element
.find( ':input' ).length
) {
9107 $focused
= this.pages
[ this.currentPageName
].$element
.find( ':focus' );
9108 if ( $focused
.length
) {
9109 $focused
[ 0 ].blur();
9113 this.currentPageName
= name
;
9114 this.stackLayout
.setItem( page
);
9115 page
.setActive( true );
9116 this.emit( 'set', page
);
9122 * Select the first selectable page.
9126 OO
.ui
.BookletLayout
.prototype.selectFirstSelectablePage = function () {
9127 if ( !this.outlineSelectWidget
.getSelectedItem() ) {
9128 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getFirstSelectableItem() );
9135 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
9136 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
9139 * // Example of a panel layout
9140 * var panel = new OO.ui.PanelLayout( {
9144 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
9146 * $( 'body' ).append( panel.$element );
9149 * @extends OO.ui.Layout
9152 * @param {Object} [config] Configuration options
9153 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
9154 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
9155 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
9156 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
9158 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
9159 // Configuration initialization
9160 config
= $.extend( {
9167 // Parent constructor
9168 OO
.ui
.PanelLayout
.super.call( this, config
);
9171 this.$element
.addClass( 'oo-ui-panelLayout' );
9172 if ( config
.scrollable
) {
9173 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
9175 if ( config
.padded
) {
9176 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
9178 if ( config
.expanded
) {
9179 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
9181 if ( config
.framed
) {
9182 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
9188 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
9191 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
9192 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
9193 * rather extended to include the required content and functionality.
9195 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
9196 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
9197 * {@link OO.ui.BookletLayout BookletLayout} for an example.
9200 * @extends OO.ui.PanelLayout
9203 * @param {string} name Unique symbolic name of page
9204 * @param {Object} [config] Configuration options
9206 OO
.ui
.PageLayout
= function OoUiPageLayout( name
, config
) {
9207 // Allow passing positional parameters inside the config object
9208 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
9213 // Configuration initialization
9214 config
= $.extend( { scrollable
: true }, config
);
9216 // Parent constructor
9217 OO
.ui
.PageLayout
.super.call( this, config
);
9221 this.outlineItem
= null;
9222 this.active
= false;
9225 this.$element
.addClass( 'oo-ui-pageLayout' );
9230 OO
.inheritClass( OO
.ui
.PageLayout
, OO
.ui
.PanelLayout
);
9235 * An 'active' event is emitted when the page becomes active. Pages become active when they are
9236 * shown in a booklet layout that is configured to display only one page at a time.
9239 * @param {boolean} active Page is active
9245 * Get the symbolic name of the page.
9247 * @return {string} Symbolic name of page
9249 OO
.ui
.PageLayout
.prototype.getName = function () {
9254 * Check if page is active.
9256 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
9257 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
9259 * @return {boolean} Page is active
9261 OO
.ui
.PageLayout
.prototype.isActive = function () {
9268 * The outline item allows users to access the page from the booklet's outline
9269 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
9271 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
9273 OO
.ui
.PageLayout
.prototype.getOutlineItem = function () {
9274 return this.outlineItem
;
9278 * Set or unset the outline item.
9280 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
9281 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
9282 * level), use #setupOutlineItem instead of this method.
9284 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
9287 OO
.ui
.PageLayout
.prototype.setOutlineItem = function ( outlineItem
) {
9288 this.outlineItem
= outlineItem
|| null;
9289 if ( outlineItem
) {
9290 this.setupOutlineItem();
9296 * Set up the outline item.
9298 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
9299 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
9300 * the #setOutlineItem method instead.
9302 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
9305 OO
.ui
.PageLayout
.prototype.setupOutlineItem = function () {
9310 * Set the page to its 'active' state.
9312 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
9313 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
9314 * context, setting the active state on a page does nothing.
9316 * @param {boolean} value Page is active
9319 OO
.ui
.PageLayout
.prototype.setActive = function ( active
) {
9322 if ( active
!== this.active
) {
9323 this.active
= active
;
9324 this.$element
.toggleClass( 'oo-ui-pageLayout-active', active
);
9325 this.emit( 'active', this.active
);
9330 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
9331 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
9332 * by setting the #continuous option to 'true'.
9335 * // A stack layout with two panels, configured to be displayed continously
9336 * var myStack = new OO.ui.StackLayout( {
9338 * new OO.ui.PanelLayout( {
9339 * $content: $( '<p>Panel One</p>' ),
9343 * new OO.ui.PanelLayout( {
9344 * $content: $( '<p>Panel Two</p>' ),
9351 * $( 'body' ).append( myStack.$element );
9354 * @extends OO.ui.PanelLayout
9355 * @mixins OO.ui.GroupElement
9358 * @param {Object} [config] Configuration options
9359 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
9360 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
9362 OO
.ui
.StackLayout
= function OoUiStackLayout( config
) {
9363 // Configuration initialization
9364 config
= $.extend( { scrollable
: true }, config
);
9366 // Parent constructor
9367 OO
.ui
.StackLayout
.super.call( this, config
);
9369 // Mixin constructors
9370 OO
.ui
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
9373 this.currentItem
= null;
9374 this.continuous
= !!config
.continuous
;
9377 this.$element
.addClass( 'oo-ui-stackLayout' );
9378 if ( this.continuous
) {
9379 this.$element
.addClass( 'oo-ui-stackLayout-continuous' );
9381 if ( Array
.isArray( config
.items
) ) {
9382 this.addItems( config
.items
);
9388 OO
.inheritClass( OO
.ui
.StackLayout
, OO
.ui
.PanelLayout
);
9389 OO
.mixinClass( OO
.ui
.StackLayout
, OO
.ui
.GroupElement
);
9394 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
9395 * {@link #clearItems cleared} or {@link #setItem displayed}.
9398 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
9404 * Get the current panel.
9406 * @return {OO.ui.Layout|null}
9408 OO
.ui
.StackLayout
.prototype.getCurrentItem = function () {
9409 return this.currentItem
;
9413 * Unset the current item.
9416 * @param {OO.ui.StackLayout} layout
9419 OO
.ui
.StackLayout
.prototype.unsetCurrentItem = function () {
9420 var prevItem
= this.currentItem
;
9421 if ( prevItem
=== null ) {
9425 this.currentItem
= null;
9426 this.emit( 'set', null );
9430 * Add panel layouts to the stack layout.
9432 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
9433 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
9436 * @param {OO.ui.Layout[]} items Panels to add
9437 * @param {number} [index] Index of the insertion point
9440 OO
.ui
.StackLayout
.prototype.addItems = function ( items
, index
) {
9441 // Update the visibility
9442 this.updateHiddenState( items
, this.currentItem
);
9445 OO
.ui
.GroupElement
.prototype.addItems
.call( this, items
, index
);
9447 if ( !this.currentItem
&& items
.length
) {
9448 this.setItem( items
[ 0 ] );
9455 * Remove the specified panels from the stack layout.
9457 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
9458 * you may wish to use the #clearItems method instead.
9460 * @param {OO.ui.Layout[]} items Panels to remove
9464 OO
.ui
.StackLayout
.prototype.removeItems = function ( items
) {
9466 OO
.ui
.GroupElement
.prototype.removeItems
.call( this, items
);
9468 if ( $.inArray( this.currentItem
, items
) !== -1 ) {
9469 if ( this.items
.length
) {
9470 this.setItem( this.items
[ 0 ] );
9472 this.unsetCurrentItem();
9480 * Clear all panels from the stack layout.
9482 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
9483 * a subset of panels, use the #removeItems method.
9488 OO
.ui
.StackLayout
.prototype.clearItems = function () {
9489 this.unsetCurrentItem();
9490 OO
.ui
.GroupElement
.prototype.clearItems
.call( this );
9496 * Show the specified panel.
9498 * If another panel is currently displayed, it will be hidden.
9500 * @param {OO.ui.Layout} item Panel to show
9504 OO
.ui
.StackLayout
.prototype.setItem = function ( item
) {
9505 if ( item
!== this.currentItem
) {
9506 this.updateHiddenState( this.items
, item
);
9508 if ( $.inArray( item
, this.items
) !== -1 ) {
9509 this.currentItem
= item
;
9510 this.emit( 'set', item
);
9512 this.unsetCurrentItem();
9520 * Update the visibility of all items in case of non-continuous view.
9522 * Ensure all items are hidden except for the selected one.
9523 * This method does nothing when the stack is continuous.
9526 * @param {OO.ui.Layout[]} items Item list iterate over
9527 * @param {OO.ui.Layout} [selectedItem] Selected item to show
9529 OO
.ui
.StackLayout
.prototype.updateHiddenState = function ( items
, selectedItem
) {
9532 if ( !this.continuous
) {
9533 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
9534 if ( !selectedItem
|| selectedItem
!== items
[ i
] ) {
9535 items
[ i
].$element
.addClass( 'oo-ui-element-hidden' );
9538 if ( selectedItem
) {
9539 selectedItem
.$element
.removeClass( 'oo-ui-element-hidden' );
9545 * Horizontal bar layout of tools as icon buttons.
9548 * @extends OO.ui.ToolGroup
9551 * @param {OO.ui.Toolbar} toolbar
9552 * @param {Object} [config] Configuration options
9554 OO
.ui
.BarToolGroup
= function OoUiBarToolGroup( toolbar
, config
) {
9555 // Allow passing positional parameters inside the config object
9556 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
9558 toolbar
= config
.toolbar
;
9561 // Parent constructor
9562 OO
.ui
.BarToolGroup
.super.call( this, toolbar
, config
);
9565 this.$element
.addClass( 'oo-ui-barToolGroup' );
9570 OO
.inheritClass( OO
.ui
.BarToolGroup
, OO
.ui
.ToolGroup
);
9572 /* Static Properties */
9574 OO
.ui
.BarToolGroup
.static.titleTooltips
= true;
9576 OO
.ui
.BarToolGroup
.static.accelTooltips
= true;
9578 OO
.ui
.BarToolGroup
.static.name
= 'bar';
9581 * Popup list of tools with an icon and optional label.
9585 * @extends OO.ui.ToolGroup
9586 * @mixins OO.ui.IconElement
9587 * @mixins OO.ui.IndicatorElement
9588 * @mixins OO.ui.LabelElement
9589 * @mixins OO.ui.TitledElement
9590 * @mixins OO.ui.ClippableElement
9591 * @mixins OO.ui.TabIndexedElement
9594 * @param {OO.ui.Toolbar} toolbar
9595 * @param {Object} [config] Configuration options
9596 * @cfg {string} [header] Text to display at the top of the pop-up
9598 OO
.ui
.PopupToolGroup
= function OoUiPopupToolGroup( toolbar
, config
) {
9599 // Allow passing positional parameters inside the config object
9600 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
9602 toolbar
= config
.toolbar
;
9605 // Configuration initialization
9606 config
= config
|| {};
9608 // Parent constructor
9609 OO
.ui
.PopupToolGroup
.super.call( this, toolbar
, config
);
9612 this.active
= false;
9613 this.dragging
= false;
9614 this.onBlurHandler
= this.onBlur
.bind( this );
9615 this.$handle
= $( '<span>' );
9617 // Mixin constructors
9618 OO
.ui
.IconElement
.call( this, config
);
9619 OO
.ui
.IndicatorElement
.call( this, config
);
9620 OO
.ui
.LabelElement
.call( this, config
);
9621 OO
.ui
.TitledElement
.call( this, config
);
9622 OO
.ui
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
9623 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
9627 keydown
: this.onHandleMouseKeyDown
.bind( this ),
9628 keyup
: this.onHandleMouseKeyUp
.bind( this ),
9629 mousedown
: this.onHandleMouseKeyDown
.bind( this ),
9630 mouseup
: this.onHandleMouseKeyUp
.bind( this )
9635 .addClass( 'oo-ui-popupToolGroup-handle' )
9636 .append( this.$icon
, this.$label
, this.$indicator
);
9637 // If the pop-up should have a header, add it to the top of the toolGroup.
9638 // Note: If this feature is useful for other widgets, we could abstract it into an
9639 // OO.ui.HeaderedElement mixin constructor.
9640 if ( config
.header
!== undefined ) {
9642 .prepend( $( '<span>' )
9643 .addClass( 'oo-ui-popupToolGroup-header' )
9644 .text( config
.header
)
9648 .addClass( 'oo-ui-popupToolGroup' )
9649 .prepend( this.$handle
);
9654 OO
.inheritClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ToolGroup
);
9655 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.IconElement
);
9656 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.IndicatorElement
);
9657 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.LabelElement
);
9658 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.TitledElement
);
9659 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ClippableElement
);
9660 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.TabIndexedElement
);
9662 /* Static Properties */
9669 OO
.ui
.PopupToolGroup
.prototype.setDisabled = function () {
9671 OO
.ui
.PopupToolGroup
.super.prototype.setDisabled
.apply( this, arguments
);
9673 if ( this.isDisabled() && this.isElementAttached() ) {
9674 this.setActive( false );
9679 * Handle focus being lost.
9681 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
9683 * @param {jQuery.Event} e Mouse up or key up event
9685 OO
.ui
.PopupToolGroup
.prototype.onBlur = function ( e
) {
9686 // Only deactivate when clicking outside the dropdown element
9687 if ( $( e
.target
).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element
[ 0 ] ) {
9688 this.setActive( false );
9695 OO
.ui
.PopupToolGroup
.prototype.onMouseKeyUp = function ( e
) {
9696 // Only close toolgroup when a tool was actually selected
9698 !this.isDisabled() && this.pressed
&& this.pressed
=== this.getTargetTool( e
) &&
9699 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
9701 this.setActive( false );
9703 return OO
.ui
.PopupToolGroup
.super.prototype.onMouseKeyUp
.call( this, e
);
9707 * Handle mouse up and key up events.
9709 * @param {jQuery.Event} e Mouse up or key up event
9711 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyUp = function ( e
) {
9713 !this.isDisabled() &&
9714 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
9721 * Handle mouse down and key down events.
9723 * @param {jQuery.Event} e Mouse down or key down event
9725 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyDown = function ( e
) {
9727 !this.isDisabled() &&
9728 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
9730 this.setActive( !this.active
);
9736 * Switch into active mode.
9738 * When active, mouseup events anywhere in the document will trigger deactivation.
9740 OO
.ui
.PopupToolGroup
.prototype.setActive = function ( value
) {
9742 if ( this.active
!== value
) {
9743 this.active
= value
;
9745 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler
, true );
9746 this.getElementDocument().addEventListener( 'keyup', this.onBlurHandler
, true );
9748 // Try anchoring the popup to the left first
9749 this.$element
.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
9750 this.toggleClipping( true );
9751 if ( this.isClippedHorizontally() ) {
9752 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
9753 this.toggleClipping( false );
9755 .removeClass( 'oo-ui-popupToolGroup-left' )
9756 .addClass( 'oo-ui-popupToolGroup-right' );
9757 this.toggleClipping( true );
9760 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler
, true );
9761 this.getElementDocument().removeEventListener( 'keyup', this.onBlurHandler
, true );
9762 this.$element
.removeClass(
9763 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
9765 this.toggleClipping( false );
9771 * Drop down list layout of tools as labeled icon buttons.
9773 * This layout allows some tools to be collapsible, controlled by a "More" / "Fewer" option at the
9774 * bottom of the main list. These are not automatically positioned at the bottom of the list; you
9775 * may want to use the 'promote' and 'demote' configuration options to achieve this.
9778 * @extends OO.ui.PopupToolGroup
9781 * @param {OO.ui.Toolbar} toolbar
9782 * @param {Object} [config] Configuration options
9783 * @cfg {Array} [allowCollapse] List of tools that can be collapsed. Remaining tools will be always
9785 * @cfg {Array} [forceExpand] List of tools that *may not* be collapsed. All remaining tools will be
9786 * allowed to be collapsed.
9787 * @cfg {boolean} [expanded=false] Whether the collapsible tools are expanded by default
9789 OO
.ui
.ListToolGroup
= function OoUiListToolGroup( toolbar
, config
) {
9790 // Allow passing positional parameters inside the config object
9791 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
9793 toolbar
= config
.toolbar
;
9796 // Configuration initialization
9797 config
= config
|| {};
9799 // Properties (must be set before parent constructor, which calls #populate)
9800 this.allowCollapse
= config
.allowCollapse
;
9801 this.forceExpand
= config
.forceExpand
;
9802 this.expanded
= config
.expanded
!== undefined ? config
.expanded
: false;
9803 this.collapsibleTools
= [];
9805 // Parent constructor
9806 OO
.ui
.ListToolGroup
.super.call( this, toolbar
, config
);
9809 this.$element
.addClass( 'oo-ui-listToolGroup' );
9814 OO
.inheritClass( OO
.ui
.ListToolGroup
, OO
.ui
.PopupToolGroup
);
9816 /* Static Properties */
9818 OO
.ui
.ListToolGroup
.static.accelTooltips
= true;
9820 OO
.ui
.ListToolGroup
.static.name
= 'list';
9827 OO
.ui
.ListToolGroup
.prototype.populate = function () {
9828 var i
, len
, allowCollapse
= [];
9830 OO
.ui
.ListToolGroup
.super.prototype.populate
.call( this );
9832 // Update the list of collapsible tools
9833 if ( this.allowCollapse
!== undefined ) {
9834 allowCollapse
= this.allowCollapse
;
9835 } else if ( this.forceExpand
!== undefined ) {
9836 allowCollapse
= OO
.simpleArrayDifference( Object
.keys( this.tools
), this.forceExpand
);
9839 this.collapsibleTools
= [];
9840 for ( i
= 0, len
= allowCollapse
.length
; i
< len
; i
++ ) {
9841 if ( this.tools
[ allowCollapse
[ i
] ] !== undefined ) {
9842 this.collapsibleTools
.push( this.tools
[ allowCollapse
[ i
] ] );
9846 // Keep at the end, even when tools are added
9847 this.$group
.append( this.getExpandCollapseTool().$element
);
9849 this.getExpandCollapseTool().toggle( this.collapsibleTools
.length
!== 0 );
9850 this.updateCollapsibleState();
9853 OO
.ui
.ListToolGroup
.prototype.getExpandCollapseTool = function () {
9854 if ( this.expandCollapseTool
=== undefined ) {
9855 var ExpandCollapseTool = function () {
9856 ExpandCollapseTool
.super.apply( this, arguments
);
9859 OO
.inheritClass( ExpandCollapseTool
, OO
.ui
.Tool
);
9861 ExpandCollapseTool
.prototype.onSelect = function () {
9862 this.toolGroup
.expanded
= !this.toolGroup
.expanded
;
9863 this.toolGroup
.updateCollapsibleState();
9864 this.setActive( false );
9866 ExpandCollapseTool
.prototype.onUpdateState = function () {
9867 // Do nothing. Tool interface requires an implementation of this function.
9870 ExpandCollapseTool
.static.name
= 'more-fewer';
9872 this.expandCollapseTool
= new ExpandCollapseTool( this );
9874 return this.expandCollapseTool
;
9880 OO
.ui
.ListToolGroup
.prototype.onMouseKeyUp = function ( e
) {
9881 // Do not close the popup when the user wants to show more/fewer tools
9883 $( e
.target
).closest( '.oo-ui-tool-name-more-fewer' ).length
&&
9884 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
9886 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
9887 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
9888 return OO
.ui
.ListToolGroup
.super.super.prototype.onMouseKeyUp
.call( this, e
);
9890 return OO
.ui
.ListToolGroup
.super.prototype.onMouseKeyUp
.call( this, e
);
9894 OO
.ui
.ListToolGroup
.prototype.updateCollapsibleState = function () {
9897 this.getExpandCollapseTool()
9898 .setIcon( this.expanded
? 'collapse' : 'expand' )
9899 .setTitle( OO
.ui
.msg( this.expanded
? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
9901 for ( i
= 0, len
= this.collapsibleTools
.length
; i
< len
; i
++ ) {
9902 this.collapsibleTools
[ i
].toggle( this.expanded
);
9907 * Drop down menu layout of tools as selectable menu items.
9910 * @extends OO.ui.PopupToolGroup
9913 * @param {OO.ui.Toolbar} toolbar
9914 * @param {Object} [config] Configuration options
9916 OO
.ui
.MenuToolGroup
= function OoUiMenuToolGroup( toolbar
, config
) {
9917 // Allow passing positional parameters inside the config object
9918 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
9920 toolbar
= config
.toolbar
;
9923 // Configuration initialization
9924 config
= config
|| {};
9926 // Parent constructor
9927 OO
.ui
.MenuToolGroup
.super.call( this, toolbar
, config
);
9930 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
9933 this.$element
.addClass( 'oo-ui-menuToolGroup' );
9938 OO
.inheritClass( OO
.ui
.MenuToolGroup
, OO
.ui
.PopupToolGroup
);
9940 /* Static Properties */
9942 OO
.ui
.MenuToolGroup
.static.accelTooltips
= true;
9944 OO
.ui
.MenuToolGroup
.static.name
= 'menu';
9949 * Handle the toolbar state being updated.
9951 * When the state changes, the title of each active item in the menu will be joined together and
9952 * used as a label for the group. The label will be empty if none of the items are active.
9954 OO
.ui
.MenuToolGroup
.prototype.onUpdateState = function () {
9958 for ( name
in this.tools
) {
9959 if ( this.tools
[ name
].isActive() ) {
9960 labelTexts
.push( this.tools
[ name
].getTitle() );
9964 this.setLabel( labelTexts
.join( ', ' ) || ' ' );
9968 * Tool that shows a popup when selected.
9972 * @extends OO.ui.Tool
9973 * @mixins OO.ui.PopupElement
9976 * @param {OO.ui.ToolGroup} toolGroup
9977 * @param {Object} [config] Configuration options
9979 OO
.ui
.PopupTool
= function OoUiPopupTool( toolGroup
, config
) {
9980 // Allow passing positional parameters inside the config object
9981 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
9983 toolGroup
= config
.toolGroup
;
9986 // Parent constructor
9987 OO
.ui
.PopupTool
.super.call( this, toolGroup
, config
);
9989 // Mixin constructors
9990 OO
.ui
.PopupElement
.call( this, config
);
9994 .addClass( 'oo-ui-popupTool' )
9995 .append( this.popup
.$element
);
10000 OO
.inheritClass( OO
.ui
.PopupTool
, OO
.ui
.Tool
);
10001 OO
.mixinClass( OO
.ui
.PopupTool
, OO
.ui
.PopupElement
);
10006 * Handle the tool being selected.
10010 OO
.ui
.PopupTool
.prototype.onSelect = function () {
10011 if ( !this.isDisabled() ) {
10012 this.popup
.toggle();
10014 this.setActive( false );
10019 * Handle the toolbar state being updated.
10023 OO
.ui
.PopupTool
.prototype.onUpdateState = function () {
10024 this.setActive( false );
10028 * Tool that has a tool group inside. This is a bad workaround for the lack of proper hierarchical
10029 * menus in toolbars (T74159).
10033 * @extends OO.ui.Tool
10036 * @param {OO.ui.ToolGroup} toolGroup
10037 * @param {Object} [config] Configuration options
10039 OO
.ui
.ToolGroupTool
= function OoUiToolGroupTool( toolGroup
, config
) {
10040 // Allow passing positional parameters inside the config object
10041 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
10042 config
= toolGroup
;
10043 toolGroup
= config
.toolGroup
;
10046 // Parent constructor
10047 OO
.ui
.ToolGroupTool
.super.call( this, toolGroup
, config
);
10050 this.innerToolGroup
= this.createGroup( this.constructor.static.groupConfig
);
10053 this.$link
.remove();
10055 .addClass( 'oo-ui-toolGroupTool' )
10056 .append( this.innerToolGroup
.$element
);
10061 OO
.inheritClass( OO
.ui
.ToolGroupTool
, OO
.ui
.Tool
);
10063 /* Static Properties */
10066 * Tool group configuration. See OO.ui.Toolbar#setup for the accepted values.
10068 * @property {Object.<string,Array>}
10070 OO
.ui
.ToolGroupTool
.static.groupConfig
= {};
10075 * Handle the tool being selected.
10079 OO
.ui
.ToolGroupTool
.prototype.onSelect = function () {
10080 this.innerToolGroup
.setActive( !this.innerToolGroup
.active
);
10085 * Handle the toolbar state being updated.
10089 OO
.ui
.ToolGroupTool
.prototype.onUpdateState = function () {
10090 this.setActive( false );
10094 * Build a OO.ui.ToolGroup from the configuration.
10096 * @param {Object.<string,Array>} group Tool group configuration. See OO.ui.Toolbar#setup for the
10098 * @return {OO.ui.ListToolGroup}
10100 OO
.ui
.ToolGroupTool
.prototype.createGroup = function ( group
) {
10101 if ( group
.include
=== '*' ) {
10102 // Apply defaults to catch-all groups
10103 if ( group
.label
=== undefined ) {
10104 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
10108 return this.toolbar
.getToolGroupFactory().create( 'list', this.toolbar
, group
);
10112 * Mixin for OO.ui.Widget subclasses to provide OO.ui.GroupElement.
10114 * Use together with OO.ui.ItemWidget to make disabled state inheritable.
10119 * @extends OO.ui.GroupElement
10122 * @param {Object} [config] Configuration options
10124 OO
.ui
.GroupWidget
= function OoUiGroupWidget( config
) {
10125 // Parent constructor
10126 OO
.ui
.GroupWidget
.super.call( this, config
);
10131 OO
.inheritClass( OO
.ui
.GroupWidget
, OO
.ui
.GroupElement
);
10136 * Set the disabled state of the widget.
10138 * This will also update the disabled state of child widgets.
10140 * @param {boolean} disabled Disable widget
10143 OO
.ui
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
10147 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
10148 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
10150 // During construction, #setDisabled is called before the OO.ui.GroupElement constructor
10151 if ( this.items
) {
10152 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
10153 this.items
[ i
].updateDisabled();
10161 * Mixin for widgets used as items in widgets that inherit OO.ui.GroupWidget.
10163 * Item widgets have a reference to a OO.ui.GroupWidget while they are attached to the group. This
10164 * allows bidirectional communication.
10166 * Use together with OO.ui.GroupWidget to make disabled state inheritable.
10174 OO
.ui
.ItemWidget
= function OoUiItemWidget() {
10181 * Check if widget is disabled.
10183 * Checks parent if present, making disabled state inheritable.
10185 * @return {boolean} Widget is disabled
10187 OO
.ui
.ItemWidget
.prototype.isDisabled = function () {
10188 return this.disabled
||
10189 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
10193 * Set group element is in.
10195 * @param {OO.ui.GroupElement|null} group Group element, null if none
10198 OO
.ui
.ItemWidget
.prototype.setElementGroup = function ( group
) {
10200 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
10201 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
10203 // Initialize item disabled states
10204 this.updateDisabled();
10210 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
10211 * Controls include moving items up and down, removing items, and adding different kinds of items.
10212 * ####Currently, this class is only used by {@link OO.ui.BookletLayout BookletLayouts}.####
10215 * @extends OO.ui.Widget
10216 * @mixins OO.ui.GroupElement
10217 * @mixins OO.ui.IconElement
10220 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
10221 * @param {Object} [config] Configuration options
10222 * @cfg {Object} [abilities] List of abilties
10223 * @cfg {boolean} [abilities.move=true] Allow moving movable items
10224 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
10226 OO
.ui
.OutlineControlsWidget
= function OoUiOutlineControlsWidget( outline
, config
) {
10227 // Allow passing positional parameters inside the config object
10228 if ( OO
.isPlainObject( outline
) && config
=== undefined ) {
10230 outline
= config
.outline
;
10233 // Configuration initialization
10234 config
= $.extend( { icon
: 'add' }, config
);
10236 // Parent constructor
10237 OO
.ui
.OutlineControlsWidget
.super.call( this, config
);
10239 // Mixin constructors
10240 OO
.ui
.GroupElement
.call( this, config
);
10241 OO
.ui
.IconElement
.call( this, config
);
10244 this.outline
= outline
;
10245 this.$movers
= $( '<div>' );
10246 this.upButton
= new OO
.ui
.ButtonWidget( {
10249 title
: OO
.ui
.msg( 'ooui-outline-control-move-up' )
10251 this.downButton
= new OO
.ui
.ButtonWidget( {
10254 title
: OO
.ui
.msg( 'ooui-outline-control-move-down' )
10256 this.removeButton
= new OO
.ui
.ButtonWidget( {
10259 title
: OO
.ui
.msg( 'ooui-outline-control-remove' )
10261 this.abilities
= { move: true, remove
: true };
10264 outline
.connect( this, {
10265 select
: 'onOutlineChange',
10266 add
: 'onOutlineChange',
10267 remove
: 'onOutlineChange'
10269 this.upButton
.connect( this, { click
: [ 'emit', 'move', -1 ] } );
10270 this.downButton
.connect( this, { click
: [ 'emit', 'move', 1 ] } );
10271 this.removeButton
.connect( this, { click
: [ 'emit', 'remove' ] } );
10274 this.$element
.addClass( 'oo-ui-outlineControlsWidget' );
10275 this.$group
.addClass( 'oo-ui-outlineControlsWidget-items' );
10277 .addClass( 'oo-ui-outlineControlsWidget-movers' )
10278 .append( this.removeButton
.$element
, this.upButton
.$element
, this.downButton
.$element
);
10279 this.$element
.append( this.$icon
, this.$group
, this.$movers
);
10280 this.setAbilities( config
.abilities
|| {} );
10285 OO
.inheritClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.Widget
);
10286 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.GroupElement
);
10287 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.IconElement
);
10293 * @param {number} places Number of places to move
10305 * @param {Object} abilities List of abilties
10306 * @param {boolean} [abilities.move] Allow moving movable items
10307 * @param {boolean} [abilities.remove] Allow removing removable items
10309 OO
.ui
.OutlineControlsWidget
.prototype.setAbilities = function ( abilities
) {
10312 for ( ability
in this.abilities
) {
10313 if ( abilities
[ability
] !== undefined ) {
10314 this.abilities
[ability
] = !!abilities
[ability
];
10318 this.onOutlineChange();
10324 * Handle outline change events.
10326 OO
.ui
.OutlineControlsWidget
.prototype.onOutlineChange = function () {
10327 var i
, len
, firstMovable
, lastMovable
,
10328 items
= this.outline
.getItems(),
10329 selectedItem
= this.outline
.getSelectedItem(),
10330 movable
= this.abilities
.move && selectedItem
&& selectedItem
.isMovable(),
10331 removable
= this.abilities
.remove
&& selectedItem
&& selectedItem
.isRemovable();
10335 len
= items
.length
;
10336 while ( ++i
< len
) {
10337 if ( items
[ i
].isMovable() ) {
10338 firstMovable
= items
[ i
];
10344 if ( items
[ i
].isMovable() ) {
10345 lastMovable
= items
[ i
];
10350 this.upButton
.setDisabled( !movable
|| selectedItem
=== firstMovable
);
10351 this.downButton
.setDisabled( !movable
|| selectedItem
=== lastMovable
);
10352 this.removeButton
.setDisabled( !removable
);
10356 * ToggleWidget implements basic behavior of widgets with an on/off state.
10357 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
10361 * @extends OO.ui.Widget
10364 * @param {Object} [config] Configuration options
10365 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
10366 * By default, the toggle is in the 'off' state.
10368 OO
.ui
.ToggleWidget
= function OoUiToggleWidget( config
) {
10369 // Configuration initialization
10370 config
= config
|| {};
10372 // Parent constructor
10373 OO
.ui
.ToggleWidget
.super.call( this, config
);
10379 this.$element
.addClass( 'oo-ui-toggleWidget' );
10380 this.setValue( !!config
.value
);
10385 OO
.inheritClass( OO
.ui
.ToggleWidget
, OO
.ui
.Widget
);
10392 * A change event is emitted when the on/off state of the toggle changes.
10394 * @param {boolean} value Value representing the new state of the toggle
10400 * Get the value representing the toggle’s state.
10402 * @return {boolean} The on/off state of the toggle
10404 OO
.ui
.ToggleWidget
.prototype.getValue = function () {
10409 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
10411 * @param {boolean} value The state of the toggle
10415 OO
.ui
.ToggleWidget
.prototype.setValue = function ( value
) {
10417 if ( this.value
!== value
) {
10418 this.value
= value
;
10419 this.emit( 'change', value
);
10420 this.$element
.toggleClass( 'oo-ui-toggleWidget-on', value
);
10421 this.$element
.toggleClass( 'oo-ui-toggleWidget-off', !value
);
10422 this.$element
.attr( 'aria-checked', value
.toString() );
10428 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
10429 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
10430 * removed, and cleared from the group.
10433 * // Example: A ButtonGroupWidget with two buttons
10434 * var button1 = new OO.ui.PopupButtonWidget( {
10435 * label: 'Select a category',
10438 * $content: $( '<p>List of categories...</p>' ),
10443 * var button2 = new OO.ui.ButtonWidget( {
10444 * label: 'Add item'
10446 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
10447 * items: [button1, button2]
10449 * $( 'body' ).append( buttonGroup.$element );
10452 * @extends OO.ui.Widget
10453 * @mixins OO.ui.GroupElement
10456 * @param {Object} [config] Configuration options
10457 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
10459 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
10460 // Configuration initialization
10461 config
= config
|| {};
10463 // Parent constructor
10464 OO
.ui
.ButtonGroupWidget
.super.call( this, config
);
10466 // Mixin constructors
10467 OO
.ui
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
10470 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
10471 if ( Array
.isArray( config
.items
) ) {
10472 this.addItems( config
.items
);
10478 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
10479 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.GroupElement
);
10482 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
10483 * feels, and functionality can be customized via the class’s configuration options
10484 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
10487 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
10490 * // A button widget
10491 * var button = new OO.ui.ButtonWidget( {
10492 * label: 'Button with Icon',
10494 * iconTitle: 'Remove'
10496 * $( 'body' ).append( button.$element );
10498 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
10501 * @extends OO.ui.Widget
10502 * @mixins OO.ui.ButtonElement
10503 * @mixins OO.ui.IconElement
10504 * @mixins OO.ui.IndicatorElement
10505 * @mixins OO.ui.LabelElement
10506 * @mixins OO.ui.TitledElement
10507 * @mixins OO.ui.FlaggedElement
10508 * @mixins OO.ui.TabIndexedElement
10511 * @param {Object} [config] Configuration options
10512 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
10513 * @cfg {string} [target] The frame or window in which to open the hyperlink.
10514 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
10516 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
10517 // Configuration initialization
10518 config
= config
|| {};
10520 // Parent constructor
10521 OO
.ui
.ButtonWidget
.super.call( this, config
);
10523 // Mixin constructors
10524 OO
.ui
.ButtonElement
.call( this, config
);
10525 OO
.ui
.IconElement
.call( this, config
);
10526 OO
.ui
.IndicatorElement
.call( this, config
);
10527 OO
.ui
.LabelElement
.call( this, config
);
10528 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
10529 OO
.ui
.FlaggedElement
.call( this, config
);
10530 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
10534 this.target
= null;
10535 this.noFollow
= false;
10538 this.connect( this, { disable
: 'onDisable' } );
10541 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
10543 .addClass( 'oo-ui-buttonWidget' )
10544 .append( this.$button
);
10545 this.setHref( config
.href
);
10546 this.setTarget( config
.target
);
10547 this.setNoFollow( config
.noFollow
);
10552 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
10553 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.ButtonElement
);
10554 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.IconElement
);
10555 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.IndicatorElement
);
10556 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.LabelElement
);
10557 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.TitledElement
);
10558 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.FlaggedElement
);
10559 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.TabIndexedElement
);
10566 OO
.ui
.ButtonWidget
.prototype.onMouseDown = function ( e
) {
10567 if ( !this.isDisabled() ) {
10568 // Remove the tab-index while the button is down to prevent the button from stealing focus
10569 this.$button
.removeAttr( 'tabindex' );
10572 return OO
.ui
.ButtonElement
.prototype.onMouseDown
.call( this, e
);
10578 OO
.ui
.ButtonWidget
.prototype.onMouseUp = function ( e
) {
10579 if ( !this.isDisabled() ) {
10580 // Restore the tab-index after the button is up to restore the button's accessibility
10581 this.$button
.attr( 'tabindex', this.tabIndex
);
10584 return OO
.ui
.ButtonElement
.prototype.onMouseUp
.call( this, e
);
10590 OO
.ui
.ButtonWidget
.prototype.onClick = function ( e
) {
10591 var ret
= OO
.ui
.ButtonElement
.prototype.onClick
.call( this, e
);
10601 OO
.ui
.ButtonWidget
.prototype.onKeyPress = function ( e
) {
10602 var ret
= OO
.ui
.ButtonElement
.prototype.onKeyPress
.call( this, e
);
10610 * Get hyperlink location.
10612 * @return {string} Hyperlink location
10614 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
10619 * Get hyperlink target.
10621 * @return {string} Hyperlink target
10623 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
10624 return this.target
;
10628 * Get search engine traversal hint.
10630 * @return {boolean} Whether search engines should avoid traversing this hyperlink
10632 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
10633 return this.noFollow
;
10637 * Set hyperlink location.
10639 * @param {string|null} href Hyperlink location, null to remove
10641 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
10642 href
= typeof href
=== 'string' ? href
: null;
10644 if ( href
!== this.href
) {
10653 * Update the `href` attribute, in case of changes to href or
10659 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
10660 if ( this.href
!== null && !this.isDisabled() ) {
10661 this.$button
.attr( 'href', this.href
);
10663 this.$button
.removeAttr( 'href' );
10670 * Handle disable events.
10673 * @param {boolean} disabled Element is disabled
10675 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
10680 * Set hyperlink target.
10682 * @param {string|null} target Hyperlink target, null to remove
10684 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
10685 target
= typeof target
=== 'string' ? target
: null;
10687 if ( target
!== this.target
) {
10688 this.target
= target
;
10689 if ( target
!== null ) {
10690 this.$button
.attr( 'target', target
);
10692 this.$button
.removeAttr( 'target' );
10700 * Set search engine traversal hint.
10702 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
10704 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
10705 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
10707 if ( noFollow
!== this.noFollow
) {
10708 this.noFollow
= noFollow
;
10710 this.$button
.attr( 'rel', 'nofollow' );
10712 this.$button
.removeAttr( 'rel' );
10720 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
10721 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
10724 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
10725 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
10728 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
10731 * @extends OO.ui.ButtonWidget
10732 * @mixins OO.ui.PendingElement
10735 * @param {Object} [config] Configuration options
10736 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
10737 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
10738 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
10739 * for more information about setting modes.
10740 * @cfg {boolean} [framed=false] Render the action button with a frame
10742 OO
.ui
.ActionWidget
= function OoUiActionWidget( config
) {
10743 // Configuration initialization
10744 config
= $.extend( { framed
: false }, config
);
10746 // Parent constructor
10747 OO
.ui
.ActionWidget
.super.call( this, config
);
10749 // Mixin constructors
10750 OO
.ui
.PendingElement
.call( this, config
);
10753 this.action
= config
.action
|| '';
10754 this.modes
= config
.modes
|| [];
10759 this.$element
.addClass( 'oo-ui-actionWidget' );
10764 OO
.inheritClass( OO
.ui
.ActionWidget
, OO
.ui
.ButtonWidget
);
10765 OO
.mixinClass( OO
.ui
.ActionWidget
, OO
.ui
.PendingElement
);
10770 * A resize event is emitted when the size of the widget changes.
10778 * Check if the action is configured to be available in the specified `mode`.
10780 * @param {string} mode Name of mode
10781 * @return {boolean} The action is configured with the mode
10783 OO
.ui
.ActionWidget
.prototype.hasMode = function ( mode
) {
10784 return this.modes
.indexOf( mode
) !== -1;
10788 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
10792 OO
.ui
.ActionWidget
.prototype.getAction = function () {
10793 return this.action
;
10797 * Get the symbolic name of the mode or modes for which the action is configured to be available.
10799 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
10800 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
10803 * @return {string[]}
10805 OO
.ui
.ActionWidget
.prototype.getModes = function () {
10806 return this.modes
.slice();
10810 * Emit a resize event if the size has changed.
10815 OO
.ui
.ActionWidget
.prototype.propagateResize = function () {
10818 if ( this.isElementAttached() ) {
10819 width
= this.$element
.width();
10820 height
= this.$element
.height();
10822 if ( width
!== this.width
|| height
!== this.height
) {
10823 this.width
= width
;
10824 this.height
= height
;
10825 this.emit( 'resize' );
10835 OO
.ui
.ActionWidget
.prototype.setIcon = function () {
10837 OO
.ui
.IconElement
.prototype.setIcon
.apply( this, arguments
);
10838 this.propagateResize();
10846 OO
.ui
.ActionWidget
.prototype.setLabel = function () {
10848 OO
.ui
.LabelElement
.prototype.setLabel
.apply( this, arguments
);
10849 this.propagateResize();
10857 OO
.ui
.ActionWidget
.prototype.setFlags = function () {
10859 OO
.ui
.FlaggedElement
.prototype.setFlags
.apply( this, arguments
);
10860 this.propagateResize();
10868 OO
.ui
.ActionWidget
.prototype.clearFlags = function () {
10870 OO
.ui
.FlaggedElement
.prototype.clearFlags
.apply( this, arguments
);
10871 this.propagateResize();
10877 * Toggle the visibility of the action button.
10879 * @param {boolean} [show] Show button, omit to toggle visibility
10882 OO
.ui
.ActionWidget
.prototype.toggle = function () {
10884 OO
.ui
.ActionWidget
.super.prototype.toggle
.apply( this, arguments
);
10885 this.propagateResize();
10891 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
10892 * which is used to display additional information or options.
10895 * // Example of a popup button.
10896 * var popupButton = new OO.ui.PopupButtonWidget( {
10897 * label: 'Popup button with options',
10900 * $content: $( '<p>Additional options here.</p>' ),
10905 * // Append the button to the DOM.
10906 * $( 'body' ).append( popupButton.$element );
10909 * @extends OO.ui.ButtonWidget
10910 * @mixins OO.ui.PopupElement
10913 * @param {Object} [config] Configuration options
10915 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
10916 // Parent constructor
10917 OO
.ui
.PopupButtonWidget
.super.call( this, config
);
10919 // Mixin constructors
10920 OO
.ui
.PopupElement
.call( this, config
);
10923 this.connect( this, { click
: 'onAction' } );
10927 .addClass( 'oo-ui-popupButtonWidget' )
10928 .attr( 'aria-haspopup', 'true' )
10929 .append( this.popup
.$element
);
10934 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
10935 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.PopupElement
);
10940 * Handle the button action being triggered.
10944 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
10945 this.popup
.toggle();
10949 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
10950 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
10951 * configured with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators},
10952 * {@link OO.ui.TitledElement titles}, {@link OO.ui.FlaggedElement styling flags},
10953 * and {@link OO.ui.LabelElement labels}. Please see
10954 * the [OOjs UI documentation][1] on MediaWiki for more information.
10957 * // Toggle buttons in the 'off' and 'on' state.
10958 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
10959 * label: 'Toggle Button off'
10961 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
10962 * label: 'Toggle Button on',
10965 * // Append the buttons to the DOM.
10966 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
10968 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
10971 * @extends OO.ui.ToggleWidget
10972 * @mixins OO.ui.ButtonElement
10973 * @mixins OO.ui.IconElement
10974 * @mixins OO.ui.IndicatorElement
10975 * @mixins OO.ui.LabelElement
10976 * @mixins OO.ui.TitledElement
10977 * @mixins OO.ui.FlaggedElement
10978 * @mixins OO.ui.TabIndexedElement
10981 * @param {Object} [config] Configuration options
10982 * @cfg {boolean} [value=false] The toggle button’s initial on/off
10983 * state. By default, the button is in the 'off' state.
10985 OO
.ui
.ToggleButtonWidget
= function OoUiToggleButtonWidget( config
) {
10986 // Configuration initialization
10987 config
= config
|| {};
10989 // Parent constructor
10990 OO
.ui
.ToggleButtonWidget
.super.call( this, config
);
10992 // Mixin constructors
10993 OO
.ui
.ButtonElement
.call( this, config
);
10994 OO
.ui
.IconElement
.call( this, config
);
10995 OO
.ui
.IndicatorElement
.call( this, config
);
10996 OO
.ui
.LabelElement
.call( this, config
);
10997 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
10998 OO
.ui
.FlaggedElement
.call( this, config
);
10999 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
11002 this.connect( this, { click
: 'onAction' } );
11005 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
11007 .addClass( 'oo-ui-toggleButtonWidget' )
11008 .append( this.$button
);
11013 OO
.inheritClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ToggleWidget
);
11014 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ButtonElement
);
11015 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.IconElement
);
11016 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.IndicatorElement
);
11017 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.LabelElement
);
11018 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.TitledElement
);
11019 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.FlaggedElement
);
11020 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.TabIndexedElement
);
11025 * Handle the button action being triggered.
11029 OO
.ui
.ToggleButtonWidget
.prototype.onAction = function () {
11030 this.setValue( !this.value
);
11036 OO
.ui
.ToggleButtonWidget
.prototype.setValue = function ( value
) {
11038 if ( value
!== this.value
) {
11039 // Might be called from parent constructor before ButtonElement constructor
11040 if ( this.$button
) {
11041 this.$button
.attr( 'aria-pressed', value
.toString() );
11043 this.setActive( value
);
11047 OO
.ui
.ToggleButtonWidget
.super.prototype.setValue
.call( this, value
);
11055 OO
.ui
.ToggleButtonWidget
.prototype.setButtonElement = function ( $button
) {
11056 if ( this.$button
) {
11057 this.$button
.removeAttr( 'aria-pressed' );
11059 OO
.ui
.ButtonElement
.prototype.setButtonElement
.call( this, $button
);
11060 this.$button
.attr( 'aria-pressed', this.value
.toString() );
11064 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
11065 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
11066 * users can interact with it.
11069 * // Example: A DropdownWidget with a menu that contains three options
11070 * var dropDown = new OO.ui.DropdownWidget( {
11071 * label: 'Dropdown menu: Select a menu option',
11074 * new OO.ui.MenuOptionWidget( {
11078 * new OO.ui.MenuOptionWidget( {
11082 * new OO.ui.MenuOptionWidget( {
11090 * $( 'body' ).append( dropDown.$element );
11092 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
11094 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
11097 * @extends OO.ui.Widget
11098 * @mixins OO.ui.IconElement
11099 * @mixins OO.ui.IndicatorElement
11100 * @mixins OO.ui.LabelElement
11101 * @mixins OO.ui.TitledElement
11102 * @mixins OO.ui.TabIndexedElement
11105 * @param {Object} [config] Configuration options
11106 * @cfg {Object} [menu] Configuration options to pass to menu widget
11108 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
11109 // Configuration initialization
11110 config
= $.extend( { indicator
: 'down' }, config
);
11112 // Parent constructor
11113 OO
.ui
.DropdownWidget
.super.call( this, config
);
11115 // Properties (must be set before TabIndexedElement constructor call)
11116 this.$handle
= this.$( '<span>' );
11118 // Mixin constructors
11119 OO
.ui
.IconElement
.call( this, config
);
11120 OO
.ui
.IndicatorElement
.call( this, config
);
11121 OO
.ui
.LabelElement
.call( this, config
);
11122 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
11123 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
11126 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend( { widget
: this }, config
.menu
) );
11130 click
: this.onClick
.bind( this ),
11131 keypress
: this.onKeyPress
.bind( this )
11133 this.menu
.connect( this, { select
: 'onMenuSelect' } );
11137 .addClass( 'oo-ui-dropdownWidget-handle' )
11138 .append( this.$icon
, this.$label
, this.$indicator
);
11140 .addClass( 'oo-ui-dropdownWidget' )
11141 .append( this.$handle
, this.menu
.$element
);
11146 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
11147 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.IconElement
);
11148 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.IndicatorElement
);
11149 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.LabelElement
);
11150 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.TitledElement
);
11151 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.TabIndexedElement
);
11158 * @return {OO.ui.MenuSelectWidget} Menu of widget
11160 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
11165 * Handles menu select events.
11168 * @param {OO.ui.MenuOptionWidget} item Selected menu item
11170 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
11177 selectedLabel
= item
.getLabel();
11179 // If the label is a DOM element, clone it, because setLabel will append() it
11180 if ( selectedLabel
instanceof jQuery
) {
11181 selectedLabel
= selectedLabel
.clone();
11184 this.setLabel( selectedLabel
);
11188 * Handle mouse click events.
11191 * @param {jQuery.Event} e Mouse click event
11193 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
11194 if ( !this.isDisabled() && e
.which
=== 1 ) {
11195 this.menu
.toggle();
11201 * Handle key press events.
11204 * @param {jQuery.Event} e Key press event
11206 OO
.ui
.DropdownWidget
.prototype.onKeyPress = function ( e
) {
11207 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
11208 this.menu
.toggle();
11214 * IconWidget is a generic widget for {@link OO.ui.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
11215 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
11216 * for a list of icons included in the library.
11219 * // An icon widget with a label
11220 * var myIcon = new OO.ui.IconWidget( {
11222 * iconTitle: 'Help'
11224 * // Create a label.
11225 * var iconLabel = new OO.ui.LabelWidget( {
11228 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
11230 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
11233 * @extends OO.ui.Widget
11234 * @mixins OO.ui.IconElement
11235 * @mixins OO.ui.TitledElement
11236 * @mixins OO.ui.FlaggedElement
11239 * @param {Object} [config] Configuration options
11241 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
11242 // Configuration initialization
11243 config
= config
|| {};
11245 // Parent constructor
11246 OO
.ui
.IconWidget
.super.call( this, config
);
11248 // Mixin constructors
11249 OO
.ui
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
11250 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
11251 OO
.ui
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
11254 this.$element
.addClass( 'oo-ui-iconWidget' );
11259 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
11260 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.IconElement
);
11261 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.TitledElement
);
11262 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.FlaggedElement
);
11264 /* Static Properties */
11266 OO
.ui
.IconWidget
.static.tagName
= 'span';
11269 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
11270 * attention to the status of an item or to clarify the function of a control. For a list of
11271 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
11274 * // Example of an indicator widget
11275 * var indicator1 = new OO.ui.IndicatorWidget( {
11276 * indicator: 'alert'
11279 * // Create a fieldset layout to add a label
11280 * var fieldset = new OO.ui.FieldsetLayout();
11281 * fieldset.addItems( [
11282 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
11284 * $( 'body' ).append( fieldset.$element );
11286 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
11289 * @extends OO.ui.Widget
11290 * @mixins OO.ui.IndicatorElement
11291 * @mixins OO.ui.TitledElement
11294 * @param {Object} [config] Configuration options
11296 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
11297 // Configuration initialization
11298 config
= config
|| {};
11300 // Parent constructor
11301 OO
.ui
.IndicatorWidget
.super.call( this, config
);
11303 // Mixin constructors
11304 OO
.ui
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
11305 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
11308 this.$element
.addClass( 'oo-ui-indicatorWidget' );
11313 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
11314 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.IndicatorElement
);
11315 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.TitledElement
);
11317 /* Static Properties */
11319 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
11322 * InputWidget is the base class for all input widgets, which
11323 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
11324 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
11325 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
11327 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11331 * @extends OO.ui.Widget
11332 * @mixins OO.ui.FlaggedElement
11333 * @mixins OO.ui.TabIndexedElement
11336 * @param {Object} [config] Configuration options
11337 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
11338 * @cfg {string} [value=''] The value of the input.
11339 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
11340 * before it is accepted.
11342 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
11343 // Configuration initialization
11344 config
= config
|| {};
11346 // Parent constructor
11347 OO
.ui
.InputWidget
.super.call( this, config
);
11350 this.$input
= this.getInputElement( config
);
11352 this.inputFilter
= config
.inputFilter
;
11354 // Mixin constructors
11355 OO
.ui
.FlaggedElement
.call( this, config
);
11356 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
11359 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
11363 .attr( 'name', config
.name
)
11364 .prop( 'disabled', this.isDisabled() );
11365 this.$element
.addClass( 'oo-ui-inputWidget' ).append( this.$input
, $( '<span>' ) );
11366 this.setValue( config
.value
);
11371 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
11372 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.FlaggedElement
);
11373 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.TabIndexedElement
);
11380 * A change event is emitted when the value of the input changes.
11382 * @param {string} value
11388 * Get input element.
11390 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
11391 * different circumstances. The element must have a `value` property (like form elements).
11394 * @param {Object} config Configuration options
11395 * @return {jQuery} Input element
11397 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
11398 return $( '<input>' );
11402 * Handle potentially value-changing events.
11405 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
11407 OO
.ui
.InputWidget
.prototype.onEdit = function () {
11409 if ( !this.isDisabled() ) {
11410 // Allow the stack to clear so the value will be updated
11411 setTimeout( function () {
11412 widget
.setValue( widget
.$input
.val() );
11418 * Get the value of the input.
11420 * @return {string} Input value
11422 OO
.ui
.InputWidget
.prototype.getValue = function () {
11423 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
11424 // it, and we won't know unless they're kind enough to trigger a 'change' event.
11425 var value
= this.$input
.val();
11426 if ( this.value
!== value
) {
11427 this.setValue( value
);
11433 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
11435 * @param {boolean} isRTL
11436 * Direction is right-to-left
11438 OO
.ui
.InputWidget
.prototype.setRTL = function ( isRTL
) {
11439 this.$input
.prop( 'dir', isRTL
? 'rtl' : 'ltr' );
11443 * Set the value of the input.
11445 * @param {string} value New value
11449 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
11450 value
= this.cleanUpValue( value
);
11451 // Update the DOM if it has changed. Note that with cleanUpValue, it
11452 // is possible for the DOM value to change without this.value changing.
11453 if ( this.$input
.val() !== value
) {
11454 this.$input
.val( value
);
11456 if ( this.value
!== value
) {
11457 this.value
= value
;
11458 this.emit( 'change', this.value
);
11464 * Clean up incoming value.
11466 * Ensures value is a string, and converts undefined and null to empty string.
11469 * @param {string} value Original value
11470 * @return {string} Cleaned up value
11472 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
11473 if ( value
=== undefined || value
=== null ) {
11475 } else if ( this.inputFilter
) {
11476 return this.inputFilter( String( value
) );
11478 return String( value
);
11483 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
11484 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
11487 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
11488 if ( !this.isDisabled() ) {
11489 if ( this.$input
.is( ':checkbox, :radio' ) ) {
11490 this.$input
.click();
11492 if ( this.$input
.is( ':input' ) ) {
11493 this.$input
[ 0 ].focus();
11501 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
11502 OO
.ui
.InputWidget
.super.prototype.setDisabled
.call( this, state
);
11503 if ( this.$input
) {
11504 this.$input
.prop( 'disabled', this.isDisabled() );
11514 OO
.ui
.InputWidget
.prototype.focus = function () {
11515 this.$input
[ 0 ].focus();
11524 OO
.ui
.InputWidget
.prototype.blur = function () {
11525 this.$input
[ 0 ].blur();
11530 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
11531 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
11532 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
11533 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
11534 * [OOjs UI documentation on MediaWiki] [1] for more information.
11537 * // A ButtonInputWidget rendered as an HTML button, the default.
11538 * var button = new OO.ui.ButtonInputWidget( {
11539 * label: 'Input button',
11543 * $( 'body' ).append( button.$element );
11545 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
11548 * @extends OO.ui.InputWidget
11549 * @mixins OO.ui.ButtonElement
11550 * @mixins OO.ui.IconElement
11551 * @mixins OO.ui.IndicatorElement
11552 * @mixins OO.ui.LabelElement
11553 * @mixins OO.ui.TitledElement
11556 * @param {Object} [config] Configuration options
11557 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
11558 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
11559 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
11560 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
11561 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
11563 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
11564 // Configuration initialization
11565 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
11567 // Properties (must be set before parent constructor, which calls #setValue)
11568 this.useInputTag
= config
.useInputTag
;
11570 // Parent constructor
11571 OO
.ui
.ButtonInputWidget
.super.call( this, config
);
11573 // Mixin constructors
11574 OO
.ui
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
11575 OO
.ui
.IconElement
.call( this, config
);
11576 OO
.ui
.IndicatorElement
.call( this, config
);
11577 OO
.ui
.LabelElement
.call( this, config
);
11578 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
11581 if ( !config
.useInputTag
) {
11582 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
11584 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
11589 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
11590 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.ButtonElement
);
11591 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.IconElement
);
11592 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.IndicatorElement
);
11593 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.LabelElement
);
11594 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.TitledElement
);
11602 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
11603 var html
= '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + config
.type
+ '">';
11610 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
11612 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
11613 * text, or `null` for no label
11616 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
11617 OO
.ui
.LabelElement
.prototype.setLabel
.call( this, label
);
11619 if ( this.useInputTag
) {
11620 if ( typeof label
=== 'function' ) {
11621 label
= OO
.ui
.resolveMsg( label
);
11623 if ( label
instanceof jQuery
) {
11624 label
= label
.text();
11629 this.$input
.val( label
);
11636 * Set the value of the input.
11638 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
11639 * they do not support {@link #value values}.
11641 * @param {string} value New value
11644 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
11645 if ( !this.useInputTag
) {
11646 OO
.ui
.ButtonInputWidget
.super.prototype.setValue
.call( this, value
);
11652 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
11653 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
11654 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
11655 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
11657 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
11660 * // An example of selected, unselected, and disabled checkbox inputs
11661 * var checkbox1=new OO.ui.CheckboxInputWidget( {
11665 * var checkbox2=new OO.ui.CheckboxInputWidget( {
11668 * var checkbox3=new OO.ui.CheckboxInputWidget( {
11672 * // Create a fieldset layout with fields for each checkbox.
11673 * var fieldset = new OO.ui.FieldsetLayout( {
11674 * label: 'Checkboxes'
11676 * fieldset.addItems( [
11677 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
11678 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
11679 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
11681 * $( 'body' ).append( fieldset.$element );
11683 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11686 * @extends OO.ui.InputWidget
11689 * @param {Object} [config] Configuration options
11690 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
11692 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
11693 // Configuration initialization
11694 config
= config
|| {};
11696 // Parent constructor
11697 OO
.ui
.CheckboxInputWidget
.super.call( this, config
);
11700 this.$element
.addClass( 'oo-ui-checkboxInputWidget' );
11701 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
11706 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
11714 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
11715 return $( '<input type="checkbox" />' );
11721 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
11723 if ( !this.isDisabled() ) {
11724 // Allow the stack to clear so the value will be updated
11725 setTimeout( function () {
11726 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
11732 * Set selection state of this checkbox.
11734 * @param {boolean} state `true` for selected
11737 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
11739 if ( this.selected
!== state
) {
11740 this.selected
= state
;
11741 this.$input
.prop( 'checked', this.selected
);
11742 this.emit( 'change', this.selected
);
11748 * Check if this checkbox is selected.
11750 * @return {boolean} Checkbox is selected
11752 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
11753 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
11754 // it, and we won't know unless they're kind enough to trigger a 'change' event.
11755 var selected
= this.$input
.prop( 'checked' );
11756 if ( this.selected
!== selected
) {
11757 this.setSelected( selected
);
11759 return this.selected
;
11763 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
11764 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
11765 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
11766 * more information about input widgets.
11769 * // Example: A DropdownInputWidget with three options
11770 * var dropDown = new OO.ui.DropdownInputWidget( {
11771 * label: 'Dropdown menu: Select a menu option',
11773 * { data: 'a', label: 'First' } ,
11774 * { data: 'b', label: 'Second'} ,
11775 * { data: 'c', label: 'Third' }
11778 * $( 'body' ).append( dropDown.$element );
11780 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11783 * @extends OO.ui.InputWidget
11786 * @param {Object} [config] Configuration options
11787 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11789 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
11790 // Configuration initialization
11791 config
= config
|| {};
11793 // Properties (must be done before parent constructor which calls #setDisabled)
11794 this.dropdownWidget
= new OO
.ui
.DropdownWidget();
11796 // Parent constructor
11797 OO
.ui
.DropdownInputWidget
.super.call( this, config
);
11800 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
11803 this.setOptions( config
.options
|| [] );
11805 .addClass( 'oo-ui-dropdownInputWidget' )
11806 .append( this.dropdownWidget
.$element
);
11811 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
11819 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
11820 return $( '<input type="hidden">' );
11824 * Handles menu select events.
11827 * @param {OO.ui.MenuOptionWidget} item Selected menu item
11829 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
11830 this.setValue( item
.getData() );
11836 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
11837 var item
= this.dropdownWidget
.getMenu().getItemFromData( value
);
11839 this.dropdownWidget
.getMenu().selectItem( item
);
11841 OO
.ui
.DropdownInputWidget
.super.prototype.setValue
.call( this, value
);
11848 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
11849 this.dropdownWidget
.setDisabled( state
);
11850 OO
.ui
.DropdownInputWidget
.super.prototype.setDisabled
.call( this, state
);
11855 * Set the options available for this input.
11857 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11860 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
11861 var value
= this.getValue();
11863 // Rebuild the dropdown menu
11864 this.dropdownWidget
.getMenu()
11866 .addItems( options
.map( function ( opt
) {
11867 return new OO
.ui
.MenuOptionWidget( {
11869 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
11873 // Restore the previous value, or reset to something sensible
11874 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
11875 // Previous value is still available, ensure consistency with the dropdown
11876 this.setValue( value
);
11878 // No longer valid, reset
11879 if ( options
.length
) {
11880 this.setValue( options
[ 0 ].data
);
11890 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
11891 this.dropdownWidget
.getMenu().toggle( true );
11898 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
11899 this.dropdownWidget
.getMenu().toggle( false );
11904 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
11905 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
11906 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
11907 * please see the [OOjs UI documentation on MediaWiki][1].
11909 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
11912 * // An example of selected, unselected, and disabled radio inputs
11913 * var radio1 = new OO.ui.RadioInputWidget( {
11917 * var radio2 = new OO.ui.RadioInputWidget( {
11920 * var radio3 = new OO.ui.RadioInputWidget( {
11924 * // Create a fieldset layout with fields for each radio button.
11925 * var fieldset = new OO.ui.FieldsetLayout( {
11926 * label: 'Radio inputs'
11928 * fieldset.addItems( [
11929 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
11930 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
11931 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
11933 * $( 'body' ).append( fieldset.$element );
11935 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11938 * @extends OO.ui.InputWidget
11941 * @param {Object} [config] Configuration options
11942 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
11944 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
11945 // Configuration initialization
11946 config
= config
|| {};
11948 // Parent constructor
11949 OO
.ui
.RadioInputWidget
.super.call( this, config
);
11952 this.$element
.addClass( 'oo-ui-radioInputWidget' );
11953 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
11958 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
11966 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
11967 return $( '<input type="radio" />' );
11973 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
11974 // RadioInputWidget doesn't track its state.
11978 * Set selection state of this radio button.
11980 * @param {boolean} state `true` for selected
11983 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
11984 // RadioInputWidget doesn't track its state.
11985 this.$input
.prop( 'checked', state
);
11990 * Check if this radio button is selected.
11992 * @return {boolean} Radio is selected
11994 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
11995 return this.$input
.prop( 'checked' );
11999 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
12000 * size of the field as well as its presentation. In addition, these widgets can be configured
12001 * with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators}, an optional
12002 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
12003 * which modifies incoming values rather than validating them.
12004 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
12006 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
12009 * // Example of a text input widget
12010 * var textInput = new OO.ui.TextInputWidget( {
12011 * value: 'Text input'
12013 * $( 'body' ).append( textInput.$element );
12015 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
12018 * @extends OO.ui.InputWidget
12019 * @mixins OO.ui.IconElement
12020 * @mixins OO.ui.IndicatorElement
12021 * @mixins OO.ui.PendingElement
12022 * @mixins OO.ui.LabelElement
12025 * @param {Object} [config] Configuration options
12026 * @cfg {string} [type='text'] The value of the HTML `type` attribute
12027 * @cfg {string} [placeholder] Placeholder text
12028 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
12029 * instruct the browser to focus this widget.
12030 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
12031 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
12032 * @cfg {boolean} [multiline=false] Allow multiple lines of text
12033 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
12034 * Use the #maxRows config to specify a maximum number of displayed rows.
12035 * @cfg {boolean} [maxRows=10] Maximum number of rows to display when #autosize is set to true.
12036 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
12037 * the value or placeholder text: `'before'` or `'after'`
12038 * @cfg {boolean} [required=false] Mark the field as required
12039 * @cfg {RegExp|string} [validate] Validation pattern, either a regular expression or the
12040 * symbolic name of a pattern defined by the class: 'non-empty' (the value cannot be an empty string)
12041 * or 'integer' (the value must contain only numbers).
12043 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
12044 // Configuration initialization
12045 config
= $.extend( {
12047 labelPosition
: 'after',
12051 // Parent constructor
12052 OO
.ui
.TextInputWidget
.super.call( this, config
);
12054 // Mixin constructors
12055 OO
.ui
.IconElement
.call( this, config
);
12056 OO
.ui
.IndicatorElement
.call( this, config
);
12057 OO
.ui
.PendingElement
.call( this, config
);
12058 OO
.ui
.LabelElement
.call( this, config
);
12061 this.readOnly
= false;
12062 this.multiline
= !!config
.multiline
;
12063 this.autosize
= !!config
.autosize
;
12064 this.maxRows
= config
.maxRows
;
12065 this.validate
= null;
12067 // Clone for resizing
12068 if ( this.autosize
) {
12069 this.$clone
= this.$input
12071 .insertAfter( this.$input
)
12072 .attr( 'aria-hidden', 'true' )
12073 .addClass( 'oo-ui-element-hidden' );
12076 this.setValidation( config
.validate
);
12077 this.setLabelPosition( config
.labelPosition
);
12081 keypress
: this.onKeyPress
.bind( this ),
12082 blur
: this.setValidityFlag
.bind( this )
12085 focus
: this.onElementAttach
.bind( this )
12087 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
12088 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
12089 this.on( 'labelChange', this.updatePosition
.bind( this ) );
12093 .addClass( 'oo-ui-textInputWidget' )
12094 .append( this.$icon
, this.$indicator
);
12095 this.setReadOnly( !!config
.readOnly
);
12096 if ( config
.placeholder
) {
12097 this.$input
.attr( 'placeholder', config
.placeholder
);
12099 if ( config
.maxLength
!== undefined ) {
12100 this.$input
.attr( 'maxlength', config
.maxLength
);
12102 if ( config
.autofocus
) {
12103 this.$input
.attr( 'autofocus', 'autofocus' );
12105 if ( config
.required
) {
12106 this.$input
.attr( 'required', 'true' );
12108 if ( this.label
|| config
.autosize
) {
12109 this.installParentChangeDetector();
12115 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
12116 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.IconElement
);
12117 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.IndicatorElement
);
12118 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.PendingElement
);
12119 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.LabelElement
);
12121 /* Static properties */
12123 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
12131 * An `enter` event is emitted when the user presses 'enter' inside the text box.
12133 * Not emitted if the input is multiline.
12141 * Handle icon mouse down events.
12144 * @param {jQuery.Event} e Mouse down event
12147 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
12148 if ( e
.which
=== 1 ) {
12149 this.$input
[ 0 ].focus();
12155 * Handle indicator mouse down events.
12158 * @param {jQuery.Event} e Mouse down event
12161 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
12162 if ( e
.which
=== 1 ) {
12163 this.$input
[ 0 ].focus();
12169 * Handle key press events.
12172 * @param {jQuery.Event} e Key press event
12173 * @fires enter If enter key is pressed and input is not multiline
12175 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
12176 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
12177 this.emit( 'enter', e
);
12182 * Handle element attach events.
12185 * @param {jQuery.Event} e Element attach event
12187 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
12188 // Any previously calculated size is now probably invalid if we reattached elsewhere
12189 this.valCache
= null;
12191 this.positionLabel();
12197 OO
.ui
.TextInputWidget
.prototype.onEdit = function () {
12201 return OO
.ui
.TextInputWidget
.super.prototype.onEdit
.call( this );
12207 OO
.ui
.TextInputWidget
.prototype.setValue = function ( value
) {
12209 OO
.ui
.TextInputWidget
.super.prototype.setValue
.call( this, value
);
12211 this.setValidityFlag();
12217 * Check if the input is {@link #readOnly read-only}.
12219 * @return {boolean}
12221 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
12222 return this.readOnly
;
12226 * Set the {@link #readOnly read-only} state of the input.
12228 * @param {boolean} state Make input read-only
12231 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
12232 this.readOnly
= !!state
;
12233 this.$input
.prop( 'readOnly', this.readOnly
);
12238 * Support function for making #onElementAttach work across browsers.
12240 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
12241 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
12243 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
12244 * first time that the element gets attached to the documented.
12246 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
12247 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
12248 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
12251 if ( MutationObserver
) {
12252 // The new way. If only it wasn't so ugly.
12254 if ( this.$element
.closest( 'html' ).length
) {
12255 // Widget is attached already, do nothing. This breaks the functionality of this function when
12256 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
12257 // would require observation of the whole document, which would hurt performance of other,
12258 // more important code.
12262 // Find topmost node in the tree
12263 topmostNode
= this.$element
[0];
12264 while ( topmostNode
.parentNode
) {
12265 topmostNode
= topmostNode
.parentNode
;
12268 // We have no way to detect the $element being attached somewhere without observing the entire
12269 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
12270 // parent node of $element, and instead detect when $element is removed from it (and thus
12271 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
12272 // doesn't get attached, we end up back here and create the parent.
12274 mutationObserver
= new MutationObserver( function ( mutations
) {
12275 var i
, j
, removedNodes
;
12276 for ( i
= 0; i
< mutations
.length
; i
++ ) {
12277 removedNodes
= mutations
[ i
].removedNodes
;
12278 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
12279 if ( removedNodes
[ j
] === topmostNode
) {
12280 setTimeout( onRemove
, 0 );
12287 onRemove = function () {
12288 // If the node was attached somewhere else, report it
12289 if ( widget
.$element
.closest( 'html' ).length
) {
12290 widget
.onElementAttach();
12292 mutationObserver
.disconnect();
12293 widget
.installParentChangeDetector();
12296 // Create a fake parent and observe it
12297 fakeParentNode
= $( '<div>' ).append( this.$element
)[0];
12298 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
12300 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
12301 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
12302 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
12307 * Automatically adjust the size of the text input.
12309 * This only affects #multiline inputs that are {@link #autosize autosized}.
12313 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
12314 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
, idealHeight
;
12316 if ( this.multiline
&& this.autosize
&& this.$input
.val() !== this.valCache
) {
12318 .val( this.$input
.val() )
12319 .attr( 'rows', '' )
12320 // Set inline height property to 0 to measure scroll height
12321 .css( 'height', 0 );
12323 this.$clone
.removeClass( 'oo-ui-element-hidden' );
12325 this.valCache
= this.$input
.val();
12327 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
12329 // Remove inline height property to measure natural heights
12330 this.$clone
.css( 'height', '' );
12331 innerHeight
= this.$clone
.innerHeight();
12332 outerHeight
= this.$clone
.outerHeight();
12334 // Measure max rows height
12336 .attr( 'rows', this.maxRows
)
12337 .css( 'height', 'auto' )
12339 maxInnerHeight
= this.$clone
.innerHeight();
12341 // Difference between reported innerHeight and scrollHeight with no scrollbars present
12342 // Equals 1 on Blink-based browsers and 0 everywhere else
12343 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
12344 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
12346 this.$clone
.addClass( 'oo-ui-element-hidden' );
12348 // Only apply inline height when expansion beyond natural height is needed
12349 if ( idealHeight
> innerHeight
) {
12350 // Use the difference between the inner and outer height as a buffer
12351 this.$input
.css( 'height', idealHeight
+ ( outerHeight
- innerHeight
) );
12353 this.$input
.css( 'height', '' );
12363 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
12364 return config
.multiline
? $( '<textarea>' ) : $( '<input type="' + config
.type
+ '" />' );
12368 * Check if the input supports multiple lines.
12370 * @return {boolean}
12372 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
12373 return !!this.multiline
;
12377 * Check if the input automatically adjusts its size.
12379 * @return {boolean}
12381 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
12382 return !!this.autosize
;
12386 * Select the entire text of the input.
12390 OO
.ui
.TextInputWidget
.prototype.select = function () {
12391 this.$input
.select();
12396 * Set the validation pattern.
12398 * The validation pattern is either a regular expression or the symbolic name of a pattern
12399 * defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
12400 * value must contain only numbers).
12402 * @param {RegExp|string|null} validate Regular expression or the symbolic name of a
12403 * pattern (either ‘integer’ or ‘non-empty’) defined by the class.
12405 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
12406 if ( validate
instanceof RegExp
) {
12407 this.validate
= validate
;
12409 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
12414 * Sets the 'invalid' flag appropriately.
12416 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function () {
12418 this.isValid().done( function ( valid
) {
12419 widget
.setFlags( { invalid
: !valid
} );
12424 * Check if a value is valid.
12426 * This method returns a promise that resolves with a boolean `true` if the current value is
12427 * considered valid according to the supplied {@link #validate validation pattern}.
12429 * @return {jQuery.Deferred} A promise that resolves to a boolean `true` if the value is valid.
12431 OO
.ui
.TextInputWidget
.prototype.isValid = function () {
12432 return $.Deferred().resolve( !!this.getValue().match( this.validate
) ).promise();
12436 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
12438 * @param {string} labelPosition Label position, 'before' or 'after'
12441 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
12442 this.labelPosition
= labelPosition
;
12443 this.updatePosition();
12448 * Deprecated alias of #setLabelPosition
12450 * @deprecated Use setLabelPosition instead.
12452 OO
.ui
.TextInputWidget
.prototype.setPosition
=
12453 OO
.ui
.TextInputWidget
.prototype.setLabelPosition
;
12456 * Update the position of the inline label.
12458 * This method is called by #setLabelPosition, and can also be called on its own if
12459 * something causes the label to be mispositioned.
12464 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
12465 var after
= this.labelPosition
=== 'after';
12468 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
12469 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
12471 if ( this.label
) {
12472 this.positionLabel();
12479 * Position the label by setting the correct padding on the input.
12484 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
12485 // Clear old values
12487 // Clear old values if present
12489 'padding-right': '',
12493 if ( this.label
) {
12494 this.$element
.append( this.$label
);
12496 this.$label
.detach();
12500 var after
= this.labelPosition
=== 'after',
12501 rtl
= this.$element
.css( 'direction' ) === 'rtl',
12502 property
= after
=== rtl
? 'padding-left' : 'padding-right';
12504 this.$input
.css( property
, this.$label
.outerWidth( true ) );
12510 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
12511 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
12512 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
12514 * - by typing a value in the text input field. If the value exactly matches the value of a menu
12515 * option, that option will appear to be selected.
12516 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
12519 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
12522 * // Example: A ComboBoxWidget.
12523 * var comboBox = new OO.ui.ComboBoxWidget( {
12524 * label: 'ComboBoxWidget',
12525 * input: { value: 'Option One' },
12528 * new OO.ui.MenuOptionWidget( {
12529 * data: 'Option 1',
12530 * label: 'Option One'
12532 * new OO.ui.MenuOptionWidget( {
12533 * data: 'Option 2',
12534 * label: 'Option Two'
12536 * new OO.ui.MenuOptionWidget( {
12537 * data: 'Option 3',
12538 * label: 'Option Three'
12540 * new OO.ui.MenuOptionWidget( {
12541 * data: 'Option 4',
12542 * label: 'Option Four'
12544 * new OO.ui.MenuOptionWidget( {
12545 * data: 'Option 5',
12546 * label: 'Option Five'
12551 * $( 'body' ).append( comboBox.$element );
12553 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12556 * @extends OO.ui.Widget
12557 * @mixins OO.ui.TabIndexedElement
12560 * @param {Object} [config] Configuration options
12561 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
12562 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
12563 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
12564 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
12565 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
12567 OO
.ui
.ComboBoxWidget
= function OoUiComboBoxWidget( config
) {
12568 // Configuration initialization
12569 config
= config
|| {};
12571 // Parent constructor
12572 OO
.ui
.ComboBoxWidget
.super.call( this, config
);
12574 // Properties (must be set before TabIndexedElement constructor call)
12575 this.$indicator
= this.$( '<span>' );
12577 // Mixin constructors
12578 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
12581 this.$overlay
= config
.$overlay
|| this.$element
;
12582 this.input
= new OO
.ui
.TextInputWidget( $.extend(
12585 $indicator
: this.$indicator
,
12586 disabled
: this.isDisabled()
12590 this.input
.$input
.eq( 0 ).attr( {
12592 'aria-autocomplete': 'list'
12594 this.menu
= new OO
.ui
.TextInputMenuSelectWidget( this.input
, $.extend(
12598 disabled
: this.isDisabled()
12604 this.$indicator
.on( {
12605 click
: this.onClick
.bind( this ),
12606 keypress
: this.onKeyPress
.bind( this )
12608 this.input
.connect( this, {
12609 change
: 'onInputChange',
12610 enter
: 'onInputEnter'
12612 this.menu
.connect( this, {
12613 choose
: 'onMenuChoose',
12614 add
: 'onMenuItemsChange',
12615 remove
: 'onMenuItemsChange'
12619 this.$element
.addClass( 'oo-ui-comboBoxWidget' ).append( this.input
.$element
);
12620 this.$overlay
.append( this.menu
.$element
);
12621 this.onMenuItemsChange();
12626 OO
.inheritClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.Widget
);
12627 OO
.mixinClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.TabIndexedElement
);
12632 * Get the combobox's menu.
12633 * @return {OO.ui.TextInputMenuSelectWidget} Menu widget
12635 OO
.ui
.ComboBoxWidget
.prototype.getMenu = function () {
12640 * Handle input change events.
12643 * @param {string} value New value
12645 OO
.ui
.ComboBoxWidget
.prototype.onInputChange = function ( value
) {
12646 var match
= this.menu
.getItemFromData( value
);
12648 this.menu
.selectItem( match
);
12649 if ( this.menu
.getHighlightedItem() ) {
12650 this.menu
.highlightItem( match
);
12653 if ( !this.isDisabled() ) {
12654 this.menu
.toggle( true );
12659 * Handle mouse click events.
12663 * @param {jQuery.Event} e Mouse click event
12665 OO
.ui
.ComboBoxWidget
.prototype.onClick = function ( e
) {
12666 if ( !this.isDisabled() && e
.which
=== 1 ) {
12667 this.menu
.toggle();
12668 this.input
.$input
[ 0 ].focus();
12674 * Handle key press events.
12678 * @param {jQuery.Event} e Key press event
12680 OO
.ui
.ComboBoxWidget
.prototype.onKeyPress = function ( e
) {
12681 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
12682 this.menu
.toggle();
12683 this.input
.$input
[ 0 ].focus();
12689 * Handle input enter events.
12693 OO
.ui
.ComboBoxWidget
.prototype.onInputEnter = function () {
12694 if ( !this.isDisabled() ) {
12695 this.menu
.toggle( false );
12700 * Handle menu choose events.
12703 * @param {OO.ui.OptionWidget} item Chosen item
12705 OO
.ui
.ComboBoxWidget
.prototype.onMenuChoose = function ( item
) {
12706 this.input
.setValue( item
.getData() );
12710 * Handle menu item change events.
12714 OO
.ui
.ComboBoxWidget
.prototype.onMenuItemsChange = function () {
12715 var match
= this.menu
.getItemFromData( this.input
.getValue() );
12716 this.menu
.selectItem( match
);
12717 if ( this.menu
.getHighlightedItem() ) {
12718 this.menu
.highlightItem( match
);
12720 this.$element
.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu
.isEmpty() );
12726 OO
.ui
.ComboBoxWidget
.prototype.setDisabled = function ( disabled
) {
12728 OO
.ui
.ComboBoxWidget
.super.prototype.setDisabled
.call( this, disabled
);
12730 if ( this.input
) {
12731 this.input
.setDisabled( this.isDisabled() );
12734 this.menu
.setDisabled( this.isDisabled() );
12741 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
12742 * be configured with a `label` option that is set to a string, a label node, or a function:
12744 * - String: a plaintext string
12745 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
12746 * label that includes a link or special styling, such as a gray color or additional graphical elements.
12747 * - Function: a function that will produce a string in the future. Functions are used
12748 * in cases where the value of the label is not currently defined.
12750 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
12751 * will come into focus when the label is clicked.
12754 * // Examples of LabelWidgets
12755 * var label1 = new OO.ui.LabelWidget( {
12756 * label: 'plaintext label'
12758 * var label2 = new OO.ui.LabelWidget( {
12759 * label: $( '<a href="default.html">jQuery label</a>' )
12761 * // Create a fieldset layout with fields for each example
12762 * var fieldset = new OO.ui.FieldsetLayout();
12763 * fieldset.addItems( [
12764 * new OO.ui.FieldLayout( label1 ),
12765 * new OO.ui.FieldLayout( label2 )
12767 * $( 'body' ).append( fieldset.$element );
12771 * @extends OO.ui.Widget
12772 * @mixins OO.ui.LabelElement
12775 * @param {Object} [config] Configuration options
12776 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
12777 * Clicking the label will focus the specified input field.
12779 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
12780 // Configuration initialization
12781 config
= config
|| {};
12783 // Parent constructor
12784 OO
.ui
.LabelWidget
.super.call( this, config
);
12786 // Mixin constructors
12787 OO
.ui
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
12788 OO
.ui
.TitledElement
.call( this, config
);
12791 this.input
= config
.input
;
12794 if ( this.input
instanceof OO
.ui
.InputWidget
) {
12795 this.$element
.on( 'click', this.onClick
.bind( this ) );
12799 this.$element
.addClass( 'oo-ui-labelWidget' );
12804 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
12805 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.LabelElement
);
12806 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.TitledElement
);
12808 /* Static Properties */
12810 OO
.ui
.LabelWidget
.static.tagName
= 'span';
12815 * Handles label mouse click events.
12818 * @param {jQuery.Event} e Mouse click event
12820 OO
.ui
.LabelWidget
.prototype.onClick = function () {
12821 this.input
.simulateLabelClick();
12826 * OptionWidgets are special elements that can be selected and configured with data. The
12827 * data is often unique for each option, but it does not have to be. OptionWidgets are used
12828 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
12829 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
12831 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
12834 * @extends OO.ui.Widget
12835 * @mixins OO.ui.LabelElement
12836 * @mixins OO.ui.FlaggedElement
12839 * @param {Object} [config] Configuration options
12841 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
12842 // Configuration initialization
12843 config
= config
|| {};
12845 // Parent constructor
12846 OO
.ui
.OptionWidget
.super.call( this, config
);
12848 // Mixin constructors
12849 OO
.ui
.ItemWidget
.call( this );
12850 OO
.ui
.LabelElement
.call( this, config
);
12851 OO
.ui
.FlaggedElement
.call( this, config
);
12854 this.selected
= false;
12855 this.highlighted
= false;
12856 this.pressed
= false;
12860 .data( 'oo-ui-optionWidget', this )
12861 .attr( 'role', 'option' )
12862 .addClass( 'oo-ui-optionWidget' )
12863 .append( this.$label
);
12868 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
12869 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.ItemWidget
);
12870 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.LabelElement
);
12871 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.FlaggedElement
);
12873 /* Static Properties */
12875 OO
.ui
.OptionWidget
.static.selectable
= true;
12877 OO
.ui
.OptionWidget
.static.highlightable
= true;
12879 OO
.ui
.OptionWidget
.static.pressable
= true;
12881 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
12886 * Check if the option can be selected.
12888 * @return {boolean} Item is selectable
12890 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
12891 return this.constructor.static.selectable
&& !this.isDisabled();
12895 * Check if the option can be highlighted. A highlight indicates that the option
12896 * may be selected when a user presses enter or clicks. Disabled items cannot
12899 * @return {boolean} Item is highlightable
12901 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
12902 return this.constructor.static.highlightable
&& !this.isDisabled();
12906 * Check if the option can be pressed. The pressed state occurs when a user mouses
12907 * down on an item, but has not yet let go of the mouse.
12909 * @return {boolean} Item is pressable
12911 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
12912 return this.constructor.static.pressable
&& !this.isDisabled();
12916 * Check if the option is selected.
12918 * @return {boolean} Item is selected
12920 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
12921 return this.selected
;
12925 * Check if the option is highlighted. A highlight indicates that the
12926 * item may be selected when a user presses enter or clicks.
12928 * @return {boolean} Item is highlighted
12930 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
12931 return this.highlighted
;
12935 * Check if the option is pressed. The pressed state occurs when a user mouses
12936 * down on an item, but has not yet let go of the mouse. The item may appear
12937 * selected, but it will not be selected until the user releases the mouse.
12939 * @return {boolean} Item is pressed
12941 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
12942 return this.pressed
;
12946 * Set the option’s selected state. In general, all modifications to the selection
12947 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
12948 * method instead of this method.
12950 * @param {boolean} [state=false] Select option
12953 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
12954 if ( this.constructor.static.selectable
) {
12955 this.selected
= !!state
;
12957 .toggleClass( 'oo-ui-optionWidget-selected', state
)
12958 .attr( 'aria-selected', state
.toString() );
12959 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
12960 this.scrollElementIntoView();
12962 this.updateThemeClasses();
12968 * Set the option’s highlighted state. In general, all programmatic
12969 * modifications to the highlight should be handled by the
12970 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
12971 * method instead of this method.
12973 * @param {boolean} [state=false] Highlight option
12976 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
12977 if ( this.constructor.static.highlightable
) {
12978 this.highlighted
= !!state
;
12979 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
12980 this.updateThemeClasses();
12986 * Set the option’s pressed state. In general, all
12987 * programmatic modifications to the pressed state should be handled by the
12988 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
12989 * method instead of this method.
12991 * @param {boolean} [state=false] Press option
12994 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
12995 if ( this.constructor.static.pressable
) {
12996 this.pressed
= !!state
;
12997 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
12998 this.updateThemeClasses();
13004 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
13005 * with an {@link OO.ui.IconElement icon} and/or {@link OO.ui.IndicatorElement indicator}.
13006 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
13007 * options. For more information about options and selects, please see the
13008 * [OOjs UI documentation on MediaWiki][1].
13011 * // Decorated options in a select widget
13012 * var select = new OO.ui.SelectWidget( {
13014 * new OO.ui.DecoratedOptionWidget( {
13016 * label: 'Option with icon',
13019 * new OO.ui.DecoratedOptionWidget( {
13021 * label: 'Option with indicator',
13022 * indicator: 'next'
13026 * $( 'body' ).append( select.$element );
13028 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13031 * @extends OO.ui.OptionWidget
13032 * @mixins OO.ui.IconElement
13033 * @mixins OO.ui.IndicatorElement
13036 * @param {Object} [config] Configuration options
13038 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
13039 // Parent constructor
13040 OO
.ui
.DecoratedOptionWidget
.super.call( this, config
);
13042 // Mixin constructors
13043 OO
.ui
.IconElement
.call( this, config
);
13044 OO
.ui
.IndicatorElement
.call( this, config
);
13048 .addClass( 'oo-ui-decoratedOptionWidget' )
13049 .prepend( this.$icon
)
13050 .append( this.$indicator
);
13055 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
13056 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.IconElement
);
13057 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.IndicatorElement
);
13060 * ButtonOptionWidget is a special type of {@link OO.ui.ButtonElement button element} that
13061 * can be selected and configured with data. The class is
13062 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
13063 * [OOjs UI documentation on MediaWiki] [1] for more information.
13065 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
13068 * @extends OO.ui.DecoratedOptionWidget
13069 * @mixins OO.ui.ButtonElement
13070 * @mixins OO.ui.TabIndexedElement
13073 * @param {Object} [config] Configuration options
13075 OO
.ui
.ButtonOptionWidget
= function OoUiButtonOptionWidget( config
) {
13076 // Configuration initialization
13077 config
= $.extend( { tabIndex
: -1 }, config
);
13079 // Parent constructor
13080 OO
.ui
.ButtonOptionWidget
.super.call( this, config
);
13082 // Mixin constructors
13083 OO
.ui
.ButtonElement
.call( this, config
);
13084 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
13087 this.$element
.addClass( 'oo-ui-buttonOptionWidget' );
13088 this.$button
.append( this.$element
.contents() );
13089 this.$element
.append( this.$button
);
13094 OO
.inheritClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
13095 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.ButtonElement
);
13096 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.TabIndexedElement
);
13098 /* Static Properties */
13100 // Allow button mouse down events to pass through so they can be handled by the parent select widget
13101 OO
.ui
.ButtonOptionWidget
.static.cancelButtonMouseDownEvents
= false;
13103 OO
.ui
.ButtonOptionWidget
.static.highlightable
= false;
13110 OO
.ui
.ButtonOptionWidget
.prototype.setSelected = function ( state
) {
13111 OO
.ui
.ButtonOptionWidget
.super.prototype.setSelected
.call( this, state
);
13113 if ( this.constructor.static.selectable
) {
13114 this.setActive( state
);
13121 * RadioOptionWidget is an option widget that looks like a radio button.
13122 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
13123 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
13125 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
13128 * @extends OO.ui.OptionWidget
13131 * @param {Object} [config] Configuration options
13133 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
13134 // Configuration initialization
13135 config
= config
|| {};
13137 // Properties (must be done before parent constructor which calls #setDisabled)
13138 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
13140 // Parent constructor
13141 OO
.ui
.RadioOptionWidget
.super.call( this, config
);
13145 .addClass( 'oo-ui-radioOptionWidget' )
13146 .prepend( this.radio
.$element
);
13151 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
13153 /* Static Properties */
13155 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
13157 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
13159 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
13161 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
13168 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
13169 OO
.ui
.RadioOptionWidget
.super.prototype.setSelected
.call( this, state
);
13171 this.radio
.setSelected( state
);
13179 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
13180 OO
.ui
.RadioOptionWidget
.super.prototype.setDisabled
.call( this, disabled
);
13182 this.radio
.setDisabled( this.isDisabled() );
13188 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
13189 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
13190 * the [OOjs UI documentation on MediaWiki] [1] for more information.
13192 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13195 * @extends OO.ui.DecoratedOptionWidget
13198 * @param {Object} [config] Configuration options
13200 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
13201 // Configuration initialization
13202 config
= $.extend( { icon
: 'check' }, config
);
13204 // Parent constructor
13205 OO
.ui
.MenuOptionWidget
.super.call( this, config
);
13209 .attr( 'role', 'menuitem' )
13210 .addClass( 'oo-ui-menuOptionWidget' );
13215 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
13217 /* Static Properties */
13219 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
13222 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
13223 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
13226 * var myDropdown = new OO.ui.DropdownWidget( {
13229 * new OO.ui.MenuSectionOptionWidget( {
13232 * new OO.ui.MenuOptionWidget( {
13234 * label: 'Welsh Corgi'
13236 * new OO.ui.MenuOptionWidget( {
13238 * label: 'Standard Poodle'
13240 * new OO.ui.MenuSectionOptionWidget( {
13243 * new OO.ui.MenuOptionWidget( {
13250 * $( 'body' ).append( myDropdown.$element );
13254 * @extends OO.ui.DecoratedOptionWidget
13257 * @param {Object} [config] Configuration options
13259 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
13260 // Parent constructor
13261 OO
.ui
.MenuSectionOptionWidget
.super.call( this, config
);
13264 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
13269 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
13271 /* Static Properties */
13273 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
13275 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
13278 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
13280 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
13281 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
13285 * @extends OO.ui.DecoratedOptionWidget
13288 * @param {Object} [config] Configuration options
13289 * @cfg {number} [level] Indentation level
13290 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
13292 OO
.ui
.OutlineOptionWidget
= function OoUiOutlineOptionWidget( config
) {
13293 // Configuration initialization
13294 config
= config
|| {};
13296 // Parent constructor
13297 OO
.ui
.OutlineOptionWidget
.super.call( this, config
);
13301 this.movable
= !!config
.movable
;
13302 this.removable
= !!config
.removable
;
13305 this.$element
.addClass( 'oo-ui-outlineOptionWidget' );
13306 this.setLevel( config
.level
);
13311 OO
.inheritClass( OO
.ui
.OutlineOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
13313 /* Static Properties */
13315 OO
.ui
.OutlineOptionWidget
.static.highlightable
= false;
13317 OO
.ui
.OutlineOptionWidget
.static.scrollIntoViewOnSelect
= true;
13319 OO
.ui
.OutlineOptionWidget
.static.levelClass
= 'oo-ui-outlineOptionWidget-level-';
13321 OO
.ui
.OutlineOptionWidget
.static.levels
= 3;
13326 * Check if item is movable.
13328 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13330 * @return {boolean} Item is movable
13332 OO
.ui
.OutlineOptionWidget
.prototype.isMovable = function () {
13333 return this.movable
;
13337 * Check if item is removable.
13339 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13341 * @return {boolean} Item is removable
13343 OO
.ui
.OutlineOptionWidget
.prototype.isRemovable = function () {
13344 return this.removable
;
13348 * Get indentation level.
13350 * @return {number} Indentation level
13352 OO
.ui
.OutlineOptionWidget
.prototype.getLevel = function () {
13359 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13361 * @param {boolean} movable Item is movable
13364 OO
.ui
.OutlineOptionWidget
.prototype.setMovable = function ( movable
) {
13365 this.movable
= !!movable
;
13366 this.updateThemeClasses();
13371 * Set removability.
13373 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13375 * @param {boolean} movable Item is removable
13378 OO
.ui
.OutlineOptionWidget
.prototype.setRemovable = function ( removable
) {
13379 this.removable
= !!removable
;
13380 this.updateThemeClasses();
13385 * Set indentation level.
13387 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
13390 OO
.ui
.OutlineOptionWidget
.prototype.setLevel = function ( level
) {
13391 var levels
= this.constructor.static.levels
,
13392 levelClass
= this.constructor.static.levelClass
,
13395 this.level
= level
? Math
.max( 0, Math
.min( levels
- 1, level
) ) : 0;
13397 if ( this.level
=== i
) {
13398 this.$element
.addClass( levelClass
+ i
);
13400 this.$element
.removeClass( levelClass
+ i
);
13403 this.updateThemeClasses();
13409 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
13410 * By default, each popup has an anchor that points toward its origin.
13411 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
13414 * // A popup widget.
13415 * var popup = new OO.ui.PopupWidget( {
13416 * $content: $( '<p>Hi there!</p>' ),
13421 * $( 'body' ).append( popup.$element );
13422 * // To display the popup, toggle the visibility to 'true'.
13423 * popup.toggle( true );
13425 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
13428 * @extends OO.ui.Widget
13429 * @mixins OO.ui.LabelElement
13432 * @param {Object} [config] Configuration options
13433 * @cfg {number} [width=320] Width of popup in pixels
13434 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
13435 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
13436 * @cfg {string} [align='center'] Alignment of the popup: `center`, `left`, or `right`.
13437 * If the popup is right-aligned, the right edge of the popup is aligned to the anchor.
13438 * For left-aligned popups, the left edge is aligned to the anchor.
13439 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
13440 * See the [OOjs UI docs on MediaWiki][3] for an example.
13441 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
13442 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
13443 * @cfg {jQuery} [$content] Content to append to the popup's body
13444 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
13445 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
13446 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
13448 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
13449 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
13451 * @cfg {boolean} [padded] Add padding to the popup's body
13453 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
13454 // Configuration initialization
13455 config
= config
|| {};
13457 // Parent constructor
13458 OO
.ui
.PopupWidget
.super.call( this, config
);
13460 // Properties (must be set before ClippableElement constructor call)
13461 this.$body
= $( '<div>' );
13463 // Mixin constructors
13464 OO
.ui
.LabelElement
.call( this, config
);
13465 OO
.ui
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$body
} ) );
13468 this.$popup
= $( '<div>' );
13469 this.$head
= $( '<div>' );
13470 this.$anchor
= $( '<div>' );
13471 // If undefined, will be computed lazily in updateDimensions()
13472 this.$container
= config
.$container
;
13473 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
13474 this.autoClose
= !!config
.autoClose
;
13475 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
13476 this.transitionTimeout
= null;
13477 this.anchor
= null;
13478 this.width
= config
.width
!== undefined ? config
.width
: 320;
13479 this.height
= config
.height
!== undefined ? config
.height
: null;
13480 this.align
= config
.align
|| 'center';
13481 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
13482 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
13483 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
13486 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
13489 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
13490 this.$body
.addClass( 'oo-ui-popupWidget-body' );
13491 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
13493 .addClass( 'oo-ui-popupWidget-head' )
13494 .append( this.$label
, this.closeButton
.$element
);
13495 if ( !config
.head
) {
13496 this.$head
.addClass( 'oo-ui-element-hidden' );
13499 .addClass( 'oo-ui-popupWidget-popup' )
13500 .append( this.$head
, this.$body
);
13502 .addClass( 'oo-ui-popupWidget' )
13503 .append( this.$popup
, this.$anchor
);
13504 // Move content, which was added to #$element by OO.ui.Widget, to the body
13505 if ( config
.$content
instanceof jQuery
) {
13506 this.$body
.append( config
.$content
);
13508 if ( config
.padded
) {
13509 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
13512 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
13513 // that reference properties not initialized at that time of parent class construction
13514 // TODO: Find a better way to handle post-constructor setup
13515 this.visible
= false;
13516 this.$element
.addClass( 'oo-ui-element-hidden' );
13521 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
13522 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.LabelElement
);
13523 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.ClippableElement
);
13528 * Handles mouse down events.
13531 * @param {MouseEvent} e Mouse down event
13533 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
13535 this.isVisible() &&
13536 !$.contains( this.$element
[ 0 ], e
.target
) &&
13537 ( !this.$autoCloseIgnore
|| !this.$autoCloseIgnore
.has( e
.target
).length
)
13539 this.toggle( false );
13544 * Bind mouse down listener.
13548 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
13549 // Capture clicks outside popup
13550 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler
, true );
13554 * Handles close button click events.
13558 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
13559 if ( this.isVisible() ) {
13560 this.toggle( false );
13565 * Unbind mouse down listener.
13569 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
13570 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler
, true );
13574 * Handles key down events.
13577 * @param {KeyboardEvent} e Key down event
13579 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
13581 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
13584 this.toggle( false );
13585 e
.preventDefault();
13586 e
.stopPropagation();
13591 * Bind key down listener.
13595 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
13596 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
13600 * Unbind key down listener.
13604 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
13605 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
13609 * Show, hide, or toggle the visibility of the anchor.
13611 * @param {boolean} [show] Show anchor, omit to toggle
13613 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
13614 show
= show
=== undefined ? !this.anchored
: !!show
;
13616 if ( this.anchored
!== show
) {
13618 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
13620 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
13622 this.anchored
= show
;
13627 * Check if the anchor is visible.
13629 * @return {boolean} Anchor is visible
13631 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
13632 return this.anchor
;
13638 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
13639 show
= show
=== undefined ? !this.isVisible() : !!show
;
13641 var change
= show
!== this.isVisible();
13644 OO
.ui
.PopupWidget
.super.prototype.toggle
.call( this, show
);
13648 if ( this.autoClose
) {
13649 this.bindMouseDownListener();
13650 this.bindKeyDownListener();
13652 this.updateDimensions();
13653 this.toggleClipping( true );
13655 this.toggleClipping( false );
13656 if ( this.autoClose
) {
13657 this.unbindMouseDownListener();
13658 this.unbindKeyDownListener();
13667 * Set the size of the popup.
13669 * Changing the size may also change the popup's position depending on the alignment.
13671 * @param {number} width Width in pixels
13672 * @param {number} height Height in pixels
13673 * @param {boolean} [transition=false] Use a smooth transition
13676 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
13677 this.width
= width
;
13678 this.height
= height
!== undefined ? height
: null;
13679 if ( this.isVisible() ) {
13680 this.updateDimensions( transition
);
13685 * Update the size and position.
13687 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
13688 * be called automatically.
13690 * @param {boolean} [transition=false] Use a smooth transition
13693 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
13694 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
13695 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
13698 if ( !this.$container
) {
13699 // Lazy-initialize $container if not specified in constructor
13700 this.$container
= $( this.getClosestScrollableElementContainer() );
13703 // Set height and width before measuring things, since it might cause our measurements
13704 // to change (e.g. due to scrollbars appearing or disappearing)
13707 height
: this.height
!== null ? this.height
: 'auto'
13710 // Compute initial popupOffset based on alignment
13711 popupOffset
= this.width
* ( { left
: 0, center
: -0.5, right
: -1 } )[ this.align
];
13713 // Figure out if this will cause the popup to go beyond the edge of the container
13714 originOffset
= this.$element
.offset().left
;
13715 containerLeft
= this.$container
.offset().left
;
13716 containerWidth
= this.$container
.innerWidth();
13717 containerRight
= containerLeft
+ containerWidth
;
13718 popupLeft
= popupOffset
- this.containerPadding
;
13719 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
13720 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
13721 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
13723 // Adjust offset to make the popup not go beyond the edge, if needed
13724 if ( overlapRight
< 0 ) {
13725 popupOffset
+= overlapRight
;
13726 } else if ( overlapLeft
< 0 ) {
13727 popupOffset
-= overlapLeft
;
13730 // Adjust offset to avoid anchor being rendered too close to the edge
13731 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
13732 // TODO: Find a measurement that works for CSS anchors and image anchors
13733 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
13734 if ( popupOffset
+ this.width
< anchorWidth
) {
13735 popupOffset
= anchorWidth
- this.width
;
13736 } else if ( -popupOffset
< anchorWidth
) {
13737 popupOffset
= -anchorWidth
;
13740 // Prevent transition from being interrupted
13741 clearTimeout( this.transitionTimeout
);
13742 if ( transition
) {
13743 // Enable transition
13744 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
13747 // Position body relative to anchor
13748 this.$popup
.css( 'margin-left', popupOffset
);
13750 if ( transition
) {
13751 // Prevent transitioning after transition is complete
13752 this.transitionTimeout
= setTimeout( function () {
13753 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
13756 // Prevent transitioning immediately
13757 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
13760 // Reevaluate clipping state since we've relocated and resized the popup
13767 * Progress bars visually display the status of an operation, such as a download,
13768 * and can be either determinate or indeterminate:
13770 * - **determinate** process bars show the percent of an operation that is complete.
13772 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
13773 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
13774 * not use percentages.
13776 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
13779 * // Examples of determinate and indeterminate progress bars.
13780 * var progressBar1 = new OO.ui.ProgressBarWidget( {
13783 * var progressBar2 = new OO.ui.ProgressBarWidget();
13785 * // Create a FieldsetLayout to layout progress bars
13786 * var fieldset = new OO.ui.FieldsetLayout;
13787 * fieldset.addItems( [
13788 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
13789 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
13791 * $( 'body' ).append( fieldset.$element );
13794 * @extends OO.ui.Widget
13797 * @param {Object} [config] Configuration options
13798 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
13799 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
13800 * By default, the progress bar is indeterminate.
13802 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
13803 // Configuration initialization
13804 config
= config
|| {};
13806 // Parent constructor
13807 OO
.ui
.ProgressBarWidget
.super.call( this, config
);
13810 this.$bar
= $( '<div>' );
13811 this.progress
= null;
13814 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
13815 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
13818 role
: 'progressbar',
13819 'aria-valuemin': 0,
13820 'aria-valuemax': 100
13822 .addClass( 'oo-ui-progressBarWidget' )
13823 .append( this.$bar
);
13828 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
13830 /* Static Properties */
13832 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
13837 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
13839 * @return {number|boolean} Progress percent
13841 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
13842 return this.progress
;
13846 * Set the percent of the process completed or `false` for an indeterminate process.
13848 * @param {number|boolean} progress Progress percent or `false` for indeterminate
13850 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
13851 this.progress
= progress
;
13853 if ( progress
!== false ) {
13854 this.$bar
.css( 'width', this.progress
+ '%' );
13855 this.$element
.attr( 'aria-valuenow', this.progress
);
13857 this.$bar
.css( 'width', '' );
13858 this.$element
.removeAttr( 'aria-valuenow' );
13860 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress
);
13864 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
13865 * and a {@link OO.ui.TextInputMenuSelectWidget menu} of search results, which is displayed beneath the query
13866 * field. Unlike {@link OO.ui.LookupElement lookup menus}, search result menus are always visible to the user.
13867 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
13868 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
13870 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
13871 * the [OOjs UI demos][1] for an example.
13873 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
13876 * @extends OO.ui.Widget
13879 * @param {Object} [config] Configuration options
13880 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
13881 * @cfg {string} [value] Initial query value
13883 OO
.ui
.SearchWidget
= function OoUiSearchWidget( config
) {
13884 // Configuration initialization
13885 config
= config
|| {};
13887 // Parent constructor
13888 OO
.ui
.SearchWidget
.super.call( this, config
);
13891 this.query
= new OO
.ui
.TextInputWidget( {
13893 placeholder
: config
.placeholder
,
13894 value
: config
.value
13896 this.results
= new OO
.ui
.SelectWidget();
13897 this.$query
= $( '<div>' );
13898 this.$results
= $( '<div>' );
13901 this.query
.connect( this, {
13902 change
: 'onQueryChange',
13903 enter
: 'onQueryEnter'
13905 this.results
.connect( this, {
13906 highlight
: 'onResultsHighlight',
13907 select
: 'onResultsSelect'
13909 this.query
.$input
.on( 'keydown', this.onQueryKeydown
.bind( this ) );
13913 .addClass( 'oo-ui-searchWidget-query' )
13914 .append( this.query
.$element
);
13916 .addClass( 'oo-ui-searchWidget-results' )
13917 .append( this.results
.$element
);
13919 .addClass( 'oo-ui-searchWidget' )
13920 .append( this.$results
, this.$query
);
13925 OO
.inheritClass( OO
.ui
.SearchWidget
, OO
.ui
.Widget
);
13930 * A 'highlight' event is emitted when an item is highlighted. The highlight indicates which
13931 * item will be selected. When a user mouses over a menu item, it is highlighted. If a search
13932 * string is typed into the query field instead, the first menu item that matches the query
13933 * will be highlighted.
13936 * @deprecated Connect straight to getResults() events instead
13937 * @param {Object|null} item Item data or null if no item is highlighted
13941 * A 'select' event is emitted when an item is selected. A menu item is selected when it is clicked,
13942 * or when a user types a search query, a menu result is highlighted, and the user presses enter.
13945 * @deprecated Connect straight to getResults() events instead
13946 * @param {Object|null} item Item data or null if no item is selected
13952 * Handle query key down events.
13955 * @param {jQuery.Event} e Key down event
13957 OO
.ui
.SearchWidget
.prototype.onQueryKeydown = function ( e
) {
13958 var highlightedItem
, nextItem
,
13959 dir
= e
.which
=== OO
.ui
.Keys
.DOWN
? 1 : ( e
.which
=== OO
.ui
.Keys
.UP
? -1 : 0 );
13962 highlightedItem
= this.results
.getHighlightedItem();
13963 if ( !highlightedItem
) {
13964 highlightedItem
= this.results
.getSelectedItem();
13966 nextItem
= this.results
.getRelativeSelectableItem( highlightedItem
, dir
);
13967 this.results
.highlightItem( nextItem
);
13968 nextItem
.scrollElementIntoView();
13973 * Handle select widget select events.
13975 * Clears existing results. Subclasses should repopulate items according to new query.
13978 * @param {string} value New value
13980 OO
.ui
.SearchWidget
.prototype.onQueryChange = function () {
13982 this.results
.clearItems();
13986 * Handle select widget enter key events.
13988 * Selects highlighted item.
13991 * @param {string} value New value
13993 OO
.ui
.SearchWidget
.prototype.onQueryEnter = function () {
13995 this.results
.selectItem( this.results
.getHighlightedItem() );
13999 * Handle select widget highlight events.
14002 * @deprecated Connect straight to getResults() events instead
14003 * @param {OO.ui.OptionWidget} item Highlighted item
14006 OO
.ui
.SearchWidget
.prototype.onResultsHighlight = function ( item
) {
14007 this.emit( 'highlight', item
? item
.getData() : null );
14011 * Handle select widget select events.
14014 * @deprecated Connect straight to getResults() events instead
14015 * @param {OO.ui.OptionWidget} item Selected item
14018 OO
.ui
.SearchWidget
.prototype.onResultsSelect = function ( item
) {
14019 this.emit( 'select', item
? item
.getData() : null );
14023 * Get the query input.
14025 * @return {OO.ui.TextInputWidget} Query input
14027 OO
.ui
.SearchWidget
.prototype.getQuery = function () {
14032 * Get the search results menu.
14034 * @return {OO.ui.SelectWidget} Menu of search results
14036 OO
.ui
.SearchWidget
.prototype.getResults = function () {
14037 return this.results
;
14041 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
14042 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
14043 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
14046 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
14047 * information, please see the [OOjs UI documentation on MediaWiki][1].
14050 * // Example of a select widget with three options
14051 * var select = new OO.ui.SelectWidget( {
14053 * new OO.ui.OptionWidget( {
14055 * label: 'Option One',
14057 * new OO.ui.OptionWidget( {
14059 * label: 'Option Two',
14061 * new OO.ui.OptionWidget( {
14063 * label: 'Option Three',
14067 * $( 'body' ).append( select.$element );
14069 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14072 * @extends OO.ui.Widget
14073 * @mixins OO.ui.GroupElement
14076 * @param {Object} [config] Configuration options
14077 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
14078 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
14079 * the [OOjs UI documentation on MediaWiki] [2] for examples.
14080 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14082 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
14083 // Configuration initialization
14084 config
= config
|| {};
14086 // Parent constructor
14087 OO
.ui
.SelectWidget
.super.call( this, config
);
14089 // Mixin constructors
14090 OO
.ui
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
14093 this.pressed
= false;
14094 this.selecting
= null;
14095 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
14096 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
14097 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
14100 this.$element
.on( {
14101 mousedown
: this.onMouseDown
.bind( this ),
14102 mouseover
: this.onMouseOver
.bind( this ),
14103 mouseleave
: this.onMouseLeave
.bind( this )
14108 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
14109 .attr( 'role', 'listbox' );
14110 if ( Array
.isArray( config
.items
) ) {
14111 this.addItems( config
.items
);
14117 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
14119 // Need to mixin base class as well
14120 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.GroupElement
);
14121 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.GroupWidget
);
14128 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
14130 * @param {OO.ui.OptionWidget|null} item Highlighted item
14136 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
14137 * pressed state of an option.
14139 * @param {OO.ui.OptionWidget|null} item Pressed item
14145 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
14147 * @param {OO.ui.OptionWidget|null} item Selected item
14152 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
14153 * @param {OO.ui.OptionWidget} item Chosen item
14159 * An `add` event is emitted when options are added to the select with the #addItems method.
14161 * @param {OO.ui.OptionWidget[]} items Added items
14162 * @param {number} index Index of insertion point
14168 * A `remove` event is emitted when options are removed from the select with the #clearItems
14169 * or #removeItems methods.
14171 * @param {OO.ui.OptionWidget[]} items Removed items
14177 * Handle mouse down events.
14180 * @param {jQuery.Event} e Mouse down event
14182 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
14185 if ( !this.isDisabled() && e
.which
=== 1 ) {
14186 this.togglePressed( true );
14187 item
= this.getTargetItem( e
);
14188 if ( item
&& item
.isSelectable() ) {
14189 this.pressItem( item
);
14190 this.selecting
= item
;
14191 this.getElementDocument().addEventListener(
14193 this.onMouseUpHandler
,
14196 this.getElementDocument().addEventListener(
14198 this.onMouseMoveHandler
,
14207 * Handle mouse up events.
14210 * @param {jQuery.Event} e Mouse up event
14212 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
14215 this.togglePressed( false );
14216 if ( !this.selecting
) {
14217 item
= this.getTargetItem( e
);
14218 if ( item
&& item
.isSelectable() ) {
14219 this.selecting
= item
;
14222 if ( !this.isDisabled() && e
.which
=== 1 && this.selecting
) {
14223 this.pressItem( null );
14224 this.chooseItem( this.selecting
);
14225 this.selecting
= null;
14228 this.getElementDocument().removeEventListener(
14230 this.onMouseUpHandler
,
14233 this.getElementDocument().removeEventListener(
14235 this.onMouseMoveHandler
,
14243 * Handle mouse move events.
14246 * @param {jQuery.Event} e Mouse move event
14248 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
14251 if ( !this.isDisabled() && this.pressed
) {
14252 item
= this.getTargetItem( e
);
14253 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
14254 this.pressItem( item
);
14255 this.selecting
= item
;
14262 * Handle mouse over events.
14265 * @param {jQuery.Event} e Mouse over event
14267 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
14270 if ( !this.isDisabled() ) {
14271 item
= this.getTargetItem( e
);
14272 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
14278 * Handle mouse leave events.
14281 * @param {jQuery.Event} e Mouse over event
14283 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
14284 if ( !this.isDisabled() ) {
14285 this.highlightItem( null );
14291 * Handle key down events.
14294 * @param {jQuery.Event} e Key down event
14296 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
14299 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
14301 if ( !this.isDisabled() && this.isVisible() ) {
14302 switch ( e
.keyCode
) {
14303 case OO
.ui
.Keys
.ENTER
:
14304 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
14305 // Was only highlighted, now let's select it. No-op if already selected.
14306 this.chooseItem( currentItem
);
14310 case OO
.ui
.Keys
.UP
:
14311 case OO
.ui
.Keys
.LEFT
:
14312 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
14315 case OO
.ui
.Keys
.DOWN
:
14316 case OO
.ui
.Keys
.RIGHT
:
14317 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
14320 case OO
.ui
.Keys
.ESCAPE
:
14321 case OO
.ui
.Keys
.TAB
:
14322 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
14323 currentItem
.setHighlighted( false );
14325 this.unbindKeyDownListener();
14326 // Don't prevent tabbing away / defocusing
14332 if ( nextItem
.constructor.static.highlightable
) {
14333 this.highlightItem( nextItem
);
14335 this.chooseItem( nextItem
);
14337 nextItem
.scrollElementIntoView();
14341 // Can't just return false, because e is not always a jQuery event
14342 e
.preventDefault();
14343 e
.stopPropagation();
14349 * Bind key down listener.
14353 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
14354 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler
, true );
14358 * Unbind key down listener.
14362 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
14363 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler
, true );
14367 * Get the closest item to a jQuery.Event.
14370 * @param {jQuery.Event} e
14371 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
14373 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
14374 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
14378 * Get selected item.
14380 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
14382 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
14385 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14386 if ( this.items
[ i
].isSelected() ) {
14387 return this.items
[ i
];
14394 * Get highlighted item.
14396 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
14398 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
14401 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14402 if ( this.items
[ i
].isHighlighted() ) {
14403 return this.items
[ i
];
14410 * Toggle pressed state.
14412 * Press is a state that occurs when a user mouses down on an item, but
14413 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
14414 * until the user releases the mouse.
14416 * @param {boolean} pressed An option is being pressed
14418 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
14419 if ( pressed
=== undefined ) {
14420 pressed
= !this.pressed
;
14422 if ( pressed
!== this.pressed
) {
14424 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
14425 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
14426 this.pressed
= pressed
;
14431 * Highlight an option. If the `item` param is omitted, no options will be highlighted
14432 * and any existing highlight will be removed. The highlight is mutually exclusive.
14434 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
14438 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
14439 var i
, len
, highlighted
,
14442 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14443 highlighted
= this.items
[ i
] === item
;
14444 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
14445 this.items
[ i
].setHighlighted( highlighted
);
14450 this.emit( 'highlight', item
);
14457 * Programmatically select an option by its reference. If the `item` parameter is omitted,
14458 * all options will be deselected.
14460 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
14464 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
14465 var i
, len
, selected
,
14468 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14469 selected
= this.items
[ i
] === item
;
14470 if ( this.items
[ i
].isSelected() !== selected
) {
14471 this.items
[ i
].setSelected( selected
);
14476 this.emit( 'select', item
);
14485 * Press is a state that occurs when a user mouses down on an item, but has not
14486 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
14487 * releases the mouse.
14489 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
14493 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
14494 var i
, len
, pressed
,
14497 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14498 pressed
= this.items
[ i
] === item
;
14499 if ( this.items
[ i
].isPressed() !== pressed
) {
14500 this.items
[ i
].setPressed( pressed
);
14505 this.emit( 'press', item
);
14514 * Note that ‘choose’ should never be modified programmatically. A user can choose
14515 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
14516 * use the #selectItem method.
14518 * This method is identical to #selectItem, but may vary in subclasses that take additional action
14519 * when users choose an item with the keyboard or mouse.
14521 * @param {OO.ui.OptionWidget} item Item to choose
14525 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
14526 this.selectItem( item
);
14527 this.emit( 'choose', item
);
14533 * Get an option by its position relative to the specified item (or to the start of the option array,
14534 * if item is `null`). The direction in which to search through the option array is specified with a
14535 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
14536 * `null` if there are no options in the array.
14538 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
14539 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
14540 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
14542 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
) {
14543 var currentIndex
, nextIndex
, i
,
14544 increase
= direction
> 0 ? 1 : -1,
14545 len
= this.items
.length
;
14547 if ( item
instanceof OO
.ui
.OptionWidget
) {
14548 currentIndex
= $.inArray( item
, this.items
);
14549 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
14551 // If no item is selected and moving forward, start at the beginning.
14552 // If moving backward, start at the end.
14553 nextIndex
= direction
> 0 ? 0 : len
- 1;
14556 for ( i
= 0; i
< len
; i
++ ) {
14557 item
= this.items
[ nextIndex
];
14558 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
14561 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
14567 * Get the next selectable item or `null` if there are no selectable items.
14568 * Disabled options and menu-section markers and breaks are not selectable.
14570 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
14572 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
14575 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14576 item
= this.items
[ i
];
14577 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
14586 * Add an array of options to the select. Optionally, an index number can be used to
14587 * specify an insertion point.
14589 * @param {OO.ui.OptionWidget[]} items Items to add
14590 * @param {number} [index] Index to insert items after
14594 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
14596 OO
.ui
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
14598 // Always provide an index, even if it was omitted
14599 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
14605 * Remove the specified array of options from the select. Options will be detached
14606 * from the DOM, not removed, so they can be reused later. To remove all options from
14607 * the select, you may wish to use the #clearItems method instead.
14609 * @param {OO.ui.OptionWidget[]} items Items to remove
14613 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
14616 // Deselect items being removed
14617 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
14619 if ( item
.isSelected() ) {
14620 this.selectItem( null );
14625 OO
.ui
.GroupWidget
.prototype.removeItems
.call( this, items
);
14627 this.emit( 'remove', items
);
14633 * Clear all options from the select. Options will be detached from the DOM, not removed,
14634 * so that they can be reused later. To remove a subset of options from the select, use
14635 * the #removeItems method.
14640 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
14641 var items
= this.items
.slice();
14644 OO
.ui
.GroupWidget
.prototype.clearItems
.call( this );
14647 this.selectItem( null );
14649 this.emit( 'remove', items
);
14655 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
14656 * button options and is used together with
14657 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
14658 * highlighting, choosing, and selecting mutually exclusive options. Please see
14659 * the [OOjs UI documentation on MediaWiki] [1] for more information.
14662 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
14663 * var option1 = new OO.ui.ButtonOptionWidget( {
14665 * label: 'Option 1',
14666 * title: 'Button option 1'
14669 * var option2 = new OO.ui.ButtonOptionWidget( {
14671 * label: 'Option 2',
14672 * title: 'Button option 2'
14675 * var option3 = new OO.ui.ButtonOptionWidget( {
14677 * label: 'Option 3',
14678 * title: 'Button option 3'
14681 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
14682 * items: [ option1, option2, option3 ]
14684 * $( 'body' ).append( buttonSelect.$element );
14686 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14689 * @extends OO.ui.SelectWidget
14690 * @mixins OO.ui.TabIndexedElement
14693 * @param {Object} [config] Configuration options
14695 OO
.ui
.ButtonSelectWidget
= function OoUiButtonSelectWidget( config
) {
14696 // Parent constructor
14697 OO
.ui
.ButtonSelectWidget
.super.call( this, config
);
14699 // Mixin constructors
14700 OO
.ui
.TabIndexedElement
.call( this, config
);
14703 this.$element
.on( {
14704 focus
: this.bindKeyDownListener
.bind( this ),
14705 blur
: this.unbindKeyDownListener
.bind( this )
14709 this.$element
.addClass( 'oo-ui-buttonSelectWidget' );
14714 OO
.inheritClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.SelectWidget
);
14715 OO
.mixinClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.TabIndexedElement
);
14718 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
14719 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
14720 * an interface for adding, removing and selecting options.
14721 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
14724 * // A RadioSelectWidget with RadioOptions.
14725 * var option1 = new OO.ui.RadioOptionWidget( {
14727 * label: 'Selected radio option'
14730 * var option2 = new OO.ui.RadioOptionWidget( {
14732 * label: 'Unselected radio option'
14735 * var radioSelect=new OO.ui.RadioSelectWidget( {
14736 * items: [ option1, option2 ]
14739 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
14740 * radioSelect.selectItem( option1 );
14742 * $( 'body' ).append( radioSelect.$element );
14744 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14748 * @extends OO.ui.SelectWidget
14749 * @mixins OO.ui.TabIndexedElement
14752 * @param {Object} [config] Configuration options
14754 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
14755 // Parent constructor
14756 OO
.ui
.RadioSelectWidget
.super.call( this, config
);
14758 // Mixin constructors
14759 OO
.ui
.TabIndexedElement
.call( this, config
);
14762 this.$element
.on( {
14763 focus
: this.bindKeyDownListener
.bind( this ),
14764 blur
: this.unbindKeyDownListener
.bind( this )
14768 this.$element
.addClass( 'oo-ui-radioSelectWidget' );
14773 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
14774 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.TabIndexedElement
);
14777 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
14778 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
14779 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
14780 * and {@link OO.ui.LookupElement LookupElement} for examples of widgets that contain menus.
14781 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
14782 * and customized to be opened, closed, and displayed as needed.
14784 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
14785 * mouse outside the menu.
14787 * Menus also have support for keyboard interaction:
14789 * - Enter/Return key: choose and select a menu option
14790 * - Up-arrow key: highlight the previous menu option
14791 * - Down-arrow key: highlight the next menu option
14792 * - Esc key: hide the menu
14794 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
14795 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14798 * @extends OO.ui.SelectWidget
14799 * @mixins OO.ui.ClippableElement
14802 * @param {Object} [config] Configuration options
14803 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
14804 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
14805 * and {@link OO.ui.LookupElement LookupElement}
14806 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu’s active state. If the user clicks the mouse
14807 * anywhere on the page outside of this widget, the menu is hidden.
14808 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
14810 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
14811 // Configuration initialization
14812 config
= config
|| {};
14814 // Parent constructor
14815 OO
.ui
.MenuSelectWidget
.super.call( this, config
);
14817 // Mixin constructors
14818 OO
.ui
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
14821 this.newItems
= null;
14822 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
14823 this.$input
= config
.input
? config
.input
.$input
: null;
14824 this.$widget
= config
.widget
? config
.widget
.$element
: null;
14825 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
14829 .addClass( 'oo-ui-menuSelectWidget' )
14830 .attr( 'role', 'menu' );
14832 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
14833 // that reference properties not initialized at that time of parent class construction
14834 // TODO: Find a better way to handle post-constructor setup
14835 this.visible
= false;
14836 this.$element
.addClass( 'oo-ui-element-hidden' );
14841 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
14842 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.ClippableElement
);
14847 * Handles document mouse down events.
14850 * @param {jQuery.Event} e Key down event
14852 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
14854 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
14855 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
14857 this.toggle( false );
14864 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
14865 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
14867 if ( !this.isDisabled() && this.isVisible() ) {
14868 switch ( e
.keyCode
) {
14869 case OO
.ui
.Keys
.LEFT
:
14870 case OO
.ui
.Keys
.RIGHT
:
14871 // Do nothing if a text field is associated, arrow keys will be handled natively
14872 if ( !this.$input
) {
14873 OO
.ui
.MenuSelectWidget
.super.prototype.onKeyDown
.call( this, e
);
14876 case OO
.ui
.Keys
.ESCAPE
:
14877 case OO
.ui
.Keys
.TAB
:
14878 if ( currentItem
) {
14879 currentItem
.setHighlighted( false );
14881 this.toggle( false );
14882 // Don't prevent tabbing away, prevent defocusing
14883 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
14884 e
.preventDefault();
14885 e
.stopPropagation();
14889 OO
.ui
.MenuSelectWidget
.super.prototype.onKeyDown
.call( this, e
);
14898 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
14899 if ( this.$input
) {
14900 this.$input
.on( 'keydown', this.onKeyDownHandler
);
14902 OO
.ui
.MenuSelectWidget
.super.prototype.bindKeyDownListener
.call( this );
14909 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
14910 if ( this.$input
) {
14911 this.$input
.off( 'keydown', this.onKeyDownHandler
);
14913 OO
.ui
.MenuSelectWidget
.super.prototype.unbindKeyDownListener
.call( this );
14920 * When a user chooses an item, the menu is closed.
14922 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
14923 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
14924 * @param {OO.ui.OptionWidget} item Item to choose
14927 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
14928 OO
.ui
.MenuSelectWidget
.super.prototype.chooseItem
.call( this, item
);
14929 this.toggle( false );
14936 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
14940 OO
.ui
.MenuSelectWidget
.super.prototype.addItems
.call( this, items
, index
);
14943 if ( !this.newItems
) {
14944 this.newItems
= [];
14947 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
14949 if ( this.isVisible() ) {
14950 // Defer fitting label until item has been attached
14953 this.newItems
.push( item
);
14957 // Reevaluate clipping
14966 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
14968 OO
.ui
.MenuSelectWidget
.super.prototype.removeItems
.call( this, items
);
14970 // Reevaluate clipping
14979 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
14981 OO
.ui
.MenuSelectWidget
.super.prototype.clearItems
.call( this );
14983 // Reevaluate clipping
14992 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
14993 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
14996 change
= visible
!== this.isVisible();
14999 OO
.ui
.MenuSelectWidget
.super.prototype.toggle
.call( this, visible
);
15003 this.bindKeyDownListener();
15005 if ( this.newItems
&& this.newItems
.length
) {
15006 for ( i
= 0, len
= this.newItems
.length
; i
< len
; i
++ ) {
15007 this.newItems
[ i
].fitLabel();
15009 this.newItems
= null;
15011 this.toggleClipping( true );
15014 if ( this.autoHide
) {
15015 this.getElementDocument().addEventListener(
15016 'mousedown', this.onDocumentMouseDownHandler
, true
15020 this.unbindKeyDownListener();
15021 this.getElementDocument().removeEventListener(
15022 'mousedown', this.onDocumentMouseDownHandler
, true
15024 this.toggleClipping( false );
15032 * TextInputMenuSelectWidget is a menu that is specially designed to be positioned beneath
15033 * a {@link OO.ui.TextInputWidget text input} field. The menu's position is automatically
15034 * calculated and maintained when the menu is toggled or the window is resized.
15035 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
15038 * @extends OO.ui.MenuSelectWidget
15041 * @param {OO.ui.TextInputWidget} inputWidget Text input widget to provide menu for
15042 * @param {Object} [config] Configuration options
15043 * @cfg {jQuery} [$container=input.$element] Element to render menu under
15045 OO
.ui
.TextInputMenuSelectWidget
= function OoUiTextInputMenuSelectWidget( inputWidget
, config
) {
15046 // Allow passing positional parameters inside the config object
15047 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
15048 config
= inputWidget
;
15049 inputWidget
= config
.inputWidget
;
15052 // Configuration initialization
15053 config
= config
|| {};
15055 // Parent constructor
15056 OO
.ui
.TextInputMenuSelectWidget
.super.call( this, config
);
15059 this.inputWidget
= inputWidget
;
15060 this.$container
= config
.$container
|| this.inputWidget
.$element
;
15061 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
15064 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
15069 OO
.inheritClass( OO
.ui
.TextInputMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
15074 * Handle window resize event.
15077 * @param {jQuery.Event} e Window resize event
15079 OO
.ui
.TextInputMenuSelectWidget
.prototype.onWindowResize = function () {
15086 OO
.ui
.TextInputMenuSelectWidget
.prototype.toggle = function ( visible
) {
15087 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
15089 var change
= visible
!== this.isVisible();
15091 if ( change
&& visible
) {
15092 // Make sure the width is set before the parent method runs.
15093 // After this we have to call this.position(); again to actually
15094 // position ourselves correctly.
15099 OO
.ui
.TextInputMenuSelectWidget
.super.prototype.toggle
.call( this, visible
);
15102 if ( this.isVisible() ) {
15104 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
15106 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
15114 * Position the menu.
15119 OO
.ui
.TextInputMenuSelectWidget
.prototype.position = function () {
15120 var $container
= this.$container
,
15121 pos
= OO
.ui
.Element
.static.getRelativePosition( $container
, this.$element
.offsetParent() );
15123 // Position under input
15124 pos
.top
+= $container
.height();
15125 this.$element
.css( pos
);
15128 this.setIdealSize( $container
.width() );
15129 // We updated the position, so re-evaluate the clipping state
15136 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
15137 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
15139 * ####Currently, this class is only used by {@link OO.ui.BookletLayout BookletLayouts}.####
15142 * @extends OO.ui.SelectWidget
15143 * @mixins OO.ui.TabIndexedElement
15146 * @param {Object} [config] Configuration options
15148 OO
.ui
.OutlineSelectWidget
= function OoUiOutlineSelectWidget( config
) {
15149 // Parent constructor
15150 OO
.ui
.OutlineSelectWidget
.super.call( this, config
);
15152 // Mixin constructors
15153 OO
.ui
.TabIndexedElement
.call( this, config
);
15156 this.$element
.on( {
15157 focus
: this.bindKeyDownListener
.bind( this ),
15158 blur
: this.unbindKeyDownListener
.bind( this )
15162 this.$element
.addClass( 'oo-ui-outlineSelectWidget' );
15167 OO
.inheritClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.SelectWidget
);
15168 OO
.mixinClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.TabIndexedElement
);
15171 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
15172 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
15173 * visually by a slider in the leftmost position.
15176 * // Toggle switches in the 'off' and 'on' position.
15177 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
15178 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
15182 * // Create a FieldsetLayout to layout and label switches
15183 * var fieldset = new OO.ui.FieldsetLayout( {
15184 * label: 'Toggle switches'
15186 * fieldset.addItems( [
15187 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
15188 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
15190 * $( 'body' ).append( fieldset.$element );
15193 * @extends OO.ui.ToggleWidget
15194 * @mixins OO.ui.TabIndexedElement
15197 * @param {Object} [config] Configuration options
15198 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
15199 * By default, the toggle switch is in the 'off' position.
15201 OO
.ui
.ToggleSwitchWidget
= function OoUiToggleSwitchWidget( config
) {
15202 // Parent constructor
15203 OO
.ui
.ToggleSwitchWidget
.super.call( this, config
);
15205 // Mixin constructors
15206 OO
.ui
.TabIndexedElement
.call( this, config
);
15209 this.dragging
= false;
15210 this.dragStart
= null;
15211 this.sliding
= false;
15212 this.$glow
= $( '<span>' );
15213 this.$grip
= $( '<span>' );
15216 this.$element
.on( {
15217 click
: this.onClick
.bind( this ),
15218 keypress
: this.onKeyPress
.bind( this )
15222 this.$glow
.addClass( 'oo-ui-toggleSwitchWidget-glow' );
15223 this.$grip
.addClass( 'oo-ui-toggleSwitchWidget-grip' );
15225 .addClass( 'oo-ui-toggleSwitchWidget' )
15226 .attr( 'role', 'checkbox' )
15227 .append( this.$glow
, this.$grip
);
15232 OO
.inheritClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.ToggleWidget
);
15233 OO
.mixinClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.TabIndexedElement
);
15238 * Handle mouse click events.
15241 * @param {jQuery.Event} e Mouse click event
15243 OO
.ui
.ToggleSwitchWidget
.prototype.onClick = function ( e
) {
15244 if ( !this.isDisabled() && e
.which
=== 1 ) {
15245 this.setValue( !this.value
);
15251 * Handle key press events.
15254 * @param {jQuery.Event} e Key press event
15256 OO
.ui
.ToggleSwitchWidget
.prototype.onKeyPress = function ( e
) {
15257 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
15258 this.setValue( !this.value
);