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-05-11T17:24:27Z
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 * Return a function, that, as long as it continues to be invoked, will not
155 * be triggered. The function will be called after it stops being called for
156 * N milliseconds. If `immediate` is passed, trigger the function on the
157 * leading edge, instead of the trailing.
159 * Ported from: http://underscorejs.org/underscore.js
161 * @param {Function} func
162 * @param {number} wait
163 * @param {boolean} immediate
166 OO
.ui
.debounce = function ( func
, wait
, immediate
) {
171 later = function () {
174 func
.apply( context
, args
);
177 if ( immediate
&& !timeout
) {
178 func
.apply( context
, args
);
180 clearTimeout( timeout
);
181 timeout
= setTimeout( later
, wait
);
186 * Reconstitute a JavaScript object corresponding to a widget created by
187 * the PHP implementation.
189 * This is an alias for `OO.ui.Element.static.infuse()`.
191 * @param {string|HTMLElement|jQuery} idOrNode
192 * A DOM id (if a string) or node for the widget to infuse.
193 * @return {OO.ui.Element}
194 * The `OO.ui.Element` corresponding to this (infusable) document node.
196 OO
.ui
.infuse = function ( idOrNode
) {
197 return OO
.ui
.Element
.static.infuse( idOrNode
);
202 * Message store for the default implementation of OO.ui.msg
204 * Environments that provide a localization system should not use this, but should override
205 * OO.ui.msg altogether.
210 // Tool tip for a button that moves items in a list down one place
211 'ooui-outline-control-move-down': 'Move item down',
212 // Tool tip for a button that moves items in a list up one place
213 'ooui-outline-control-move-up': 'Move item up',
214 // Tool tip for a button that removes items from a list
215 'ooui-outline-control-remove': 'Remove item',
216 // Label for the toolbar group that contains a list of all other available tools
217 'ooui-toolbar-more': 'More',
218 // Label for the fake tool that expands the full list of tools in a toolbar group
219 'ooui-toolgroup-expand': 'More',
220 // Label for the fake tool that collapses the full list of tools in a toolbar group
221 'ooui-toolgroup-collapse': 'Fewer',
222 // Default label for the accept button of a confirmation dialog
223 'ooui-dialog-message-accept': 'OK',
224 // Default label for the reject button of a confirmation dialog
225 'ooui-dialog-message-reject': 'Cancel',
226 // Title for process dialog error description
227 'ooui-dialog-process-error': 'Something went wrong',
228 // Label for process dialog dismiss error button, visible when describing errors
229 'ooui-dialog-process-dismiss': 'Dismiss',
230 // Label for process dialog retry action button, visible when describing only recoverable errors
231 'ooui-dialog-process-retry': 'Try again',
232 // Label for process dialog retry action button, visible when describing only warnings
233 'ooui-dialog-process-continue': 'Continue'
237 * Get a localized message.
239 * In environments that provide a localization system, this function should be overridden to
240 * return the message translated in the user's language. The default implementation always returns
243 * After the message key, message parameters may optionally be passed. In the default implementation,
244 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
245 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
246 * they support unnamed, ordered message parameters.
249 * @param {string} key Message key
250 * @param {Mixed...} [params] Message parameters
251 * @return {string} Translated message with parameters substituted
253 OO
.ui
.msg = function ( key
) {
254 var message
= messages
[ key
],
255 params
= Array
.prototype.slice
.call( arguments
, 1 );
256 if ( typeof message
=== 'string' ) {
257 // Perform $1 substitution
258 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
259 var i
= parseInt( n
, 10 );
260 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
263 // Return placeholder if message not found
264 message
= '[' + key
+ ']';
270 * Package a message and arguments for deferred resolution.
272 * Use this when you are statically specifying a message and the message may not yet be present.
274 * @param {string} key Message key
275 * @param {Mixed...} [params] Message parameters
276 * @return {Function} Function that returns the resolved message when executed
278 OO
.ui
.deferMsg = function () {
279 var args
= arguments
;
281 return OO
.ui
.msg
.apply( OO
.ui
, args
);
288 * If the message is a function it will be executed, otherwise it will pass through directly.
290 * @param {Function|string} msg Deferred message, or message text
291 * @return {string} Resolved message
293 OO
.ui
.resolveMsg = function ( msg
) {
294 if ( $.isFunction( msg
) ) {
303 * Element that can be marked as pending.
309 * @param {Object} [config] Configuration options
310 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
312 OO
.ui
.PendingElement
= function OoUiPendingElement( config
) {
313 // Configuration initialization
314 config
= config
|| {};
318 this.$pending
= null;
321 this.setPendingElement( config
.$pending
|| this.$element
);
326 OO
.initClass( OO
.ui
.PendingElement
);
331 * Set the pending element (and clean up any existing one).
333 * @param {jQuery} $pending The element to set to pending.
335 OO
.ui
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
336 if ( this.$pending
) {
337 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
340 this.$pending
= $pending
;
341 if ( this.pending
> 0 ) {
342 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
347 * Check if input is pending.
351 OO
.ui
.PendingElement
.prototype.isPending = function () {
352 return !!this.pending
;
356 * Increase the pending stack.
360 OO
.ui
.PendingElement
.prototype.pushPending = function () {
361 if ( this.pending
=== 0 ) {
362 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
363 this.updateThemeClasses();
371 * Reduce the pending stack.
377 OO
.ui
.PendingElement
.prototype.popPending = function () {
378 if ( this.pending
=== 1 ) {
379 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
380 this.updateThemeClasses();
382 this.pending
= Math
.max( 0, this.pending
- 1 );
388 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
389 * Actions can be made available for specific contexts (modes) and circumstances
390 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
392 * ActionSets contain two types of actions:
394 * - 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.
395 * - Other: Other actions include all non-special visible actions.
397 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
400 * // Example: An action set used in a process dialog
401 * function MyProcessDialog( config ) {
402 * MyProcessDialog.super.call( this, config );
404 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
405 * MyProcessDialog.static.title = 'An action set in a process dialog';
406 * // An action set that uses modes ('edit' and 'help' mode, in this example).
407 * MyProcessDialog.static.actions = [
408 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
409 * { action: 'help', modes: 'edit', label: 'Help' },
410 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
411 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
414 * MyProcessDialog.prototype.initialize = function () {
415 * MyProcessDialog.super.prototype.initialize.apply( this, arguments );
416 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
417 * 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>' );
418 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
419 * 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>' );
420 * this.stackLayout = new OO.ui.StackLayout( {
421 * items: [ this.panel1, this.panel2 ]
423 * this.$body.append( this.stackLayout.$element );
425 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
426 * return MyProcessDialog.super.prototype.getSetupProcess.call( this, data )
427 * .next( function () {
428 * this.actions.setMode( 'edit' );
431 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
432 * if ( action === 'help' ) {
433 * this.actions.setMode( 'help' );
434 * this.stackLayout.setItem( this.panel2 );
435 * } else if ( action === 'back' ) {
436 * this.actions.setMode( 'edit' );
437 * this.stackLayout.setItem( this.panel1 );
438 * } else if ( action === 'continue' ) {
440 * return new OO.ui.Process( function () {
444 * return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
446 * MyProcessDialog.prototype.getBodyHeight = function () {
447 * return this.panel1.$element.outerHeight( true );
449 * var windowManager = new OO.ui.WindowManager();
450 * $( 'body' ).append( windowManager.$element );
451 * var dialog = new MyProcessDialog( {
454 * windowManager.addWindows( [ dialog ] );
455 * windowManager.openWindow( dialog );
457 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
461 * @mixins OO.EventEmitter
464 * @param {Object} [config] Configuration options
466 OO
.ui
.ActionSet
= function OoUiActionSet( config
) {
467 // Configuration initialization
468 config
= config
|| {};
470 // Mixin constructors
471 OO
.EventEmitter
.call( this );
476 actions
: 'getAction',
480 this.categorized
= {};
483 this.organized
= false;
484 this.changing
= false;
485 this.changed
= false;
490 OO
.mixinClass( OO
.ui
.ActionSet
, OO
.EventEmitter
);
492 /* Static Properties */
495 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
496 * header of a {@link OO.ui.ProcessDialog process dialog}.
497 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
499 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
506 OO
.ui
.ActionSet
.static.specialFlags
= [ 'safe', 'primary' ];
513 * A 'click' event is emitted when an action is clicked.
515 * @param {OO.ui.ActionWidget} action Action that was clicked
521 * A 'resize' event is emitted when an action widget is resized.
523 * @param {OO.ui.ActionWidget} action Action that was resized
529 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
531 * @param {OO.ui.ActionWidget[]} added Actions added
537 * A 'remove' event is emitted when actions are {@link #method-remove removed}
538 * or {@link #clear cleared}.
540 * @param {OO.ui.ActionWidget[]} added Actions removed
546 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
547 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
554 * Handle action change events.
559 OO
.ui
.ActionSet
.prototype.onActionChange = function () {
560 this.organized
= false;
561 if ( this.changing
) {
564 this.emit( 'change' );
569 * Check if an action is one of the special actions.
571 * @param {OO.ui.ActionWidget} action Action to check
572 * @return {boolean} Action is special
574 OO
.ui
.ActionSet
.prototype.isSpecial = function ( action
) {
577 for ( flag
in this.special
) {
578 if ( action
=== this.special
[ flag
] ) {
587 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
590 * @param {Object} [filters] Filters to use, omit to get all actions
591 * @param {string|string[]} [filters.actions] Actions that action widgets must have
592 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
593 * @param {string|string[]} [filters.modes] Modes that action widgets must have
594 * @param {boolean} [filters.visible] Action widgets must be visible
595 * @param {boolean} [filters.disabled] Action widgets must be disabled
596 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
598 OO
.ui
.ActionSet
.prototype.get = function ( filters
) {
599 var i
, len
, list
, category
, actions
, index
, match
, matches
;
604 // Collect category candidates
606 for ( category
in this.categorized
) {
607 list
= filters
[ category
];
609 if ( !Array
.isArray( list
) ) {
612 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
613 actions
= this.categorized
[ category
][ list
[ i
] ];
614 if ( Array
.isArray( actions
) ) {
615 matches
.push
.apply( matches
, actions
);
620 // Remove by boolean filters
621 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
622 match
= matches
[ i
];
624 ( filters
.visible
!== undefined && match
.isVisible() !== filters
.visible
) ||
625 ( filters
.disabled
!== undefined && match
.isDisabled() !== filters
.disabled
)
627 matches
.splice( i
, 1 );
633 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
634 match
= matches
[ i
];
635 index
= matches
.lastIndexOf( match
);
636 while ( index
!== i
) {
637 matches
.splice( index
, 1 );
639 index
= matches
.lastIndexOf( match
);
644 return this.list
.slice();
648 * Get 'special' actions.
650 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
651 * Special flags can be configured in subclasses by changing the static #specialFlags property.
653 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
655 OO
.ui
.ActionSet
.prototype.getSpecial = function () {
657 return $.extend( {}, this.special
);
661 * Get 'other' actions.
663 * Other actions include all non-special visible action widgets.
665 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
667 OO
.ui
.ActionSet
.prototype.getOthers = function () {
669 return this.others
.slice();
673 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
674 * to be available in the specified mode will be made visible. All other actions will be hidden.
676 * @param {string} mode The mode. Only actions configured to be available in the specified
677 * mode will be made visible.
682 OO
.ui
.ActionSet
.prototype.setMode = function ( mode
) {
685 this.changing
= true;
686 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
687 action
= this.list
[ i
];
688 action
.toggle( action
.hasMode( mode
) );
691 this.organized
= false;
692 this.changing
= false;
693 this.emit( 'change' );
699 * Set the abilities of the specified actions.
701 * Action widgets that are configured with the specified actions will be enabled
702 * or disabled based on the boolean values specified in the `actions`
705 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
706 * values that indicate whether or not the action should be enabled.
709 OO
.ui
.ActionSet
.prototype.setAbilities = function ( actions
) {
710 var i
, len
, action
, item
;
712 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
713 item
= this.list
[ i
];
714 action
= item
.getAction();
715 if ( actions
[ action
] !== undefined ) {
716 item
.setDisabled( !actions
[ action
] );
724 * Executes a function once per action.
726 * When making changes to multiple actions, use this method instead of iterating over the actions
727 * manually to defer emitting a #change event until after all actions have been changed.
729 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
730 * @param {Function} callback Callback to run for each action; callback is invoked with three
731 * arguments: the action, the action's index, the list of actions being iterated over
734 OO
.ui
.ActionSet
.prototype.forEach = function ( filter
, callback
) {
735 this.changed
= false;
736 this.changing
= true;
737 this.get( filter
).forEach( callback
);
738 this.changing
= false;
739 if ( this.changed
) {
740 this.emit( 'change' );
747 * Add action widgets to the action set.
749 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
754 OO
.ui
.ActionSet
.prototype.add = function ( actions
) {
757 this.changing
= true;
758 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
759 action
= actions
[ i
];
760 action
.connect( this, {
761 click
: [ 'emit', 'click', action
],
762 resize
: [ 'emit', 'resize', action
],
763 toggle
: [ 'onActionChange' ]
765 this.list
.push( action
);
767 this.organized
= false;
768 this.emit( 'add', actions
);
769 this.changing
= false;
770 this.emit( 'change' );
776 * Remove action widgets from the set.
778 * To remove all actions, you may wish to use the #clear method instead.
780 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
785 OO
.ui
.ActionSet
.prototype.remove = function ( actions
) {
786 var i
, len
, index
, action
;
788 this.changing
= true;
789 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
790 action
= actions
[ i
];
791 index
= this.list
.indexOf( action
);
792 if ( index
!== -1 ) {
793 action
.disconnect( this );
794 this.list
.splice( index
, 1 );
797 this.organized
= false;
798 this.emit( 'remove', actions
);
799 this.changing
= false;
800 this.emit( 'change' );
806 * Remove all action widets from the set.
808 * To remove only specified actions, use the {@link #method-remove remove} method instead.
814 OO
.ui
.ActionSet
.prototype.clear = function () {
816 removed
= this.list
.slice();
818 this.changing
= true;
819 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
820 action
= this.list
[ i
];
821 action
.disconnect( this );
826 this.organized
= false;
827 this.emit( 'remove', removed
);
828 this.changing
= false;
829 this.emit( 'change' );
837 * This is called whenever organized information is requested. It will only reorganize the actions
838 * if something has changed since the last time it ran.
843 OO
.ui
.ActionSet
.prototype.organize = function () {
844 var i
, iLen
, j
, jLen
, flag
, action
, category
, list
, item
, special
,
845 specialFlags
= this.constructor.static.specialFlags
;
847 if ( !this.organized
) {
848 this.categorized
= {};
851 for ( i
= 0, iLen
= this.list
.length
; i
< iLen
; i
++ ) {
852 action
= this.list
[ i
];
853 if ( action
.isVisible() ) {
854 // Populate categories
855 for ( category
in this.categories
) {
856 if ( !this.categorized
[ category
] ) {
857 this.categorized
[ category
] = {};
859 list
= action
[ this.categories
[ category
] ]();
860 if ( !Array
.isArray( list
) ) {
863 for ( j
= 0, jLen
= list
.length
; j
< jLen
; j
++ ) {
865 if ( !this.categorized
[ category
][ item
] ) {
866 this.categorized
[ category
][ item
] = [];
868 this.categorized
[ category
][ item
].push( action
);
871 // Populate special/others
873 for ( j
= 0, jLen
= specialFlags
.length
; j
< jLen
; j
++ ) {
874 flag
= specialFlags
[ j
];
875 if ( !this.special
[ flag
] && action
.hasFlag( flag
) ) {
876 this.special
[ flag
] = action
;
882 this.others
.push( action
);
886 this.organized
= true;
893 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
894 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
895 * connected to them and can't be interacted with.
901 * @param {Object} [config] Configuration options
902 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
903 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
905 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
906 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
907 * @cfg {string} [text] Text to insert
908 * @cfg {Array} [content] An array of content elements to append (after #text).
909 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
910 * Instances of OO.ui.Element will have their $element appended.
911 * @cfg {jQuery} [$content] Content elements to append (after #text)
912 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
913 * Data can also be specified with the #setData method.
915 OO
.ui
.Element
= function OoUiElement( config
) {
916 // Configuration initialization
917 config
= config
|| {};
922 this.data
= config
.data
;
923 this.$element
= config
.$element
||
924 $( document
.createElement( this.getTagName() ) );
925 this.elementGroup
= null;
926 this.debouncedUpdateThemeClassesHandler
= this.debouncedUpdateThemeClasses
.bind( this );
927 this.updateThemeClassesPending
= false;
930 if ( Array
.isArray( config
.classes
) ) {
931 this.$element
.addClass( config
.classes
.join( ' ' ) );
934 this.$element
.attr( 'id', config
.id
);
937 this.$element
.text( config
.text
);
939 if ( config
.content
) {
940 // The `content` property treats plain strings as text; use an
941 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
942 // appropriate $element appended.
943 this.$element
.append( config
.content
.map( function ( v
) {
944 if ( typeof v
=== 'string' ) {
945 // Escape string so it is properly represented in HTML.
946 return document
.createTextNode( v
);
947 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
950 } else if ( v
instanceof OO
.ui
.Element
) {
956 if ( config
.$content
) {
957 // The `$content` property treats plain strings as HTML.
958 this.$element
.append( config
.$content
);
964 OO
.initClass( OO
.ui
.Element
);
966 /* Static Properties */
969 * The name of the HTML tag used by the element.
971 * The static value may be ignored if the #getTagName method is overridden.
977 OO
.ui
.Element
.static.tagName
= 'div';
982 * Reconstitute a JavaScript object corresponding to a widget created
983 * by the PHP implementation.
985 * @param {string|HTMLElement|jQuery} idOrNode
986 * A DOM id (if a string) or node for the widget to infuse.
987 * @return {OO.ui.Element}
988 * The `OO.ui.Element` corresponding to this (infusable) document node.
989 * For `Tag` objects emitted on the HTML side (used occasionally for content)
990 * the value returned is a newly-created Element wrapping around the existing
993 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
994 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, true );
995 // Verify that the type matches up.
996 // FIXME: uncomment after T89721 is fixed (see T90929)
998 if ( !( obj instanceof this['class'] ) ) {
999 throw new Error( 'Infusion type mismatch!' );
1006 * Implementation helper for `infuse`; skips the type check and has an
1007 * extra property so that only the top-level invocation touches the DOM.
1009 * @param {string|HTMLElement|jQuery} idOrNode
1010 * @param {boolean} top True only for top-level invocation.
1011 * @return {OO.ui.Element}
1013 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, top
) {
1014 // look for a cached result of a previous infusion.
1015 var id
, $elem
, data
, cls
, obj
;
1016 if ( typeof idOrNode
=== 'string' ) {
1018 $elem
= $( document
.getElementById( id
) );
1020 $elem
= $( idOrNode
);
1021 id
= $elem
.attr( 'id' );
1023 data
= $elem
.data( 'ooui-infused' );
1026 if ( data
=== true ) {
1027 throw new Error( 'Circular dependency! ' + id
);
1031 if ( !$elem
.length
) {
1032 throw new Error( 'Widget not found: ' + id
);
1034 data
= $elem
.attr( 'data-ooui' );
1036 throw new Error( 'No infusion data found: ' + id
);
1039 data
= $.parseJSON( data
);
1043 if ( !( data
&& data
._
) ) {
1044 throw new Error( 'No valid infusion data found: ' + id
);
1046 if ( data
._
=== 'Tag' ) {
1047 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1048 return new OO
.ui
.Element( { $element
: $elem
} );
1050 cls
= OO
.ui
[data
._
];
1052 throw new Error( 'Unknown widget type: ' + id
);
1054 $elem
.data( 'ooui-infused', true ); // prevent loops
1055 data
.id
= id
; // implicit
1056 data
= OO
.copy( data
, null, function deserialize( value
) {
1057 if ( OO
.isPlainObject( value
) ) {
1059 return OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, false );
1062 return new OO
.ui
.HtmlSnippet( value
.html
);
1066 // jscs:disable requireCapitalizedConstructors
1067 obj
= new cls( data
); // rebuild widget
1068 // now replace old DOM with this new DOM.
1070 $elem
.replaceWith( obj
.$element
);
1072 obj
.$element
.data( 'ooui-infused', obj
);
1073 // set the 'data-ooui' attribute so we can identify infused widgets
1074 obj
.$element
.attr( 'data-ooui', '' );
1079 * Get a jQuery function within a specific document.
1082 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1083 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1085 * @return {Function} Bound jQuery function
1087 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
1088 function wrapper( selector
) {
1089 return $( selector
, wrapper
.context
);
1092 wrapper
.context
= this.getDocument( context
);
1095 wrapper
.$iframe
= $iframe
;
1102 * Get the document of an element.
1105 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1106 * @return {HTMLDocument|null} Document object
1108 OO
.ui
.Element
.static.getDocument = function ( obj
) {
1109 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1110 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
1111 // Empty jQuery selections might have a context
1114 obj
.ownerDocument
||
1118 ( obj
.nodeType
=== 9 && obj
) ||
1123 * Get the window of an element or document.
1126 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1127 * @return {Window} Window object
1129 OO
.ui
.Element
.static.getWindow = function ( obj
) {
1130 var doc
= this.getDocument( obj
);
1131 return doc
.parentWindow
|| doc
.defaultView
;
1135 * Get the direction of an element or document.
1138 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1139 * @return {string} Text direction, either 'ltr' or 'rtl'
1141 OO
.ui
.Element
.static.getDir = function ( obj
) {
1144 if ( obj
instanceof jQuery
) {
1147 isDoc
= obj
.nodeType
=== 9;
1148 isWin
= obj
.document
!== undefined;
1149 if ( isDoc
|| isWin
) {
1155 return $( obj
).css( 'direction' );
1159 * Get the offset between two frames.
1161 * TODO: Make this function not use recursion.
1164 * @param {Window} from Window of the child frame
1165 * @param {Window} [to=window] Window of the parent frame
1166 * @param {Object} [offset] Offset to start with, used internally
1167 * @return {Object} Offset object, containing left and top properties
1169 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
1170 var i
, len
, frames
, frame
, rect
;
1176 offset
= { top
: 0, left
: 0 };
1178 if ( from.parent
=== from ) {
1182 // Get iframe element
1183 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
1184 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
1185 if ( frames
[ i
].contentWindow
=== from ) {
1186 frame
= frames
[ i
];
1191 // Recursively accumulate offset values
1193 rect
= frame
.getBoundingClientRect();
1194 offset
.left
+= rect
.left
;
1195 offset
.top
+= rect
.top
;
1196 if ( from !== to
) {
1197 this.getFrameOffset( from.parent
, offset
);
1204 * Get the offset between two elements.
1206 * The two elements may be in a different frame, but in that case the frame $element is in must
1207 * be contained in the frame $anchor is in.
1210 * @param {jQuery} $element Element whose position to get
1211 * @param {jQuery} $anchor Element to get $element's position relative to
1212 * @return {Object} Translated position coordinates, containing top and left properties
1214 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
1215 var iframe
, iframePos
,
1216 pos
= $element
.offset(),
1217 anchorPos
= $anchor
.offset(),
1218 elementDocument
= this.getDocument( $element
),
1219 anchorDocument
= this.getDocument( $anchor
);
1221 // If $element isn't in the same document as $anchor, traverse up
1222 while ( elementDocument
!== anchorDocument
) {
1223 iframe
= elementDocument
.defaultView
.frameElement
;
1225 throw new Error( '$element frame is not contained in $anchor frame' );
1227 iframePos
= $( iframe
).offset();
1228 pos
.left
+= iframePos
.left
;
1229 pos
.top
+= iframePos
.top
;
1230 elementDocument
= iframe
.ownerDocument
;
1232 pos
.left
-= anchorPos
.left
;
1233 pos
.top
-= anchorPos
.top
;
1238 * Get element border sizes.
1241 * @param {HTMLElement} el Element to measure
1242 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1244 OO
.ui
.Element
.static.getBorders = function ( el
) {
1245 var doc
= el
.ownerDocument
,
1246 win
= doc
.parentWindow
|| doc
.defaultView
,
1247 style
= win
&& win
.getComputedStyle
?
1248 win
.getComputedStyle( el
, null ) :
1251 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1252 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1253 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1254 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1265 * Get dimensions of an element or window.
1268 * @param {HTMLElement|Window} el Element to measure
1269 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1271 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1273 doc
= el
.ownerDocument
|| el
.document
,
1274 win
= doc
.parentWindow
|| doc
.defaultView
;
1276 if ( win
=== el
|| el
=== doc
.documentElement
) {
1279 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1281 top
: $win
.scrollTop(),
1282 left
: $win
.scrollLeft()
1284 scrollbar
: { right
: 0, bottom
: 0 },
1288 bottom
: $win
.innerHeight(),
1289 right
: $win
.innerWidth()
1295 borders
: this.getBorders( el
),
1297 top
: $el
.scrollTop(),
1298 left
: $el
.scrollLeft()
1301 right
: $el
.innerWidth() - el
.clientWidth
,
1302 bottom
: $el
.innerHeight() - el
.clientHeight
1304 rect
: el
.getBoundingClientRect()
1310 * Get scrollable object parent
1312 * documentElement can't be used to get or set the scrollTop
1313 * property on Blink. Changing and testing its value lets us
1314 * use 'body' or 'documentElement' based on what is working.
1316 * https://code.google.com/p/chromium/issues/detail?id=303131
1319 * @param {HTMLElement} el Element to find scrollable parent for
1320 * @return {HTMLElement} Scrollable parent
1322 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1323 var scrollTop
, body
;
1325 if ( OO
.ui
.scrollableElement
=== undefined ) {
1326 body
= el
.ownerDocument
.body
;
1327 scrollTop
= body
.scrollTop
;
1330 if ( body
.scrollTop
=== 1 ) {
1331 body
.scrollTop
= scrollTop
;
1332 OO
.ui
.scrollableElement
= 'body';
1334 OO
.ui
.scrollableElement
= 'documentElement';
1338 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1342 * Get closest scrollable container.
1344 * Traverses up until either a scrollable element or the root is reached, in which case the window
1348 * @param {HTMLElement} el Element to find scrollable container for
1349 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1350 * @return {HTMLElement} Closest scrollable container
1352 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1354 props
= [ 'overflow' ],
1355 $parent
= $( el
).parent();
1357 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1358 props
.push( 'overflow-' + dimension
);
1361 while ( $parent
.length
) {
1362 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1363 return $parent
[ 0 ];
1367 val
= $parent
.css( props
[ i
] );
1368 if ( val
=== 'auto' || val
=== 'scroll' ) {
1369 return $parent
[ 0 ];
1372 $parent
= $parent
.parent();
1374 return this.getDocument( el
).body
;
1378 * Scroll element into view.
1381 * @param {HTMLElement} el Element to scroll into view
1382 * @param {Object} [config] Configuration options
1383 * @param {string} [config.duration] jQuery animation duration value
1384 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1385 * to scroll in both directions
1386 * @param {Function} [config.complete] Function to call when scrolling completes
1388 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1389 // Configuration initialization
1390 config
= config
|| {};
1393 callback
= typeof config
.complete
=== 'function' && config
.complete
,
1394 sc
= this.getClosestScrollableContainer( el
, config
.direction
),
1396 eld
= this.getDimensions( el
),
1397 scd
= this.getDimensions( sc
),
1398 $win
= $( this.getWindow( el
) );
1400 // Compute the distances between the edges of el and the edges of the scroll viewport
1401 if ( $sc
.is( 'html, body' ) ) {
1402 // If the scrollable container is the root, this is easy
1405 bottom
: $win
.innerHeight() - eld
.rect
.bottom
,
1406 left
: eld
.rect
.left
,
1407 right
: $win
.innerWidth() - eld
.rect
.right
1410 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1412 top
: eld
.rect
.top
- ( scd
.rect
.top
+ scd
.borders
.top
),
1413 bottom
: scd
.rect
.bottom
- scd
.borders
.bottom
- scd
.scrollbar
.bottom
- eld
.rect
.bottom
,
1414 left
: eld
.rect
.left
- ( scd
.rect
.left
+ scd
.borders
.left
),
1415 right
: scd
.rect
.right
- scd
.borders
.right
- scd
.scrollbar
.right
- eld
.rect
.right
1419 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1420 if ( rel
.top
< 0 ) {
1421 anim
.scrollTop
= scd
.scroll
.top
+ rel
.top
;
1422 } else if ( rel
.top
> 0 && rel
.bottom
< 0 ) {
1423 anim
.scrollTop
= scd
.scroll
.top
+ Math
.min( rel
.top
, -rel
.bottom
);
1426 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1427 if ( rel
.left
< 0 ) {
1428 anim
.scrollLeft
= scd
.scroll
.left
+ rel
.left
;
1429 } else if ( rel
.left
> 0 && rel
.right
< 0 ) {
1430 anim
.scrollLeft
= scd
.scroll
.left
+ Math
.min( rel
.left
, -rel
.right
);
1433 if ( !$.isEmptyObject( anim
) ) {
1434 $sc
.stop( true ).animate( anim
, config
.duration
|| 'fast' );
1436 $sc
.queue( function ( next
) {
1449 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1450 * and reserve space for them, because it probably doesn't.
1452 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1453 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1454 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1455 * and then reattach (or show) them back.
1458 * @param {HTMLElement} el Element to reconsider the scrollbars on
1460 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1461 var i
, len
, nodes
= [];
1462 // Detach all children
1463 while ( el
.firstChild
) {
1464 nodes
.push( el
.firstChild
);
1465 el
.removeChild( el
.firstChild
);
1468 void el
.offsetHeight
;
1469 // Reattach all children
1470 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1471 el
.appendChild( nodes
[ i
] );
1478 * Toggle visibility of an element.
1480 * @param {boolean} [show] Make element visible, omit to toggle visibility
1484 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1485 show
= show
=== undefined ? !this.visible
: !!show
;
1487 if ( show
!== this.isVisible() ) {
1488 this.visible
= show
;
1489 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1490 this.emit( 'toggle', show
);
1497 * Check if element is visible.
1499 * @return {boolean} element is visible
1501 OO
.ui
.Element
.prototype.isVisible = function () {
1502 return this.visible
;
1508 * @return {Mixed} Element data
1510 OO
.ui
.Element
.prototype.getData = function () {
1517 * @param {Mixed} Element data
1520 OO
.ui
.Element
.prototype.setData = function ( data
) {
1526 * Check if element supports one or more methods.
1528 * @param {string|string[]} methods Method or list of methods to check
1529 * @return {boolean} All methods are supported
1531 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1535 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1536 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1537 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1542 return methods
.length
=== support
;
1546 * Update the theme-provided classes.
1548 * @localdoc This is called in element mixins and widget classes any time state changes.
1549 * Updating is debounced, minimizing overhead of changing multiple attributes and
1550 * guaranteeing that theme updates do not occur within an element's constructor
1552 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1553 if ( !this.updateThemeClassesPending
) {
1554 this.updateThemeClassesPending
= true;
1555 setTimeout( this.debouncedUpdateThemeClassesHandler
);
1562 OO
.ui
.Element
.prototype.debouncedUpdateThemeClasses = function () {
1563 OO
.ui
.theme
.updateElementClasses( this );
1564 this.updateThemeClassesPending
= false;
1568 * Get the HTML tag name.
1570 * Override this method to base the result on instance information.
1572 * @return {string} HTML tag name
1574 OO
.ui
.Element
.prototype.getTagName = function () {
1575 return this.constructor.static.tagName
;
1579 * Check if the element is attached to the DOM
1580 * @return {boolean} The element is attached to the DOM
1582 OO
.ui
.Element
.prototype.isElementAttached = function () {
1583 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1587 * Get the DOM document.
1589 * @return {HTMLDocument} Document object
1591 OO
.ui
.Element
.prototype.getElementDocument = function () {
1592 // Don't cache this in other ways either because subclasses could can change this.$element
1593 return OO
.ui
.Element
.static.getDocument( this.$element
);
1597 * Get the DOM window.
1599 * @return {Window} Window object
1601 OO
.ui
.Element
.prototype.getElementWindow = function () {
1602 return OO
.ui
.Element
.static.getWindow( this.$element
);
1606 * Get closest scrollable container.
1608 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1609 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1613 * Get group element is in.
1615 * @return {OO.ui.GroupElement|null} Group element, null if none
1617 OO
.ui
.Element
.prototype.getElementGroup = function () {
1618 return this.elementGroup
;
1622 * Set group element is in.
1624 * @param {OO.ui.GroupElement|null} group Group element, null if none
1627 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1628 this.elementGroup
= group
;
1633 * Scroll element into view.
1635 * @param {Object} [config] Configuration options
1637 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1638 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1642 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1643 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1644 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1645 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1646 * and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1650 * @extends OO.ui.Element
1651 * @mixins OO.EventEmitter
1654 * @param {Object} [config] Configuration options
1656 OO
.ui
.Layout
= function OoUiLayout( config
) {
1657 // Configuration initialization
1658 config
= config
|| {};
1660 // Parent constructor
1661 OO
.ui
.Layout
.super.call( this, config
);
1663 // Mixin constructors
1664 OO
.EventEmitter
.call( this );
1667 this.$element
.addClass( 'oo-ui-layout' );
1672 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1673 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1676 * Widgets are compositions of one or more OOjs UI elements that users can both view
1677 * and interact with. All widgets can be configured and modified via a standard API,
1678 * and their state can change dynamically according to a model.
1682 * @extends OO.ui.Element
1683 * @mixins OO.EventEmitter
1686 * @param {Object} [config] Configuration options
1687 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1688 * appearance reflects this state.
1690 OO
.ui
.Widget
= function OoUiWidget( config
) {
1691 // Initialize config
1692 config
= $.extend( { disabled
: false }, config
);
1694 // Parent constructor
1695 OO
.ui
.Widget
.super.call( this, config
);
1697 // Mixin constructors
1698 OO
.EventEmitter
.call( this );
1701 this.disabled
= null;
1702 this.wasDisabled
= null;
1705 this.$element
.addClass( 'oo-ui-widget' );
1706 this.setDisabled( !!config
.disabled
);
1711 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1712 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1719 * A 'disable' event is emitted when a widget is disabled.
1721 * @param {boolean} disabled Widget is disabled
1727 * A 'toggle' event is emitted when the visibility of the widget changes.
1729 * @param {boolean} visible Widget is visible
1735 * Check if the widget is disabled.
1737 * @return {boolean} Widget is disabled
1739 OO
.ui
.Widget
.prototype.isDisabled = function () {
1740 return this.disabled
;
1744 * Set the 'disabled' state of the widget.
1746 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1748 * @param {boolean} disabled Disable widget
1751 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1754 this.disabled
= !!disabled
;
1755 isDisabled
= this.isDisabled();
1756 if ( isDisabled
!== this.wasDisabled
) {
1757 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1758 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1759 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1760 this.emit( 'disable', isDisabled
);
1761 this.updateThemeClasses();
1763 this.wasDisabled
= isDisabled
;
1769 * Update the disabled state, in case of changes in parent widget.
1773 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1774 this.setDisabled( this.disabled
);
1779 * A window is a container for elements that are in a child frame. They are used with
1780 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
1781 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
1782 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
1783 * the window manager will choose a sensible fallback.
1785 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
1786 * different processes are executed:
1788 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
1789 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
1792 * - {@link #getSetupProcess} method is called and its result executed
1793 * - {@link #getReadyProcess} method is called and its result executed
1795 * **opened**: The window is now open
1797 * **closing**: The closing stage begins when the window manager's
1798 * {@link OO.ui.WindowManager#closeWindow closeWindow}
1799 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
1801 * - {@link #getHoldProcess} method is called and its result executed
1802 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
1804 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
1805 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
1806 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
1807 * processing can complete. Always assume window processes are executed asynchronously.
1809 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
1811 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
1815 * @extends OO.ui.Element
1816 * @mixins OO.EventEmitter
1819 * @param {Object} [config] Configuration options
1820 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
1821 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
1823 OO
.ui
.Window
= function OoUiWindow( config
) {
1824 // Configuration initialization
1825 config
= config
|| {};
1827 // Parent constructor
1828 OO
.ui
.Window
.super.call( this, config
);
1830 // Mixin constructors
1831 OO
.EventEmitter
.call( this );
1834 this.manager
= null;
1835 this.size
= config
.size
|| this.constructor.static.size
;
1836 this.$frame
= $( '<div>' );
1837 this.$overlay
= $( '<div>' );
1838 this.$content
= $( '<div>' );
1841 this.$overlay
.addClass( 'oo-ui-window-overlay' );
1843 .addClass( 'oo-ui-window-content' )
1844 .attr( 'tabindex', 0 );
1846 .addClass( 'oo-ui-window-frame' )
1847 .append( this.$content
);
1850 .addClass( 'oo-ui-window' )
1851 .append( this.$frame
, this.$overlay
);
1853 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
1854 // that reference properties not initialized at that time of parent class construction
1855 // TODO: Find a better way to handle post-constructor setup
1856 this.visible
= false;
1857 this.$element
.addClass( 'oo-ui-element-hidden' );
1862 OO
.inheritClass( OO
.ui
.Window
, OO
.ui
.Element
);
1863 OO
.mixinClass( OO
.ui
.Window
, OO
.EventEmitter
);
1865 /* Static Properties */
1868 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
1870 * The static size is used if no #size is configured during construction.
1874 * @property {string}
1876 OO
.ui
.Window
.static.size
= 'medium';
1881 * Handle mouse down events.
1884 * @param {jQuery.Event} e Mouse down event
1886 OO
.ui
.Window
.prototype.onMouseDown = function ( e
) {
1887 // Prevent clicking on the click-block from stealing focus
1888 if ( e
.target
=== this.$element
[ 0 ] ) {
1894 * Check if the window has been initialized.
1896 * Initialization occurs when a window is added to a manager.
1898 * @return {boolean} Window has been initialized
1900 OO
.ui
.Window
.prototype.isInitialized = function () {
1901 return !!this.manager
;
1905 * Check if the window is visible.
1907 * @return {boolean} Window is visible
1909 OO
.ui
.Window
.prototype.isVisible = function () {
1910 return this.visible
;
1914 * Check if the window is opening.
1916 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
1919 * @return {boolean} Window is opening
1921 OO
.ui
.Window
.prototype.isOpening = function () {
1922 return this.manager
.isOpening( this );
1926 * Check if the window is closing.
1928 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
1930 * @return {boolean} Window is closing
1932 OO
.ui
.Window
.prototype.isClosing = function () {
1933 return this.manager
.isClosing( this );
1937 * Check if the window is opened.
1939 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
1941 * @return {boolean} Window is opened
1943 OO
.ui
.Window
.prototype.isOpened = function () {
1944 return this.manager
.isOpened( this );
1948 * Get the window manager.
1950 * All windows must be attached to a window manager, which is used to open
1951 * and close the window and control its presentation.
1953 * @return {OO.ui.WindowManager} Manager of window
1955 OO
.ui
.Window
.prototype.getManager = function () {
1956 return this.manager
;
1960 * Get the symbolic name of the window size (e.g., `small` or `medium`).
1962 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
1964 OO
.ui
.Window
.prototype.getSize = function () {
1969 * Disable transitions on window's frame for the duration of the callback function, then enable them
1973 * @param {Function} callback Function to call while transitions are disabled
1975 OO
.ui
.Window
.prototype.withoutSizeTransitions = function ( callback
) {
1976 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1977 // Disable transitions first, otherwise we'll get values from when the window was animating.
1979 styleObj
= this.$frame
[ 0 ].style
;
1980 oldTransition
= styleObj
.transition
|| styleObj
.OTransition
|| styleObj
.MsTransition
||
1981 styleObj
.MozTransition
|| styleObj
.WebkitTransition
;
1982 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
1983 styleObj
.MozTransition
= styleObj
.WebkitTransition
= 'none';
1985 // Force reflow to make sure the style changes done inside callback really are not transitioned
1986 this.$frame
.height();
1987 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
1988 styleObj
.MozTransition
= styleObj
.WebkitTransition
= oldTransition
;
1992 * Get the height of the full window contents (i.e., the window head, body and foot together).
1994 * What consistitutes the head, body, and foot varies depending on the window type.
1995 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
1996 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
1997 * and special actions in the head, and dialog content in the body.
1999 * To get just the height of the dialog body, use the #getBodyHeight method.
2001 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2003 OO
.ui
.Window
.prototype.getContentHeight = function () {
2006 bodyStyleObj
= this.$body
[ 0 ].style
,
2007 frameStyleObj
= this.$frame
[ 0 ].style
;
2009 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2010 // Disable transitions first, otherwise we'll get values from when the window was animating.
2011 this.withoutSizeTransitions( function () {
2012 var oldHeight
= frameStyleObj
.height
,
2013 oldPosition
= bodyStyleObj
.position
;
2014 frameStyleObj
.height
= '1px';
2015 // Force body to resize to new width
2016 bodyStyleObj
.position
= 'relative';
2017 bodyHeight
= win
.getBodyHeight();
2018 frameStyleObj
.height
= oldHeight
;
2019 bodyStyleObj
.position
= oldPosition
;
2023 // Add buffer for border
2024 ( this.$frame
.outerHeight() - this.$frame
.innerHeight() ) +
2025 // Use combined heights of children
2026 ( this.$head
.outerHeight( true ) + bodyHeight
+ this.$foot
.outerHeight( true ) )
2031 * Get the height of the window body.
2033 * To get the height of the full window contents (the window body, head, and foot together),
2034 * use #getContentHeight.
2036 * When this function is called, the window will temporarily have been resized
2037 * to height=1px, so .scrollHeight measurements can be taken accurately.
2039 * @return {number} Height of the window body in pixels
2041 OO
.ui
.Window
.prototype.getBodyHeight = function () {
2042 return this.$body
[ 0 ].scrollHeight
;
2046 * Get the directionality of the frame (right-to-left or left-to-right).
2048 * @return {string} Directionality: `'ltr'` or `'rtl'`
2050 OO
.ui
.Window
.prototype.getDir = function () {
2055 * Get the 'setup' process.
2057 * The setup process is used to set up a window for use in a particular context,
2058 * based on the `data` argument. This method is called during the opening phase of the window’s
2061 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2062 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2065 * To add window content that persists between openings, you may wish to use the #initialize method
2069 * @param {Object} [data] Window opening data
2070 * @return {OO.ui.Process} Setup process
2072 OO
.ui
.Window
.prototype.getSetupProcess = function () {
2073 return new OO
.ui
.Process();
2077 * Get the ‘ready’ process.
2079 * The ready process is used to ready a window for use in a particular
2080 * context, based on the `data` argument. This method is called during the opening phase of
2081 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2083 * Override this method to add additional steps to the ‘ready’ process the parent method
2084 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2085 * methods of OO.ui.Process.
2088 * @param {Object} [data] Window opening data
2089 * @return {OO.ui.Process} Ready process
2091 OO
.ui
.Window
.prototype.getReadyProcess = function () {
2092 return new OO
.ui
.Process();
2096 * Get the 'hold' process.
2098 * The hold proccess is used to keep a window from being used in a particular context,
2099 * based on the `data` argument. This method is called during the closing phase of the window’s
2102 * Override this method to add additional steps to the 'hold' process the parent method provides
2103 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2107 * @param {Object} [data] Window closing data
2108 * @return {OO.ui.Process} Hold process
2110 OO
.ui
.Window
.prototype.getHoldProcess = function () {
2111 return new OO
.ui
.Process();
2115 * Get the ‘teardown’ process.
2117 * The teardown process is used to teardown a window after use. During teardown,
2118 * user interactions within the window are conveyed and the window is closed, based on the `data`
2119 * argument. This method is called during the closing phase of the window’s lifecycle.
2121 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2122 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2126 * @param {Object} [data] Window closing data
2127 * @return {OO.ui.Process} Teardown process
2129 OO
.ui
.Window
.prototype.getTeardownProcess = function () {
2130 return new OO
.ui
.Process();
2134 * Set the window manager.
2136 * This will cause the window to initialize. Calling it more than once will cause an error.
2138 * @param {OO.ui.WindowManager} manager Manager for this window
2139 * @throws {Error} An error is thrown if the method is called more than once
2142 OO
.ui
.Window
.prototype.setManager = function ( manager
) {
2143 if ( this.manager
) {
2144 throw new Error( 'Cannot set window manager, window already has a manager' );
2147 this.manager
= manager
;
2154 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2156 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2160 OO
.ui
.Window
.prototype.setSize = function ( size
) {
2167 * Update the window size.
2169 * @throws {Error} An error is thrown if the window is not attached to a window manager
2172 OO
.ui
.Window
.prototype.updateSize = function () {
2173 if ( !this.manager
) {
2174 throw new Error( 'Cannot update window size, must be attached to a manager' );
2177 this.manager
.updateWindowSize( this );
2183 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2184 * when the window is opening. In general, setDimensions should not be called directly.
2186 * To set the size of the window, use the #setSize method.
2188 * @param {Object} dim CSS dimension properties
2189 * @param {string|number} [dim.width] Width
2190 * @param {string|number} [dim.minWidth] Minimum width
2191 * @param {string|number} [dim.maxWidth] Maximum width
2192 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2193 * @param {string|number} [dim.minWidth] Minimum height
2194 * @param {string|number} [dim.maxWidth] Maximum height
2197 OO
.ui
.Window
.prototype.setDimensions = function ( dim
) {
2200 styleObj
= this.$frame
[ 0 ].style
;
2202 // Calculate the height we need to set using the correct width
2203 if ( dim
.height
=== undefined ) {
2204 this.withoutSizeTransitions( function () {
2205 var oldWidth
= styleObj
.width
;
2206 win
.$frame
.css( 'width', dim
.width
|| '' );
2207 height
= win
.getContentHeight();
2208 styleObj
.width
= oldWidth
;
2211 height
= dim
.height
;
2215 width
: dim
.width
|| '',
2216 minWidth
: dim
.minWidth
|| '',
2217 maxWidth
: dim
.maxWidth
|| '',
2218 height
: height
|| '',
2219 minHeight
: dim
.minHeight
|| '',
2220 maxHeight
: dim
.maxHeight
|| ''
2227 * Initialize window contents.
2229 * Before the window is opened for the first time, #initialize is called so that content that
2230 * persists between openings can be added to the window.
2232 * To set up a window with new content each time the window opens, use #getSetupProcess.
2234 * @throws {Error} An error is thrown if the window is not attached to a window manager
2237 OO
.ui
.Window
.prototype.initialize = function () {
2238 if ( !this.manager
) {
2239 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2243 this.$head
= $( '<div>' );
2244 this.$body
= $( '<div>' );
2245 this.$foot
= $( '<div>' );
2246 this.dir
= OO
.ui
.Element
.static.getDir( this.$content
) || 'ltr';
2247 this.$document
= $( this.getElementDocument() );
2250 this.$element
.on( 'mousedown', this.onMouseDown
.bind( this ) );
2253 this.$head
.addClass( 'oo-ui-window-head' );
2254 this.$body
.addClass( 'oo-ui-window-body' );
2255 this.$foot
.addClass( 'oo-ui-window-foot' );
2256 this.$content
.append( this.$head
, this.$body
, this.$foot
);
2264 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2265 * method, which returns a promise resolved when the window is done opening.
2267 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2269 * @param {Object} [data] Window opening data
2270 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2271 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2272 * value is a new promise, which is resolved when the window begins closing.
2273 * @throws {Error} An error is thrown if the window is not attached to a window manager
2275 OO
.ui
.Window
.prototype.open = function ( data
) {
2276 if ( !this.manager
) {
2277 throw new Error( 'Cannot open window, must be attached to a manager' );
2280 return this.manager
.openWindow( this, data
);
2286 * This method is a wrapper around a call to the window
2287 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2288 * which returns a closing promise resolved when the window is done closing.
2290 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2291 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2292 * the window closes.
2294 * @param {Object} [data] Window closing data
2295 * @return {jQuery.Promise} Promise resolved when window is closed
2296 * @throws {Error} An error is thrown if the window is not attached to a window manager
2298 OO
.ui
.Window
.prototype.close = function ( data
) {
2299 if ( !this.manager
) {
2300 throw new Error( 'Cannot close window, must be attached to a manager' );
2303 return this.manager
.closeWindow( this, data
);
2309 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2312 * @param {Object} [data] Window opening data
2313 * @return {jQuery.Promise} Promise resolved when window is setup
2315 OO
.ui
.Window
.prototype.setup = function ( data
) {
2317 deferred
= $.Deferred();
2319 this.toggle( true );
2321 this.getSetupProcess( data
).execute().done( function () {
2322 // Force redraw by asking the browser to measure the elements' widths
2323 win
.$element
.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2324 win
.$content
.addClass( 'oo-ui-window-content-setup' ).width();
2328 return deferred
.promise();
2334 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2337 * @param {Object} [data] Window opening data
2338 * @return {jQuery.Promise} Promise resolved when window is ready
2340 OO
.ui
.Window
.prototype.ready = function ( data
) {
2342 deferred
= $.Deferred();
2344 this.$content
.focus();
2345 this.getReadyProcess( data
).execute().done( function () {
2346 // Force redraw by asking the browser to measure the elements' widths
2347 win
.$element
.addClass( 'oo-ui-window-ready' ).width();
2348 win
.$content
.addClass( 'oo-ui-window-content-ready' ).width();
2352 return deferred
.promise();
2358 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2361 * @param {Object} [data] Window closing data
2362 * @return {jQuery.Promise} Promise resolved when window is held
2364 OO
.ui
.Window
.prototype.hold = function ( data
) {
2366 deferred
= $.Deferred();
2368 this.getHoldProcess( data
).execute().done( function () {
2369 // Get the focused element within the window's content
2370 var $focus
= win
.$content
.find( OO
.ui
.Element
.static.getDocument( win
.$content
).activeElement
);
2372 // Blur the focused element
2373 if ( $focus
.length
) {
2377 // Force redraw by asking the browser to measure the elements' widths
2378 win
.$element
.removeClass( 'oo-ui-window-ready' ).width();
2379 win
.$content
.removeClass( 'oo-ui-window-content-ready' ).width();
2383 return deferred
.promise();
2389 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2392 * @param {Object} [data] Window closing data
2393 * @return {jQuery.Promise} Promise resolved when window is torn down
2395 OO
.ui
.Window
.prototype.teardown = function ( data
) {
2398 return this.getTeardownProcess( data
).execute()
2399 .done( function () {
2400 // Force redraw by asking the browser to measure the elements' widths
2401 win
.$element
.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2402 win
.$content
.removeClass( 'oo-ui-window-content-setup' ).width();
2403 win
.toggle( false );
2408 * The Dialog class serves as the base class for the other types of dialogs.
2409 * Unless extended to include controls, the rendered dialog box is a simple window
2410 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2411 * which opens, closes, and controls the presentation of the window. See the
2412 * [OOjs UI documentation on MediaWiki] [1] for more information.
2415 * // A simple dialog window.
2416 * function MyDialog( config ) {
2417 * MyDialog.super.call( this, config );
2419 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2420 * MyDialog.prototype.initialize = function () {
2421 * MyDialog.super.prototype.initialize.call( this );
2422 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2423 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2424 * this.$body.append( this.content.$element );
2426 * MyDialog.prototype.getBodyHeight = function () {
2427 * return this.content.$element.outerHeight( true );
2429 * var myDialog = new MyDialog( {
2432 * // Create and append a window manager, which opens and closes the window.
2433 * var windowManager = new OO.ui.WindowManager();
2434 * $( 'body' ).append( windowManager.$element );
2435 * windowManager.addWindows( [ myDialog ] );
2436 * // Open the window!
2437 * windowManager.openWindow( myDialog );
2439 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2443 * @extends OO.ui.Window
2444 * @mixins OO.ui.PendingElement
2447 * @param {Object} [config] Configuration options
2449 OO
.ui
.Dialog
= function OoUiDialog( config
) {
2450 // Parent constructor
2451 OO
.ui
.Dialog
.super.call( this, config
);
2453 // Mixin constructors
2454 OO
.ui
.PendingElement
.call( this );
2457 this.actions
= new OO
.ui
.ActionSet();
2458 this.attachedActions
= [];
2459 this.currentAction
= null;
2460 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
2463 this.actions
.connect( this, {
2464 click
: 'onActionClick',
2465 resize
: 'onActionResize',
2466 change
: 'onActionsChange'
2471 .addClass( 'oo-ui-dialog' )
2472 .attr( 'role', 'dialog' );
2477 OO
.inheritClass( OO
.ui
.Dialog
, OO
.ui
.Window
);
2478 OO
.mixinClass( OO
.ui
.Dialog
, OO
.ui
.PendingElement
);
2480 /* Static Properties */
2483 * Symbolic name of dialog.
2485 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2486 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2488 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2493 * @property {string}
2495 OO
.ui
.Dialog
.static.name
= '';
2500 * The title can be specified as a plaintext string, a {@link OO.ui.LabelElement Label} node, or a function
2501 * that will produce a Label node or string. The title can also be specified with data passed to the
2502 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2507 * @property {jQuery|string|Function}
2509 OO
.ui
.Dialog
.static.title
= '';
2512 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2514 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2515 * value will be overriden.
2517 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2521 * @property {Object[]}
2523 OO
.ui
.Dialog
.static.actions
= [];
2526 * Close the dialog when the 'Esc' key is pressed.
2531 * @property {boolean}
2533 OO
.ui
.Dialog
.static.escapable
= true;
2538 * Handle frame document key down events.
2541 * @param {jQuery.Event} e Key down event
2543 OO
.ui
.Dialog
.prototype.onDocumentKeyDown = function ( e
) {
2544 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
2547 e
.stopPropagation();
2552 * Handle action resized events.
2555 * @param {OO.ui.ActionWidget} action Action that was resized
2557 OO
.ui
.Dialog
.prototype.onActionResize = function () {
2558 // Override in subclass
2562 * Handle action click events.
2565 * @param {OO.ui.ActionWidget} action Action that was clicked
2567 OO
.ui
.Dialog
.prototype.onActionClick = function ( action
) {
2568 if ( !this.isPending() ) {
2569 this.executeAction( action
.getAction() );
2574 * Handle actions change event.
2578 OO
.ui
.Dialog
.prototype.onActionsChange = function () {
2579 this.detachActions();
2580 if ( !this.isClosing() ) {
2581 this.attachActions();
2586 * Get the set of actions used by the dialog.
2588 * @return {OO.ui.ActionSet}
2590 OO
.ui
.Dialog
.prototype.getActions = function () {
2591 return this.actions
;
2595 * Get a process for taking action.
2597 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2598 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2599 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2602 * @param {string} [action] Symbolic name of action
2603 * @return {OO.ui.Process} Action process
2605 OO
.ui
.Dialog
.prototype.getActionProcess = function ( action
) {
2606 return new OO
.ui
.Process()
2607 .next( function () {
2609 // An empty action always closes the dialog without data, which should always be
2610 // safe and make no changes
2619 * @param {Object} [data] Dialog opening data
2620 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2621 * the {@link #static-title static title}
2622 * @param {Object[]} [data.actions] List of configuration options for each
2623 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2625 OO
.ui
.Dialog
.prototype.getSetupProcess = function ( data
) {
2629 return OO
.ui
.Dialog
.super.prototype.getSetupProcess
.call( this, data
)
2630 .next( function () {
2631 var config
= this.constructor.static,
2632 actions
= data
.actions
!== undefined ? data
.actions
: config
.actions
;
2634 this.title
.setLabel(
2635 data
.title
!== undefined ? data
.title
: this.constructor.static.title
2637 this.actions
.add( this.getActionWidgets( actions
) );
2639 if ( this.constructor.static.escapable
) {
2640 this.$document
.on( 'keydown', this.onDocumentKeyDownHandler
);
2648 OO
.ui
.Dialog
.prototype.getTeardownProcess = function ( data
) {
2650 return OO
.ui
.Dialog
.super.prototype.getTeardownProcess
.call( this, data
)
2651 .first( function () {
2652 if ( this.constructor.static.escapable
) {
2653 this.$document
.off( 'keydown', this.onDocumentKeyDownHandler
);
2656 this.actions
.clear();
2657 this.currentAction
= null;
2664 OO
.ui
.Dialog
.prototype.initialize = function () {
2666 OO
.ui
.Dialog
.super.prototype.initialize
.call( this );
2669 this.title
= new OO
.ui
.LabelWidget();
2672 this.$content
.addClass( 'oo-ui-dialog-content' );
2673 this.setPendingElement( this.$head
);
2677 * Get action widgets from a list of configs
2679 * @param {Object[]} actions Action widget configs
2680 * @return {OO.ui.ActionWidget[]} Action widgets
2682 OO
.ui
.Dialog
.prototype.getActionWidgets = function ( actions
) {
2683 var i
, len
, widgets
= [];
2684 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
2686 new OO
.ui
.ActionWidget( actions
[ i
] )
2693 * Attach action actions.
2697 OO
.ui
.Dialog
.prototype.attachActions = function () {
2698 // Remember the list of potentially attached actions
2699 this.attachedActions
= this.actions
.get();
2703 * Detach action actions.
2708 OO
.ui
.Dialog
.prototype.detachActions = function () {
2711 // Detach all actions that may have been previously attached
2712 for ( i
= 0, len
= this.attachedActions
.length
; i
< len
; i
++ ) {
2713 this.attachedActions
[ i
].$element
.detach();
2715 this.attachedActions
= [];
2719 * Execute an action.
2721 * @param {string} action Symbolic name of action to execute
2722 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2724 OO
.ui
.Dialog
.prototype.executeAction = function ( action
) {
2726 this.currentAction
= action
;
2727 return this.getActionProcess( action
).execute()
2728 .always( this.popPending
.bind( this ) );
2732 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
2733 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
2734 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
2735 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
2736 * pertinent data and reused.
2738 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
2739 * `opened`, and `closing`, which represent the primary stages of the cycle:
2741 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
2742 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
2744 * - an `opening` event is emitted with an `opening` promise
2745 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
2746 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
2747 * window and its result executed
2748 * - a `setup` progress notification is emitted from the `opening` promise
2749 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
2750 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
2751 * window and its result executed
2752 * - a `ready` progress notification is emitted from the `opening` promise
2753 * - the `opening` promise is resolved with an `opened` promise
2755 * **Opened**: the window is now open.
2757 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
2758 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
2759 * to close the window.
2761 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
2762 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
2763 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
2764 * window and its result executed
2765 * - a `hold` progress notification is emitted from the `closing` promise
2766 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
2767 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
2768 * window and its result executed
2769 * - a `teardown` progress notification is emitted from the `closing` promise
2770 * - the `closing` promise is resolved. The window is now closed
2772 * See the [OOjs UI documentation on MediaWiki][1] for more information.
2774 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2777 * @extends OO.ui.Element
2778 * @mixins OO.EventEmitter
2781 * @param {Object} [config] Configuration options
2782 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
2783 * Note that window classes that are instantiated with a factory must have
2784 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
2785 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
2787 OO
.ui
.WindowManager
= function OoUiWindowManager( config
) {
2788 // Configuration initialization
2789 config
= config
|| {};
2791 // Parent constructor
2792 OO
.ui
.WindowManager
.super.call( this, config
);
2794 // Mixin constructors
2795 OO
.EventEmitter
.call( this );
2798 this.factory
= config
.factory
;
2799 this.modal
= config
.modal
=== undefined || !!config
.modal
;
2801 this.opening
= null;
2803 this.closing
= null;
2804 this.preparingToOpen
= null;
2805 this.preparingToClose
= null;
2806 this.currentWindow
= null;
2807 this.globalEvents
= false;
2808 this.$ariaHidden
= null;
2809 this.onWindowResizeTimeout
= null;
2810 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
2811 this.afterWindowResizeHandler
= this.afterWindowResize
.bind( this );
2815 .addClass( 'oo-ui-windowManager' )
2816 .toggleClass( 'oo-ui-windowManager-modal', this.modal
);
2821 OO
.inheritClass( OO
.ui
.WindowManager
, OO
.ui
.Element
);
2822 OO
.mixinClass( OO
.ui
.WindowManager
, OO
.EventEmitter
);
2827 * An 'opening' event is emitted when the window begins to be opened.
2830 * @param {OO.ui.Window} win Window that's being opened
2831 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
2832 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
2833 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
2834 * @param {Object} data Window opening data
2838 * A 'closing' event is emitted when the window begins to be closed.
2841 * @param {OO.ui.Window} win Window that's being closed
2842 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
2843 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
2844 * processes are complete. When the `closing` promise is resolved, the first argument of its value
2845 * is the closing data.
2846 * @param {Object} data Window closing data
2850 * A 'resize' event is emitted when a window is resized.
2853 * @param {OO.ui.Window} win Window that was resized
2856 /* Static Properties */
2859 * Map of the symbolic name of each window size and its CSS properties.
2863 * @property {Object}
2865 OO
.ui
.WindowManager
.static.sizes
= {
2879 // These can be non-numeric because they are never used in calculations
2886 * Symbolic name of the default window size.
2888 * The default size is used if the window's requested size is not recognized.
2892 * @property {string}
2894 OO
.ui
.WindowManager
.static.defaultSize
= 'medium';
2899 * Handle window resize events.
2902 * @param {jQuery.Event} e Window resize event
2904 OO
.ui
.WindowManager
.prototype.onWindowResize = function () {
2905 clearTimeout( this.onWindowResizeTimeout
);
2906 this.onWindowResizeTimeout
= setTimeout( this.afterWindowResizeHandler
, 200 );
2910 * Handle window resize events.
2913 * @param {jQuery.Event} e Window resize event
2915 OO
.ui
.WindowManager
.prototype.afterWindowResize = function () {
2916 if ( this.currentWindow
) {
2917 this.updateWindowSize( this.currentWindow
);
2922 * Check if window is opening.
2924 * @return {boolean} Window is opening
2926 OO
.ui
.WindowManager
.prototype.isOpening = function ( win
) {
2927 return win
=== this.currentWindow
&& !!this.opening
&& this.opening
.state() === 'pending';
2931 * Check if window is closing.
2933 * @return {boolean} Window is closing
2935 OO
.ui
.WindowManager
.prototype.isClosing = function ( win
) {
2936 return win
=== this.currentWindow
&& !!this.closing
&& this.closing
.state() === 'pending';
2940 * Check if window is opened.
2942 * @return {boolean} Window is opened
2944 OO
.ui
.WindowManager
.prototype.isOpened = function ( win
) {
2945 return win
=== this.currentWindow
&& !!this.opened
&& this.opened
.state() === 'pending';
2949 * Check if a window is being managed.
2951 * @param {OO.ui.Window} win Window to check
2952 * @return {boolean} Window is being managed
2954 OO
.ui
.WindowManager
.prototype.hasWindow = function ( win
) {
2957 for ( name
in this.windows
) {
2958 if ( this.windows
[ name
] === win
) {
2967 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
2969 * @param {OO.ui.Window} win Window being opened
2970 * @param {Object} [data] Window opening data
2971 * @return {number} Milliseconds to wait
2973 OO
.ui
.WindowManager
.prototype.getSetupDelay = function () {
2978 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
2980 * @param {OO.ui.Window} win Window being opened
2981 * @param {Object} [data] Window opening data
2982 * @return {number} Milliseconds to wait
2984 OO
.ui
.WindowManager
.prototype.getReadyDelay = function () {
2989 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
2991 * @param {OO.ui.Window} win Window being closed
2992 * @param {Object} [data] Window closing data
2993 * @return {number} Milliseconds to wait
2995 OO
.ui
.WindowManager
.prototype.getHoldDelay = function () {
3000 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3001 * executing the ‘teardown’ process.
3003 * @param {OO.ui.Window} win Window being closed
3004 * @param {Object} [data] Window closing data
3005 * @return {number} Milliseconds to wait
3007 OO
.ui
.WindowManager
.prototype.getTeardownDelay = function () {
3008 return this.modal
? 250 : 0;
3012 * Get a window by its symbolic name.
3014 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3015 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3016 * for more information about using factories.
3017 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3019 * @param {string} name Symbolic name of the window
3020 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3021 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3022 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3024 OO
.ui
.WindowManager
.prototype.getWindow = function ( name
) {
3025 var deferred
= $.Deferred(),
3026 win
= this.windows
[ name
];
3028 if ( !( win
instanceof OO
.ui
.Window
) ) {
3029 if ( this.factory
) {
3030 if ( !this.factory
.lookup( name
) ) {
3031 deferred
.reject( new OO
.ui
.Error(
3032 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3035 win
= this.factory
.create( name
);
3036 this.addWindows( [ win
] );
3037 deferred
.resolve( win
);
3040 deferred
.reject( new OO
.ui
.Error(
3041 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3045 deferred
.resolve( win
);
3048 return deferred
.promise();
3052 * Get current window.
3054 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3056 OO
.ui
.WindowManager
.prototype.getCurrentWindow = function () {
3057 return this.currentWindow
;
3063 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3064 * @param {Object} [data] Window opening data
3065 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3066 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3069 OO
.ui
.WindowManager
.prototype.openWindow = function ( win
, data
) {
3071 opening
= $.Deferred();
3073 // Argument handling
3074 if ( typeof win
=== 'string' ) {
3075 return this.getWindow( win
).then( function ( win
) {
3076 return manager
.openWindow( win
, data
);
3081 if ( !this.hasWindow( win
) ) {
3082 opening
.reject( new OO
.ui
.Error(
3083 'Cannot open window: window is not attached to manager'
3085 } else if ( this.preparingToOpen
|| this.opening
|| this.opened
) {
3086 opening
.reject( new OO
.ui
.Error(
3087 'Cannot open window: another window is opening or open'
3092 if ( opening
.state() !== 'rejected' ) {
3093 // If a window is currently closing, wait for it to complete
3094 this.preparingToOpen
= $.when( this.closing
);
3095 // Ensure handlers get called after preparingToOpen is set
3096 this.preparingToOpen
.done( function () {
3097 if ( manager
.modal
) {
3098 manager
.toggleGlobalEvents( true );
3099 manager
.toggleAriaIsolation( true );
3101 manager
.currentWindow
= win
;
3102 manager
.opening
= opening
;
3103 manager
.preparingToOpen
= null;
3104 manager
.emit( 'opening', win
, opening
, data
);
3105 setTimeout( function () {
3106 win
.setup( data
).then( function () {
3107 manager
.updateWindowSize( win
);
3108 manager
.opening
.notify( { state
: 'setup' } );
3109 setTimeout( function () {
3110 win
.ready( data
).then( function () {
3111 manager
.opening
.notify( { state
: 'ready' } );
3112 manager
.opening
= null;
3113 manager
.opened
= $.Deferred();
3114 opening
.resolve( manager
.opened
.promise(), data
);
3116 }, manager
.getReadyDelay() );
3118 }, manager
.getSetupDelay() );
3122 return opening
.promise();
3128 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3129 * @param {Object} [data] Window closing data
3130 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3131 * See {@link #event-closing 'closing' event} for more information about closing promises.
3132 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3135 OO
.ui
.WindowManager
.prototype.closeWindow = function ( win
, data
) {
3137 closing
= $.Deferred(),
3140 // Argument handling
3141 if ( typeof win
=== 'string' ) {
3142 win
= this.windows
[ win
];
3143 } else if ( !this.hasWindow( win
) ) {
3149 closing
.reject( new OO
.ui
.Error(
3150 'Cannot close window: window is not attached to manager'
3152 } else if ( win
!== this.currentWindow
) {
3153 closing
.reject( new OO
.ui
.Error(
3154 'Cannot close window: window already closed with different data'
3156 } else if ( this.preparingToClose
|| this.closing
) {
3157 closing
.reject( new OO
.ui
.Error(
3158 'Cannot close window: window already closing with different data'
3163 if ( closing
.state() !== 'rejected' ) {
3164 // If the window is currently opening, close it when it's done
3165 this.preparingToClose
= $.when( this.opening
);
3166 // Ensure handlers get called after preparingToClose is set
3167 this.preparingToClose
.done( function () {
3168 manager
.closing
= closing
;
3169 manager
.preparingToClose
= null;
3170 manager
.emit( 'closing', win
, closing
, data
);
3171 opened
= manager
.opened
;
3172 manager
.opened
= null;
3173 opened
.resolve( closing
.promise(), data
);
3174 setTimeout( function () {
3175 win
.hold( data
).then( function () {
3176 closing
.notify( { state
: 'hold' } );
3177 setTimeout( function () {
3178 win
.teardown( data
).then( function () {
3179 closing
.notify( { state
: 'teardown' } );
3180 if ( manager
.modal
) {
3181 manager
.toggleGlobalEvents( false );
3182 manager
.toggleAriaIsolation( false );
3184 manager
.closing
= null;
3185 manager
.currentWindow
= null;
3186 closing
.resolve( data
);
3188 }, manager
.getTeardownDelay() );
3190 }, manager
.getHoldDelay() );
3194 return closing
.promise();
3198 * Add windows to the window manager.
3200 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3201 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3202 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3204 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3205 * by reference, symbolic name, or explicitly defined symbolic names.
3206 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3207 * explicit nor a statically configured symbolic name.
3209 OO
.ui
.WindowManager
.prototype.addWindows = function ( windows
) {
3210 var i
, len
, win
, name
, list
;
3212 if ( Array
.isArray( windows
) ) {
3213 // Convert to map of windows by looking up symbolic names from static configuration
3215 for ( i
= 0, len
= windows
.length
; i
< len
; i
++ ) {
3216 name
= windows
[ i
].constructor.static.name
;
3217 if ( typeof name
!== 'string' ) {
3218 throw new Error( 'Cannot add window' );
3220 list
[ name
] = windows
[ i
];
3222 } else if ( OO
.isPlainObject( windows
) ) {
3227 for ( name
in list
) {
3229 this.windows
[ name
] = win
.toggle( false );
3230 this.$element
.append( win
.$element
);
3231 win
.setManager( this );
3236 * Remove the specified windows from the windows manager.
3238 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3239 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3240 * longer listens to events, use the #destroy method.
3242 * @param {string[]} names Symbolic names of windows to remove
3243 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3244 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3246 OO
.ui
.WindowManager
.prototype.removeWindows = function ( names
) {
3247 var i
, len
, win
, name
, cleanupWindow
,
3250 cleanup = function ( name
, win
) {
3251 delete manager
.windows
[ name
];
3252 win
.$element
.detach();
3255 for ( i
= 0, len
= names
.length
; i
< len
; i
++ ) {
3257 win
= this.windows
[ name
];
3259 throw new Error( 'Cannot remove window' );
3261 cleanupWindow
= cleanup
.bind( null, name
, win
);
3262 promises
.push( this.closeWindow( name
).then( cleanupWindow
, cleanupWindow
) );
3265 return $.when
.apply( $, promises
);
3269 * Remove all windows from the window manager.
3271 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3272 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3273 * To remove just a subset of windows, use the #removeWindows method.
3275 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3277 OO
.ui
.WindowManager
.prototype.clearWindows = function () {
3278 return this.removeWindows( Object
.keys( this.windows
) );
3282 * Set dialog size. In general, this method should not be called directly.
3284 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3288 OO
.ui
.WindowManager
.prototype.updateWindowSize = function ( win
) {
3289 // Bypass for non-current, and thus invisible, windows
3290 if ( win
!== this.currentWindow
) {
3294 var viewport
= OO
.ui
.Element
.static.getDimensions( win
.getElementWindow() ),
3295 sizes
= this.constructor.static.sizes
,
3296 size
= win
.getSize();
3298 if ( !sizes
[ size
] ) {
3299 size
= this.constructor.static.defaultSize
;
3301 if ( size
!== 'full' && viewport
.rect
.right
- viewport
.rect
.left
< sizes
[ size
].width
) {
3305 this.$element
.toggleClass( 'oo-ui-windowManager-fullscreen', size
=== 'full' );
3306 this.$element
.toggleClass( 'oo-ui-windowManager-floating', size
!== 'full' );
3307 win
.setDimensions( sizes
[ size
] );
3309 this.emit( 'resize', win
);
3315 * Bind or unbind global events for scrolling.
3318 * @param {boolean} [on] Bind global events
3321 OO
.ui
.WindowManager
.prototype.toggleGlobalEvents = function ( on
) {
3322 on
= on
=== undefined ? !!this.globalEvents
: !!on
;
3324 var scrollWidth
, bodyMargin
,
3325 $body
= $( this.getElementDocument().body
),
3326 // We could have multiple window managers open so only modify
3327 // the body css at the bottom of the stack
3328 stackDepth
= $body
.data( 'windowManagerGlobalEvents' ) || 0 ;
3331 if ( !this.globalEvents
) {
3332 $( this.getElementWindow() ).on( {
3333 // Start listening for top-level window dimension changes
3334 'orientationchange resize': this.onWindowResizeHandler
3336 if ( stackDepth
=== 0 ) {
3337 scrollWidth
= window
.innerWidth
- document
.documentElement
.clientWidth
;
3338 bodyMargin
= parseFloat( $body
.css( 'margin-right' ) ) || 0;
3341 'margin-right': bodyMargin
+ scrollWidth
3345 this.globalEvents
= true;
3347 } else if ( this.globalEvents
) {
3348 $( this.getElementWindow() ).off( {
3349 // Stop listening for top-level window dimension changes
3350 'orientationchange resize': this.onWindowResizeHandler
3353 if ( stackDepth
=== 0 ) {
3359 this.globalEvents
= false;
3361 $body
.data( 'windowManagerGlobalEvents', stackDepth
);
3367 * Toggle screen reader visibility of content other than the window manager.
3370 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3373 OO
.ui
.WindowManager
.prototype.toggleAriaIsolation = function ( isolate
) {
3374 isolate
= isolate
=== undefined ? !this.$ariaHidden
: !!isolate
;
3377 if ( !this.$ariaHidden
) {
3378 // Hide everything other than the window manager from screen readers
3379 this.$ariaHidden
= $( 'body' )
3381 .not( this.$element
.parentsUntil( 'body' ).last() )
3382 .attr( 'aria-hidden', '' );
3384 } else if ( this.$ariaHidden
) {
3385 // Restore screen reader visibility
3386 this.$ariaHidden
.removeAttr( 'aria-hidden' );
3387 this.$ariaHidden
= null;
3394 * Destroy the window manager.
3396 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3397 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3400 OO
.ui
.WindowManager
.prototype.destroy = function () {
3401 this.toggleGlobalEvents( false );
3402 this.toggleAriaIsolation( false );
3403 this.clearWindows();
3404 this.$element
.remove();
3408 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3409 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3410 * appearance and functionality of the error interface.
3412 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3413 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3414 * that initiated the failed process will be disabled.
3416 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3419 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3421 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3426 * @param {string|jQuery} message Description of error
3427 * @param {Object} [config] Configuration options
3428 * @cfg {boolean} [recoverable=true] Error is recoverable.
3429 * By default, errors are recoverable, and users can try the process again.
3430 * @cfg {boolean} [warning=false] Error is a warning.
3431 * If the error is a warning, the error interface will include a
3432 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3433 * is not triggered a second time if the user chooses to continue.
3435 OO
.ui
.Error
= function OoUiError( message
, config
) {
3436 // Allow passing positional parameters inside the config object
3437 if ( OO
.isPlainObject( message
) && config
=== undefined ) {
3439 message
= config
.message
;
3442 // Configuration initialization
3443 config
= config
|| {};
3446 this.message
= message
instanceof jQuery
? message
: String( message
);
3447 this.recoverable
= config
.recoverable
=== undefined || !!config
.recoverable
;
3448 this.warning
= !!config
.warning
;
3453 OO
.initClass( OO
.ui
.Error
);
3458 * Check if the error is recoverable.
3460 * If the error is recoverable, users are able to try the process again.
3462 * @return {boolean} Error is recoverable
3464 OO
.ui
.Error
.prototype.isRecoverable = function () {
3465 return this.recoverable
;
3469 * Check if the error is a warning.
3471 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3473 * @return {boolean} Error is warning
3475 OO
.ui
.Error
.prototype.isWarning = function () {
3476 return this.warning
;
3480 * Get error message as DOM nodes.
3482 * @return {jQuery} Error message in DOM nodes
3484 OO
.ui
.Error
.prototype.getMessage = function () {
3485 return this.message
instanceof jQuery
?
3486 this.message
.clone() :
3487 $( '<div>' ).text( this.message
).contents();
3491 * Get the error message text.
3493 * @return {string} Error message
3495 OO
.ui
.Error
.prototype.getMessageText = function () {
3496 return this.message
instanceof jQuery
? this.message
.text() : this.message
;
3500 * Wraps an HTML snippet for use with configuration values which default
3501 * to strings. This bypasses the default html-escaping done to string
3507 * @param {string} [content] HTML content
3509 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
3511 this.content
= content
;
3516 OO
.initClass( OO
.ui
.HtmlSnippet
);
3523 * @return {string} Unchanged HTML snippet.
3525 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
3526 return this.content
;
3530 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3533 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3534 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3535 * or stop if the promise is rejected.
3536 * - **function**: the process will execute the function. The process will stop if the function returns
3537 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3538 * will wait for that number of milliseconds before proceeding.
3540 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3541 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3542 * its remaining steps will not be performed.
3547 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3548 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3549 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3550 * a number or promise.
3551 * @return {Object} Step object, with `callback` and `context` properties
3553 OO
.ui
.Process = function ( step
, context
) {
3558 if ( step
!== undefined ) {
3559 this.next( step
, context
);
3565 OO
.initClass( OO
.ui
.Process
);
3570 * Start the process.
3572 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3573 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3574 * and any remaining steps are not performed.
3576 OO
.ui
.Process
.prototype.execute = function () {
3577 var i
, len
, promise
;
3580 * Continue execution.
3583 * @param {Array} step A function and the context it should be called in
3584 * @return {Function} Function that continues the process
3586 function proceed( step
) {
3587 return function () {
3588 // Execute step in the correct context
3590 result
= step
.callback
.call( step
.context
);
3592 if ( result
=== false ) {
3593 // Use rejected promise for boolean false results
3594 return $.Deferred().reject( [] ).promise();
3596 if ( typeof result
=== 'number' ) {
3598 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3600 // Use a delayed promise for numbers, expecting them to be in milliseconds
3601 deferred
= $.Deferred();
3602 setTimeout( deferred
.resolve
, result
);
3603 return deferred
.promise();
3605 if ( result
instanceof OO
.ui
.Error
) {
3606 // Use rejected promise for error
3607 return $.Deferred().reject( [ result
] ).promise();
3609 if ( Array
.isArray( result
) && result
.length
&& result
[ 0 ] instanceof OO
.ui
.Error
) {
3610 // Use rejected promise for list of errors
3611 return $.Deferred().reject( result
).promise();
3613 // Duck-type the object to see if it can produce a promise
3614 if ( result
&& $.isFunction( result
.promise
) ) {
3615 // Use a promise generated from the result
3616 return result
.promise();
3618 // Use resolved promise for other results
3619 return $.Deferred().resolve().promise();
3623 if ( this.steps
.length
) {
3624 // Generate a chain reaction of promises
3625 promise
= proceed( this.steps
[ 0 ] )();
3626 for ( i
= 1, len
= this.steps
.length
; i
< len
; i
++ ) {
3627 promise
= promise
.then( proceed( this.steps
[ i
] ) );
3630 promise
= $.Deferred().resolve().promise();
3637 * Create a process step.
3640 * @param {number|jQuery.Promise|Function} step
3642 * - Number of milliseconds to wait before proceeding
3643 * - Promise that must be resolved before proceeding
3644 * - Function to execute
3645 * - If the function returns a boolean false the process will stop
3646 * - If the function returns a promise, the process will continue to the next
3647 * step when the promise is resolved or stop if the promise is rejected
3648 * - If the function returns a number, the process will wait for that number of
3649 * milliseconds before proceeding
3650 * @param {Object} [context=null] Execution context of the function. The context is
3651 * ignored if the step is a number or promise.
3652 * @return {Object} Step object, with `callback` and `context` properties
3654 OO
.ui
.Process
.prototype.createStep = function ( step
, context
) {
3655 if ( typeof step
=== 'number' || $.isFunction( step
.promise
) ) {
3657 callback: function () {
3663 if ( $.isFunction( step
) ) {
3669 throw new Error( 'Cannot create process step: number, promise or function expected' );
3673 * Add step to the beginning of the process.
3675 * @inheritdoc #createStep
3676 * @return {OO.ui.Process} this
3679 OO
.ui
.Process
.prototype.first = function ( step
, context
) {
3680 this.steps
.unshift( this.createStep( step
, context
) );
3685 * Add step to the end of the process.
3687 * @inheritdoc #createStep
3688 * @return {OO.ui.Process} this
3691 OO
.ui
.Process
.prototype.next = function ( step
, context
) {
3692 this.steps
.push( this.createStep( step
, context
) );
3697 * Factory for tools.
3700 * @extends OO.Factory
3703 OO
.ui
.ToolFactory
= function OoUiToolFactory() {
3704 // Parent constructor
3705 OO
.ui
.ToolFactory
.super.call( this );
3710 OO
.inheritClass( OO
.ui
.ToolFactory
, OO
.Factory
);
3715 * Get tools from the factory
3717 * @param {Array} include Included tools
3718 * @param {Array} exclude Excluded tools
3719 * @param {Array} promote Promoted tools
3720 * @param {Array} demote Demoted tools
3721 * @return {string[]} List of tools
3723 OO
.ui
.ToolFactory
.prototype.getTools = function ( include
, exclude
, promote
, demote
) {
3724 var i
, len
, included
, promoted
, demoted
,
3728 // Collect included and not excluded tools
3729 included
= OO
.simpleArrayDifference( this.extract( include
), this.extract( exclude
) );
3732 promoted
= this.extract( promote
, used
);
3733 demoted
= this.extract( demote
, used
);
3736 for ( i
= 0, len
= included
.length
; i
< len
; i
++ ) {
3737 if ( !used
[ included
[ i
] ] ) {
3738 auto
.push( included
[ i
] );
3742 return promoted
.concat( auto
).concat( demoted
);
3746 * Get a flat list of names from a list of names or groups.
3748 * Tools can be specified in the following ways:
3750 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
3751 * - All tools in a group: `{ group: 'group-name' }`
3752 * - All tools: `'*'`
3755 * @param {Array|string} collection List of tools
3756 * @param {Object} [used] Object with names that should be skipped as properties; extracted
3757 * names will be added as properties
3758 * @return {string[]} List of extracted names
3760 OO
.ui
.ToolFactory
.prototype.extract = function ( collection
, used
) {
3761 var i
, len
, item
, name
, tool
,
3764 if ( collection
=== '*' ) {
3765 for ( name
in this.registry
) {
3766 tool
= this.registry
[ name
];
3768 // Only add tools by group name when auto-add is enabled
3769 tool
.static.autoAddToCatchall
&&
3770 // Exclude already used tools
3771 ( !used
|| !used
[ name
] )
3775 used
[ name
] = true;
3779 } else if ( Array
.isArray( collection
) ) {
3780 for ( i
= 0, len
= collection
.length
; i
< len
; i
++ ) {
3781 item
= collection
[ i
];
3782 // Allow plain strings as shorthand for named tools
3783 if ( typeof item
=== 'string' ) {
3784 item
= { name
: item
};
3786 if ( OO
.isPlainObject( item
) ) {
3788 for ( name
in this.registry
) {
3789 tool
= this.registry
[ name
];
3791 // Include tools with matching group
3792 tool
.static.group
=== item
.group
&&
3793 // Only add tools by group name when auto-add is enabled
3794 tool
.static.autoAddToGroup
&&
3795 // Exclude already used tools
3796 ( !used
|| !used
[ name
] )
3800 used
[ name
] = true;
3804 // Include tools with matching name and exclude already used tools
3805 } else if ( item
.name
&& ( !used
|| !used
[ item
.name
] ) ) {
3806 names
.push( item
.name
);
3808 used
[ item
.name
] = true;
3818 * Factory for tool groups.
3821 * @extends OO.Factory
3824 OO
.ui
.ToolGroupFactory
= function OoUiToolGroupFactory() {
3825 // Parent constructor
3826 OO
.Factory
.call( this );
3829 defaultClasses
= this.constructor.static.getDefaultClasses();
3831 // Register default toolgroups
3832 for ( i
= 0, l
= defaultClasses
.length
; i
< l
; i
++ ) {
3833 this.register( defaultClasses
[ i
] );
3839 OO
.inheritClass( OO
.ui
.ToolGroupFactory
, OO
.Factory
);
3841 /* Static Methods */
3844 * Get a default set of classes to be registered on construction
3846 * @return {Function[]} Default classes
3848 OO
.ui
.ToolGroupFactory
.static.getDefaultClasses = function () {
3851 OO
.ui
.ListToolGroup
,
3863 * @param {Object} [config] Configuration options
3865 OO
.ui
.Theme
= function OoUiTheme( config
) {
3866 // Configuration initialization
3867 config
= config
|| {};
3872 OO
.initClass( OO
.ui
.Theme
);
3877 * Get a list of classes to be applied to a widget.
3879 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
3880 * otherwise state transitions will not work properly.
3882 * @param {OO.ui.Element} element Element for which to get classes
3883 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3885 OO
.ui
.Theme
.prototype.getElementClasses = function ( /* element */ ) {
3886 return { on
: [], off
: [] };
3890 * Update CSS classes provided by the theme.
3892 * For elements with theme logic hooks, this should be called any time there's a state change.
3894 * @param {OO.ui.Element} element Element for which to update classes
3895 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3897 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
3898 var classes
= this.getElementClasses( element
);
3901 .removeClass( classes
.off
.join( ' ' ) )
3902 .addClass( classes
.on
.join( ' ' ) );
3906 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
3907 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
3908 * order in which users will navigate through the focusable elements via the "tab" key.
3911 * // TabIndexedElement is mixed into the ButtonWidget class
3912 * // to provide a tabIndex property.
3913 * var button1 = new OO.ui.ButtonWidget( {
3917 * var button2 = new OO.ui.ButtonWidget( {
3921 * var button3 = new OO.ui.ButtonWidget( {
3925 * var button4 = new OO.ui.ButtonWidget( {
3929 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
3935 * @param {Object} [config] Configuration options
3936 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
3937 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
3938 * functionality will be applied to it instead.
3939 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
3940 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
3941 * to remove the element from the tab-navigation flow.
3943 OO
.ui
.TabIndexedElement
= function OoUiTabIndexedElement( config
) {
3944 // Configuration initialization
3945 config
= $.extend( { tabIndex
: 0 }, config
);
3948 this.$tabIndexed
= null;
3949 this.tabIndex
= null;
3952 this.connect( this, { disable
: 'onDisable' } );
3955 this.setTabIndex( config
.tabIndex
);
3956 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
3961 OO
.initClass( OO
.ui
.TabIndexedElement
);
3966 * Set the element that should use the tabindex functionality.
3968 * This method is used to retarget a tabindex mixin so that its functionality applies
3969 * to the specified element. If an element is currently using the functionality, the mixin’s
3970 * effect on that element is removed before the new element is set up.
3972 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
3975 OO
.ui
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
3976 var tabIndex
= this.tabIndex
;
3977 // Remove attributes from old $tabIndexed
3978 this.setTabIndex( null );
3979 // Force update of new $tabIndexed
3980 this.$tabIndexed
= $tabIndexed
;
3981 this.tabIndex
= tabIndex
;
3982 return this.updateTabIndex();
3986 * Set the value of the tabindex.
3988 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
3991 OO
.ui
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
3992 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
3994 if ( this.tabIndex
!== tabIndex
) {
3995 this.tabIndex
= tabIndex
;
3996 this.updateTabIndex();
4003 * Update the `tabindex` attribute, in case of changes to tab index or
4009 OO
.ui
.TabIndexedElement
.prototype.updateTabIndex = function () {
4010 if ( this.$tabIndexed
) {
4011 if ( this.tabIndex
!== null ) {
4012 // Do not index over disabled elements
4013 this.$tabIndexed
.attr( {
4014 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
4015 // ChromeVox and NVDA do not seem to inherit this from parent elements
4016 'aria-disabled': this.isDisabled().toString()
4019 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
4026 * Handle disable events.
4029 * @param {boolean} disabled Element is disabled
4031 OO
.ui
.TabIndexedElement
.prototype.onDisable = function () {
4032 this.updateTabIndex();
4036 * Get the value of the tabindex.
4038 * @return {number|null} Tabindex value
4040 OO
.ui
.TabIndexedElement
.prototype.getTabIndex = function () {
4041 return this.tabIndex
;
4045 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4046 * interface element that can be configured with access keys for accessibility.
4047 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4049 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4054 * @param {Object} [config] Configuration options
4055 * @cfg {jQuery} [$button] The button element created by the class.
4056 * If this configuration is omitted, the button element will use a generated `<a>`.
4057 * @cfg {boolean} [framed=true] Render the button with a frame
4058 * @cfg {string} [accessKey] Button's access key
4060 OO
.ui
.ButtonElement
= function OoUiButtonElement( config
) {
4061 // Configuration initialization
4062 config
= config
|| {};
4065 this.$button
= null;
4067 this.accessKey
= null;
4068 this.active
= false;
4069 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
4070 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4071 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
4072 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
4073 this.onClickHandler
= this.onClick
.bind( this );
4074 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
4077 this.$element
.addClass( 'oo-ui-buttonElement' );
4078 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
4079 this.setAccessKey( config
.accessKey
);
4080 this.setButtonElement( config
.$button
|| $( '<a>' ) );
4085 OO
.initClass( OO
.ui
.ButtonElement
);
4087 /* Static Properties */
4090 * Cancel mouse down events.
4092 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4093 * Classes such as {@link OO.ui.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4094 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4099 * @property {boolean}
4101 OO
.ui
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
4106 * A 'click' event is emitted when the button element is clicked.
4114 * Set the button element.
4116 * This method is used to retarget a button mixin so that its functionality applies to
4117 * the specified button element instead of the one created by the class. If a button element
4118 * is already set, the method will remove the mixin’s effect on that element.
4120 * @param {jQuery} $button Element to use as button
4122 OO
.ui
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
4123 if ( this.$button
) {
4125 .removeClass( 'oo-ui-buttonElement-button' )
4126 .removeAttr( 'role accesskey' )
4128 mousedown
: this.onMouseDownHandler
,
4129 keydown
: this.onKeyDownHandler
,
4130 click
: this.onClickHandler
,
4131 keypress
: this.onKeyPressHandler
4135 this.$button
= $button
4136 .addClass( 'oo-ui-buttonElement-button' )
4137 .attr( { role
: 'button', accesskey
: this.accessKey
} )
4139 mousedown
: this.onMouseDownHandler
,
4140 keydown
: this.onKeyDownHandler
,
4141 click
: this.onClickHandler
,
4142 keypress
: this.onKeyPressHandler
4147 * Handles mouse down events.
4150 * @param {jQuery.Event} e Mouse down event
4152 OO
.ui
.ButtonElement
.prototype.onMouseDown = function ( e
) {
4153 if ( this.isDisabled() || e
.which
!== 1 ) {
4156 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4157 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4158 // reliably remove the pressed class
4159 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
4160 // Prevent change of focus unless specifically configured otherwise
4161 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
4167 * Handles mouse up events.
4170 * @param {jQuery.Event} e Mouse up event
4172 OO
.ui
.ButtonElement
.prototype.onMouseUp = function ( e
) {
4173 if ( this.isDisabled() || e
.which
!== 1 ) {
4176 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4177 // Stop listening for mouseup, since we only needed this once
4178 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
4182 * Handles mouse click events.
4185 * @param {jQuery.Event} e Mouse click event
4188 OO
.ui
.ButtonElement
.prototype.onClick = function ( e
) {
4189 if ( !this.isDisabled() && e
.which
=== 1 ) {
4190 if ( this.emit( 'click' ) ) {
4197 * Handles key down events.
4200 * @param {jQuery.Event} e Key down event
4202 OO
.ui
.ButtonElement
.prototype.onKeyDown = function ( e
) {
4203 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4206 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4207 // Run the keyup handler no matter where the key is when the button is let go, so we can
4208 // reliably remove the pressed class
4209 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler
, true );
4213 * Handles key up events.
4216 * @param {jQuery.Event} e Key up event
4218 OO
.ui
.ButtonElement
.prototype.onKeyUp = function ( e
) {
4219 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4222 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4223 // Stop listening for keyup, since we only needed this once
4224 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler
, true );
4228 * Handles key press events.
4231 * @param {jQuery.Event} e Key press event
4234 OO
.ui
.ButtonElement
.prototype.onKeyPress = function ( e
) {
4235 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
4236 if ( this.emit( 'click' ) ) {
4243 * Check if button has a frame.
4245 * @return {boolean} Button is framed
4247 OO
.ui
.ButtonElement
.prototype.isFramed = function () {
4252 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4254 * @param {boolean} [framed] Make button framed, omit to toggle
4257 OO
.ui
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
4258 framed
= framed
=== undefined ? !this.framed
: !!framed
;
4259 if ( framed
!== this.framed
) {
4260 this.framed
= framed
;
4262 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
4263 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
4264 this.updateThemeClasses();
4271 * Set the button's access key.
4273 * @param {string} accessKey Button's access key, use empty string to remove
4276 OO
.ui
.ButtonElement
.prototype.setAccessKey = function ( accessKey
) {
4277 accessKey
= typeof accessKey
=== 'string' && accessKey
.length
? accessKey
: null;
4279 if ( this.accessKey
!== accessKey
) {
4280 if ( this.$button
) {
4281 if ( accessKey
!== null ) {
4282 this.$button
.attr( 'accesskey', accessKey
);
4284 this.$button
.removeAttr( 'accesskey' );
4287 this.accessKey
= accessKey
;
4294 * Set the button to its 'active' state.
4296 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4297 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4298 * for other button types.
4300 * @param {boolean} [value] Make button active
4303 OO
.ui
.ButtonElement
.prototype.setActive = function ( value
) {
4304 this.$element
.toggleClass( 'oo-ui-buttonElement-active', !!value
);
4309 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4310 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4311 * items from the group is done through the interface the class provides.
4312 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4314 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4320 * @param {Object} [config] Configuration options
4321 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4322 * is omitted, the group element will use a generated `<div>`.
4324 OO
.ui
.GroupElement
= function OoUiGroupElement( config
) {
4325 // Configuration initialization
4326 config
= config
|| {};
4331 this.aggregateItemEvents
= {};
4334 this.setGroupElement( config
.$group
|| $( '<div>' ) );
4340 * Set the group element.
4342 * If an element is already set, items will be moved to the new element.
4344 * @param {jQuery} $group Element to use as group
4346 OO
.ui
.GroupElement
.prototype.setGroupElement = function ( $group
) {
4349 this.$group
= $group
;
4350 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4351 this.$group
.append( this.items
[ i
].$element
);
4356 * Check if a group contains no items.
4358 * @return {boolean} Group is empty
4360 OO
.ui
.GroupElement
.prototype.isEmpty = function () {
4361 return !this.items
.length
;
4365 * Get all items in the group.
4367 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4368 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4371 * @return {OO.ui.Element[]} An array of items.
4373 OO
.ui
.GroupElement
.prototype.getItems = function () {
4374 return this.items
.slice( 0 );
4378 * Get an item by its data.
4380 * Only the first item with matching data will be returned. To return all matching items,
4381 * use the #getItemsFromData method.
4383 * @param {Object} data Item data to search for
4384 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4386 OO
.ui
.GroupElement
.prototype.getItemFromData = function ( data
) {
4388 hash
= OO
.getHash( data
);
4390 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4391 item
= this.items
[ i
];
4392 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4401 * Get items by their data.
4403 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4405 * @param {Object} data Item data to search for
4406 * @return {OO.ui.Element[]} Items with equivalent data
4408 OO
.ui
.GroupElement
.prototype.getItemsFromData = function ( data
) {
4410 hash
= OO
.getHash( data
),
4413 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4414 item
= this.items
[ i
];
4415 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4424 * Aggregate the events emitted by the group.
4426 * When events are aggregated, the group will listen to all contained items for the event,
4427 * and then emit the event under a new name. The new event will contain an additional leading
4428 * parameter containing the item that emitted the original event. Other arguments emitted from
4429 * the original event are passed through.
4431 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4432 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4433 * A `null` value will remove aggregated events.
4435 * @throws {Error} An error is thrown if aggregation already exists.
4437 OO
.ui
.GroupElement
.prototype.aggregate = function ( events
) {
4438 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
4440 for ( itemEvent
in events
) {
4441 groupEvent
= events
[ itemEvent
];
4443 // Remove existing aggregated event
4444 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4445 // Don't allow duplicate aggregations
4447 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
4449 // Remove event aggregation from existing items
4450 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4451 item
= this.items
[ i
];
4452 if ( item
.connect
&& item
.disconnect
) {
4454 remove
[ itemEvent
] = [ 'emit', groupEvent
, item
];
4455 item
.disconnect( this, remove
);
4458 // Prevent future items from aggregating event
4459 delete this.aggregateItemEvents
[ itemEvent
];
4462 // Add new aggregate event
4464 // Make future items aggregate event
4465 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
4466 // Add event aggregation to existing items
4467 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4468 item
= this.items
[ i
];
4469 if ( item
.connect
&& item
.disconnect
) {
4471 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
4472 item
.connect( this, add
);
4480 * Add items to the group.
4482 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4483 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4485 * @param {OO.ui.Element[]} items An array of items to add to the group
4486 * @param {number} [index] Index of the insertion point
4489 OO
.ui
.GroupElement
.prototype.addItems = function ( items
, index
) {
4490 var i
, len
, item
, event
, events
, currentIndex
,
4493 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4496 // Check if item exists then remove it first, effectively "moving" it
4497 currentIndex
= $.inArray( item
, this.items
);
4498 if ( currentIndex
>= 0 ) {
4499 this.removeItems( [ item
] );
4500 // Adjust index to compensate for removal
4501 if ( currentIndex
< index
) {
4506 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
4508 for ( event
in this.aggregateItemEvents
) {
4509 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
4511 item
.connect( this, events
);
4513 item
.setElementGroup( this );
4514 itemElements
.push( item
.$element
.get( 0 ) );
4517 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
4518 this.$group
.append( itemElements
);
4519 this.items
.push
.apply( this.items
, items
);
4520 } else if ( index
=== 0 ) {
4521 this.$group
.prepend( itemElements
);
4522 this.items
.unshift
.apply( this.items
, items
);
4524 this.items
[ index
].$element
.before( itemElements
);
4525 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
4532 * Remove the specified items from a group.
4534 * Removed items are detached (not removed) from the DOM so that they may be reused.
4535 * To remove all items from a group, you may wish to use the #clearItems method instead.
4537 * @param {OO.ui.Element[]} items An array of items to remove
4540 OO
.ui
.GroupElement
.prototype.removeItems = function ( items
) {
4541 var i
, len
, item
, index
, remove
, itemEvent
;
4543 // Remove specific items
4544 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4546 index
= $.inArray( item
, this.items
);
4547 if ( index
!== -1 ) {
4549 item
.connect
&& item
.disconnect
&&
4550 !$.isEmptyObject( this.aggregateItemEvents
)
4553 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4554 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4556 item
.disconnect( this, remove
);
4558 item
.setElementGroup( null );
4559 this.items
.splice( index
, 1 );
4560 item
.$element
.detach();
4568 * Clear all items from the group.
4570 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4571 * To remove only a subset of items from a group, use the #removeItems method.
4575 OO
.ui
.GroupElement
.prototype.clearItems = function () {
4576 var i
, len
, item
, remove
, itemEvent
;
4579 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4580 item
= this.items
[ i
];
4582 item
.connect
&& item
.disconnect
&&
4583 !$.isEmptyObject( this.aggregateItemEvents
)
4586 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4587 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4589 item
.disconnect( this, remove
);
4591 item
.setElementGroup( null );
4592 item
.$element
.detach();
4600 * DraggableElement is a mixin class used to create elements that can be clicked
4601 * and dragged by a mouse to a new position within a group. This class must be used
4602 * in conjunction with OO.ui.DraggableGroupElement, which provides a container for
4603 * the draggable elements.
4610 OO
.ui
.DraggableElement
= function OoUiDraggableElement() {
4614 // Initialize and events
4616 .attr( 'draggable', true )
4617 .addClass( 'oo-ui-draggableElement' )
4619 dragstart
: this.onDragStart
.bind( this ),
4620 dragover
: this.onDragOver
.bind( this ),
4621 dragend
: this.onDragEnd
.bind( this ),
4622 drop
: this.onDrop
.bind( this )
4626 OO
.initClass( OO
.ui
.DraggableElement
);
4633 * A dragstart event is emitted when the user clicks and begins dragging an item.
4634 * @param {OO.ui.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4639 * A dragend event is emitted when the user drags an item and releases the mouse,
4640 * thus terminating the drag operation.
4645 * A drop event is emitted when the user drags an item and then releases the mouse button
4646 * over a valid target.
4649 /* Static Properties */
4652 * @inheritdoc OO.ui.ButtonElement
4654 OO
.ui
.DraggableElement
.static.cancelButtonMouseDownEvents
= false;
4659 * Respond to dragstart event.
4662 * @param {jQuery.Event} event jQuery event
4665 OO
.ui
.DraggableElement
.prototype.onDragStart = function ( e
) {
4666 var dataTransfer
= e
.originalEvent
.dataTransfer
;
4667 // Define drop effect
4668 dataTransfer
.dropEffect
= 'none';
4669 dataTransfer
.effectAllowed
= 'move';
4670 // We must set up a dataTransfer data property or Firefox seems to
4671 // ignore the fact the element is draggable.
4673 dataTransfer
.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4675 // The above is only for firefox. No need to set a catch clause
4676 // if it fails, move on.
4678 // Add dragging class
4679 this.$element
.addClass( 'oo-ui-draggableElement-dragging' );
4681 this.emit( 'dragstart', this );
4686 * Respond to dragend event.
4691 OO
.ui
.DraggableElement
.prototype.onDragEnd = function () {
4692 this.$element
.removeClass( 'oo-ui-draggableElement-dragging' );
4693 this.emit( 'dragend' );
4697 * Handle drop event.
4700 * @param {jQuery.Event} event jQuery event
4703 OO
.ui
.DraggableElement
.prototype.onDrop = function ( e
) {
4705 this.emit( 'drop', e
);
4709 * In order for drag/drop to work, the dragover event must
4710 * return false and stop propogation.
4714 OO
.ui
.DraggableElement
.prototype.onDragOver = function ( e
) {
4720 * Store it in the DOM so we can access from the widget drag event
4723 * @param {number} Item index
4725 OO
.ui
.DraggableElement
.prototype.setIndex = function ( index
) {
4726 if ( this.index
!== index
) {
4728 this.$element
.data( 'index', index
);
4736 * @return {number} Item index
4738 OO
.ui
.DraggableElement
.prototype.getIndex = function () {
4743 * DraggableGroupElement is a mixin class used to create a group element to
4744 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
4745 * The class is used with OO.ui.DraggableElement.
4749 * @mixins OO.ui.GroupElement
4752 * @param {Object} [config] Configuration options
4753 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
4754 * should match the layout of the items. Items displayed in a single row
4755 * or in several rows should use horizontal orientation. The vertical orientation should only be
4756 * used when the items are displayed in a single column. Defaults to 'vertical'
4758 OO
.ui
.DraggableGroupElement
= function OoUiDraggableGroupElement( config
) {
4759 // Configuration initialization
4760 config
= config
|| {};
4762 // Parent constructor
4763 OO
.ui
.GroupElement
.call( this, config
);
4766 this.orientation
= config
.orientation
|| 'vertical';
4767 this.dragItem
= null;
4768 this.itemDragOver
= null;
4770 this.sideInsertion
= '';
4774 dragstart
: 'itemDragStart',
4775 dragend
: 'itemDragEnd',
4778 this.connect( this, {
4779 itemDragStart
: 'onItemDragStart',
4780 itemDrop
: 'onItemDrop',
4781 itemDragEnd
: 'onItemDragEnd'
4784 dragover
: $.proxy( this.onDragOver
, this ),
4785 dragleave
: $.proxy( this.onDragLeave
, this )
4789 if ( Array
.isArray( config
.items
) ) {
4790 this.addItems( config
.items
);
4792 this.$placeholder
= $( '<div>' )
4793 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
4795 .addClass( 'oo-ui-draggableGroupElement' )
4796 .append( this.$status
)
4797 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation
=== 'horizontal' )
4798 .prepend( this.$placeholder
);
4802 OO
.mixinClass( OO
.ui
.DraggableGroupElement
, OO
.ui
.GroupElement
);
4807 * A 'reorder' event is emitted when the order of items in the group changes.
4810 * @param {OO.ui.DraggableElement} item Reordered item
4811 * @param {number} [newIndex] New index for the item
4817 * Respond to item drag start event
4820 * @param {OO.ui.DraggableElement} item Dragged item
4822 OO
.ui
.DraggableGroupElement
.prototype.onItemDragStart = function ( item
) {
4825 // Map the index of each object
4826 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4827 this.items
[ i
].setIndex( i
);
4830 if ( this.orientation
=== 'horizontal' ) {
4831 // Set the height of the indicator
4832 this.$placeholder
.css( {
4833 height
: item
.$element
.outerHeight(),
4837 // Set the width of the indicator
4838 this.$placeholder
.css( {
4840 width
: item
.$element
.outerWidth()
4843 this.setDragItem( item
);
4847 * Respond to item drag end event
4851 OO
.ui
.DraggableGroupElement
.prototype.onItemDragEnd = function () {
4852 this.unsetDragItem();
4857 * Handle drop event and switch the order of the items accordingly
4860 * @param {OO.ui.DraggableElement} item Dropped item
4863 OO
.ui
.DraggableGroupElement
.prototype.onItemDrop = function ( item
) {
4864 var toIndex
= item
.getIndex();
4865 // Check if the dropped item is from the current group
4866 // TODO: Figure out a way to configure a list of legally droppable
4867 // elements even if they are not yet in the list
4868 if ( this.getDragItem() ) {
4869 // If the insertion point is 'after', the insertion index
4870 // is shifted to the right (or to the left in RTL, hence 'after')
4871 if ( this.sideInsertion
=== 'after' ) {
4874 // Emit change event
4875 this.emit( 'reorder', this.getDragItem(), toIndex
);
4877 this.unsetDragItem();
4878 // Return false to prevent propogation
4883 * Handle dragleave event.
4887 OO
.ui
.DraggableGroupElement
.prototype.onDragLeave = function () {
4888 // This means the item was dragged outside the widget
4891 .addClass( 'oo-ui-element-hidden' );
4895 * Respond to dragover event
4898 * @param {jQuery.Event} event Event details
4900 OO
.ui
.DraggableGroupElement
.prototype.onDragOver = function ( e
) {
4901 var dragOverObj
, $optionWidget
, itemOffset
, itemMidpoint
, itemBoundingRect
,
4902 itemSize
, cssOutput
, dragPosition
, itemIndex
, itemPosition
,
4903 clientX
= e
.originalEvent
.clientX
,
4904 clientY
= e
.originalEvent
.clientY
;
4906 // Get the OptionWidget item we are dragging over
4907 dragOverObj
= this.getElementDocument().elementFromPoint( clientX
, clientY
);
4908 $optionWidget
= $( dragOverObj
).closest( '.oo-ui-draggableElement' );
4909 if ( $optionWidget
[ 0 ] ) {
4910 itemOffset
= $optionWidget
.offset();
4911 itemBoundingRect
= $optionWidget
[ 0 ].getBoundingClientRect();
4912 itemPosition
= $optionWidget
.position();
4913 itemIndex
= $optionWidget
.data( 'index' );
4918 this.isDragging() &&
4919 itemIndex
!== this.getDragItem().getIndex()
4921 if ( this.orientation
=== 'horizontal' ) {
4922 // Calculate where the mouse is relative to the item width
4923 itemSize
= itemBoundingRect
.width
;
4924 itemMidpoint
= itemBoundingRect
.left
+ itemSize
/ 2;
4925 dragPosition
= clientX
;
4926 // Which side of the item we hover over will dictate
4927 // where the placeholder will appear, on the left or
4930 left
: dragPosition
< itemMidpoint
? itemPosition
.left
: itemPosition
.left
+ itemSize
,
4931 top
: itemPosition
.top
4934 // Calculate where the mouse is relative to the item height
4935 itemSize
= itemBoundingRect
.height
;
4936 itemMidpoint
= itemBoundingRect
.top
+ itemSize
/ 2;
4937 dragPosition
= clientY
;
4938 // Which side of the item we hover over will dictate
4939 // where the placeholder will appear, on the top or
4942 top
: dragPosition
< itemMidpoint
? itemPosition
.top
: itemPosition
.top
+ itemSize
,
4943 left
: itemPosition
.left
4946 // Store whether we are before or after an item to rearrange
4947 // For horizontal layout, we need to account for RTL, as this is flipped
4948 if ( this.orientation
=== 'horizontal' && this.$element
.css( 'direction' ) === 'rtl' ) {
4949 this.sideInsertion
= dragPosition
< itemMidpoint
? 'after' : 'before';
4951 this.sideInsertion
= dragPosition
< itemMidpoint
? 'before' : 'after';
4953 // Add drop indicator between objects
4956 .removeClass( 'oo-ui-element-hidden' );
4958 // This means the item was dragged outside the widget
4961 .addClass( 'oo-ui-element-hidden' );
4968 * Set a dragged item
4970 * @param {OO.ui.DraggableElement} item Dragged item
4972 OO
.ui
.DraggableGroupElement
.prototype.setDragItem = function ( item
) {
4973 this.dragItem
= item
;
4977 * Unset the current dragged item
4979 OO
.ui
.DraggableGroupElement
.prototype.unsetDragItem = function () {
4980 this.dragItem
= null;
4981 this.itemDragOver
= null;
4982 this.$placeholder
.addClass( 'oo-ui-element-hidden' );
4983 this.sideInsertion
= '';
4987 * Get the item that is currently being dragged.
4989 * @return {OO.ui.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
4991 OO
.ui
.DraggableGroupElement
.prototype.getDragItem = function () {
4992 return this.dragItem
;
4996 * Check if an item in the group is currently being dragged.
4998 * @return {Boolean} Item is being dragged
5000 OO
.ui
.DraggableGroupElement
.prototype.isDragging = function () {
5001 return this.getDragItem() !== null;
5005 * IconElement is often mixed into other classes to generate an icon.
5006 * Icons are graphics, about the size of normal text. They are used to aid the user
5007 * in locating a control or to convey information in a space-efficient way. See the
5008 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5009 * included in the library.
5011 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5017 * @param {Object} [config] Configuration options
5018 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5019 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5020 * the icon element be set to an existing icon instead of the one generated by this class, set a
5021 * value using a jQuery selection. For example:
5023 * // Use a <div> tag instead of a <span>
5025 * // Use an existing icon element instead of the one generated by the class
5026 * $icon: this.$element
5027 * // Use an icon element from a child widget
5028 * $icon: this.childwidget.$element
5029 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5030 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5031 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5032 * by the user's language.
5034 * Example of an i18n map:
5036 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5037 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5038 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5039 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5040 * text. The icon title is displayed when users move the mouse over the icon.
5042 OO
.ui
.IconElement
= function OoUiIconElement( config
) {
5043 // Configuration initialization
5044 config
= config
|| {};
5049 this.iconTitle
= null;
5052 this.setIcon( config
.icon
|| this.constructor.static.icon
);
5053 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
5054 this.setIconElement( config
.$icon
|| $( '<span>' ) );
5059 OO
.initClass( OO
.ui
.IconElement
);
5061 /* Static Properties */
5064 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5065 * for i18n purposes and contains a `default` icon name and additional names keyed by
5066 * language code. The `default` name is used when no icon is keyed by the user's language.
5068 * Example of an i18n map:
5070 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5072 * Note: the static property will be overridden if the #icon configuration is used.
5076 * @property {Object|string}
5078 OO
.ui
.IconElement
.static.icon
= null;
5081 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5082 * function that returns title text, or `null` for no title.
5084 * The static property will be overridden if the #iconTitle configuration is used.
5088 * @property {string|Function|null}
5090 OO
.ui
.IconElement
.static.iconTitle
= null;
5095 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5096 * applies to the specified icon element instead of the one created by the class. If an icon
5097 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5098 * and mixin methods will no longer affect the element.
5100 * @param {jQuery} $icon Element to use as icon
5102 OO
.ui
.IconElement
.prototype.setIconElement = function ( $icon
) {
5105 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
5106 .removeAttr( 'title' );
5110 .addClass( 'oo-ui-iconElement-icon' )
5111 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
5112 if ( this.iconTitle
!== null ) {
5113 this.$icon
.attr( 'title', this.iconTitle
);
5118 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5119 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5122 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5123 * by language code, or `null` to remove the icon.
5126 OO
.ui
.IconElement
.prototype.setIcon = function ( icon
) {
5127 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
5128 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
5130 if ( this.icon
!== icon
) {
5132 if ( this.icon
!== null ) {
5133 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
5135 if ( icon
!== null ) {
5136 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
5142 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
5143 this.updateThemeClasses();
5149 * Set the icon title. Use `null` to remove the title.
5151 * @param {string|Function|null} iconTitle A text string used as the icon title,
5152 * a function that returns title text, or `null` for no title.
5155 OO
.ui
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
5156 iconTitle
= typeof iconTitle
=== 'function' ||
5157 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
5158 OO
.ui
.resolveMsg( iconTitle
) : null;
5160 if ( this.iconTitle
!== iconTitle
) {
5161 this.iconTitle
= iconTitle
;
5163 if ( this.iconTitle
!== null ) {
5164 this.$icon
.attr( 'title', iconTitle
);
5166 this.$icon
.removeAttr( 'title' );
5175 * Get the symbolic name of the icon.
5177 * @return {string} Icon name
5179 OO
.ui
.IconElement
.prototype.getIcon = function () {
5184 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5186 * @return {string} Icon title text
5188 OO
.ui
.IconElement
.prototype.getIconTitle = function () {
5189 return this.iconTitle
;
5193 * IndicatorElement is often mixed into other classes to generate an indicator.
5194 * Indicators are small graphics that are generally used in two ways:
5196 * - To draw attention to the status of an item. For example, an indicator might be
5197 * used to show that an item in a list has errors that need to be resolved.
5198 * - To clarify the function of a control that acts in an exceptional way (a button
5199 * that opens a menu instead of performing an action directly, for example).
5201 * For a list of indicators included in the library, please see the
5202 * [OOjs UI documentation on MediaWiki] [1].
5204 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5210 * @param {Object} [config] Configuration options
5211 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5212 * configuration is omitted, the indicator element will use a generated `<span>`.
5213 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5214 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5216 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5217 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5218 * or a function that returns title text. The indicator title is displayed when users move
5219 * the mouse over the indicator.
5221 OO
.ui
.IndicatorElement
= function OoUiIndicatorElement( config
) {
5222 // Configuration initialization
5223 config
= config
|| {};
5226 this.$indicator
= null;
5227 this.indicator
= null;
5228 this.indicatorTitle
= null;
5231 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
5232 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
5233 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
5238 OO
.initClass( OO
.ui
.IndicatorElement
);
5240 /* Static Properties */
5243 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5244 * The static property will be overridden if the #indicator configuration is used.
5248 * @property {string|null}
5250 OO
.ui
.IndicatorElement
.static.indicator
= null;
5253 * A text string used as the indicator title, a function that returns title text, or `null`
5254 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5258 * @property {string|Function|null}
5260 OO
.ui
.IndicatorElement
.static.indicatorTitle
= null;
5265 * Set the indicator element.
5267 * If an element is already set, it will be cleaned up before setting up the new element.
5269 * @param {jQuery} $indicator Element to use as indicator
5271 OO
.ui
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
5272 if ( this.$indicator
) {
5274 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
5275 .removeAttr( 'title' );
5278 this.$indicator
= $indicator
5279 .addClass( 'oo-ui-indicatorElement-indicator' )
5280 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
5281 if ( this.indicatorTitle
!== null ) {
5282 this.$indicator
.attr( 'title', this.indicatorTitle
);
5287 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5289 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5292 OO
.ui
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
5293 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
5295 if ( this.indicator
!== indicator
) {
5296 if ( this.$indicator
) {
5297 if ( this.indicator
!== null ) {
5298 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
5300 if ( indicator
!== null ) {
5301 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
5304 this.indicator
= indicator
;
5307 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
5308 this.updateThemeClasses();
5314 * Set the indicator title.
5316 * The title is displayed when a user moves the mouse over the indicator.
5318 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5319 * `null` for no indicator title
5322 OO
.ui
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
5323 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
5324 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
5325 OO
.ui
.resolveMsg( indicatorTitle
) : null;
5327 if ( this.indicatorTitle
!== indicatorTitle
) {
5328 this.indicatorTitle
= indicatorTitle
;
5329 if ( this.$indicator
) {
5330 if ( this.indicatorTitle
!== null ) {
5331 this.$indicator
.attr( 'title', indicatorTitle
);
5333 this.$indicator
.removeAttr( 'title' );
5342 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5344 * @return {string} Symbolic name of indicator
5346 OO
.ui
.IndicatorElement
.prototype.getIndicator = function () {
5347 return this.indicator
;
5351 * Get the indicator title.
5353 * The title is displayed when a user moves the mouse over the indicator.
5355 * @return {string} Indicator title text
5357 OO
.ui
.IndicatorElement
.prototype.getIndicatorTitle = function () {
5358 return this.indicatorTitle
;
5362 * LabelElement is often mixed into other classes to generate a label, which
5363 * helps identify the function of an interface element.
5364 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5366 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5372 * @param {Object} [config] Configuration options
5373 * @cfg {jQuery} [$label] The label element created by the class. If this
5374 * configuration is omitted, the label element will use a generated `<span>`.
5375 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5376 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5377 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5378 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5379 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5380 * The label will be truncated to fit if necessary.
5382 OO
.ui
.LabelElement
= function OoUiLabelElement( config
) {
5383 // Configuration initialization
5384 config
= config
|| {};
5389 this.autoFitLabel
= config
.autoFitLabel
=== undefined || !!config
.autoFitLabel
;
5392 this.setLabel( config
.label
|| this.constructor.static.label
);
5393 this.setLabelElement( config
.$label
|| $( '<span>' ) );
5398 OO
.initClass( OO
.ui
.LabelElement
);
5403 * @event labelChange
5404 * @param {string} value
5407 /* Static Properties */
5410 * The label text. The label can be specified as a plaintext string, a function that will
5411 * produce a string in the future, or `null` for no label. The static value will
5412 * be overridden if a label is specified with the #label config option.
5416 * @property {string|Function|null}
5418 OO
.ui
.LabelElement
.static.label
= null;
5423 * Set the label element.
5425 * If an element is already set, it will be cleaned up before setting up the new element.
5427 * @param {jQuery} $label Element to use as label
5429 OO
.ui
.LabelElement
.prototype.setLabelElement = function ( $label
) {
5430 if ( this.$label
) {
5431 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
5434 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
5435 this.setLabelContent( this.label
);
5441 * An empty string will result in the label being hidden. A string containing only whitespace will
5442 * be converted to a single ` `.
5444 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5445 * text; or null for no label
5448 OO
.ui
.LabelElement
.prototype.setLabel = function ( label
) {
5449 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
5450 label
= ( ( typeof label
=== 'string' && label
.length
) || label
instanceof jQuery
|| label
instanceof OO
.ui
.HtmlSnippet
) ? label
: null;
5452 this.$element
.toggleClass( 'oo-ui-labelElement', !!label
);
5454 if ( this.label
!== label
) {
5455 if ( this.$label
) {
5456 this.setLabelContent( label
);
5459 this.emit( 'labelChange' );
5468 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5469 * text; or null for no label
5471 OO
.ui
.LabelElement
.prototype.getLabel = function () {
5480 OO
.ui
.LabelElement
.prototype.fitLabel = function () {
5481 if ( this.$label
&& this.$label
.autoEllipsis
&& this.autoFitLabel
) {
5482 this.$label
.autoEllipsis( { hasSpan
: false, tooltip
: true } );
5489 * Set the content of the label.
5491 * Do not call this method until after the label element has been set by #setLabelElement.
5494 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5495 * text; or null for no label
5497 OO
.ui
.LabelElement
.prototype.setLabelContent = function ( label
) {
5498 if ( typeof label
=== 'string' ) {
5499 if ( label
.match( /^\s*$/ ) ) {
5500 // Convert whitespace only string to a single non-breaking space
5501 this.$label
.html( ' ' );
5503 this.$label
.text( label
);
5505 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
5506 this.$label
.html( label
.toString() );
5507 } else if ( label
instanceof jQuery
) {
5508 this.$label
.empty().append( label
);
5510 this.$label
.empty();
5515 * LookupElement is a mixin that creates a {@link OO.ui.TextInputMenuSelectWidget menu} of suggested values for
5516 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5517 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5518 * from the lookup menu, that value becomes the value of the input field.
5520 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5521 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5522 * re-enable lookups.
5524 * See the [OOjs UI demos][1] for an example.
5526 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5532 * @param {Object} [config] Configuration options
5533 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5534 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5535 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5536 * By default, the lookup menu is not generated and displayed until the user begins to type.
5538 OO
.ui
.LookupElement
= function OoUiLookupElement( config
) {
5539 // Configuration initialization
5540 config
= config
|| {};
5543 this.$overlay
= config
.$overlay
|| this.$element
;
5544 this.lookupMenu
= new OO
.ui
.TextInputMenuSelectWidget( this, {
5547 $container
: config
.$container
5550 this.allowSuggestionsWhenEmpty
= config
.allowSuggestionsWhenEmpty
|| false;
5552 this.lookupCache
= {};
5553 this.lookupQuery
= null;
5554 this.lookupRequest
= null;
5555 this.lookupsDisabled
= false;
5556 this.lookupInputFocused
= false;
5560 focus
: this.onLookupInputFocus
.bind( this ),
5561 blur
: this.onLookupInputBlur
.bind( this ),
5562 mousedown
: this.onLookupInputMouseDown
.bind( this )
5564 this.connect( this, { change
: 'onLookupInputChange' } );
5565 this.lookupMenu
.connect( this, {
5566 toggle
: 'onLookupMenuToggle',
5567 choose
: 'onLookupMenuItemChoose'
5571 this.$element
.addClass( 'oo-ui-lookupElement' );
5572 this.lookupMenu
.$element
.addClass( 'oo-ui-lookupElement-menu' );
5573 this.$overlay
.append( this.lookupMenu
.$element
);
5579 * Handle input focus event.
5582 * @param {jQuery.Event} e Input focus event
5584 OO
.ui
.LookupElement
.prototype.onLookupInputFocus = function () {
5585 this.lookupInputFocused
= true;
5586 this.populateLookupMenu();
5590 * Handle input blur event.
5593 * @param {jQuery.Event} e Input blur event
5595 OO
.ui
.LookupElement
.prototype.onLookupInputBlur = function () {
5596 this.closeLookupMenu();
5597 this.lookupInputFocused
= false;
5601 * Handle input mouse down event.
5604 * @param {jQuery.Event} e Input mouse down event
5606 OO
.ui
.LookupElement
.prototype.onLookupInputMouseDown = function () {
5607 // Only open the menu if the input was already focused.
5608 // This way we allow the user to open the menu again after closing it with Esc
5609 // by clicking in the input. Opening (and populating) the menu when initially
5610 // clicking into the input is handled by the focus handler.
5611 if ( this.lookupInputFocused
&& !this.lookupMenu
.isVisible() ) {
5612 this.populateLookupMenu();
5617 * Handle input change event.
5620 * @param {string} value New input value
5622 OO
.ui
.LookupElement
.prototype.onLookupInputChange = function () {
5623 if ( this.lookupInputFocused
) {
5624 this.populateLookupMenu();
5629 * Handle the lookup menu being shown/hidden.
5632 * @param {boolean} visible Whether the lookup menu is now visible.
5634 OO
.ui
.LookupElement
.prototype.onLookupMenuToggle = function ( visible
) {
5636 // When the menu is hidden, abort any active request and clear the menu.
5637 // This has to be done here in addition to closeLookupMenu(), because
5638 // MenuSelectWidget will close itself when the user presses Esc.
5639 this.abortLookupRequest();
5640 this.lookupMenu
.clearItems();
5645 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5648 * @param {OO.ui.MenuOptionWidget} item Selected item
5650 OO
.ui
.LookupElement
.prototype.onLookupMenuItemChoose = function ( item
) {
5651 this.setValue( item
.getData() );
5658 * @return {OO.ui.TextInputMenuSelectWidget}
5660 OO
.ui
.LookupElement
.prototype.getLookupMenu = function () {
5661 return this.lookupMenu
;
5665 * Disable or re-enable lookups.
5667 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
5669 * @param {boolean} disabled Disable lookups
5671 OO
.ui
.LookupElement
.prototype.setLookupsDisabled = function ( disabled
) {
5672 this.lookupsDisabled
= !!disabled
;
5676 * Open the menu. If there are no entries in the menu, this does nothing.
5681 OO
.ui
.LookupElement
.prototype.openLookupMenu = function () {
5682 if ( !this.lookupMenu
.isEmpty() ) {
5683 this.lookupMenu
.toggle( true );
5689 * Close the menu, empty it, and abort any pending request.
5694 OO
.ui
.LookupElement
.prototype.closeLookupMenu = function () {
5695 this.lookupMenu
.toggle( false );
5696 this.abortLookupRequest();
5697 this.lookupMenu
.clearItems();
5702 * Request menu items based on the input's current value, and when they arrive,
5703 * populate the menu with these items and show the menu.
5705 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
5710 OO
.ui
.LookupElement
.prototype.populateLookupMenu = function () {
5712 value
= this.getValue();
5714 if ( this.lookupsDisabled
) {
5718 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
5719 if ( !this.allowSuggestionsWhenEmpty
&& value
=== '' ) {
5720 this.closeLookupMenu();
5721 // Skip population if there is already a request pending for the current value
5722 } else if ( value
!== this.lookupQuery
) {
5723 this.getLookupMenuItems()
5724 .done( function ( items
) {
5725 widget
.lookupMenu
.clearItems();
5726 if ( items
.length
) {
5730 widget
.initializeLookupMenuSelection();
5732 widget
.lookupMenu
.toggle( false );
5735 .fail( function () {
5736 widget
.lookupMenu
.clearItems();
5744 * Highlight the first selectable item in the menu.
5749 OO
.ui
.LookupElement
.prototype.initializeLookupMenuSelection = function () {
5750 if ( !this.lookupMenu
.getSelectedItem() ) {
5751 this.lookupMenu
.highlightItem( this.lookupMenu
.getFirstSelectableItem() );
5756 * Get lookup menu items for the current query.
5759 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
5760 * the done event. If the request was aborted to make way for a subsequent request, this promise
5761 * will not be rejected: it will remain pending forever.
5763 OO
.ui
.LookupElement
.prototype.getLookupMenuItems = function () {
5765 value
= this.getValue(),
5766 deferred
= $.Deferred(),
5769 this.abortLookupRequest();
5770 if ( Object
.prototype.hasOwnProperty
.call( this.lookupCache
, value
) ) {
5771 deferred
.resolve( this.getLookupMenuOptionsFromData( this.lookupCache
[ value
] ) );
5774 this.lookupQuery
= value
;
5775 ourRequest
= this.lookupRequest
= this.getLookupRequest();
5777 .always( function () {
5778 // We need to pop pending even if this is an old request, otherwise
5779 // the widget will remain pending forever.
5780 // TODO: this assumes that an aborted request will fail or succeed soon after
5781 // being aborted, or at least eventually. It would be nice if we could popPending()
5782 // at abort time, but only if we knew that we hadn't already called popPending()
5783 // for that request.
5784 widget
.popPending();
5786 .done( function ( response
) {
5787 // If this is an old request (and aborting it somehow caused it to still succeed),
5788 // ignore its success completely
5789 if ( ourRequest
=== widget
.lookupRequest
) {
5790 widget
.lookupQuery
= null;
5791 widget
.lookupRequest
= null;
5792 widget
.lookupCache
[ value
] = widget
.getLookupCacheDataFromResponse( response
);
5793 deferred
.resolve( widget
.getLookupMenuOptionsFromData( widget
.lookupCache
[ value
] ) );
5796 .fail( function () {
5797 // If this is an old request (or a request failing because it's being aborted),
5798 // ignore its failure completely
5799 if ( ourRequest
=== widget
.lookupRequest
) {
5800 widget
.lookupQuery
= null;
5801 widget
.lookupRequest
= null;
5806 return deferred
.promise();
5810 * Abort the currently pending lookup request, if any.
5814 OO
.ui
.LookupElement
.prototype.abortLookupRequest = function () {
5815 var oldRequest
= this.lookupRequest
;
5817 // First unset this.lookupRequest to the fail handler will notice
5818 // that the request is no longer current
5819 this.lookupRequest
= null;
5820 this.lookupQuery
= null;
5826 * Get a new request object of the current lookup query value.
5830 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
5832 OO
.ui
.LookupElement
.prototype.getLookupRequest = function () {
5833 // Stub, implemented in subclass
5838 * Pre-process data returned by the request from #getLookupRequest.
5840 * The return value of this function will be cached, and any further queries for the given value
5841 * will use the cache rather than doing API requests.
5845 * @param {Mixed} response Response from server
5846 * @return {Mixed} Cached result data
5848 OO
.ui
.LookupElement
.prototype.getLookupCacheDataFromResponse = function () {
5849 // Stub, implemented in subclass
5854 * Get a list of menu option widgets from the (possibly cached) data returned by
5855 * #getLookupCacheDataFromResponse.
5859 * @param {Mixed} data Cached result data, usually an array
5860 * @return {OO.ui.MenuOptionWidget[]} Menu items
5862 OO
.ui
.LookupElement
.prototype.getLookupMenuOptionsFromData = function () {
5863 // Stub, implemented in subclass
5868 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5869 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5870 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5871 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5877 * @param {Object} [config] Configuration options
5878 * @cfg {Object} [popup] Configuration to pass to popup
5879 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5881 OO
.ui
.PopupElement
= function OoUiPopupElement( config
) {
5882 // Configuration initialization
5883 config
= config
|| {};
5886 this.popup
= new OO
.ui
.PopupWidget( $.extend(
5887 { autoClose
: true },
5889 { $autoCloseIgnore
: this.$element
}
5898 * @return {OO.ui.PopupWidget} Popup widget
5900 OO
.ui
.PopupElement
.prototype.getPopup = function () {
5905 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
5906 * additional functionality to an element created by another class. The class provides
5907 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
5908 * which are used to customize the look and feel of a widget to better describe its
5909 * importance and functionality.
5911 * The library currently contains the following styling flags for general use:
5913 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
5914 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
5915 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
5917 * The flags affect the appearance of the buttons:
5920 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
5921 * var button1 = new OO.ui.ButtonWidget( {
5922 * label: 'Constructive',
5923 * flags: 'constructive'
5925 * var button2 = new OO.ui.ButtonWidget( {
5926 * label: 'Destructive',
5927 * flags: 'destructive'
5929 * var button3 = new OO.ui.ButtonWidget( {
5930 * label: 'Progressive',
5931 * flags: 'progressive'
5933 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
5935 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
5936 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
5938 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5944 * @param {Object} [config] Configuration options
5945 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
5946 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
5947 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5948 * @cfg {jQuery} [$flagged] The flagged element. By default,
5949 * the flagged functionality is applied to the element created by the class ($element).
5950 * If a different element is specified, the flagged functionality will be applied to it instead.
5952 OO
.ui
.FlaggedElement
= function OoUiFlaggedElement( config
) {
5953 // Configuration initialization
5954 config
= config
|| {};
5958 this.$flagged
= null;
5961 this.setFlags( config
.flags
);
5962 this.setFlaggedElement( config
.$flagged
|| this.$element
);
5969 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
5970 * parameter contains the name of each modified flag and indicates whether it was
5973 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
5974 * that the flag was added, `false` that the flag was removed.
5980 * Set the flagged element.
5982 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
5983 * If an element is already set, the method will remove the mixin’s effect on that element.
5985 * @param {jQuery} $flagged Element that should be flagged
5987 OO
.ui
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
5988 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
5989 return 'oo-ui-flaggedElement-' + flag
;
5992 if ( this.$flagged
) {
5993 this.$flagged
.removeClass( classNames
);
5996 this.$flagged
= $flagged
.addClass( classNames
);
6000 * Check if the specified flag is set.
6002 * @param {string} flag Name of flag
6003 * @return {boolean} The flag is set
6005 OO
.ui
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
6006 return flag
in this.flags
;
6010 * Get the names of all flags set.
6012 * @return {string[]} Flag names
6014 OO
.ui
.FlaggedElement
.prototype.getFlags = function () {
6015 return Object
.keys( this.flags
);
6024 OO
.ui
.FlaggedElement
.prototype.clearFlags = function () {
6025 var flag
, className
,
6028 classPrefix
= 'oo-ui-flaggedElement-';
6030 for ( flag
in this.flags
) {
6031 className
= classPrefix
+ flag
;
6032 changes
[ flag
] = false;
6033 delete this.flags
[ flag
];
6034 remove
.push( className
);
6037 if ( this.$flagged
) {
6038 this.$flagged
.removeClass( remove
.join( ' ' ) );
6041 this.updateThemeClasses();
6042 this.emit( 'flag', changes
);
6048 * Add one or more flags.
6050 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6051 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6052 * be added (`true`) or removed (`false`).
6056 OO
.ui
.FlaggedElement
.prototype.setFlags = function ( flags
) {
6057 var i
, len
, flag
, className
,
6061 classPrefix
= 'oo-ui-flaggedElement-';
6063 if ( typeof flags
=== 'string' ) {
6064 className
= classPrefix
+ flags
;
6066 if ( !this.flags
[ flags
] ) {
6067 this.flags
[ flags
] = true;
6068 add
.push( className
);
6070 } else if ( Array
.isArray( flags
) ) {
6071 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
6073 className
= classPrefix
+ flag
;
6075 if ( !this.flags
[ flag
] ) {
6076 changes
[ flag
] = true;
6077 this.flags
[ flag
] = true;
6078 add
.push( className
);
6081 } else if ( OO
.isPlainObject( flags
) ) {
6082 for ( flag
in flags
) {
6083 className
= classPrefix
+ flag
;
6084 if ( flags
[ flag
] ) {
6086 if ( !this.flags
[ flag
] ) {
6087 changes
[ flag
] = true;
6088 this.flags
[ flag
] = true;
6089 add
.push( className
);
6093 if ( this.flags
[ flag
] ) {
6094 changes
[ flag
] = false;
6095 delete this.flags
[ flag
];
6096 remove
.push( className
);
6102 if ( this.$flagged
) {
6104 .addClass( add
.join( ' ' ) )
6105 .removeClass( remove
.join( ' ' ) );
6108 this.updateThemeClasses();
6109 this.emit( 'flag', changes
);
6115 * TitledElement is mixed into other classes to provide a `title` attribute.
6116 * Titles are rendered by the browser and are made visible when the user moves
6117 * the mouse over the element. Titles are not visible on touch devices.
6120 * // TitledElement provides a 'title' attribute to the
6121 * // ButtonWidget class
6122 * var button = new OO.ui.ButtonWidget( {
6123 * label: 'Button with Title',
6124 * title: 'I am a button'
6126 * $( 'body' ).append( button.$element );
6132 * @param {Object} [config] Configuration options
6133 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6134 * If this config is omitted, the title functionality is applied to $element, the
6135 * element created by the class.
6136 * @cfg {string|Function} [title] The title text or a function that returns text. If
6137 * this config is omitted, the value of the {@link #static-title static title} property is used.
6139 OO
.ui
.TitledElement
= function OoUiTitledElement( config
) {
6140 // Configuration initialization
6141 config
= config
|| {};
6144 this.$titled
= null;
6148 this.setTitle( config
.title
|| this.constructor.static.title
);
6149 this.setTitledElement( config
.$titled
|| this.$element
);
6154 OO
.initClass( OO
.ui
.TitledElement
);
6156 /* Static Properties */
6159 * The title text, a function that returns text, or `null` for no title. The value of the static property
6160 * is overridden if the #title config option is used.
6164 * @property {string|Function|null}
6166 OO
.ui
.TitledElement
.static.title
= null;
6171 * Set the titled element.
6173 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6174 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6176 * @param {jQuery} $titled Element that should use the 'titled' functionality
6178 OO
.ui
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
6179 if ( this.$titled
) {
6180 this.$titled
.removeAttr( 'title' );
6183 this.$titled
= $titled
;
6185 this.$titled
.attr( 'title', this.title
);
6192 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6195 OO
.ui
.TitledElement
.prototype.setTitle = function ( title
) {
6196 title
= typeof title
=== 'string' ? OO
.ui
.resolveMsg( title
) : null;
6198 if ( this.title
!== title
) {
6199 if ( this.$titled
) {
6200 if ( title
!== null ) {
6201 this.$titled
.attr( 'title', title
);
6203 this.$titled
.removeAttr( 'title' );
6215 * @return {string} Title string
6217 OO
.ui
.TitledElement
.prototype.getTitle = function () {
6222 * Element that can be automatically clipped to visible boundaries.
6224 * Whenever the element's natural height changes, you have to call
6225 * #clip to make sure it's still clipping correctly.
6231 * @param {Object} [config] Configuration options
6232 * @cfg {jQuery} [$clippable] Nodes to clip, assigned to #$clippable, omit to use #$element
6234 OO
.ui
.ClippableElement
= function OoUiClippableElement( config
) {
6235 // Configuration initialization
6236 config
= config
|| {};
6239 this.$clippable
= null;
6240 this.clipping
= false;
6241 this.clippedHorizontally
= false;
6242 this.clippedVertically
= false;
6243 this.$clippableContainer
= null;
6244 this.$clippableScroller
= null;
6245 this.$clippableWindow
= null;
6246 this.idealWidth
= null;
6247 this.idealHeight
= null;
6248 this.onClippableContainerScrollHandler
= this.clip
.bind( this );
6249 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
6252 this.setClippableElement( config
.$clippable
|| this.$element
);
6258 * Set clippable element.
6260 * If an element is already set, it will be cleaned up before setting up the new element.
6262 * @param {jQuery} $clippable Element to make clippable
6264 OO
.ui
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
6265 if ( this.$clippable
) {
6266 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
6267 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6268 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6271 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
6278 * Do not turn clipping on until after the element is attached to the DOM and visible.
6280 * @param {boolean} [clipping] Enable clipping, omit to toggle
6283 OO
.ui
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
6284 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
6286 if ( this.clipping
!== clipping
) {
6287 this.clipping
= clipping
;
6289 this.$clippableContainer
= $( this.getClosestScrollableElementContainer() );
6290 // If the clippable container is the root, we have to listen to scroll events and check
6291 // jQuery.scrollTop on the window because of browser inconsistencies
6292 this.$clippableScroller
= this.$clippableContainer
.is( 'html, body' ) ?
6293 $( OO
.ui
.Element
.static.getWindow( this.$clippableContainer
) ) :
6294 this.$clippableContainer
;
6295 this.$clippableScroller
.on( 'scroll', this.onClippableContainerScrollHandler
);
6296 this.$clippableWindow
= $( this.getElementWindow() )
6297 .on( 'resize', this.onClippableWindowResizeHandler
);
6298 // Initial clip after visible
6301 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6302 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6304 this.$clippableContainer
= null;
6305 this.$clippableScroller
.off( 'scroll', this.onClippableContainerScrollHandler
);
6306 this.$clippableScroller
= null;
6307 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
6308 this.$clippableWindow
= null;
6316 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6318 * @return {boolean} Element will be clipped to the visible area
6320 OO
.ui
.ClippableElement
.prototype.isClipping = function () {
6321 return this.clipping
;
6325 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6327 * @return {boolean} Part of the element is being clipped
6329 OO
.ui
.ClippableElement
.prototype.isClipped = function () {
6330 return this.clippedHorizontally
|| this.clippedVertically
;
6334 * Check if the right of the element is being clipped by the nearest scrollable container.
6336 * @return {boolean} Part of the element is being clipped
6338 OO
.ui
.ClippableElement
.prototype.isClippedHorizontally = function () {
6339 return this.clippedHorizontally
;
6343 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6345 * @return {boolean} Part of the element is being clipped
6347 OO
.ui
.ClippableElement
.prototype.isClippedVertically = function () {
6348 return this.clippedVertically
;
6352 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6354 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6355 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6357 OO
.ui
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
6358 this.idealWidth
= width
;
6359 this.idealHeight
= height
;
6361 if ( !this.clipping
) {
6362 // Update dimensions
6363 this.$clippable
.css( { width
: width
, height
: height
} );
6365 // While clipping, idealWidth and idealHeight are not considered
6369 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6370 * the element's natural height changes.
6372 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6373 * overlapped by, the visible area of the nearest scrollable container.
6377 OO
.ui
.ClippableElement
.prototype.clip = function () {
6378 if ( !this.clipping
) {
6379 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
6383 var buffer
= 7, // Chosen by fair dice roll
6384 cOffset
= this.$clippable
.offset(),
6385 $container
= this.$clippableContainer
.is( 'html, body' ) ?
6386 this.$clippableWindow
: this.$clippableContainer
,
6387 ccOffset
= $container
.offset() || { top
: 0, left
: 0 },
6388 ccHeight
= $container
.innerHeight() - buffer
,
6389 ccWidth
= $container
.innerWidth() - buffer
,
6390 cHeight
= this.$clippable
.outerHeight() + buffer
,
6391 cWidth
= this.$clippable
.outerWidth() + buffer
,
6392 scrollTop
= this.$clippableScroller
.scrollTop(),
6393 scrollLeft
= this.$clippableScroller
.scrollLeft(),
6394 desiredWidth
= cOffset
.left
< 0 ?
6395 cWidth
+ cOffset
.left
:
6396 ( ccOffset
.left
+ scrollLeft
+ ccWidth
) - cOffset
.left
,
6397 desiredHeight
= cOffset
.top
< 0 ?
6398 cHeight
+ cOffset
.top
:
6399 ( ccOffset
.top
+ scrollTop
+ ccHeight
) - cOffset
.top
,
6400 naturalWidth
= this.$clippable
.prop( 'scrollWidth' ),
6401 naturalHeight
= this.$clippable
.prop( 'scrollHeight' ),
6402 clipWidth
= desiredWidth
< naturalWidth
,
6403 clipHeight
= desiredHeight
< naturalHeight
;
6406 this.$clippable
.css( { overflowX
: 'scroll', width
: desiredWidth
} );
6408 this.$clippable
.css( { width
: this.idealWidth
|| '', overflowX
: '' } );
6411 this.$clippable
.css( { overflowY
: 'scroll', height
: desiredHeight
} );
6413 this.$clippable
.css( { height
: this.idealHeight
|| '', overflowY
: '' } );
6416 // If we stopped clipping in at least one of the dimensions
6417 if ( !clipWidth
|| !clipHeight
) {
6418 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6421 this.clippedHorizontally
= clipWidth
;
6422 this.clippedVertically
= clipHeight
;
6428 * Generic toolbar tool.
6432 * @extends OO.ui.Widget
6433 * @mixins OO.ui.IconElement
6434 * @mixins OO.ui.FlaggedElement
6435 * @mixins OO.ui.TabIndexedElement
6438 * @param {OO.ui.ToolGroup} toolGroup
6439 * @param {Object} [config] Configuration options
6440 * @cfg {string|Function} [title] Title text or a function that returns text
6442 OO
.ui
.Tool
= function OoUiTool( toolGroup
, config
) {
6443 // Allow passing positional parameters inside the config object
6444 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
6446 toolGroup
= config
.toolGroup
;
6449 // Configuration initialization
6450 config
= config
|| {};
6452 // Parent constructor
6453 OO
.ui
.Tool
.super.call( this, config
);
6456 this.toolGroup
= toolGroup
;
6457 this.toolbar
= this.toolGroup
.getToolbar();
6458 this.active
= false;
6459 this.$title
= $( '<span>' );
6460 this.$accel
= $( '<span>' );
6461 this.$link
= $( '<a>' );
6464 // Mixin constructors
6465 OO
.ui
.IconElement
.call( this, config
);
6466 OO
.ui
.FlaggedElement
.call( this, config
);
6467 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$link
} ) );
6470 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
6473 this.$title
.addClass( 'oo-ui-tool-title' );
6475 .addClass( 'oo-ui-tool-accel' )
6477 // This may need to be changed if the key names are ever localized,
6478 // but for now they are essentially written in English
6483 .addClass( 'oo-ui-tool-link' )
6484 .append( this.$icon
, this.$title
, this.$accel
)
6485 .attr( 'role', 'button' );
6487 .data( 'oo-ui-tool', this )
6489 'oo-ui-tool ' + 'oo-ui-tool-name-' +
6490 this.constructor.static.name
.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
6492 .append( this.$link
);
6493 this.setTitle( config
.title
|| this.constructor.static.title
);
6498 OO
.inheritClass( OO
.ui
.Tool
, OO
.ui
.Widget
);
6499 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.IconElement
);
6500 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.FlaggedElement
);
6501 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.TabIndexedElement
);
6509 /* Static Properties */
6515 OO
.ui
.Tool
.static.tagName
= 'span';
6518 * Symbolic name of tool.
6523 * @property {string}
6525 OO
.ui
.Tool
.static.name
= '';
6533 * @property {string}
6535 OO
.ui
.Tool
.static.group
= '';
6540 * Title is used as a tooltip when the tool is part of a bar tool group, or a label when the tool
6541 * is part of a list or menu tool group. If a trigger is associated with an action by the same name
6542 * as the tool, a description of its keyboard shortcut for the appropriate platform will be
6543 * appended to the title if the tool is part of a bar tool group.
6548 * @property {string|Function} Title text or a function that returns text
6550 OO
.ui
.Tool
.static.title
= '';
6553 * Tool can be automatically added to catch-all groups.
6557 * @property {boolean}
6559 OO
.ui
.Tool
.static.autoAddToCatchall
= true;
6562 * Tool can be automatically added to named groups.
6565 * @property {boolean}
6568 OO
.ui
.Tool
.static.autoAddToGroup
= true;
6571 * Check if this tool is compatible with given data.
6575 * @param {Mixed} data Data to check
6576 * @return {boolean} Tool can be used with data
6578 OO
.ui
.Tool
.static.isCompatibleWith = function () {
6585 * Handle the toolbar state being updated.
6587 * This is an abstract method that must be overridden in a concrete subclass.
6591 OO
.ui
.Tool
.prototype.onUpdateState = function () {
6593 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
6598 * Handle the tool being selected.
6600 * This is an abstract method that must be overridden in a concrete subclass.
6604 OO
.ui
.Tool
.prototype.onSelect = function () {
6606 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
6611 * Check if the button is active.
6613 * @return {boolean} Button is active
6615 OO
.ui
.Tool
.prototype.isActive = function () {
6620 * Make the button appear active or inactive.
6622 * @param {boolean} state Make button appear active
6624 OO
.ui
.Tool
.prototype.setActive = function ( state
) {
6625 this.active
= !!state
;
6626 if ( this.active
) {
6627 this.$element
.addClass( 'oo-ui-tool-active' );
6629 this.$element
.removeClass( 'oo-ui-tool-active' );
6634 * Get the tool title.
6636 * @param {string|Function} title Title text or a function that returns text
6639 OO
.ui
.Tool
.prototype.setTitle = function ( title
) {
6640 this.title
= OO
.ui
.resolveMsg( title
);
6646 * Get the tool title.
6648 * @return {string} Title text
6650 OO
.ui
.Tool
.prototype.getTitle = function () {
6655 * Get the tool's symbolic name.
6657 * @return {string} Symbolic name of tool
6659 OO
.ui
.Tool
.prototype.getName = function () {
6660 return this.constructor.static.name
;
6666 OO
.ui
.Tool
.prototype.updateTitle = function () {
6667 var titleTooltips
= this.toolGroup
.constructor.static.titleTooltips
,
6668 accelTooltips
= this.toolGroup
.constructor.static.accelTooltips
,
6669 accel
= this.toolbar
.getToolAccelerator( this.constructor.static.name
),
6672 this.$title
.text( this.title
);
6673 this.$accel
.text( accel
);
6675 if ( titleTooltips
&& typeof this.title
=== 'string' && this.title
.length
) {
6676 tooltipParts
.push( this.title
);
6678 if ( accelTooltips
&& typeof accel
=== 'string' && accel
.length
) {
6679 tooltipParts
.push( accel
);
6681 if ( tooltipParts
.length
) {
6682 this.$link
.attr( 'title', tooltipParts
.join( ' ' ) );
6684 this.$link
.removeAttr( 'title' );
6691 OO
.ui
.Tool
.prototype.destroy = function () {
6692 this.toolbar
.disconnect( this );
6693 this.$element
.remove();
6697 * Collection of tool groups.
6699 * The following is a minimal example using several tools and tool groups.
6702 * // Create the toolbar
6703 * var toolFactory = new OO.ui.ToolFactory();
6704 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
6705 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
6707 * // We will be placing status text in this element when tools are used
6708 * var $area = $( '<p>' ).text( 'Toolbar example' );
6710 * // Define the tools that we're going to place in our toolbar
6712 * // Create a class inheriting from OO.ui.Tool
6713 * function PictureTool() {
6714 * PictureTool.super.apply( this, arguments );
6716 * OO.inheritClass( PictureTool, OO.ui.Tool );
6717 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
6718 * // of 'icon' and 'title' (displayed icon and text).
6719 * PictureTool.static.name = 'picture';
6720 * PictureTool.static.icon = 'picture';
6721 * PictureTool.static.title = 'Insert picture';
6722 * // Defines the action that will happen when this tool is selected (clicked).
6723 * PictureTool.prototype.onSelect = function () {
6724 * $area.text( 'Picture tool clicked!' );
6725 * // Never display this tool as "active" (selected).
6726 * this.setActive( false );
6728 * // Make this tool available in our toolFactory and thus our toolbar
6729 * toolFactory.register( PictureTool );
6731 * // Register two more tools, nothing interesting here
6732 * function SettingsTool() {
6733 * SettingsTool.super.apply( this, arguments );
6735 * OO.inheritClass( SettingsTool, OO.ui.Tool );
6736 * SettingsTool.static.name = 'settings';
6737 * SettingsTool.static.icon = 'settings';
6738 * SettingsTool.static.title = 'Change settings';
6739 * SettingsTool.prototype.onSelect = function () {
6740 * $area.text( 'Settings tool clicked!' );
6741 * this.setActive( false );
6743 * toolFactory.register( SettingsTool );
6745 * // Register two more tools, nothing interesting here
6746 * function StuffTool() {
6747 * StuffTool.super.apply( this, arguments );
6749 * OO.inheritClass( StuffTool, OO.ui.Tool );
6750 * StuffTool.static.name = 'stuff';
6751 * StuffTool.static.icon = 'ellipsis';
6752 * StuffTool.static.title = 'More stuff';
6753 * StuffTool.prototype.onSelect = function () {
6754 * $area.text( 'More stuff tool clicked!' );
6755 * this.setActive( false );
6757 * toolFactory.register( StuffTool );
6759 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
6760 * // little popup window (a PopupWidget).
6761 * function HelpTool( toolGroup, config ) {
6762 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
6767 * this.popup.$body.append( '<p>I am helpful!</p>' );
6769 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
6770 * HelpTool.static.name = 'help';
6771 * HelpTool.static.icon = 'help';
6772 * HelpTool.static.title = 'Help';
6773 * toolFactory.register( HelpTool );
6775 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
6776 * // used once (but not all defined tools must be used).
6779 * // 'bar' tool groups display tools' icons only, side-by-side.
6781 * include: [ 'picture', 'help' ]
6784 * // 'list' tool groups display both the titles and icons, in a dropdown list.
6786 * indicator: 'down',
6788 * include: [ 'settings', 'stuff' ]
6790 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
6791 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
6792 * // since it's more complicated to use. (See the next example snippet on this page.)
6795 * // Create some UI around the toolbar and place it in the document
6796 * var frame = new OO.ui.PanelLayout( {
6800 * var contentFrame = new OO.ui.PanelLayout( {
6804 * frame.$element.append(
6806 * contentFrame.$element.append( $area )
6808 * $( 'body' ).append( frame.$element );
6810 * // Here is where the toolbar is actually built. This must be done after inserting it into the
6812 * toolbar.initialize();
6814 * The following example extends the previous one to illustrate 'menu' tool groups and the usage of
6815 * 'updateState' event.
6818 * // Create the toolbar
6819 * var toolFactory = new OO.ui.ToolFactory();
6820 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
6821 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
6823 * // We will be placing status text in this element when tools are used
6824 * var $area = $( '<p>' ).text( 'Toolbar example' );
6826 * // Define the tools that we're going to place in our toolbar
6828 * // Create a class inheriting from OO.ui.Tool
6829 * function PictureTool() {
6830 * PictureTool.super.apply( this, arguments );
6832 * OO.inheritClass( PictureTool, OO.ui.Tool );
6833 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
6834 * // of 'icon' and 'title' (displayed icon and text).
6835 * PictureTool.static.name = 'picture';
6836 * PictureTool.static.icon = 'picture';
6837 * PictureTool.static.title = 'Insert picture';
6838 * // Defines the action that will happen when this tool is selected (clicked).
6839 * PictureTool.prototype.onSelect = function () {
6840 * $area.text( 'Picture tool clicked!' );
6841 * // Never display this tool as "active" (selected).
6842 * this.setActive( false );
6844 * // The toolbar can be synchronized with the state of some external stuff, like a text
6845 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
6846 * // when the text cursor was inside bolded text). Here we simply disable this feature.
6847 * PictureTool.prototype.onUpdateState = function () {
6849 * // Make this tool available in our toolFactory and thus our toolbar
6850 * toolFactory.register( PictureTool );
6852 * // Register two more tools, nothing interesting here
6853 * function SettingsTool() {
6854 * SettingsTool.super.apply( this, arguments );
6855 * this.reallyActive = false;
6857 * OO.inheritClass( SettingsTool, OO.ui.Tool );
6858 * SettingsTool.static.name = 'settings';
6859 * SettingsTool.static.icon = 'settings';
6860 * SettingsTool.static.title = 'Change settings';
6861 * SettingsTool.prototype.onSelect = function () {
6862 * $area.text( 'Settings tool clicked!' );
6863 * // Toggle the active state on each click
6864 * this.reallyActive = !this.reallyActive;
6865 * this.setActive( this.reallyActive );
6866 * // To update the menu label
6867 * this.toolbar.emit( 'updateState' );
6869 * SettingsTool.prototype.onUpdateState = function () {
6871 * toolFactory.register( SettingsTool );
6873 * // Register two more tools, nothing interesting here
6874 * function StuffTool() {
6875 * StuffTool.super.apply( this, arguments );
6876 * this.reallyActive = false;
6878 * OO.inheritClass( StuffTool, OO.ui.Tool );
6879 * StuffTool.static.name = 'stuff';
6880 * StuffTool.static.icon = 'ellipsis';
6881 * StuffTool.static.title = 'More stuff';
6882 * StuffTool.prototype.onSelect = function () {
6883 * $area.text( 'More stuff tool clicked!' );
6884 * // Toggle the active state on each click
6885 * this.reallyActive = !this.reallyActive;
6886 * this.setActive( this.reallyActive );
6887 * // To update the menu label
6888 * this.toolbar.emit( 'updateState' );
6890 * StuffTool.prototype.onUpdateState = function () {
6892 * toolFactory.register( StuffTool );
6894 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
6895 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
6896 * function HelpTool( toolGroup, config ) {
6897 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
6902 * this.popup.$body.append( '<p>I am helpful!</p>' );
6904 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
6905 * HelpTool.static.name = 'help';
6906 * HelpTool.static.icon = 'help';
6907 * HelpTool.static.title = 'Help';
6908 * toolFactory.register( HelpTool );
6910 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
6911 * // used once (but not all defined tools must be used).
6914 * // 'bar' tool groups display tools' icons only, side-by-side.
6916 * include: [ 'picture', 'help' ]
6919 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
6920 * // Menu label indicates which items are selected.
6922 * indicator: 'down',
6923 * include: [ 'settings', 'stuff' ]
6927 * // Create some UI around the toolbar and place it in the document
6928 * var frame = new OO.ui.PanelLayout( {
6932 * var contentFrame = new OO.ui.PanelLayout( {
6936 * frame.$element.append(
6938 * contentFrame.$element.append( $area )
6940 * $( 'body' ).append( frame.$element );
6942 * // Here is where the toolbar is actually built. This must be done after inserting it into the
6944 * toolbar.initialize();
6945 * toolbar.emit( 'updateState' );
6948 * @extends OO.ui.Element
6949 * @mixins OO.EventEmitter
6950 * @mixins OO.ui.GroupElement
6953 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
6954 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating tool groups
6955 * @param {Object} [config] Configuration options
6956 * @cfg {boolean} [actions] Add an actions section opposite to the tools
6957 * @cfg {boolean} [shadow] Add a shadow below the toolbar
6959 OO
.ui
.Toolbar
= function OoUiToolbar( toolFactory
, toolGroupFactory
, config
) {
6960 // Allow passing positional parameters inside the config object
6961 if ( OO
.isPlainObject( toolFactory
) && config
=== undefined ) {
6962 config
= toolFactory
;
6963 toolFactory
= config
.toolFactory
;
6964 toolGroupFactory
= config
.toolGroupFactory
;
6967 // Configuration initialization
6968 config
= config
|| {};
6970 // Parent constructor
6971 OO
.ui
.Toolbar
.super.call( this, config
);
6973 // Mixin constructors
6974 OO
.EventEmitter
.call( this );
6975 OO
.ui
.GroupElement
.call( this, config
);
6978 this.toolFactory
= toolFactory
;
6979 this.toolGroupFactory
= toolGroupFactory
;
6982 this.$bar
= $( '<div>' );
6983 this.$actions
= $( '<div>' );
6984 this.initialized
= false;
6985 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
6989 .add( this.$bar
).add( this.$group
).add( this.$actions
)
6990 .on( 'mousedown keydown', this.onPointerDown
.bind( this ) );
6993 this.$group
.addClass( 'oo-ui-toolbar-tools' );
6994 if ( config
.actions
) {
6995 this.$bar
.append( this.$actions
.addClass( 'oo-ui-toolbar-actions' ) );
6998 .addClass( 'oo-ui-toolbar-bar' )
6999 .append( this.$group
, '<div style="clear:both"></div>' );
7000 if ( config
.shadow
) {
7001 this.$bar
.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7003 this.$element
.addClass( 'oo-ui-toolbar' ).append( this.$bar
);
7008 OO
.inheritClass( OO
.ui
.Toolbar
, OO
.ui
.Element
);
7009 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.EventEmitter
);
7010 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.ui
.GroupElement
);
7015 * Get the tool factory.
7017 * @return {OO.ui.ToolFactory} Tool factory
7019 OO
.ui
.Toolbar
.prototype.getToolFactory = function () {
7020 return this.toolFactory
;
7024 * Get the tool group factory.
7026 * @return {OO.Factory} Tool group factory
7028 OO
.ui
.Toolbar
.prototype.getToolGroupFactory = function () {
7029 return this.toolGroupFactory
;
7033 * Handles mouse down events.
7035 * @param {jQuery.Event} e Mouse down event
7037 OO
.ui
.Toolbar
.prototype.onPointerDown = function ( e
) {
7038 var $closestWidgetToEvent
= $( e
.target
).closest( '.oo-ui-widget' ),
7039 $closestWidgetToToolbar
= this.$element
.closest( '.oo-ui-widget' );
7040 if ( !$closestWidgetToEvent
.length
|| $closestWidgetToEvent
[ 0 ] === $closestWidgetToToolbar
[ 0 ] ) {
7046 * Handle window resize event.
7049 * @param {jQuery.Event} e Window resize event
7051 OO
.ui
.Toolbar
.prototype.onWindowResize = function () {
7052 this.$element
.toggleClass(
7053 'oo-ui-toolbar-narrow',
7054 this.$bar
.width() <= this.narrowThreshold
7059 * Sets up handles and preloads required information for the toolbar to work.
7060 * This must be called after it is attached to a visible document and before doing anything else.
7062 OO
.ui
.Toolbar
.prototype.initialize = function () {
7063 this.initialized
= true;
7064 this.narrowThreshold
= this.$group
.width() + this.$actions
.width();
7065 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
7066 this.onWindowResize();
7072 * Tools can be specified in the following ways:
7074 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
7075 * - All tools in a group: `{ group: 'group-name' }`
7076 * - All tools: `'*'` - Using this will make the group a list with a "More" label by default
7078 * @param {Object.<string,Array>} groups List of tool group configurations
7079 * @param {Array|string} [groups.include] Tools to include
7080 * @param {Array|string} [groups.exclude] Tools to exclude
7081 * @param {Array|string} [groups.promote] Tools to promote to the beginning
7082 * @param {Array|string} [groups.demote] Tools to demote to the end
7084 OO
.ui
.Toolbar
.prototype.setup = function ( groups
) {
7085 var i
, len
, type
, group
,
7087 defaultType
= 'bar';
7089 // Cleanup previous groups
7092 // Build out new groups
7093 for ( i
= 0, len
= groups
.length
; i
< len
; i
++ ) {
7094 group
= groups
[ i
];
7095 if ( group
.include
=== '*' ) {
7096 // Apply defaults to catch-all groups
7097 if ( group
.type
=== undefined ) {
7098 group
.type
= 'list';
7100 if ( group
.label
=== undefined ) {
7101 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
7104 // Check type has been registered
7105 type
= this.getToolGroupFactory().lookup( group
.type
) ? group
.type
: defaultType
;
7107 this.getToolGroupFactory().create( type
, this, group
)
7110 this.addItems( items
);
7114 * Remove all tools and groups from the toolbar.
7116 OO
.ui
.Toolbar
.prototype.reset = function () {
7121 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7122 this.items
[ i
].destroy();
7128 * Destroys toolbar, removing event handlers and DOM elements.
7130 * Call this whenever you are done using a toolbar.
7132 OO
.ui
.Toolbar
.prototype.destroy = function () {
7133 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
7135 this.$element
.remove();
7139 * Check if tool has not been used yet.
7141 * @param {string} name Symbolic name of tool
7142 * @return {boolean} Tool is available
7144 OO
.ui
.Toolbar
.prototype.isToolAvailable = function ( name
) {
7145 return !this.tools
[ name
];
7149 * Prevent tool from being used again.
7151 * @param {OO.ui.Tool} tool Tool to reserve
7153 OO
.ui
.Toolbar
.prototype.reserveTool = function ( tool
) {
7154 this.tools
[ tool
.getName() ] = tool
;
7158 * Allow tool to be used again.
7160 * @param {OO.ui.Tool} tool Tool to release
7162 OO
.ui
.Toolbar
.prototype.releaseTool = function ( tool
) {
7163 delete this.tools
[ tool
.getName() ];
7167 * Get accelerator label for tool.
7169 * This is a stub that should be overridden to provide access to accelerator information.
7171 * @param {string} name Symbolic name of tool
7172 * @return {string|undefined} Tool accelerator label if available
7174 OO
.ui
.Toolbar
.prototype.getToolAccelerator = function () {
7179 * Collection of tools.
7181 * Tools can be specified in the following ways:
7183 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
7184 * - All tools in a group: `{ group: 'group-name' }`
7185 * - All tools: `'*'`
7189 * @extends OO.ui.Widget
7190 * @mixins OO.ui.GroupElement
7193 * @param {OO.ui.Toolbar} toolbar
7194 * @param {Object} [config] Configuration options
7195 * @cfg {Array|string} [include=[]] List of tools to include
7196 * @cfg {Array|string} [exclude=[]] List of tools to exclude
7197 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning
7198 * @cfg {Array|string} [demote=[]] List of tools to demote to the end
7200 OO
.ui
.ToolGroup
= function OoUiToolGroup( toolbar
, config
) {
7201 // Allow passing positional parameters inside the config object
7202 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
7204 toolbar
= config
.toolbar
;
7207 // Configuration initialization
7208 config
= config
|| {};
7210 // Parent constructor
7211 OO
.ui
.ToolGroup
.super.call( this, config
);
7213 // Mixin constructors
7214 OO
.ui
.GroupElement
.call( this, config
);
7217 this.toolbar
= toolbar
;
7219 this.pressed
= null;
7220 this.autoDisabled
= false;
7221 this.include
= config
.include
|| [];
7222 this.exclude
= config
.exclude
|| [];
7223 this.promote
= config
.promote
|| [];
7224 this.demote
= config
.demote
|| [];
7225 this.onCapturedMouseKeyUpHandler
= this.onCapturedMouseKeyUp
.bind( this );
7229 mousedown
: this.onMouseKeyDown
.bind( this ),
7230 mouseup
: this.onMouseKeyUp
.bind( this ),
7231 keydown
: this.onMouseKeyDown
.bind( this ),
7232 keyup
: this.onMouseKeyUp
.bind( this ),
7233 focus
: this.onMouseOverFocus
.bind( this ),
7234 blur
: this.onMouseOutBlur
.bind( this ),
7235 mouseover
: this.onMouseOverFocus
.bind( this ),
7236 mouseout
: this.onMouseOutBlur
.bind( this )
7238 this.toolbar
.getToolFactory().connect( this, { register
: 'onToolFactoryRegister' } );
7239 this.aggregate( { disable
: 'itemDisable' } );
7240 this.connect( this, { itemDisable
: 'updateDisabled' } );
7243 this.$group
.addClass( 'oo-ui-toolGroup-tools' );
7245 .addClass( 'oo-ui-toolGroup' )
7246 .append( this.$group
);
7252 OO
.inheritClass( OO
.ui
.ToolGroup
, OO
.ui
.Widget
);
7253 OO
.mixinClass( OO
.ui
.ToolGroup
, OO
.ui
.GroupElement
);
7261 /* Static Properties */
7264 * Show labels in tooltips.
7268 * @property {boolean}
7270 OO
.ui
.ToolGroup
.static.titleTooltips
= false;
7273 * Show acceleration labels in tooltips.
7277 * @property {boolean}
7279 OO
.ui
.ToolGroup
.static.accelTooltips
= false;
7282 * Automatically disable the toolgroup when all tools are disabled
7286 * @property {boolean}
7288 OO
.ui
.ToolGroup
.static.autoDisable
= true;
7295 OO
.ui
.ToolGroup
.prototype.isDisabled = function () {
7296 return this.autoDisabled
|| OO
.ui
.ToolGroup
.super.prototype.isDisabled
.apply( this, arguments
);
7302 OO
.ui
.ToolGroup
.prototype.updateDisabled = function () {
7303 var i
, item
, allDisabled
= true;
7305 if ( this.constructor.static.autoDisable
) {
7306 for ( i
= this.items
.length
- 1; i
>= 0; i
-- ) {
7307 item
= this.items
[ i
];
7308 if ( !item
.isDisabled() ) {
7309 allDisabled
= false;
7313 this.autoDisabled
= allDisabled
;
7315 OO
.ui
.ToolGroup
.super.prototype.updateDisabled
.apply( this, arguments
);
7319 * Handle mouse down and key down events.
7321 * @param {jQuery.Event} e Mouse down or key down event
7323 OO
.ui
.ToolGroup
.prototype.onMouseKeyDown = function ( e
) {
7325 !this.isDisabled() &&
7326 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
7328 this.pressed
= this.getTargetTool( e
);
7329 if ( this.pressed
) {
7330 this.pressed
.setActive( true );
7331 this.getElementDocument().addEventListener( 'mouseup', this.onCapturedMouseKeyUpHandler
, true );
7332 this.getElementDocument().addEventListener( 'keyup', this.onCapturedMouseKeyUpHandler
, true );
7339 * Handle captured mouse up and key up events.
7341 * @param {Event} e Mouse up or key up event
7343 OO
.ui
.ToolGroup
.prototype.onCapturedMouseKeyUp = function ( e
) {
7344 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseKeyUpHandler
, true );
7345 this.getElementDocument().removeEventListener( 'keyup', this.onCapturedMouseKeyUpHandler
, true );
7346 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
7347 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
7348 this.onMouseKeyUp( e
);
7352 * Handle mouse up and key up events.
7354 * @param {jQuery.Event} e Mouse up or key up event
7356 OO
.ui
.ToolGroup
.prototype.onMouseKeyUp = function ( e
) {
7357 var tool
= this.getTargetTool( e
);
7360 !this.isDisabled() && this.pressed
&& this.pressed
=== tool
&&
7361 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
7363 this.pressed
.onSelect();
7364 this.pressed
= null;
7368 this.pressed
= null;
7372 * Handle mouse over and focus events.
7374 * @param {jQuery.Event} e Mouse over or focus event
7376 OO
.ui
.ToolGroup
.prototype.onMouseOverFocus = function ( e
) {
7377 var tool
= this.getTargetTool( e
);
7379 if ( this.pressed
&& this.pressed
=== tool
) {
7380 this.pressed
.setActive( true );
7385 * Handle mouse out and blur events.
7387 * @param {jQuery.Event} e Mouse out or blur event
7389 OO
.ui
.ToolGroup
.prototype.onMouseOutBlur = function ( e
) {
7390 var tool
= this.getTargetTool( e
);
7392 if ( this.pressed
&& this.pressed
=== tool
) {
7393 this.pressed
.setActive( false );
7398 * Get the closest tool to a jQuery.Event.
7400 * Only tool links are considered, which prevents other elements in the tool such as popups from
7401 * triggering tool group interactions.
7404 * @param {jQuery.Event} e
7405 * @return {OO.ui.Tool|null} Tool, `null` if none was found
7407 OO
.ui
.ToolGroup
.prototype.getTargetTool = function ( e
) {
7409 $item
= $( e
.target
).closest( '.oo-ui-tool-link' );
7411 if ( $item
.length
) {
7412 tool
= $item
.parent().data( 'oo-ui-tool' );
7415 return tool
&& !tool
.isDisabled() ? tool
: null;
7419 * Handle tool registry register events.
7421 * If a tool is registered after the group is created, we must repopulate the list to account for:
7423 * - a tool being added that may be included
7424 * - a tool already included being overridden
7426 * @param {string} name Symbolic name of tool
7428 OO
.ui
.ToolGroup
.prototype.onToolFactoryRegister = function () {
7433 * Get the toolbar this group is in.
7435 * @return {OO.ui.Toolbar} Toolbar of group
7437 OO
.ui
.ToolGroup
.prototype.getToolbar = function () {
7438 return this.toolbar
;
7442 * Add and remove tools based on configuration.
7444 OO
.ui
.ToolGroup
.prototype.populate = function () {
7445 var i
, len
, name
, tool
,
7446 toolFactory
= this.toolbar
.getToolFactory(),
7450 list
= this.toolbar
.getToolFactory().getTools(
7451 this.include
, this.exclude
, this.promote
, this.demote
7454 // Build a list of needed tools
7455 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
7459 toolFactory
.lookup( name
) &&
7460 // Tool is available or is already in this group
7461 ( this.toolbar
.isToolAvailable( name
) || this.tools
[ name
] )
7463 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
7464 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
7465 this.toolbar
.tools
[ name
] = true;
7466 tool
= this.tools
[ name
];
7468 // Auto-initialize tools on first use
7469 this.tools
[ name
] = tool
= toolFactory
.create( name
, this );
7472 this.toolbar
.reserveTool( tool
);
7474 names
[ name
] = true;
7477 // Remove tools that are no longer needed
7478 for ( name
in this.tools
) {
7479 if ( !names
[ name
] ) {
7480 this.tools
[ name
].destroy();
7481 this.toolbar
.releaseTool( this.tools
[ name
] );
7482 remove
.push( this.tools
[ name
] );
7483 delete this.tools
[ name
];
7486 if ( remove
.length
) {
7487 this.removeItems( remove
);
7489 // Update emptiness state
7491 this.$element
.removeClass( 'oo-ui-toolGroup-empty' );
7493 this.$element
.addClass( 'oo-ui-toolGroup-empty' );
7495 // Re-add tools (moving existing ones to new locations)
7496 this.addItems( add
);
7497 // Disabled state may depend on items
7498 this.updateDisabled();
7502 * Destroy tool group.
7504 OO
.ui
.ToolGroup
.prototype.destroy = function () {
7508 this.toolbar
.getToolFactory().disconnect( this );
7509 for ( name
in this.tools
) {
7510 this.toolbar
.releaseTool( this.tools
[ name
] );
7511 this.tools
[ name
].disconnect( this ).destroy();
7512 delete this.tools
[ name
];
7514 this.$element
.remove();
7518 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
7519 * consists of a header that contains the dialog title, a body with the message, and a footer that
7520 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
7521 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
7523 * There are two basic types of message dialogs, confirmation and alert:
7525 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
7526 * more details about the consequences.
7527 * - **alert**: the dialog title describes which event occurred and the message provides more information
7528 * about why the event occurred.
7530 * The MessageDialog class specifies two actions: ‘accept’, the primary
7531 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
7532 * passing along the selected action.
7534 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
7537 * // Example: Creating and opening a message dialog window.
7538 * var messageDialog = new OO.ui.MessageDialog();
7540 * // Create and append a window manager.
7541 * var windowManager = new OO.ui.WindowManager();
7542 * $( 'body' ).append( windowManager.$element );
7543 * windowManager.addWindows( [ messageDialog ] );
7544 * // Open the window.
7545 * windowManager.openWindow( messageDialog, {
7546 * title: 'Basic message dialog',
7547 * message: 'This is the message'
7550 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
7553 * @extends OO.ui.Dialog
7556 * @param {Object} [config] Configuration options
7558 OO
.ui
.MessageDialog
= function OoUiMessageDialog( config
) {
7559 // Parent constructor
7560 OO
.ui
.MessageDialog
.super.call( this, config
);
7563 this.verticalActionLayout
= null;
7566 this.$element
.addClass( 'oo-ui-messageDialog' );
7571 OO
.inheritClass( OO
.ui
.MessageDialog
, OO
.ui
.Dialog
);
7573 /* Static Properties */
7575 OO
.ui
.MessageDialog
.static.name
= 'message';
7577 OO
.ui
.MessageDialog
.static.size
= 'small';
7579 OO
.ui
.MessageDialog
.static.verbose
= false;
7584 * The title of a confirmation dialog describes what a progressive action will do. The
7585 * title of an alert dialog describes which event occurred.
7589 * @property {jQuery|string|Function|null}
7591 OO
.ui
.MessageDialog
.static.title
= null;
7594 * The message displayed in the dialog body.
7596 * A confirmation message describes the consequences of a progressive action. An alert
7597 * message describes why an event occurred.
7601 * @property {jQuery|string|Function|null}
7603 OO
.ui
.MessageDialog
.static.message
= null;
7605 OO
.ui
.MessageDialog
.static.actions
= [
7606 { action
: 'accept', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-accept' ), flags
: 'primary' },
7607 { action
: 'reject', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-reject' ), flags
: 'safe' }
7615 OO
.ui
.MessageDialog
.prototype.setManager = function ( manager
) {
7616 OO
.ui
.MessageDialog
.super.prototype.setManager
.call( this, manager
);
7619 this.manager
.connect( this, {
7629 OO
.ui
.MessageDialog
.prototype.onActionResize = function ( action
) {
7631 return OO
.ui
.MessageDialog
.super.prototype.onActionResize
.call( this, action
);
7635 * Handle window resized events.
7639 OO
.ui
.MessageDialog
.prototype.onResize = function () {
7641 dialog
.fitActions();
7642 // Wait for CSS transition to finish and do it again :(
7643 setTimeout( function () {
7644 dialog
.fitActions();
7649 * Toggle action layout between vertical and horizontal.
7653 * @param {boolean} [value] Layout actions vertically, omit to toggle
7656 OO
.ui
.MessageDialog
.prototype.toggleVerticalActionLayout = function ( value
) {
7657 value
= value
=== undefined ? !this.verticalActionLayout
: !!value
;
7659 if ( value
!== this.verticalActionLayout
) {
7660 this.verticalActionLayout
= value
;
7662 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value
)
7663 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value
);
7672 OO
.ui
.MessageDialog
.prototype.getActionProcess = function ( action
) {
7674 return new OO
.ui
.Process( function () {
7675 this.close( { action
: action
} );
7678 return OO
.ui
.MessageDialog
.super.prototype.getActionProcess
.call( this, action
);
7684 * @param {Object} [data] Dialog opening data
7685 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
7686 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
7687 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
7688 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
7691 OO
.ui
.MessageDialog
.prototype.getSetupProcess = function ( data
) {
7695 return OO
.ui
.MessageDialog
.super.prototype.getSetupProcess
.call( this, data
)
7696 .next( function () {
7697 this.title
.setLabel(
7698 data
.title
!== undefined ? data
.title
: this.constructor.static.title
7700 this.message
.setLabel(
7701 data
.message
!== undefined ? data
.message
: this.constructor.static.message
7703 this.message
.$element
.toggleClass(
7704 'oo-ui-messageDialog-message-verbose',
7705 data
.verbose
!== undefined ? data
.verbose
: this.constructor.static.verbose
7713 OO
.ui
.MessageDialog
.prototype.getBodyHeight = function () {
7714 var bodyHeight
, oldOverflow
,
7715 $scrollable
= this.container
.$element
;
7717 oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
7718 $scrollable
[ 0 ].style
.overflow
= 'hidden';
7720 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
7722 bodyHeight
= this.text
.$element
.outerHeight( true );
7723 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
7731 OO
.ui
.MessageDialog
.prototype.setDimensions = function ( dim
) {
7732 var $scrollable
= this.container
.$element
;
7733 OO
.ui
.MessageDialog
.super.prototype.setDimensions
.call( this, dim
);
7735 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
7736 // Need to do it after transition completes (250ms), add 50ms just in case.
7737 setTimeout( function () {
7738 var oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
7739 $scrollable
[ 0 ].style
.overflow
= 'hidden';
7741 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
7743 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
7752 OO
.ui
.MessageDialog
.prototype.initialize = function () {
7754 OO
.ui
.MessageDialog
.super.prototype.initialize
.call( this );
7757 this.$actions
= $( '<div>' );
7758 this.container
= new OO
.ui
.PanelLayout( {
7759 scrollable
: true, classes
: [ 'oo-ui-messageDialog-container' ]
7761 this.text
= new OO
.ui
.PanelLayout( {
7762 padded
: true, expanded
: false, classes
: [ 'oo-ui-messageDialog-text' ]
7764 this.message
= new OO
.ui
.LabelWidget( {
7765 classes
: [ 'oo-ui-messageDialog-message' ]
7769 this.title
.$element
.addClass( 'oo-ui-messageDialog-title' );
7770 this.$content
.addClass( 'oo-ui-messageDialog-content' );
7771 this.container
.$element
.append( this.text
.$element
);
7772 this.text
.$element
.append( this.title
.$element
, this.message
.$element
);
7773 this.$body
.append( this.container
.$element
);
7774 this.$actions
.addClass( 'oo-ui-messageDialog-actions' );
7775 this.$foot
.append( this.$actions
);
7781 OO
.ui
.MessageDialog
.prototype.attachActions = function () {
7782 var i
, len
, other
, special
, others
;
7785 OO
.ui
.MessageDialog
.super.prototype.attachActions
.call( this );
7787 special
= this.actions
.getSpecial();
7788 others
= this.actions
.getOthers();
7789 if ( special
.safe
) {
7790 this.$actions
.append( special
.safe
.$element
);
7791 special
.safe
.toggleFramed( false );
7793 if ( others
.length
) {
7794 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
7795 other
= others
[ i
];
7796 this.$actions
.append( other
.$element
);
7797 other
.toggleFramed( false );
7800 if ( special
.primary
) {
7801 this.$actions
.append( special
.primary
.$element
);
7802 special
.primary
.toggleFramed( false );
7805 if ( !this.isOpening() ) {
7806 // If the dialog is currently opening, this will be called automatically soon.
7807 // This also calls #fitActions.
7813 * Fit action actions into columns or rows.
7815 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
7819 OO
.ui
.MessageDialog
.prototype.fitActions = function () {
7821 previous
= this.verticalActionLayout
,
7822 actions
= this.actions
.get();
7825 this.toggleVerticalActionLayout( false );
7826 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
7827 action
= actions
[ i
];
7828 if ( action
.$element
.innerWidth() < action
.$label
.outerWidth( true ) ) {
7829 this.toggleVerticalActionLayout( true );
7834 // Move the body out of the way of the foot
7835 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
7837 if ( this.verticalActionLayout
!== previous
) {
7838 // We changed the layout, window height might need to be updated.
7844 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
7845 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
7846 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
7847 * relevant. The ProcessDialog class is always extended and customized with the actions and content
7848 * required for each process.
7850 * The process dialog box consists of a header that visually represents the ‘working’ state of long
7851 * processes with an animation. The header contains the dialog title as well as
7852 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
7853 * a ‘primary’ action on the right (e.g., ‘Done’).
7855 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
7856 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
7859 * // Example: Creating and opening a process dialog window.
7860 * function MyProcessDialog( config ) {
7861 * MyProcessDialog.super.call( this, config );
7863 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
7865 * MyProcessDialog.static.title = 'Process dialog';
7866 * MyProcessDialog.static.actions = [
7867 * { action: 'save', label: 'Done', flags: 'primary' },
7868 * { label: 'Cancel', flags: 'safe' }
7871 * MyProcessDialog.prototype.initialize = function () {
7872 * MyProcessDialog.super.prototype.initialize.apply( this, arguments );
7873 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
7874 * 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>' );
7875 * this.$body.append( this.content.$element );
7877 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
7878 * var dialog = this;
7880 * return new OO.ui.Process( function () {
7881 * dialog.close( { action: action } );
7884 * return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
7887 * var windowManager = new OO.ui.WindowManager();
7888 * $( 'body' ).append( windowManager.$element );
7890 * var dialog = new MyProcessDialog();
7891 * windowManager.addWindows( [ dialog ] );
7892 * windowManager.openWindow( dialog );
7894 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
7898 * @extends OO.ui.Dialog
7901 * @param {Object} [config] Configuration options
7903 OO
.ui
.ProcessDialog
= function OoUiProcessDialog( config
) {
7904 // Parent constructor
7905 OO
.ui
.ProcessDialog
.super.call( this, config
);
7908 this.$element
.addClass( 'oo-ui-processDialog' );
7913 OO
.inheritClass( OO
.ui
.ProcessDialog
, OO
.ui
.Dialog
);
7918 * Handle dismiss button click events.
7924 OO
.ui
.ProcessDialog
.prototype.onDismissErrorButtonClick = function () {
7929 * Handle retry button click events.
7931 * Hides errors and then tries again.
7935 OO
.ui
.ProcessDialog
.prototype.onRetryButtonClick = function () {
7937 this.executeAction( this.currentAction
);
7943 OO
.ui
.ProcessDialog
.prototype.onActionResize = function ( action
) {
7944 if ( this.actions
.isSpecial( action
) ) {
7947 return OO
.ui
.ProcessDialog
.super.prototype.onActionResize
.call( this, action
);
7953 OO
.ui
.ProcessDialog
.prototype.initialize = function () {
7955 OO
.ui
.ProcessDialog
.super.prototype.initialize
.call( this );
7958 this.$navigation
= $( '<div>' );
7959 this.$location
= $( '<div>' );
7960 this.$safeActions
= $( '<div>' );
7961 this.$primaryActions
= $( '<div>' );
7962 this.$otherActions
= $( '<div>' );
7963 this.dismissButton
= new OO
.ui
.ButtonWidget( {
7964 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' )
7966 this.retryButton
= new OO
.ui
.ButtonWidget();
7967 this.$errors
= $( '<div>' );
7968 this.$errorsTitle
= $( '<div>' );
7971 this.dismissButton
.connect( this, { click
: 'onDismissErrorButtonClick' } );
7972 this.retryButton
.connect( this, { click
: 'onRetryButtonClick' } );
7975 this.title
.$element
.addClass( 'oo-ui-processDialog-title' );
7977 .append( this.title
.$element
)
7978 .addClass( 'oo-ui-processDialog-location' );
7979 this.$safeActions
.addClass( 'oo-ui-processDialog-actions-safe' );
7980 this.$primaryActions
.addClass( 'oo-ui-processDialog-actions-primary' );
7981 this.$otherActions
.addClass( 'oo-ui-processDialog-actions-other' );
7983 .addClass( 'oo-ui-processDialog-errors-title' )
7984 .text( OO
.ui
.msg( 'ooui-dialog-process-error' ) );
7986 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
7987 .append( this.$errorsTitle
, this.dismissButton
.$element
, this.retryButton
.$element
);
7989 .addClass( 'oo-ui-processDialog-content' )
7990 .append( this.$errors
);
7992 .addClass( 'oo-ui-processDialog-navigation' )
7993 .append( this.$safeActions
, this.$location
, this.$primaryActions
);
7994 this.$head
.append( this.$navigation
);
7995 this.$foot
.append( this.$otherActions
);
8001 OO
.ui
.ProcessDialog
.prototype.getActionWidgets = function ( actions
) {
8002 var i
, len
, widgets
= [];
8003 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
8005 new OO
.ui
.ActionWidget( $.extend( { framed
: true }, actions
[ i
] ) )
8014 OO
.ui
.ProcessDialog
.prototype.attachActions = function () {
8015 var i
, len
, other
, special
, others
;
8018 OO
.ui
.ProcessDialog
.super.prototype.attachActions
.call( this );
8020 special
= this.actions
.getSpecial();
8021 others
= this.actions
.getOthers();
8022 if ( special
.primary
) {
8023 this.$primaryActions
.append( special
.primary
.$element
);
8025 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
8026 other
= others
[ i
];
8027 this.$otherActions
.append( other
.$element
);
8029 if ( special
.safe
) {
8030 this.$safeActions
.append( special
.safe
.$element
);
8034 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
8040 OO
.ui
.ProcessDialog
.prototype.executeAction = function ( action
) {
8042 return OO
.ui
.ProcessDialog
.super.prototype.executeAction
.call( this, action
)
8043 .fail( function ( errors
) {
8044 process
.showErrors( errors
|| [] );
8049 * Fit label between actions.
8054 OO
.ui
.ProcessDialog
.prototype.fitLabel = function () {
8055 var width
= Math
.max(
8056 this.$safeActions
.is( ':visible' ) ? this.$safeActions
.width() : 0,
8057 this.$primaryActions
.is( ':visible' ) ? this.$primaryActions
.width() : 0
8059 this.$location
.css( { paddingLeft
: width
, paddingRight
: width
} );
8065 * Handle errors that occurred during accept or reject processes.
8068 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
8070 OO
.ui
.ProcessDialog
.prototype.showErrors = function ( errors
) {
8071 var i
, len
, $item
, actions
,
8077 if ( errors
instanceof OO
.ui
.Error
) {
8078 errors
= [ errors
];
8081 for ( i
= 0, len
= errors
.length
; i
< len
; i
++ ) {
8082 if ( !errors
[ i
].isRecoverable() ) {
8083 recoverable
= false;
8085 if ( errors
[ i
].isWarning() ) {
8088 $item
= $( '<div>' )
8089 .addClass( 'oo-ui-processDialog-error' )
8090 .append( errors
[ i
].getMessage() );
8091 items
.push( $item
[ 0 ] );
8093 this.$errorItems
= $( items
);
8094 if ( recoverable
) {
8095 abilities
[this.currentAction
] = true;
8096 // Copy the flags from the first matching action
8097 actions
= this.actions
.get( { actions
: this.currentAction
} );
8098 if ( actions
.length
) {
8099 this.retryButton
.clearFlags().setFlags( actions
[0].getFlags() );
8102 abilities
[this.currentAction
] = false;
8103 this.actions
.setAbilities( abilities
);
8106 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-continue' ) );
8108 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-retry' ) );
8110 this.retryButton
.toggle( recoverable
);
8111 this.$errorsTitle
.after( this.$errorItems
);
8112 this.$errors
.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
8120 OO
.ui
.ProcessDialog
.prototype.hideErrors = function () {
8121 this.$errors
.addClass( 'oo-ui-element-hidden' );
8122 if ( this.$errorItems
) {
8123 this.$errorItems
.remove();
8124 this.$errorItems
= null;
8131 OO
.ui
.ProcessDialog
.prototype.getTeardownProcess = function ( data
) {
8133 return OO
.ui
.ProcessDialog
.super.prototype.getTeardownProcess
.call( this, data
)
8134 .first( function () {
8135 // Make sure to hide errors
8141 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8142 * which is a widget that is specified by reference before any optional configuration settings.
8144 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8146 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8147 * A left-alignment is used for forms with many fields.
8148 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8149 * A right-alignment is used for long but familiar forms which users tab through,
8150 * verifying the current field with a quick glance at the label.
8151 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8152 * that users fill out from top to bottom.
8153 * - **inline**: The label is placed after the field-widget and aligned to the left.
8154 * An inline-alignment is best used with checkboxes or radio buttons.
8156 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
8157 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
8159 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8161 * @extends OO.ui.Layout
8162 * @mixins OO.ui.LabelElement
8165 * @param {OO.ui.Widget} fieldWidget Field widget
8166 * @param {Object} [config] Configuration options
8167 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8168 * @cfg {string} [help] Help text. When help text is specified, a help icon will appear
8169 * in the upper-right corner of the rendered field.
8171 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
8172 // Allow passing positional parameters inside the config object
8173 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
8174 config
= fieldWidget
;
8175 fieldWidget
= config
.fieldWidget
;
8178 var hasInputWidget
= fieldWidget
instanceof OO
.ui
.InputWidget
;
8180 // Configuration initialization
8181 config
= $.extend( { align
: 'left' }, config
);
8183 // Parent constructor
8184 OO
.ui
.FieldLayout
.super.call( this, config
);
8186 // Mixin constructors
8187 OO
.ui
.LabelElement
.call( this, config
);
8190 this.fieldWidget
= fieldWidget
;
8191 this.$field
= $( '<div>' );
8192 this.$body
= $( '<' + ( hasInputWidget
? 'label' : 'div' ) + '>' );
8194 if ( config
.help
) {
8195 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
8196 classes
: [ 'oo-ui-fieldLayout-help' ],
8201 this.popupButtonWidget
.getPopup().$body
.append(
8203 .text( config
.help
)
8204 .addClass( 'oo-ui-fieldLayout-help-content' )
8206 this.$help
= this.popupButtonWidget
.$element
;
8208 this.$help
= $( [] );
8212 if ( hasInputWidget
) {
8213 this.$label
.on( 'click', this.onLabelClick
.bind( this ) );
8215 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
8219 .addClass( 'oo-ui-fieldLayout' )
8220 .append( this.$help
, this.$body
);
8221 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
8223 .addClass( 'oo-ui-fieldLayout-field' )
8224 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget
.isDisabled() )
8225 .append( this.fieldWidget
.$element
);
8227 this.setAlignment( config
.align
);
8232 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
8233 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.LabelElement
);
8238 * Handle field disable events.
8241 * @param {boolean} value Field is disabled
8243 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
8244 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
8248 * Handle label mouse click events.
8251 * @param {jQuery.Event} e Mouse click event
8253 OO
.ui
.FieldLayout
.prototype.onLabelClick = function () {
8254 this.fieldWidget
.simulateLabelClick();
8259 * Get the widget contained by the field.
8261 * @return {OO.ui.Widget} Field widget
8263 OO
.ui
.FieldLayout
.prototype.getField = function () {
8264 return this.fieldWidget
;
8268 * Set the field alignment mode.
8271 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
8274 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
8275 if ( value
!== this.align
) {
8276 // Default to 'left'
8277 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
8281 if ( value
=== 'inline' ) {
8282 this.$body
.append( this.$field
, this.$label
);
8284 this.$body
.append( this.$label
, this.$field
);
8286 // Set classes. The following classes can be used here:
8287 // * oo-ui-fieldLayout-align-left
8288 // * oo-ui-fieldLayout-align-right
8289 // * oo-ui-fieldLayout-align-top
8290 // * oo-ui-fieldLayout-align-inline
8292 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
8294 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
8302 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
8303 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
8304 * is required and is specified before any optional configuration settings.
8306 * Labels can be aligned in one of four ways:
8308 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8309 * A left-alignment is used for forms with many fields.
8310 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8311 * A right-alignment is used for long but familiar forms which users tab through,
8312 * verifying the current field with a quick glance at the label.
8313 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8314 * that users fill out from top to bottom.
8315 * - **inline**: The label is placed after the field-widget and aligned to the left.
8316 * An inline-alignment is best used with checkboxes or radio buttons.
8318 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
8319 * text is specified.
8322 * // Example of an ActionFieldLayout
8323 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
8324 * new OO.ui.TextInputWidget( {
8325 * placeholder: 'Field widget'
8327 * new OO.ui.ButtonWidget( {
8331 * label: 'An ActionFieldLayout. This label is aligned top',
8333 * help: 'This is help text'
8337 * $( 'body' ).append( actionFieldLayout.$element );
8341 * @extends OO.ui.FieldLayout
8344 * @param {OO.ui.Widget} fieldWidget Field widget
8345 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
8346 * @param {Object} [config] Configuration options
8347 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8348 * @cfg {string} [help] Help text. When help text is specified, a help icon will appear in the
8349 * upper-right corner of the rendered field.
8351 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
8352 // Allow passing positional parameters inside the config object
8353 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
8354 config
= fieldWidget
;
8355 fieldWidget
= config
.fieldWidget
;
8356 buttonWidget
= config
.buttonWidget
;
8359 // Configuration initialization
8360 config
= $.extend( { align
: 'left' }, config
);
8362 // Parent constructor
8363 OO
.ui
.ActionFieldLayout
.super.call( this, fieldWidget
, config
);
8366 this.fieldWidget
= fieldWidget
;
8367 this.buttonWidget
= buttonWidget
;
8368 this.$button
= $( '<div>' )
8369 .addClass( 'oo-ui-actionFieldLayout-button' )
8370 .append( this.buttonWidget
.$element
);
8371 this.$input
= $( '<div>' )
8372 .addClass( 'oo-ui-actionFieldLayout-input' )
8373 .append( this.fieldWidget
.$element
);
8375 .addClass( 'oo-ui-actionFieldLayout' )
8376 .append( this.$input
, this.$button
);
8381 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
8384 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
8385 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
8386 * configured with a label as well. For more information and examples,
8387 * please see the [OOjs UI documentation on MediaWiki][1].
8390 * // Example of a fieldset layout
8391 * var input1 = new OO.ui.TextInputWidget( {
8392 * placeholder: 'A text input field'
8395 * var input2 = new OO.ui.TextInputWidget( {
8396 * placeholder: 'A text input field'
8399 * var fieldset = new OO.ui.FieldsetLayout( {
8400 * label: 'Example of a fieldset layout'
8403 * fieldset.addItems( [
8404 * new OO.ui.FieldLayout( input1, {
8405 * label: 'Field One'
8407 * new OO.ui.FieldLayout( input2, {
8408 * label: 'Field Two'
8411 * $( 'body' ).append( fieldset.$element );
8413 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8416 * @extends OO.ui.Layout
8417 * @mixins OO.ui.IconElement
8418 * @mixins OO.ui.LabelElement
8419 * @mixins OO.ui.GroupElement
8422 * @param {Object} [config] Configuration options
8423 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
8425 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
8426 // Configuration initialization
8427 config
= config
|| {};
8429 // Parent constructor
8430 OO
.ui
.FieldsetLayout
.super.call( this, config
);
8432 // Mixin constructors
8433 OO
.ui
.IconElement
.call( this, config
);
8434 OO
.ui
.LabelElement
.call( this, config
);
8435 OO
.ui
.GroupElement
.call( this, config
);
8437 if ( config
.help
) {
8438 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
8439 classes
: [ 'oo-ui-fieldsetLayout-help' ],
8444 this.popupButtonWidget
.getPopup().$body
.append(
8446 .text( config
.help
)
8447 .addClass( 'oo-ui-fieldsetLayout-help-content' )
8449 this.$help
= this.popupButtonWidget
.$element
;
8451 this.$help
= $( [] );
8456 .addClass( 'oo-ui-fieldsetLayout' )
8457 .prepend( this.$help
, this.$icon
, this.$label
, this.$group
);
8458 if ( Array
.isArray( config
.items
) ) {
8459 this.addItems( config
.items
);
8465 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
8466 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.IconElement
);
8467 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.LabelElement
);
8468 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.GroupElement
);
8471 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
8472 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
8473 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
8474 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
8476 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
8477 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
8478 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
8479 * some fancier controls. Some controls have both regular and InputWidget variants, for example
8480 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
8481 * often have simplified APIs to match the capabilities of HTML forms.
8482 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
8484 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
8485 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8488 * // Example of a form layout that wraps a fieldset layout
8489 * var input1 = new OO.ui.TextInputWidget( {
8490 * placeholder: 'Username'
8492 * var input2 = new OO.ui.TextInputWidget( {
8493 * placeholder: 'Password',
8496 * var submit = new OO.ui.ButtonInputWidget( {
8500 * var fieldset = new OO.ui.FieldsetLayout( {
8501 * label: 'A form layout'
8503 * fieldset.addItems( [
8504 * new OO.ui.FieldLayout( input1, {
8505 * label: 'Username',
8508 * new OO.ui.FieldLayout( input2, {
8509 * label: 'Password',
8512 * new OO.ui.FieldLayout( submit )
8514 * var form = new OO.ui.FormLayout( {
8515 * items: [ fieldset ],
8516 * action: '/api/formhandler',
8519 * $( 'body' ).append( form.$element );
8522 * @extends OO.ui.Layout
8523 * @mixins OO.ui.GroupElement
8526 * @param {Object} [config] Configuration options
8527 * @cfg {string} [method] HTML form `method` attribute
8528 * @cfg {string} [action] HTML form `action` attribute
8529 * @cfg {string} [enctype] HTML form `enctype` attribute
8530 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
8532 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
8533 // Configuration initialization
8534 config
= config
|| {};
8536 // Parent constructor
8537 OO
.ui
.FormLayout
.super.call( this, config
);
8539 // Mixin constructors
8540 OO
.ui
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
8543 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
8547 .addClass( 'oo-ui-formLayout' )
8549 method
: config
.method
,
8550 action
: config
.action
,
8551 enctype
: config
.enctype
8553 if ( Array
.isArray( config
.items
) ) {
8554 this.addItems( config
.items
);
8560 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
8561 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.GroupElement
);
8566 * A 'submit' event is emitted when the form is submitted.
8571 /* Static Properties */
8573 OO
.ui
.FormLayout
.static.tagName
= 'form';
8578 * Handle form submit events.
8581 * @param {jQuery.Event} e Submit event
8584 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
8585 if ( this.emit( 'submit' ) ) {
8591 * 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)
8592 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
8595 * var menuLayout = new OO.ui.MenuLayout( {
8598 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
8599 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
8600 * select = new OO.ui.SelectWidget( {
8602 * new OO.ui.OptionWidget( {
8606 * new OO.ui.OptionWidget( {
8610 * new OO.ui.OptionWidget( {
8614 * new OO.ui.OptionWidget( {
8619 * } ).on( 'select', function ( item ) {
8620 * menuLayout.setMenuPosition( item.getData() );
8623 * menuLayout.$menu.append(
8624 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
8626 * menuLayout.$content.append(
8627 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
8629 * $( 'body' ).append( menuLayout.$element );
8631 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
8632 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
8633 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
8636 * .oo-ui-menuLayout-menu {
8640 * .oo-ui-menuLayout-content {
8648 * @extends OO.ui.Layout
8651 * @param {Object} [config] Configuration options
8652 * @cfg {boolean} [showMenu=true] Show menu
8653 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
8655 OO
.ui
.MenuLayout
= function OoUiMenuLayout( config
) {
8656 // Configuration initialization
8657 config
= $.extend( {
8659 menuPosition
: 'before'
8662 // Parent constructor
8663 OO
.ui
.MenuLayout
.super.call( this, config
);
8668 * @property {jQuery}
8670 this.$menu
= $( '<div>' );
8674 * @property {jQuery}
8676 this.$content
= $( '<div>' );
8680 .addClass( 'oo-ui-menuLayout-menu' );
8681 this.$content
.addClass( 'oo-ui-menuLayout-content' );
8683 .addClass( 'oo-ui-menuLayout' )
8684 .append( this.$content
, this.$menu
);
8685 this.setMenuPosition( config
.menuPosition
);
8686 this.toggleMenu( config
.showMenu
);
8691 OO
.inheritClass( OO
.ui
.MenuLayout
, OO
.ui
.Layout
);
8698 * @param {boolean} showMenu Show menu, omit to toggle
8701 OO
.ui
.MenuLayout
.prototype.toggleMenu = function ( showMenu
) {
8702 showMenu
= showMenu
=== undefined ? !this.showMenu
: !!showMenu
;
8704 if ( this.showMenu
!== showMenu
) {
8705 this.showMenu
= showMenu
;
8707 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu
)
8708 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu
);
8715 * Check if menu is visible
8717 * @return {boolean} Menu is visible
8719 OO
.ui
.MenuLayout
.prototype.isMenuVisible = function () {
8720 return this.showMenu
;
8724 * Set menu position.
8726 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
8727 * @throws {Error} If position value is not supported
8730 OO
.ui
.MenuLayout
.prototype.setMenuPosition = function ( position
) {
8731 this.$element
.removeClass( 'oo-ui-menuLayout-' + this.menuPosition
);
8732 this.menuPosition
= position
;
8733 this.$element
.addClass( 'oo-ui-menuLayout-' + position
);
8739 * Get menu position.
8741 * @return {string} Menu position
8743 OO
.ui
.MenuLayout
.prototype.getMenuPosition = function () {
8744 return this.menuPosition
;
8748 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
8749 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
8750 * through the pages and select which one to display. By default, only one page is
8751 * displayed at a time and the outline is hidden. When a user navigates to a new page,
8752 * the booklet layout automatically focuses on the first focusable element, unless the
8753 * default setting is changed. Optionally, booklets can be configured to show
8754 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
8757 * // Example of a BookletLayout that contains two PageLayouts.
8759 * function PageOneLayout( name, config ) {
8760 * PageOneLayout.super.call( this, name, config );
8761 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
8763 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
8764 * PageOneLayout.prototype.setupOutlineItem = function () {
8765 * this.outlineItem.setLabel( 'Page One' );
8768 * function PageTwoLayout( name, config ) {
8769 * PageTwoLayout.super.call( this, name, config );
8770 * this.$element.append( '<p>Second page</p>' );
8772 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
8773 * PageTwoLayout.prototype.setupOutlineItem = function () {
8774 * this.outlineItem.setLabel( 'Page Two' );
8777 * var page1 = new PageOneLayout( 'one' ),
8778 * page2 = new PageTwoLayout( 'two' );
8780 * var booklet = new OO.ui.BookletLayout( {
8784 * booklet.addPages ( [ page1, page2 ] );
8785 * $( 'body' ).append( booklet.$element );
8788 * @extends OO.ui.MenuLayout
8791 * @param {Object} [config] Configuration options
8792 * @cfg {boolean} [continuous=false] Show all pages, one after another
8793 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
8794 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
8795 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
8797 OO
.ui
.BookletLayout
= function OoUiBookletLayout( config
) {
8798 // Configuration initialization
8799 config
= config
|| {};
8801 // Parent constructor
8802 OO
.ui
.BookletLayout
.super.call( this, config
);
8805 this.currentPageName
= null;
8807 this.ignoreFocus
= false;
8808 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
8809 this.$content
.append( this.stackLayout
.$element
);
8810 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
8811 this.outlineVisible
= false;
8812 this.outlined
= !!config
.outlined
;
8813 if ( this.outlined
) {
8814 this.editable
= !!config
.editable
;
8815 this.outlineControlsWidget
= null;
8816 this.outlineSelectWidget
= new OO
.ui
.OutlineSelectWidget();
8817 this.outlinePanel
= new OO
.ui
.PanelLayout( { scrollable
: true } );
8818 this.$menu
.append( this.outlinePanel
.$element
);
8819 this.outlineVisible
= true;
8820 if ( this.editable
) {
8821 this.outlineControlsWidget
= new OO
.ui
.OutlineControlsWidget(
8822 this.outlineSelectWidget
8826 this.toggleMenu( this.outlined
);
8829 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
8830 if ( this.outlined
) {
8831 this.outlineSelectWidget
.connect( this, { select
: 'onOutlineSelectWidgetSelect' } );
8833 if ( this.autoFocus
) {
8834 // Event 'focus' does not bubble, but 'focusin' does
8835 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
8839 this.$element
.addClass( 'oo-ui-bookletLayout' );
8840 this.stackLayout
.$element
.addClass( 'oo-ui-bookletLayout-stackLayout' );
8841 if ( this.outlined
) {
8842 this.outlinePanel
.$element
8843 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
8844 .append( this.outlineSelectWidget
.$element
);
8845 if ( this.editable
) {
8846 this.outlinePanel
.$element
8847 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
8848 .append( this.outlineControlsWidget
.$element
);
8855 OO
.inheritClass( OO
.ui
.BookletLayout
, OO
.ui
.MenuLayout
);
8860 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
8862 * @param {OO.ui.PageLayout} page Current page
8866 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
8869 * @param {OO.ui.PageLayout[]} page Added pages
8870 * @param {number} index Index pages were added at
8874 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
8875 * {@link #removePages removed} from the booklet.
8878 * @param {OO.ui.PageLayout[]} pages Removed pages
8884 * Handle stack layout focus.
8887 * @param {jQuery.Event} e Focusin event
8889 OO
.ui
.BookletLayout
.prototype.onStackLayoutFocus = function ( e
) {
8892 // Find the page that an element was focused within
8893 $target
= $( e
.target
).closest( '.oo-ui-pageLayout' );
8894 for ( name
in this.pages
) {
8895 // Check for page match, exclude current page to find only page changes
8896 if ( this.pages
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentPageName
) {
8897 this.setPage( name
);
8904 * Handle stack layout set events.
8907 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
8909 OO
.ui
.BookletLayout
.prototype.onStackLayoutSet = function ( page
) {
8912 page
.scrollElementIntoView( { complete: function () {
8913 if ( layout
.autoFocus
) {
8921 * Focus the first input in the current page.
8923 * If no page is selected, the first selectable page will be selected.
8924 * If the focus is already in an element on the current page, nothing will happen.
8925 * @param {number} [itemIndex] A specific item to focus on
8927 OO
.ui
.BookletLayout
.prototype.focus = function ( itemIndex
) {
8929 items
= this.stackLayout
.getItems();
8931 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
8932 page
= items
[ itemIndex
];
8934 page
= this.stackLayout
.getCurrentItem();
8937 if ( !page
&& this.outlined
) {
8938 this.selectFirstSelectablePage();
8939 page
= this.stackLayout
.getCurrentItem();
8944 // Only change the focus if is not already in the current page
8945 if ( !page
.$element
.find( ':focus' ).length
) {
8946 $input
= page
.$element
.find( ':input:first' );
8947 if ( $input
.length
) {
8948 $input
[ 0 ].focus();
8954 * Find the first focusable input in the booklet layout and focus
8957 OO
.ui
.BookletLayout
.prototype.focusFirstFocusable = function () {
8960 items
= this.stackLayout
.getItems(),
8961 checkAndFocus = function () {
8962 if ( OO
.ui
.isFocusableElement( $( this ) ) ) {
8969 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
8973 // Find all potentially focusable elements in the item
8974 // and check if they are focusable
8976 .find( 'input, select, textarea, button, object' )
8977 /* jshint loopfunc:true */
8978 .each( checkAndFocus
);
8983 * Handle outline widget select events.
8986 * @param {OO.ui.OptionWidget|null} item Selected item
8988 OO
.ui
.BookletLayout
.prototype.onOutlineSelectWidgetSelect = function ( item
) {
8990 this.setPage( item
.getData() );
8995 * Check if booklet has an outline.
8997 * @return {boolean} Booklet has an outline
8999 OO
.ui
.BookletLayout
.prototype.isOutlined = function () {
9000 return this.outlined
;
9004 * Check if booklet has editing controls.
9006 * @return {boolean} Booklet is editable
9008 OO
.ui
.BookletLayout
.prototype.isEditable = function () {
9009 return this.editable
;
9013 * Check if booklet has a visible outline.
9015 * @return {boolean} Outline is visible
9017 OO
.ui
.BookletLayout
.prototype.isOutlineVisible = function () {
9018 return this.outlined
&& this.outlineVisible
;
9022 * Hide or show the outline.
9024 * @param {boolean} [show] Show outline, omit to invert current state
9027 OO
.ui
.BookletLayout
.prototype.toggleOutline = function ( show
) {
9028 if ( this.outlined
) {
9029 show
= show
=== undefined ? !this.outlineVisible
: !!show
;
9030 this.outlineVisible
= show
;
9031 this.toggleMenu( show
);
9038 * Get the page closest to the specified page.
9040 * @param {OO.ui.PageLayout} page Page to use as a reference point
9041 * @return {OO.ui.PageLayout|null} Page closest to the specified page
9043 OO
.ui
.BookletLayout
.prototype.getClosestPage = function ( page
) {
9044 var next
, prev
, level
,
9045 pages
= this.stackLayout
.getItems(),
9046 index
= $.inArray( page
, pages
);
9048 if ( index
!== -1 ) {
9049 next
= pages
[ index
+ 1 ];
9050 prev
= pages
[ index
- 1 ];
9051 // Prefer adjacent pages at the same level
9052 if ( this.outlined
) {
9053 level
= this.outlineSelectWidget
.getItemFromData( page
.getName() ).getLevel();
9056 level
=== this.outlineSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
9062 level
=== this.outlineSelectWidget
.getItemFromData( next
.getName() ).getLevel()
9068 return prev
|| next
|| null;
9072 * Get the outline widget.
9074 * If the booklet is not outlined, the method will return `null`.
9076 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
9078 OO
.ui
.BookletLayout
.prototype.getOutline = function () {
9079 return this.outlineSelectWidget
;
9083 * Get the outline controls widget.
9085 * If the outline is not editable, the method will return `null`.
9087 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
9089 OO
.ui
.BookletLayout
.prototype.getOutlineControls = function () {
9090 return this.outlineControlsWidget
;
9094 * Get a page by its symbolic name.
9096 * @param {string} name Symbolic name of page
9097 * @return {OO.ui.PageLayout|undefined} Page, if found
9099 OO
.ui
.BookletLayout
.prototype.getPage = function ( name
) {
9100 return this.pages
[ name
];
9104 * Get the current page.
9106 * @return {OO.ui.PageLayout|undefined} Current page, if found
9108 OO
.ui
.BookletLayout
.prototype.getCurrentPage = function () {
9109 var name
= this.getCurrentPageName();
9110 return name
? this.getPage( name
) : undefined;
9114 * Get the symbolic name of the current page.
9116 * @return {string|null} Symbolic name of the current page
9118 OO
.ui
.BookletLayout
.prototype.getCurrentPageName = function () {
9119 return this.currentPageName
;
9123 * Add pages to the booklet layout
9125 * When pages are added with the same names as existing pages, the existing pages will be
9126 * automatically removed before the new pages are added.
9128 * @param {OO.ui.PageLayout[]} pages Pages to add
9129 * @param {number} index Index of the insertion point
9133 OO
.ui
.BookletLayout
.prototype.addPages = function ( pages
, index
) {
9134 var i
, len
, name
, page
, item
, currentIndex
,
9135 stackLayoutPages
= this.stackLayout
.getItems(),
9139 // Remove pages with same names
9140 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9142 name
= page
.getName();
9144 if ( Object
.prototype.hasOwnProperty
.call( this.pages
, name
) ) {
9145 // Correct the insertion index
9146 currentIndex
= $.inArray( this.pages
[ name
], stackLayoutPages
);
9147 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
9150 remove
.push( this.pages
[ name
] );
9153 if ( remove
.length
) {
9154 this.removePages( remove
);
9158 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9160 name
= page
.getName();
9161 this.pages
[ page
.getName() ] = page
;
9162 if ( this.outlined
) {
9163 item
= new OO
.ui
.OutlineOptionWidget( { data
: name
} );
9164 page
.setOutlineItem( item
);
9169 if ( this.outlined
&& items
.length
) {
9170 this.outlineSelectWidget
.addItems( items
, index
);
9171 this.selectFirstSelectablePage();
9173 this.stackLayout
.addItems( pages
, index
);
9174 this.emit( 'add', pages
, index
);
9180 * Remove the specified pages from the booklet layout.
9182 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
9184 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
9188 OO
.ui
.BookletLayout
.prototype.removePages = function ( pages
) {
9189 var i
, len
, name
, page
,
9192 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9194 name
= page
.getName();
9195 delete this.pages
[ name
];
9196 if ( this.outlined
) {
9197 items
.push( this.outlineSelectWidget
.getItemFromData( name
) );
9198 page
.setOutlineItem( null );
9201 if ( this.outlined
&& items
.length
) {
9202 this.outlineSelectWidget
.removeItems( items
);
9203 this.selectFirstSelectablePage();
9205 this.stackLayout
.removeItems( pages
);
9206 this.emit( 'remove', pages
);
9212 * Clear all pages from the booklet layout.
9214 * To remove only a subset of pages from the booklet, use the #removePages method.
9219 OO
.ui
.BookletLayout
.prototype.clearPages = function () {
9221 pages
= this.stackLayout
.getItems();
9224 this.currentPageName
= null;
9225 if ( this.outlined
) {
9226 this.outlineSelectWidget
.clearItems();
9227 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9228 pages
[ i
].setOutlineItem( null );
9231 this.stackLayout
.clearItems();
9233 this.emit( 'remove', pages
);
9239 * Set the current page by symbolic name.
9242 * @param {string} name Symbolic name of page
9244 OO
.ui
.BookletLayout
.prototype.setPage = function ( name
) {
9247 page
= this.pages
[ name
];
9249 if ( name
!== this.currentPageName
) {
9250 if ( this.outlined
) {
9251 selectedItem
= this.outlineSelectWidget
.getSelectedItem();
9252 if ( selectedItem
&& selectedItem
.getData() !== name
) {
9253 this.outlineSelectWidget
.selectItemByData( name
);
9257 if ( this.currentPageName
&& this.pages
[ this.currentPageName
] ) {
9258 this.pages
[ this.currentPageName
].setActive( false );
9259 // Blur anything focused if the next page doesn't have anything focusable - this
9260 // is not needed if the next page has something focusable because once it is focused
9261 // this blur happens automatically
9262 if ( this.autoFocus
&& !page
.$element
.find( ':input' ).length
) {
9263 $focused
= this.pages
[ this.currentPageName
].$element
.find( ':focus' );
9264 if ( $focused
.length
) {
9265 $focused
[ 0 ].blur();
9269 this.currentPageName
= name
;
9270 this.stackLayout
.setItem( page
);
9271 page
.setActive( true );
9272 this.emit( 'set', page
);
9278 * Select the first selectable page.
9282 OO
.ui
.BookletLayout
.prototype.selectFirstSelectablePage = function () {
9283 if ( !this.outlineSelectWidget
.getSelectedItem() ) {
9284 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getFirstSelectableItem() );
9291 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
9292 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
9293 * select which one to display. By default, only one card is displayed at a time. When a user
9294 * navigates to a new card, the index layout automatically focuses on the first focusable element,
9295 * unless the default setting is changed.
9297 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
9300 * // Example of a IndexLayout that contains two CardLayouts.
9302 * function CardOneLayout( name, config ) {
9303 * CardOneLayout.super.call( this, name, config );
9304 * this.$element.append( '<p>First card</p>' );
9306 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
9307 * CardOneLayout.prototype.setupTabItem = function () {
9308 * this.tabItem.setLabel( 'Card One' );
9311 * function CardTwoLayout( name, config ) {
9312 * CardTwoLayout.super.call( this, name, config );
9313 * this.$element.append( '<p>Second card</p>' );
9315 * OO.inheritClass( CardTwoLayout, OO.ui.CardLayout );
9316 * CardTwoLayout.prototype.setupTabItem = function () {
9317 * this.tabItem.setLabel( 'Card Two' );
9320 * var card1 = new CardOneLayout( 'one' ),
9321 * card2 = new CardTwoLayout( 'two' );
9323 * var index = new OO.ui.IndexLayout();
9325 * index.addCards ( [ card1, card2 ] );
9326 * $( 'body' ).append( index.$element );
9329 * @extends OO.ui.MenuLayout
9332 * @param {Object} [config] Configuration options
9333 * @cfg {boolean} [continuous=false] Show all cards, one after another
9334 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
9336 OO
.ui
.IndexLayout
= function OoUiIndexLayout( config
) {
9337 // Configuration initialization
9338 config
= $.extend( {}, config
, { menuPosition
: 'top' } );
9340 // Parent constructor
9341 OO
.ui
.IndexLayout
.super.call( this, config
);
9344 this.currentCardName
= null;
9346 this.ignoreFocus
= false;
9347 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
9348 this.$content
.append( this.stackLayout
.$element
);
9349 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
9351 this.tabSelectWidget
= new OO
.ui
.TabSelectWidget();
9352 this.tabPanel
= new OO
.ui
.PanelLayout();
9353 this.$menu
.append( this.tabPanel
.$element
);
9355 this.toggleMenu( true );
9358 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
9359 this.tabSelectWidget
.connect( this, { select
: 'onTabSelectWidgetSelect' } );
9360 if ( this.autoFocus
) {
9361 // Event 'focus' does not bubble, but 'focusin' does
9362 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
9366 this.$element
.addClass( 'oo-ui-indexLayout' );
9367 this.stackLayout
.$element
.addClass( 'oo-ui-indexLayout-stackLayout' );
9368 this.tabPanel
.$element
9369 .addClass( 'oo-ui-indexLayout-tabPanel' )
9370 .append( this.tabSelectWidget
.$element
);
9375 OO
.inheritClass( OO
.ui
.IndexLayout
, OO
.ui
.MenuLayout
);
9380 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
9382 * @param {OO.ui.CardLayout} card Current card
9386 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
9389 * @param {OO.ui.CardLayout[]} card Added cards
9390 * @param {number} index Index cards were added at
9394 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
9395 * {@link #removeCards removed} from the index.
9398 * @param {OO.ui.CardLayout[]} cards Removed cards
9404 * Handle stack layout focus.
9407 * @param {jQuery.Event} e Focusin event
9409 OO
.ui
.IndexLayout
.prototype.onStackLayoutFocus = function ( e
) {
9412 // Find the card that an element was focused within
9413 $target
= $( e
.target
).closest( '.oo-ui-cardLayout' );
9414 for ( name
in this.cards
) {
9415 // Check for card match, exclude current card to find only card changes
9416 if ( this.cards
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentCardName
) {
9417 this.setCard( name
);
9424 * Handle stack layout set events.
9427 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
9429 OO
.ui
.IndexLayout
.prototype.onStackLayoutSet = function ( card
) {
9432 card
.scrollElementIntoView( { complete: function () {
9433 if ( layout
.autoFocus
) {
9441 * Focus the first input in the current card.
9443 * If no card is selected, the first selectable card will be selected.
9444 * If the focus is already in an element on the current card, nothing will happen.
9445 * @param {number} [itemIndex] A specific item to focus on
9447 OO
.ui
.IndexLayout
.prototype.focus = function ( itemIndex
) {
9449 items
= this.stackLayout
.getItems();
9451 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
9452 card
= items
[ itemIndex
];
9454 card
= this.stackLayout
.getCurrentItem();
9458 this.selectFirstSelectableCard();
9459 card
= this.stackLayout
.getCurrentItem();
9464 // Only change the focus if is not already in the current card
9465 if ( !card
.$element
.find( ':focus' ).length
) {
9466 $input
= card
.$element
.find( ':input:first' );
9467 if ( $input
.length
) {
9468 $input
[ 0 ].focus();
9474 * Find the first focusable input in the index layout and focus
9477 OO
.ui
.IndexLayout
.prototype.focusFirstFocusable = function () {
9480 items
= this.stackLayout
.getItems(),
9481 checkAndFocus = function () {
9482 if ( OO
.ui
.isFocusableElement( $( this ) ) ) {
9489 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
9493 // Find all potentially focusable elements in the item
9494 // and check if they are focusable
9496 .find( 'input, select, textarea, button, object' )
9497 .each( checkAndFocus
);
9502 * Handle tab widget select events.
9505 * @param {OO.ui.OptionWidget|null} item Selected item
9507 OO
.ui
.IndexLayout
.prototype.onTabSelectWidgetSelect = function ( item
) {
9509 this.setCard( item
.getData() );
9514 * Get the card closest to the specified card.
9516 * @param {OO.ui.CardLayout} card Card to use as a reference point
9517 * @return {OO.ui.CardLayout|null} Card closest to the specified card
9519 OO
.ui
.IndexLayout
.prototype.getClosestCard = function ( card
) {
9520 var next
, prev
, level
,
9521 cards
= this.stackLayout
.getItems(),
9522 index
= $.inArray( card
, cards
);
9524 if ( index
!== -1 ) {
9525 next
= cards
[ index
+ 1 ];
9526 prev
= cards
[ index
- 1 ];
9527 // Prefer adjacent cards at the same level
9528 level
= this.tabSelectWidget
.getItemFromData( card
.getName() ).getLevel();
9531 level
=== this.tabSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
9537 level
=== this.tabSelectWidget
.getItemFromData( next
.getName() ).getLevel()
9542 return prev
|| next
|| null;
9546 * Get the tabs widget.
9548 * @return {OO.ui.TabSelectWidget} Tabs widget
9550 OO
.ui
.IndexLayout
.prototype.getTabs = function () {
9551 return this.tabSelectWidget
;
9555 * Get a card by its symbolic name.
9557 * @param {string} name Symbolic name of card
9558 * @return {OO.ui.CardLayout|undefined} Card, if found
9560 OO
.ui
.IndexLayout
.prototype.getCard = function ( name
) {
9561 return this.cards
[ name
];
9565 * Get the current card.
9567 * @return {OO.ui.CardLayout|undefined} Current card, if found
9569 OO
.ui
.IndexLayout
.prototype.getCurrentCard = function () {
9570 var name
= this.getCurrentCardName();
9571 return name
? this.getCard( name
) : undefined;
9575 * Get the symbolic name of the current card.
9577 * @return {string|null} Symbolic name of the current card
9579 OO
.ui
.IndexLayout
.prototype.getCurrentCardName = function () {
9580 return this.currentCardName
;
9584 * Add cards to the index layout
9586 * When cards are added with the same names as existing cards, the existing cards will be
9587 * automatically removed before the new cards are added.
9589 * @param {OO.ui.CardLayout[]} cards Cards to add
9590 * @param {number} index Index of the insertion point
9594 OO
.ui
.IndexLayout
.prototype.addCards = function ( cards
, index
) {
9595 var i
, len
, name
, card
, item
, currentIndex
,
9596 stackLayoutCards
= this.stackLayout
.getItems(),
9600 // Remove cards with same names
9601 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
9603 name
= card
.getName();
9605 if ( Object
.prototype.hasOwnProperty
.call( this.cards
, name
) ) {
9606 // Correct the insertion index
9607 currentIndex
= $.inArray( this.cards
[ name
], stackLayoutCards
);
9608 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
9611 remove
.push( this.cards
[ name
] );
9614 if ( remove
.length
) {
9615 this.removeCards( remove
);
9619 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
9621 name
= card
.getName();
9622 this.cards
[ card
.getName() ] = card
;
9623 item
= new OO
.ui
.TabOptionWidget( { data
: name
} );
9624 card
.setTabItem( item
);
9628 if ( items
.length
) {
9629 this.tabSelectWidget
.addItems( items
, index
);
9630 this.selectFirstSelectableCard();
9632 this.stackLayout
.addItems( cards
, index
);
9633 this.emit( 'add', cards
, index
);
9639 * Remove the specified cards from the index layout.
9641 * To remove all cards from the index, you may wish to use the #clearCards method instead.
9643 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
9647 OO
.ui
.IndexLayout
.prototype.removeCards = function ( cards
) {
9648 var i
, len
, name
, card
,
9651 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
9653 name
= card
.getName();
9654 delete this.cards
[ name
];
9655 items
.push( this.tabSelectWidget
.getItemFromData( name
) );
9656 card
.setTabItem( null );
9658 if ( items
.length
) {
9659 this.tabSelectWidget
.removeItems( items
);
9660 this.selectFirstSelectableCard();
9662 this.stackLayout
.removeItems( cards
);
9663 this.emit( 'remove', cards
);
9669 * Clear all cards from the index layout.
9671 * To remove only a subset of cards from the index, use the #removeCards method.
9676 OO
.ui
.IndexLayout
.prototype.clearCards = function () {
9678 cards
= this.stackLayout
.getItems();
9681 this.currentCardName
= null;
9682 this.tabSelectWidget
.clearItems();
9683 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
9684 cards
[ i
].setTabItem( null );
9686 this.stackLayout
.clearItems();
9688 this.emit( 'remove', cards
);
9694 * Set the current card by symbolic name.
9697 * @param {string} name Symbolic name of card
9699 OO
.ui
.IndexLayout
.prototype.setCard = function ( name
) {
9702 card
= this.cards
[ name
];
9704 if ( name
!== this.currentCardName
) {
9705 selectedItem
= this.tabSelectWidget
.getSelectedItem();
9706 if ( selectedItem
&& selectedItem
.getData() !== name
) {
9707 this.tabSelectWidget
.selectItemByData( name
);
9710 if ( this.currentCardName
&& this.cards
[ this.currentCardName
] ) {
9711 this.cards
[ this.currentCardName
].setActive( false );
9712 // Blur anything focused if the next card doesn't have anything focusable - this
9713 // is not needed if the next card has something focusable because once it is focused
9714 // this blur happens automatically
9715 if ( this.autoFocus
&& !card
.$element
.find( ':input' ).length
) {
9716 $focused
= this.cards
[ this.currentCardName
].$element
.find( ':focus' );
9717 if ( $focused
.length
) {
9718 $focused
[ 0 ].blur();
9722 this.currentCardName
= name
;
9723 this.stackLayout
.setItem( card
);
9724 card
.setActive( true );
9725 this.emit( 'set', card
);
9731 * Select the first selectable card.
9735 OO
.ui
.IndexLayout
.prototype.selectFirstSelectableCard = function () {
9736 if ( !this.tabSelectWidget
.getSelectedItem() ) {
9737 this.tabSelectWidget
.selectItem( this.tabSelectWidget
.getFirstSelectableItem() );
9744 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
9745 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
9748 * // Example of a panel layout
9749 * var panel = new OO.ui.PanelLayout( {
9753 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
9755 * $( 'body' ).append( panel.$element );
9758 * @extends OO.ui.Layout
9761 * @param {Object} [config] Configuration options
9762 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
9763 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
9764 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
9765 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
9767 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
9768 // Configuration initialization
9769 config
= $.extend( {
9776 // Parent constructor
9777 OO
.ui
.PanelLayout
.super.call( this, config
);
9780 this.$element
.addClass( 'oo-ui-panelLayout' );
9781 if ( config
.scrollable
) {
9782 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
9784 if ( config
.padded
) {
9785 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
9787 if ( config
.expanded
) {
9788 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
9790 if ( config
.framed
) {
9791 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
9797 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
9800 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
9801 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
9802 * rather extended to include the required content and functionality.
9804 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
9805 * item is customized (with a label) using the #setupTabItem method. See
9806 * {@link OO.ui.IndexLayout IndexLayout} for an example.
9809 * @extends OO.ui.PanelLayout
9812 * @param {string} name Unique symbolic name of card
9813 * @param {Object} [config] Configuration options
9815 OO
.ui
.CardLayout
= function OoUiCardLayout( name
, config
) {
9816 // Allow passing positional parameters inside the config object
9817 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
9822 // Configuration initialization
9823 config
= $.extend( { scrollable
: true }, config
);
9825 // Parent constructor
9826 OO
.ui
.CardLayout
.super.call( this, config
);
9830 this.tabItem
= null;
9831 this.active
= false;
9834 this.$element
.addClass( 'oo-ui-cardLayout' );
9839 OO
.inheritClass( OO
.ui
.CardLayout
, OO
.ui
.PanelLayout
);
9844 * An 'active' event is emitted when the card becomes active. Cards become active when they are
9845 * shown in a index layout that is configured to display only one card at a time.
9848 * @param {boolean} active Card is active
9854 * Get the symbolic name of the card.
9856 * @return {string} Symbolic name of card
9858 OO
.ui
.CardLayout
.prototype.getName = function () {
9863 * Check if card is active.
9865 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
9866 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
9868 * @return {boolean} Card is active
9870 OO
.ui
.CardLayout
.prototype.isActive = function () {
9877 * The tab item allows users to access the card from the index's tab
9878 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
9880 * @return {OO.ui.TabOptionWidget|null} Tab option widget
9882 OO
.ui
.CardLayout
.prototype.getTabItem = function () {
9883 return this.tabItem
;
9887 * Set or unset the tab item.
9889 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
9890 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
9891 * level), use #setupTabItem instead of this method.
9893 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
9896 OO
.ui
.CardLayout
.prototype.setTabItem = function ( tabItem
) {
9897 this.tabItem
= tabItem
|| null;
9899 this.setupTabItem();
9905 * Set up the tab item.
9907 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
9908 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
9909 * the #setTabItem method instead.
9911 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
9914 OO
.ui
.CardLayout
.prototype.setupTabItem = function () {
9919 * Set the card to its 'active' state.
9921 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
9922 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
9923 * context, setting the active state on a card does nothing.
9925 * @param {boolean} value Card is active
9928 OO
.ui
.CardLayout
.prototype.setActive = function ( active
) {
9931 if ( active
!== this.active
) {
9932 this.active
= active
;
9933 this.$element
.toggleClass( 'oo-ui-cardLayout-active', this.active
);
9934 this.emit( 'active', this.active
);
9939 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
9940 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
9941 * rather extended to include the required content and functionality.
9943 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
9944 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
9945 * {@link OO.ui.BookletLayout BookletLayout} for an example.
9948 * @extends OO.ui.PanelLayout
9951 * @param {string} name Unique symbolic name of page
9952 * @param {Object} [config] Configuration options
9954 OO
.ui
.PageLayout
= function OoUiPageLayout( name
, config
) {
9955 // Allow passing positional parameters inside the config object
9956 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
9961 // Configuration initialization
9962 config
= $.extend( { scrollable
: true }, config
);
9964 // Parent constructor
9965 OO
.ui
.PageLayout
.super.call( this, config
);
9969 this.outlineItem
= null;
9970 this.active
= false;
9973 this.$element
.addClass( 'oo-ui-pageLayout' );
9978 OO
.inheritClass( OO
.ui
.PageLayout
, OO
.ui
.PanelLayout
);
9983 * An 'active' event is emitted when the page becomes active. Pages become active when they are
9984 * shown in a booklet layout that is configured to display only one page at a time.
9987 * @param {boolean} active Page is active
9993 * Get the symbolic name of the page.
9995 * @return {string} Symbolic name of page
9997 OO
.ui
.PageLayout
.prototype.getName = function () {
10002 * Check if page is active.
10004 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
10005 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
10007 * @return {boolean} Page is active
10009 OO
.ui
.PageLayout
.prototype.isActive = function () {
10010 return this.active
;
10014 * Get outline item.
10016 * The outline item allows users to access the page from the booklet's outline
10017 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
10019 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
10021 OO
.ui
.PageLayout
.prototype.getOutlineItem = function () {
10022 return this.outlineItem
;
10026 * Set or unset the outline item.
10028 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
10029 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
10030 * level), use #setupOutlineItem instead of this method.
10032 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
10035 OO
.ui
.PageLayout
.prototype.setOutlineItem = function ( outlineItem
) {
10036 this.outlineItem
= outlineItem
|| null;
10037 if ( outlineItem
) {
10038 this.setupOutlineItem();
10044 * Set up the outline item.
10046 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
10047 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
10048 * the #setOutlineItem method instead.
10050 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
10053 OO
.ui
.PageLayout
.prototype.setupOutlineItem = function () {
10058 * Set the page to its 'active' state.
10060 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
10061 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
10062 * context, setting the active state on a page does nothing.
10064 * @param {boolean} value Page is active
10067 OO
.ui
.PageLayout
.prototype.setActive = function ( active
) {
10070 if ( active
!== this.active
) {
10071 this.active
= active
;
10072 this.$element
.toggleClass( 'oo-ui-pageLayout-active', active
);
10073 this.emit( 'active', this.active
);
10078 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
10079 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
10080 * by setting the #continuous option to 'true'.
10083 * // A stack layout with two panels, configured to be displayed continously
10084 * var myStack = new OO.ui.StackLayout( {
10086 * new OO.ui.PanelLayout( {
10087 * $content: $( '<p>Panel One</p>' ),
10091 * new OO.ui.PanelLayout( {
10092 * $content: $( '<p>Panel Two</p>' ),
10099 * $( 'body' ).append( myStack.$element );
10102 * @extends OO.ui.PanelLayout
10103 * @mixins OO.ui.GroupElement
10106 * @param {Object} [config] Configuration options
10107 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
10108 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
10110 OO
.ui
.StackLayout
= function OoUiStackLayout( config
) {
10111 // Configuration initialization
10112 config
= $.extend( { scrollable
: true }, config
);
10114 // Parent constructor
10115 OO
.ui
.StackLayout
.super.call( this, config
);
10117 // Mixin constructors
10118 OO
.ui
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
10121 this.currentItem
= null;
10122 this.continuous
= !!config
.continuous
;
10125 this.$element
.addClass( 'oo-ui-stackLayout' );
10126 if ( this.continuous
) {
10127 this.$element
.addClass( 'oo-ui-stackLayout-continuous' );
10129 if ( Array
.isArray( config
.items
) ) {
10130 this.addItems( config
.items
);
10136 OO
.inheritClass( OO
.ui
.StackLayout
, OO
.ui
.PanelLayout
);
10137 OO
.mixinClass( OO
.ui
.StackLayout
, OO
.ui
.GroupElement
);
10142 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
10143 * {@link #clearItems cleared} or {@link #setItem displayed}.
10146 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
10152 * Get the current panel.
10154 * @return {OO.ui.Layout|null}
10156 OO
.ui
.StackLayout
.prototype.getCurrentItem = function () {
10157 return this.currentItem
;
10161 * Unset the current item.
10164 * @param {OO.ui.StackLayout} layout
10167 OO
.ui
.StackLayout
.prototype.unsetCurrentItem = function () {
10168 var prevItem
= this.currentItem
;
10169 if ( prevItem
=== null ) {
10173 this.currentItem
= null;
10174 this.emit( 'set', null );
10178 * Add panel layouts to the stack layout.
10180 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
10181 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
10184 * @param {OO.ui.Layout[]} items Panels to add
10185 * @param {number} [index] Index of the insertion point
10188 OO
.ui
.StackLayout
.prototype.addItems = function ( items
, index
) {
10189 // Update the visibility
10190 this.updateHiddenState( items
, this.currentItem
);
10193 OO
.ui
.GroupElement
.prototype.addItems
.call( this, items
, index
);
10195 if ( !this.currentItem
&& items
.length
) {
10196 this.setItem( items
[ 0 ] );
10203 * Remove the specified panels from the stack layout.
10205 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
10206 * you may wish to use the #clearItems method instead.
10208 * @param {OO.ui.Layout[]} items Panels to remove
10212 OO
.ui
.StackLayout
.prototype.removeItems = function ( items
) {
10214 OO
.ui
.GroupElement
.prototype.removeItems
.call( this, items
);
10216 if ( $.inArray( this.currentItem
, items
) !== -1 ) {
10217 if ( this.items
.length
) {
10218 this.setItem( this.items
[ 0 ] );
10220 this.unsetCurrentItem();
10228 * Clear all panels from the stack layout.
10230 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
10231 * a subset of panels, use the #removeItems method.
10236 OO
.ui
.StackLayout
.prototype.clearItems = function () {
10237 this.unsetCurrentItem();
10238 OO
.ui
.GroupElement
.prototype.clearItems
.call( this );
10244 * Show the specified panel.
10246 * If another panel is currently displayed, it will be hidden.
10248 * @param {OO.ui.Layout} item Panel to show
10252 OO
.ui
.StackLayout
.prototype.setItem = function ( item
) {
10253 if ( item
!== this.currentItem
) {
10254 this.updateHiddenState( this.items
, item
);
10256 if ( $.inArray( item
, this.items
) !== -1 ) {
10257 this.currentItem
= item
;
10258 this.emit( 'set', item
);
10260 this.unsetCurrentItem();
10268 * Update the visibility of all items in case of non-continuous view.
10270 * Ensure all items are hidden except for the selected one.
10271 * This method does nothing when the stack is continuous.
10274 * @param {OO.ui.Layout[]} items Item list iterate over
10275 * @param {OO.ui.Layout} [selectedItem] Selected item to show
10277 OO
.ui
.StackLayout
.prototype.updateHiddenState = function ( items
, selectedItem
) {
10280 if ( !this.continuous
) {
10281 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
10282 if ( !selectedItem
|| selectedItem
!== items
[ i
] ) {
10283 items
[ i
].$element
.addClass( 'oo-ui-element-hidden' );
10286 if ( selectedItem
) {
10287 selectedItem
.$element
.removeClass( 'oo-ui-element-hidden' );
10293 * Horizontal bar layout of tools as icon buttons.
10296 * @extends OO.ui.ToolGroup
10299 * @param {OO.ui.Toolbar} toolbar
10300 * @param {Object} [config] Configuration options
10302 OO
.ui
.BarToolGroup
= function OoUiBarToolGroup( toolbar
, config
) {
10303 // Allow passing positional parameters inside the config object
10304 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
10306 toolbar
= config
.toolbar
;
10309 // Parent constructor
10310 OO
.ui
.BarToolGroup
.super.call( this, toolbar
, config
);
10313 this.$element
.addClass( 'oo-ui-barToolGroup' );
10318 OO
.inheritClass( OO
.ui
.BarToolGroup
, OO
.ui
.ToolGroup
);
10320 /* Static Properties */
10322 OO
.ui
.BarToolGroup
.static.titleTooltips
= true;
10324 OO
.ui
.BarToolGroup
.static.accelTooltips
= true;
10326 OO
.ui
.BarToolGroup
.static.name
= 'bar';
10329 * Popup list of tools with an icon and optional label.
10333 * @extends OO.ui.ToolGroup
10334 * @mixins OO.ui.IconElement
10335 * @mixins OO.ui.IndicatorElement
10336 * @mixins OO.ui.LabelElement
10337 * @mixins OO.ui.TitledElement
10338 * @mixins OO.ui.ClippableElement
10339 * @mixins OO.ui.TabIndexedElement
10342 * @param {OO.ui.Toolbar} toolbar
10343 * @param {Object} [config] Configuration options
10344 * @cfg {string} [header] Text to display at the top of the pop-up
10346 OO
.ui
.PopupToolGroup
= function OoUiPopupToolGroup( toolbar
, config
) {
10347 // Allow passing positional parameters inside the config object
10348 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
10350 toolbar
= config
.toolbar
;
10353 // Configuration initialization
10354 config
= config
|| {};
10356 // Parent constructor
10357 OO
.ui
.PopupToolGroup
.super.call( this, toolbar
, config
);
10360 this.active
= false;
10361 this.dragging
= false;
10362 this.onBlurHandler
= this.onBlur
.bind( this );
10363 this.$handle
= $( '<span>' );
10365 // Mixin constructors
10366 OO
.ui
.IconElement
.call( this, config
);
10367 OO
.ui
.IndicatorElement
.call( this, config
);
10368 OO
.ui
.LabelElement
.call( this, config
);
10369 OO
.ui
.TitledElement
.call( this, config
);
10370 OO
.ui
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
10371 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
10375 keydown
: this.onHandleMouseKeyDown
.bind( this ),
10376 keyup
: this.onHandleMouseKeyUp
.bind( this ),
10377 mousedown
: this.onHandleMouseKeyDown
.bind( this ),
10378 mouseup
: this.onHandleMouseKeyUp
.bind( this )
10383 .addClass( 'oo-ui-popupToolGroup-handle' )
10384 .append( this.$icon
, this.$label
, this.$indicator
);
10385 // If the pop-up should have a header, add it to the top of the toolGroup.
10386 // Note: If this feature is useful for other widgets, we could abstract it into an
10387 // OO.ui.HeaderedElement mixin constructor.
10388 if ( config
.header
!== undefined ) {
10390 .prepend( $( '<span>' )
10391 .addClass( 'oo-ui-popupToolGroup-header' )
10392 .text( config
.header
)
10396 .addClass( 'oo-ui-popupToolGroup' )
10397 .prepend( this.$handle
);
10402 OO
.inheritClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ToolGroup
);
10403 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.IconElement
);
10404 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.IndicatorElement
);
10405 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.LabelElement
);
10406 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.TitledElement
);
10407 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ClippableElement
);
10408 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.TabIndexedElement
);
10415 OO
.ui
.PopupToolGroup
.prototype.setDisabled = function () {
10417 OO
.ui
.PopupToolGroup
.super.prototype.setDisabled
.apply( this, arguments
);
10419 if ( this.isDisabled() && this.isElementAttached() ) {
10420 this.setActive( false );
10425 * Handle focus being lost.
10427 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
10429 * @param {jQuery.Event} e Mouse up or key up event
10431 OO
.ui
.PopupToolGroup
.prototype.onBlur = function ( e
) {
10432 // Only deactivate when clicking outside the dropdown element
10433 if ( $( e
.target
).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element
[ 0 ] ) {
10434 this.setActive( false );
10441 OO
.ui
.PopupToolGroup
.prototype.onMouseKeyUp = function ( e
) {
10442 // Only close toolgroup when a tool was actually selected
10444 !this.isDisabled() && this.pressed
&& this.pressed
=== this.getTargetTool( e
) &&
10445 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
10447 this.setActive( false );
10449 return OO
.ui
.PopupToolGroup
.super.prototype.onMouseKeyUp
.call( this, e
);
10453 * Handle mouse up and key up events.
10455 * @param {jQuery.Event} e Mouse up or key up event
10457 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyUp = function ( e
) {
10459 !this.isDisabled() &&
10460 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
10467 * Handle mouse down and key down events.
10469 * @param {jQuery.Event} e Mouse down or key down event
10471 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyDown = function ( e
) {
10473 !this.isDisabled() &&
10474 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
10476 this.setActive( !this.active
);
10482 * Switch into active mode.
10484 * When active, mouseup events anywhere in the document will trigger deactivation.
10486 OO
.ui
.PopupToolGroup
.prototype.setActive = function ( value
) {
10488 if ( this.active
!== value
) {
10489 this.active
= value
;
10491 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler
, true );
10492 this.getElementDocument().addEventListener( 'keyup', this.onBlurHandler
, true );
10494 // Try anchoring the popup to the left first
10495 this.$element
.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
10496 this.toggleClipping( true );
10497 if ( this.isClippedHorizontally() ) {
10498 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
10499 this.toggleClipping( false );
10501 .removeClass( 'oo-ui-popupToolGroup-left' )
10502 .addClass( 'oo-ui-popupToolGroup-right' );
10503 this.toggleClipping( true );
10506 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler
, true );
10507 this.getElementDocument().removeEventListener( 'keyup', this.onBlurHandler
, true );
10508 this.$element
.removeClass(
10509 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
10511 this.toggleClipping( false );
10517 * Drop down list layout of tools as labeled icon buttons.
10519 * This layout allows some tools to be collapsible, controlled by a "More" / "Fewer" option at the
10520 * bottom of the main list. These are not automatically positioned at the bottom of the list; you
10521 * may want to use the 'promote' and 'demote' configuration options to achieve this.
10524 * @extends OO.ui.PopupToolGroup
10527 * @param {OO.ui.Toolbar} toolbar
10528 * @param {Object} [config] Configuration options
10529 * @cfg {Array} [allowCollapse] List of tools that can be collapsed. Remaining tools will be always
10531 * @cfg {Array} [forceExpand] List of tools that *may not* be collapsed. All remaining tools will be
10532 * allowed to be collapsed.
10533 * @cfg {boolean} [expanded=false] Whether the collapsible tools are expanded by default
10535 OO
.ui
.ListToolGroup
= function OoUiListToolGroup( toolbar
, config
) {
10536 // Allow passing positional parameters inside the config object
10537 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
10539 toolbar
= config
.toolbar
;
10542 // Configuration initialization
10543 config
= config
|| {};
10545 // Properties (must be set before parent constructor, which calls #populate)
10546 this.allowCollapse
= config
.allowCollapse
;
10547 this.forceExpand
= config
.forceExpand
;
10548 this.expanded
= config
.expanded
!== undefined ? config
.expanded
: false;
10549 this.collapsibleTools
= [];
10551 // Parent constructor
10552 OO
.ui
.ListToolGroup
.super.call( this, toolbar
, config
);
10555 this.$element
.addClass( 'oo-ui-listToolGroup' );
10560 OO
.inheritClass( OO
.ui
.ListToolGroup
, OO
.ui
.PopupToolGroup
);
10562 /* Static Properties */
10564 OO
.ui
.ListToolGroup
.static.name
= 'list';
10571 OO
.ui
.ListToolGroup
.prototype.populate = function () {
10572 var i
, len
, allowCollapse
= [];
10574 OO
.ui
.ListToolGroup
.super.prototype.populate
.call( this );
10576 // Update the list of collapsible tools
10577 if ( this.allowCollapse
!== undefined ) {
10578 allowCollapse
= this.allowCollapse
;
10579 } else if ( this.forceExpand
!== undefined ) {
10580 allowCollapse
= OO
.simpleArrayDifference( Object
.keys( this.tools
), this.forceExpand
);
10583 this.collapsibleTools
= [];
10584 for ( i
= 0, len
= allowCollapse
.length
; i
< len
; i
++ ) {
10585 if ( this.tools
[ allowCollapse
[ i
] ] !== undefined ) {
10586 this.collapsibleTools
.push( this.tools
[ allowCollapse
[ i
] ] );
10590 // Keep at the end, even when tools are added
10591 this.$group
.append( this.getExpandCollapseTool().$element
);
10593 this.getExpandCollapseTool().toggle( this.collapsibleTools
.length
!== 0 );
10594 this.updateCollapsibleState();
10597 OO
.ui
.ListToolGroup
.prototype.getExpandCollapseTool = function () {
10598 if ( this.expandCollapseTool
=== undefined ) {
10599 var ExpandCollapseTool = function () {
10600 ExpandCollapseTool
.super.apply( this, arguments
);
10603 OO
.inheritClass( ExpandCollapseTool
, OO
.ui
.Tool
);
10605 ExpandCollapseTool
.prototype.onSelect = function () {
10606 this.toolGroup
.expanded
= !this.toolGroup
.expanded
;
10607 this.toolGroup
.updateCollapsibleState();
10608 this.setActive( false );
10610 ExpandCollapseTool
.prototype.onUpdateState = function () {
10611 // Do nothing. Tool interface requires an implementation of this function.
10614 ExpandCollapseTool
.static.name
= 'more-fewer';
10616 this.expandCollapseTool
= new ExpandCollapseTool( this );
10618 return this.expandCollapseTool
;
10624 OO
.ui
.ListToolGroup
.prototype.onMouseKeyUp = function ( e
) {
10625 // Do not close the popup when the user wants to show more/fewer tools
10627 $( e
.target
).closest( '.oo-ui-tool-name-more-fewer' ).length
&&
10628 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
10630 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
10631 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
10632 return OO
.ui
.ListToolGroup
.super.super.prototype.onMouseKeyUp
.call( this, e
);
10634 return OO
.ui
.ListToolGroup
.super.prototype.onMouseKeyUp
.call( this, e
);
10638 OO
.ui
.ListToolGroup
.prototype.updateCollapsibleState = function () {
10641 this.getExpandCollapseTool()
10642 .setIcon( this.expanded
? 'collapse' : 'expand' )
10643 .setTitle( OO
.ui
.msg( this.expanded
? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
10645 for ( i
= 0, len
= this.collapsibleTools
.length
; i
< len
; i
++ ) {
10646 this.collapsibleTools
[ i
].toggle( this.expanded
);
10651 * Drop down menu layout of tools as selectable menu items.
10654 * @extends OO.ui.PopupToolGroup
10657 * @param {OO.ui.Toolbar} toolbar
10658 * @param {Object} [config] Configuration options
10660 OO
.ui
.MenuToolGroup
= function OoUiMenuToolGroup( toolbar
, config
) {
10661 // Allow passing positional parameters inside the config object
10662 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
10664 toolbar
= config
.toolbar
;
10667 // Configuration initialization
10668 config
= config
|| {};
10670 // Parent constructor
10671 OO
.ui
.MenuToolGroup
.super.call( this, toolbar
, config
);
10674 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
10677 this.$element
.addClass( 'oo-ui-menuToolGroup' );
10682 OO
.inheritClass( OO
.ui
.MenuToolGroup
, OO
.ui
.PopupToolGroup
);
10684 /* Static Properties */
10686 OO
.ui
.MenuToolGroup
.static.name
= 'menu';
10691 * Handle the toolbar state being updated.
10693 * When the state changes, the title of each active item in the menu will be joined together and
10694 * used as a label for the group. The label will be empty if none of the items are active.
10696 OO
.ui
.MenuToolGroup
.prototype.onUpdateState = function () {
10700 for ( name
in this.tools
) {
10701 if ( this.tools
[ name
].isActive() ) {
10702 labelTexts
.push( this.tools
[ name
].getTitle() );
10706 this.setLabel( labelTexts
.join( ', ' ) || ' ' );
10710 * Tool that shows a popup when selected.
10714 * @extends OO.ui.Tool
10715 * @mixins OO.ui.PopupElement
10718 * @param {OO.ui.ToolGroup} toolGroup
10719 * @param {Object} [config] Configuration options
10721 OO
.ui
.PopupTool
= function OoUiPopupTool( toolGroup
, config
) {
10722 // Allow passing positional parameters inside the config object
10723 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
10724 config
= toolGroup
;
10725 toolGroup
= config
.toolGroup
;
10728 // Parent constructor
10729 OO
.ui
.PopupTool
.super.call( this, toolGroup
, config
);
10731 // Mixin constructors
10732 OO
.ui
.PopupElement
.call( this, config
);
10736 .addClass( 'oo-ui-popupTool' )
10737 .append( this.popup
.$element
);
10742 OO
.inheritClass( OO
.ui
.PopupTool
, OO
.ui
.Tool
);
10743 OO
.mixinClass( OO
.ui
.PopupTool
, OO
.ui
.PopupElement
);
10748 * Handle the tool being selected.
10752 OO
.ui
.PopupTool
.prototype.onSelect = function () {
10753 if ( !this.isDisabled() ) {
10754 this.popup
.toggle();
10756 this.setActive( false );
10761 * Handle the toolbar state being updated.
10765 OO
.ui
.PopupTool
.prototype.onUpdateState = function () {
10766 this.setActive( false );
10770 * Tool that has a tool group inside. This is a bad workaround for the lack of proper hierarchical
10771 * menus in toolbars (T74159).
10775 * @extends OO.ui.Tool
10778 * @param {OO.ui.ToolGroup} toolGroup
10779 * @param {Object} [config] Configuration options
10781 OO
.ui
.ToolGroupTool
= function OoUiToolGroupTool( toolGroup
, config
) {
10782 // Allow passing positional parameters inside the config object
10783 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
10784 config
= toolGroup
;
10785 toolGroup
= config
.toolGroup
;
10788 // Parent constructor
10789 OO
.ui
.ToolGroupTool
.super.call( this, toolGroup
, config
);
10792 this.innerToolGroup
= this.createGroup( this.constructor.static.groupConfig
);
10795 this.$link
.remove();
10797 .addClass( 'oo-ui-toolGroupTool' )
10798 .append( this.innerToolGroup
.$element
);
10803 OO
.inheritClass( OO
.ui
.ToolGroupTool
, OO
.ui
.Tool
);
10805 /* Static Properties */
10808 * Tool group configuration. See OO.ui.Toolbar#setup for the accepted values.
10810 * @property {Object.<string,Array>}
10812 OO
.ui
.ToolGroupTool
.static.groupConfig
= {};
10817 * Handle the tool being selected.
10821 OO
.ui
.ToolGroupTool
.prototype.onSelect = function () {
10822 this.innerToolGroup
.setActive( !this.innerToolGroup
.active
);
10827 * Handle the toolbar state being updated.
10831 OO
.ui
.ToolGroupTool
.prototype.onUpdateState = function () {
10832 this.setActive( false );
10836 * Build a OO.ui.ToolGroup from the configuration.
10838 * @param {Object.<string,Array>} group Tool group configuration. See OO.ui.Toolbar#setup for the
10840 * @return {OO.ui.ListToolGroup}
10842 OO
.ui
.ToolGroupTool
.prototype.createGroup = function ( group
) {
10843 if ( group
.include
=== '*' ) {
10844 // Apply defaults to catch-all groups
10845 if ( group
.label
=== undefined ) {
10846 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
10850 return this.toolbar
.getToolGroupFactory().create( 'list', this.toolbar
, group
);
10854 * Mixin for OO.ui.Widget subclasses to provide OO.ui.GroupElement.
10856 * Use together with OO.ui.ItemWidget to make disabled state inheritable.
10861 * @extends OO.ui.GroupElement
10864 * @param {Object} [config] Configuration options
10866 OO
.ui
.GroupWidget
= function OoUiGroupWidget( config
) {
10867 // Parent constructor
10868 OO
.ui
.GroupWidget
.super.call( this, config
);
10873 OO
.inheritClass( OO
.ui
.GroupWidget
, OO
.ui
.GroupElement
);
10878 * Set the disabled state of the widget.
10880 * This will also update the disabled state of child widgets.
10882 * @param {boolean} disabled Disable widget
10885 OO
.ui
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
10889 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
10890 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
10892 // During construction, #setDisabled is called before the OO.ui.GroupElement constructor
10893 if ( this.items
) {
10894 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
10895 this.items
[ i
].updateDisabled();
10903 * Mixin for widgets used as items in widgets that inherit OO.ui.GroupWidget.
10905 * Item widgets have a reference to a OO.ui.GroupWidget while they are attached to the group. This
10906 * allows bidirectional communication.
10908 * Use together with OO.ui.GroupWidget to make disabled state inheritable.
10916 OO
.ui
.ItemWidget
= function OoUiItemWidget() {
10923 * Check if widget is disabled.
10925 * Checks parent if present, making disabled state inheritable.
10927 * @return {boolean} Widget is disabled
10929 OO
.ui
.ItemWidget
.prototype.isDisabled = function () {
10930 return this.disabled
||
10931 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
10935 * Set group element is in.
10937 * @param {OO.ui.GroupElement|null} group Group element, null if none
10940 OO
.ui
.ItemWidget
.prototype.setElementGroup = function ( group
) {
10942 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
10943 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
10945 // Initialize item disabled states
10946 this.updateDisabled();
10952 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
10953 * Controls include moving items up and down, removing items, and adding different kinds of items.
10954 * ####Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.####
10957 * @extends OO.ui.Widget
10958 * @mixins OO.ui.GroupElement
10959 * @mixins OO.ui.IconElement
10962 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
10963 * @param {Object} [config] Configuration options
10964 * @cfg {Object} [abilities] List of abilties
10965 * @cfg {boolean} [abilities.move=true] Allow moving movable items
10966 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
10968 OO
.ui
.OutlineControlsWidget
= function OoUiOutlineControlsWidget( outline
, config
) {
10969 // Allow passing positional parameters inside the config object
10970 if ( OO
.isPlainObject( outline
) && config
=== undefined ) {
10972 outline
= config
.outline
;
10975 // Configuration initialization
10976 config
= $.extend( { icon
: 'add' }, config
);
10978 // Parent constructor
10979 OO
.ui
.OutlineControlsWidget
.super.call( this, config
);
10981 // Mixin constructors
10982 OO
.ui
.GroupElement
.call( this, config
);
10983 OO
.ui
.IconElement
.call( this, config
);
10986 this.outline
= outline
;
10987 this.$movers
= $( '<div>' );
10988 this.upButton
= new OO
.ui
.ButtonWidget( {
10991 title
: OO
.ui
.msg( 'ooui-outline-control-move-up' )
10993 this.downButton
= new OO
.ui
.ButtonWidget( {
10996 title
: OO
.ui
.msg( 'ooui-outline-control-move-down' )
10998 this.removeButton
= new OO
.ui
.ButtonWidget( {
11001 title
: OO
.ui
.msg( 'ooui-outline-control-remove' )
11003 this.abilities
= { move: true, remove
: true };
11006 outline
.connect( this, {
11007 select
: 'onOutlineChange',
11008 add
: 'onOutlineChange',
11009 remove
: 'onOutlineChange'
11011 this.upButton
.connect( this, { click
: [ 'emit', 'move', -1 ] } );
11012 this.downButton
.connect( this, { click
: [ 'emit', 'move', 1 ] } );
11013 this.removeButton
.connect( this, { click
: [ 'emit', 'remove' ] } );
11016 this.$element
.addClass( 'oo-ui-outlineControlsWidget' );
11017 this.$group
.addClass( 'oo-ui-outlineControlsWidget-items' );
11019 .addClass( 'oo-ui-outlineControlsWidget-movers' )
11020 .append( this.removeButton
.$element
, this.upButton
.$element
, this.downButton
.$element
);
11021 this.$element
.append( this.$icon
, this.$group
, this.$movers
);
11022 this.setAbilities( config
.abilities
|| {} );
11027 OO
.inheritClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.Widget
);
11028 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.GroupElement
);
11029 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.IconElement
);
11035 * @param {number} places Number of places to move
11047 * @param {Object} abilities List of abilties
11048 * @param {boolean} [abilities.move] Allow moving movable items
11049 * @param {boolean} [abilities.remove] Allow removing removable items
11051 OO
.ui
.OutlineControlsWidget
.prototype.setAbilities = function ( abilities
) {
11054 for ( ability
in this.abilities
) {
11055 if ( abilities
[ability
] !== undefined ) {
11056 this.abilities
[ability
] = !!abilities
[ability
];
11060 this.onOutlineChange();
11066 * Handle outline change events.
11068 OO
.ui
.OutlineControlsWidget
.prototype.onOutlineChange = function () {
11069 var i
, len
, firstMovable
, lastMovable
,
11070 items
= this.outline
.getItems(),
11071 selectedItem
= this.outline
.getSelectedItem(),
11072 movable
= this.abilities
.move && selectedItem
&& selectedItem
.isMovable(),
11073 removable
= this.abilities
.remove
&& selectedItem
&& selectedItem
.isRemovable();
11077 len
= items
.length
;
11078 while ( ++i
< len
) {
11079 if ( items
[ i
].isMovable() ) {
11080 firstMovable
= items
[ i
];
11086 if ( items
[ i
].isMovable() ) {
11087 lastMovable
= items
[ i
];
11092 this.upButton
.setDisabled( !movable
|| selectedItem
=== firstMovable
);
11093 this.downButton
.setDisabled( !movable
|| selectedItem
=== lastMovable
);
11094 this.removeButton
.setDisabled( !removable
);
11098 * ToggleWidget implements basic behavior of widgets with an on/off state.
11099 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
11103 * @extends OO.ui.Widget
11106 * @param {Object} [config] Configuration options
11107 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
11108 * By default, the toggle is in the 'off' state.
11110 OO
.ui
.ToggleWidget
= function OoUiToggleWidget( config
) {
11111 // Configuration initialization
11112 config
= config
|| {};
11114 // Parent constructor
11115 OO
.ui
.ToggleWidget
.super.call( this, config
);
11121 this.$element
.addClass( 'oo-ui-toggleWidget' );
11122 this.setValue( !!config
.value
);
11127 OO
.inheritClass( OO
.ui
.ToggleWidget
, OO
.ui
.Widget
);
11134 * A change event is emitted when the on/off state of the toggle changes.
11136 * @param {boolean} value Value representing the new state of the toggle
11142 * Get the value representing the toggle’s state.
11144 * @return {boolean} The on/off state of the toggle
11146 OO
.ui
.ToggleWidget
.prototype.getValue = function () {
11151 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
11153 * @param {boolean} value The state of the toggle
11157 OO
.ui
.ToggleWidget
.prototype.setValue = function ( value
) {
11159 if ( this.value
!== value
) {
11160 this.value
= value
;
11161 this.emit( 'change', value
);
11162 this.$element
.toggleClass( 'oo-ui-toggleWidget-on', value
);
11163 this.$element
.toggleClass( 'oo-ui-toggleWidget-off', !value
);
11164 this.$element
.attr( 'aria-checked', value
.toString() );
11170 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
11171 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
11172 * removed, and cleared from the group.
11175 * // Example: A ButtonGroupWidget with two buttons
11176 * var button1 = new OO.ui.PopupButtonWidget( {
11177 * label: 'Select a category',
11180 * $content: $( '<p>List of categories...</p>' ),
11185 * var button2 = new OO.ui.ButtonWidget( {
11186 * label: 'Add item'
11188 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
11189 * items: [button1, button2]
11191 * $( 'body' ).append( buttonGroup.$element );
11194 * @extends OO.ui.Widget
11195 * @mixins OO.ui.GroupElement
11198 * @param {Object} [config] Configuration options
11199 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
11201 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
11202 // Configuration initialization
11203 config
= config
|| {};
11205 // Parent constructor
11206 OO
.ui
.ButtonGroupWidget
.super.call( this, config
);
11208 // Mixin constructors
11209 OO
.ui
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11212 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
11213 if ( Array
.isArray( config
.items
) ) {
11214 this.addItems( config
.items
);
11220 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
11221 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.GroupElement
);
11224 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
11225 * feels, and functionality can be customized via the class’s configuration options
11226 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
11229 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
11232 * // A button widget
11233 * var button = new OO.ui.ButtonWidget( {
11234 * label: 'Button with Icon',
11236 * iconTitle: 'Remove'
11238 * $( 'body' ).append( button.$element );
11240 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
11243 * @extends OO.ui.Widget
11244 * @mixins OO.ui.ButtonElement
11245 * @mixins OO.ui.IconElement
11246 * @mixins OO.ui.IndicatorElement
11247 * @mixins OO.ui.LabelElement
11248 * @mixins OO.ui.TitledElement
11249 * @mixins OO.ui.FlaggedElement
11250 * @mixins OO.ui.TabIndexedElement
11253 * @param {Object} [config] Configuration options
11254 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
11255 * @cfg {string} [target] The frame or window in which to open the hyperlink.
11256 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
11258 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
11259 // Configuration initialization
11260 config
= config
|| {};
11262 // Parent constructor
11263 OO
.ui
.ButtonWidget
.super.call( this, config
);
11265 // Mixin constructors
11266 OO
.ui
.ButtonElement
.call( this, config
);
11267 OO
.ui
.IconElement
.call( this, config
);
11268 OO
.ui
.IndicatorElement
.call( this, config
);
11269 OO
.ui
.LabelElement
.call( this, config
);
11270 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
11271 OO
.ui
.FlaggedElement
.call( this, config
);
11272 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
11276 this.target
= null;
11277 this.noFollow
= false;
11280 this.connect( this, { disable
: 'onDisable' } );
11283 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
11285 .addClass( 'oo-ui-buttonWidget' )
11286 .append( this.$button
);
11287 this.setHref( config
.href
);
11288 this.setTarget( config
.target
);
11289 this.setNoFollow( config
.noFollow
);
11294 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
11295 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.ButtonElement
);
11296 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.IconElement
);
11297 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.IndicatorElement
);
11298 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.LabelElement
);
11299 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.TitledElement
);
11300 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.FlaggedElement
);
11301 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.TabIndexedElement
);
11308 OO
.ui
.ButtonWidget
.prototype.onMouseDown = function ( e
) {
11309 if ( !this.isDisabled() ) {
11310 // Remove the tab-index while the button is down to prevent the button from stealing focus
11311 this.$button
.removeAttr( 'tabindex' );
11314 return OO
.ui
.ButtonElement
.prototype.onMouseDown
.call( this, e
);
11320 OO
.ui
.ButtonWidget
.prototype.onMouseUp = function ( e
) {
11321 if ( !this.isDisabled() ) {
11322 // Restore the tab-index after the button is up to restore the button's accessibility
11323 this.$button
.attr( 'tabindex', this.tabIndex
);
11326 return OO
.ui
.ButtonElement
.prototype.onMouseUp
.call( this, e
);
11330 * Get hyperlink location.
11332 * @return {string} Hyperlink location
11334 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
11339 * Get hyperlink target.
11341 * @return {string} Hyperlink target
11343 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
11344 return this.target
;
11348 * Get search engine traversal hint.
11350 * @return {boolean} Whether search engines should avoid traversing this hyperlink
11352 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
11353 return this.noFollow
;
11357 * Set hyperlink location.
11359 * @param {string|null} href Hyperlink location, null to remove
11361 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
11362 href
= typeof href
=== 'string' ? href
: null;
11364 if ( href
!== this.href
) {
11373 * Update the `href` attribute, in case of changes to href or
11379 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
11380 if ( this.href
!== null && !this.isDisabled() ) {
11381 this.$button
.attr( 'href', this.href
);
11383 this.$button
.removeAttr( 'href' );
11390 * Handle disable events.
11393 * @param {boolean} disabled Element is disabled
11395 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
11400 * Set hyperlink target.
11402 * @param {string|null} target Hyperlink target, null to remove
11404 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
11405 target
= typeof target
=== 'string' ? target
: null;
11407 if ( target
!== this.target
) {
11408 this.target
= target
;
11409 if ( target
!== null ) {
11410 this.$button
.attr( 'target', target
);
11412 this.$button
.removeAttr( 'target' );
11420 * Set search engine traversal hint.
11422 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
11424 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
11425 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
11427 if ( noFollow
!== this.noFollow
) {
11428 this.noFollow
= noFollow
;
11430 this.$button
.attr( 'rel', 'nofollow' );
11432 this.$button
.removeAttr( 'rel' );
11440 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
11441 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
11444 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
11445 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
11448 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
11451 * @extends OO.ui.ButtonWidget
11452 * @mixins OO.ui.PendingElement
11455 * @param {Object} [config] Configuration options
11456 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
11457 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
11458 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
11459 * for more information about setting modes.
11460 * @cfg {boolean} [framed=false] Render the action button with a frame
11462 OO
.ui
.ActionWidget
= function OoUiActionWidget( config
) {
11463 // Configuration initialization
11464 config
= $.extend( { framed
: false }, config
);
11466 // Parent constructor
11467 OO
.ui
.ActionWidget
.super.call( this, config
);
11469 // Mixin constructors
11470 OO
.ui
.PendingElement
.call( this, config
);
11473 this.action
= config
.action
|| '';
11474 this.modes
= config
.modes
|| [];
11479 this.$element
.addClass( 'oo-ui-actionWidget' );
11484 OO
.inheritClass( OO
.ui
.ActionWidget
, OO
.ui
.ButtonWidget
);
11485 OO
.mixinClass( OO
.ui
.ActionWidget
, OO
.ui
.PendingElement
);
11490 * A resize event is emitted when the size of the widget changes.
11498 * Check if the action is configured to be available in the specified `mode`.
11500 * @param {string} mode Name of mode
11501 * @return {boolean} The action is configured with the mode
11503 OO
.ui
.ActionWidget
.prototype.hasMode = function ( mode
) {
11504 return this.modes
.indexOf( mode
) !== -1;
11508 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
11512 OO
.ui
.ActionWidget
.prototype.getAction = function () {
11513 return this.action
;
11517 * Get the symbolic name of the mode or modes for which the action is configured to be available.
11519 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
11520 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
11523 * @return {string[]}
11525 OO
.ui
.ActionWidget
.prototype.getModes = function () {
11526 return this.modes
.slice();
11530 * Emit a resize event if the size has changed.
11535 OO
.ui
.ActionWidget
.prototype.propagateResize = function () {
11538 if ( this.isElementAttached() ) {
11539 width
= this.$element
.width();
11540 height
= this.$element
.height();
11542 if ( width
!== this.width
|| height
!== this.height
) {
11543 this.width
= width
;
11544 this.height
= height
;
11545 this.emit( 'resize' );
11555 OO
.ui
.ActionWidget
.prototype.setIcon = function () {
11557 OO
.ui
.IconElement
.prototype.setIcon
.apply( this, arguments
);
11558 this.propagateResize();
11566 OO
.ui
.ActionWidget
.prototype.setLabel = function () {
11568 OO
.ui
.LabelElement
.prototype.setLabel
.apply( this, arguments
);
11569 this.propagateResize();
11577 OO
.ui
.ActionWidget
.prototype.setFlags = function () {
11579 OO
.ui
.FlaggedElement
.prototype.setFlags
.apply( this, arguments
);
11580 this.propagateResize();
11588 OO
.ui
.ActionWidget
.prototype.clearFlags = function () {
11590 OO
.ui
.FlaggedElement
.prototype.clearFlags
.apply( this, arguments
);
11591 this.propagateResize();
11597 * Toggle the visibility of the action button.
11599 * @param {boolean} [show] Show button, omit to toggle visibility
11602 OO
.ui
.ActionWidget
.prototype.toggle = function () {
11604 OO
.ui
.ActionWidget
.super.prototype.toggle
.apply( this, arguments
);
11605 this.propagateResize();
11611 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
11612 * which is used to display additional information or options.
11615 * // Example of a popup button.
11616 * var popupButton = new OO.ui.PopupButtonWidget( {
11617 * label: 'Popup button with options',
11620 * $content: $( '<p>Additional options here.</p>' ),
11622 * align: 'force-left'
11625 * // Append the button to the DOM.
11626 * $( 'body' ).append( popupButton.$element );
11629 * @extends OO.ui.ButtonWidget
11630 * @mixins OO.ui.PopupElement
11633 * @param {Object} [config] Configuration options
11635 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
11636 // Parent constructor
11637 OO
.ui
.PopupButtonWidget
.super.call( this, config
);
11639 // Mixin constructors
11640 OO
.ui
.PopupElement
.call( this, config
);
11643 this.connect( this, { click
: 'onAction' } );
11647 .addClass( 'oo-ui-popupButtonWidget' )
11648 .attr( 'aria-haspopup', 'true' )
11649 .append( this.popup
.$element
);
11654 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
11655 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.PopupElement
);
11660 * Handle the button action being triggered.
11664 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
11665 this.popup
.toggle();
11669 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
11670 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
11671 * configured with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators},
11672 * {@link OO.ui.TitledElement titles}, {@link OO.ui.FlaggedElement styling flags},
11673 * and {@link OO.ui.LabelElement labels}. Please see
11674 * the [OOjs UI documentation][1] on MediaWiki for more information.
11677 * // Toggle buttons in the 'off' and 'on' state.
11678 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
11679 * label: 'Toggle Button off'
11681 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
11682 * label: 'Toggle Button on',
11685 * // Append the buttons to the DOM.
11686 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
11688 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
11691 * @extends OO.ui.ToggleWidget
11692 * @mixins OO.ui.ButtonElement
11693 * @mixins OO.ui.IconElement
11694 * @mixins OO.ui.IndicatorElement
11695 * @mixins OO.ui.LabelElement
11696 * @mixins OO.ui.TitledElement
11697 * @mixins OO.ui.FlaggedElement
11698 * @mixins OO.ui.TabIndexedElement
11701 * @param {Object} [config] Configuration options
11702 * @cfg {boolean} [value=false] The toggle button’s initial on/off
11703 * state. By default, the button is in the 'off' state.
11705 OO
.ui
.ToggleButtonWidget
= function OoUiToggleButtonWidget( config
) {
11706 // Configuration initialization
11707 config
= config
|| {};
11709 // Parent constructor
11710 OO
.ui
.ToggleButtonWidget
.super.call( this, config
);
11712 // Mixin constructors
11713 OO
.ui
.ButtonElement
.call( this, config
);
11714 OO
.ui
.IconElement
.call( this, config
);
11715 OO
.ui
.IndicatorElement
.call( this, config
);
11716 OO
.ui
.LabelElement
.call( this, config
);
11717 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
11718 OO
.ui
.FlaggedElement
.call( this, config
);
11719 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
11722 this.connect( this, { click
: 'onAction' } );
11725 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
11727 .addClass( 'oo-ui-toggleButtonWidget' )
11728 .append( this.$button
);
11733 OO
.inheritClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ToggleWidget
);
11734 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ButtonElement
);
11735 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.IconElement
);
11736 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.IndicatorElement
);
11737 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.LabelElement
);
11738 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.TitledElement
);
11739 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.FlaggedElement
);
11740 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.TabIndexedElement
);
11745 * Handle the button action being triggered.
11749 OO
.ui
.ToggleButtonWidget
.prototype.onAction = function () {
11750 this.setValue( !this.value
);
11756 OO
.ui
.ToggleButtonWidget
.prototype.setValue = function ( value
) {
11758 if ( value
!== this.value
) {
11759 // Might be called from parent constructor before ButtonElement constructor
11760 if ( this.$button
) {
11761 this.$button
.attr( 'aria-pressed', value
.toString() );
11763 this.setActive( value
);
11767 OO
.ui
.ToggleButtonWidget
.super.prototype.setValue
.call( this, value
);
11775 OO
.ui
.ToggleButtonWidget
.prototype.setButtonElement = function ( $button
) {
11776 if ( this.$button
) {
11777 this.$button
.removeAttr( 'aria-pressed' );
11779 OO
.ui
.ButtonElement
.prototype.setButtonElement
.call( this, $button
);
11780 this.$button
.attr( 'aria-pressed', this.value
.toString() );
11784 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
11785 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
11786 * users can interact with it.
11789 * // Example: A DropdownWidget with a menu that contains three options
11790 * var dropDown = new OO.ui.DropdownWidget( {
11791 * label: 'Dropdown menu: Select a menu option',
11794 * new OO.ui.MenuOptionWidget( {
11798 * new OO.ui.MenuOptionWidget( {
11802 * new OO.ui.MenuOptionWidget( {
11810 * $( 'body' ).append( dropDown.$element );
11812 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
11814 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
11817 * @extends OO.ui.Widget
11818 * @mixins OO.ui.IconElement
11819 * @mixins OO.ui.IndicatorElement
11820 * @mixins OO.ui.LabelElement
11821 * @mixins OO.ui.TitledElement
11822 * @mixins OO.ui.TabIndexedElement
11825 * @param {Object} [config] Configuration options
11826 * @cfg {Object} [menu] Configuration options to pass to menu widget
11828 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
11829 // Configuration initialization
11830 config
= $.extend( { indicator
: 'down' }, config
);
11832 // Parent constructor
11833 OO
.ui
.DropdownWidget
.super.call( this, config
);
11835 // Properties (must be set before TabIndexedElement constructor call)
11836 this.$handle
= this.$( '<span>' );
11838 // Mixin constructors
11839 OO
.ui
.IconElement
.call( this, config
);
11840 OO
.ui
.IndicatorElement
.call( this, config
);
11841 OO
.ui
.LabelElement
.call( this, config
);
11842 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
11843 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
11846 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend( { widget
: this }, config
.menu
) );
11850 click
: this.onClick
.bind( this ),
11851 keypress
: this.onKeyPress
.bind( this )
11853 this.menu
.connect( this, { select
: 'onMenuSelect' } );
11857 .addClass( 'oo-ui-dropdownWidget-handle' )
11858 .append( this.$icon
, this.$label
, this.$indicator
);
11860 .addClass( 'oo-ui-dropdownWidget' )
11861 .append( this.$handle
, this.menu
.$element
);
11866 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
11867 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.IconElement
);
11868 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.IndicatorElement
);
11869 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.LabelElement
);
11870 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.TitledElement
);
11871 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.TabIndexedElement
);
11878 * @return {OO.ui.MenuSelectWidget} Menu of widget
11880 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
11885 * Handles menu select events.
11888 * @param {OO.ui.MenuOptionWidget} item Selected menu item
11890 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
11897 selectedLabel
= item
.getLabel();
11899 // If the label is a DOM element, clone it, because setLabel will append() it
11900 if ( selectedLabel
instanceof jQuery
) {
11901 selectedLabel
= selectedLabel
.clone();
11904 this.setLabel( selectedLabel
);
11908 * Handle mouse click events.
11911 * @param {jQuery.Event} e Mouse click event
11913 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
11914 if ( !this.isDisabled() && e
.which
=== 1 ) {
11915 this.menu
.toggle();
11921 * Handle key press events.
11924 * @param {jQuery.Event} e Key press event
11926 OO
.ui
.DropdownWidget
.prototype.onKeyPress = function ( e
) {
11927 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
11928 this.menu
.toggle();
11934 * IconWidget is a generic widget for {@link OO.ui.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
11935 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
11936 * for a list of icons included in the library.
11939 * // An icon widget with a label
11940 * var myIcon = new OO.ui.IconWidget( {
11942 * iconTitle: 'Help'
11944 * // Create a label.
11945 * var iconLabel = new OO.ui.LabelWidget( {
11948 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
11950 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
11953 * @extends OO.ui.Widget
11954 * @mixins OO.ui.IconElement
11955 * @mixins OO.ui.TitledElement
11956 * @mixins OO.ui.FlaggedElement
11959 * @param {Object} [config] Configuration options
11961 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
11962 // Configuration initialization
11963 config
= config
|| {};
11965 // Parent constructor
11966 OO
.ui
.IconWidget
.super.call( this, config
);
11968 // Mixin constructors
11969 OO
.ui
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
11970 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
11971 OO
.ui
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
11974 this.$element
.addClass( 'oo-ui-iconWidget' );
11979 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
11980 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.IconElement
);
11981 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.TitledElement
);
11982 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.FlaggedElement
);
11984 /* Static Properties */
11986 OO
.ui
.IconWidget
.static.tagName
= 'span';
11989 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
11990 * attention to the status of an item or to clarify the function of a control. For a list of
11991 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
11994 * // Example of an indicator widget
11995 * var indicator1 = new OO.ui.IndicatorWidget( {
11996 * indicator: 'alert'
11999 * // Create a fieldset layout to add a label
12000 * var fieldset = new OO.ui.FieldsetLayout();
12001 * fieldset.addItems( [
12002 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
12004 * $( 'body' ).append( fieldset.$element );
12006 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
12009 * @extends OO.ui.Widget
12010 * @mixins OO.ui.IndicatorElement
12011 * @mixins OO.ui.TitledElement
12014 * @param {Object} [config] Configuration options
12016 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
12017 // Configuration initialization
12018 config
= config
|| {};
12020 // Parent constructor
12021 OO
.ui
.IndicatorWidget
.super.call( this, config
);
12023 // Mixin constructors
12024 OO
.ui
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
12025 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
12028 this.$element
.addClass( 'oo-ui-indicatorWidget' );
12033 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
12034 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.IndicatorElement
);
12035 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.TitledElement
);
12037 /* Static Properties */
12039 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
12042 * InputWidget is the base class for all input widgets, which
12043 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
12044 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
12045 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
12047 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
12051 * @extends OO.ui.Widget
12052 * @mixins OO.ui.FlaggedElement
12053 * @mixins OO.ui.TabIndexedElement
12056 * @param {Object} [config] Configuration options
12057 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
12058 * @cfg {string} [value=''] The value of the input.
12059 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
12060 * before it is accepted.
12062 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
12063 // Configuration initialization
12064 config
= config
|| {};
12066 // Parent constructor
12067 OO
.ui
.InputWidget
.super.call( this, config
);
12070 this.$input
= this.getInputElement( config
);
12072 this.inputFilter
= config
.inputFilter
;
12074 // Mixin constructors
12075 OO
.ui
.FlaggedElement
.call( this, config
);
12076 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
12079 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
12083 .attr( 'name', config
.name
)
12084 .prop( 'disabled', this.isDisabled() );
12085 this.$element
.addClass( 'oo-ui-inputWidget' ).append( this.$input
, $( '<span>' ) );
12086 this.setValue( config
.value
);
12091 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
12092 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.FlaggedElement
);
12093 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.TabIndexedElement
);
12100 * A change event is emitted when the value of the input changes.
12102 * @param {string} value
12108 * Get input element.
12110 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
12111 * different circumstances. The element must have a `value` property (like form elements).
12114 * @param {Object} config Configuration options
12115 * @return {jQuery} Input element
12117 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
12118 return $( '<input>' );
12122 * Handle potentially value-changing events.
12125 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
12127 OO
.ui
.InputWidget
.prototype.onEdit = function () {
12129 if ( !this.isDisabled() ) {
12130 // Allow the stack to clear so the value will be updated
12131 setTimeout( function () {
12132 widget
.setValue( widget
.$input
.val() );
12138 * Get the value of the input.
12140 * @return {string} Input value
12142 OO
.ui
.InputWidget
.prototype.getValue = function () {
12143 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
12144 // it, and we won't know unless they're kind enough to trigger a 'change' event.
12145 var value
= this.$input
.val();
12146 if ( this.value
!== value
) {
12147 this.setValue( value
);
12153 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
12155 * @param {boolean} isRTL
12156 * Direction is right-to-left
12158 OO
.ui
.InputWidget
.prototype.setRTL = function ( isRTL
) {
12159 this.$input
.prop( 'dir', isRTL
? 'rtl' : 'ltr' );
12163 * Set the value of the input.
12165 * @param {string} value New value
12169 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
12170 value
= this.cleanUpValue( value
);
12171 // Update the DOM if it has changed. Note that with cleanUpValue, it
12172 // is possible for the DOM value to change without this.value changing.
12173 if ( this.$input
.val() !== value
) {
12174 this.$input
.val( value
);
12176 if ( this.value
!== value
) {
12177 this.value
= value
;
12178 this.emit( 'change', this.value
);
12184 * Clean up incoming value.
12186 * Ensures value is a string, and converts undefined and null to empty string.
12189 * @param {string} value Original value
12190 * @return {string} Cleaned up value
12192 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
12193 if ( value
=== undefined || value
=== null ) {
12195 } else if ( this.inputFilter
) {
12196 return this.inputFilter( String( value
) );
12198 return String( value
);
12203 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
12204 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
12207 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
12208 if ( !this.isDisabled() ) {
12209 if ( this.$input
.is( ':checkbox, :radio' ) ) {
12210 this.$input
.click();
12212 if ( this.$input
.is( ':input' ) ) {
12213 this.$input
[ 0 ].focus();
12221 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
12222 OO
.ui
.InputWidget
.super.prototype.setDisabled
.call( this, state
);
12223 if ( this.$input
) {
12224 this.$input
.prop( 'disabled', this.isDisabled() );
12234 OO
.ui
.InputWidget
.prototype.focus = function () {
12235 this.$input
[ 0 ].focus();
12244 OO
.ui
.InputWidget
.prototype.blur = function () {
12245 this.$input
[ 0 ].blur();
12250 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
12251 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
12252 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
12253 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
12254 * [OOjs UI documentation on MediaWiki] [1] for more information.
12257 * // A ButtonInputWidget rendered as an HTML button, the default.
12258 * var button = new OO.ui.ButtonInputWidget( {
12259 * label: 'Input button',
12263 * $( 'body' ).append( button.$element );
12265 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
12268 * @extends OO.ui.InputWidget
12269 * @mixins OO.ui.ButtonElement
12270 * @mixins OO.ui.IconElement
12271 * @mixins OO.ui.IndicatorElement
12272 * @mixins OO.ui.LabelElement
12273 * @mixins OO.ui.TitledElement
12276 * @param {Object} [config] Configuration options
12277 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
12278 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
12279 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
12280 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
12281 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
12283 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
12284 // Configuration initialization
12285 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
12287 // Properties (must be set before parent constructor, which calls #setValue)
12288 this.useInputTag
= config
.useInputTag
;
12290 // Parent constructor
12291 OO
.ui
.ButtonInputWidget
.super.call( this, config
);
12293 // Mixin constructors
12294 OO
.ui
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
12295 OO
.ui
.IconElement
.call( this, config
);
12296 OO
.ui
.IndicatorElement
.call( this, config
);
12297 OO
.ui
.LabelElement
.call( this, config
);
12298 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
12301 if ( !config
.useInputTag
) {
12302 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
12304 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
12309 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
12310 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.ButtonElement
);
12311 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.IconElement
);
12312 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.IndicatorElement
);
12313 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.LabelElement
);
12314 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.TitledElement
);
12322 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
12323 var html
= '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + config
.type
+ '">';
12330 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
12332 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
12333 * text, or `null` for no label
12336 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
12337 OO
.ui
.LabelElement
.prototype.setLabel
.call( this, label
);
12339 if ( this.useInputTag
) {
12340 if ( typeof label
=== 'function' ) {
12341 label
= OO
.ui
.resolveMsg( label
);
12343 if ( label
instanceof jQuery
) {
12344 label
= label
.text();
12349 this.$input
.val( label
);
12356 * Set the value of the input.
12358 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
12359 * they do not support {@link #value values}.
12361 * @param {string} value New value
12364 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
12365 if ( !this.useInputTag
) {
12366 OO
.ui
.ButtonInputWidget
.super.prototype.setValue
.call( this, value
);
12372 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
12373 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
12374 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
12375 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
12377 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
12380 * // An example of selected, unselected, and disabled checkbox inputs
12381 * var checkbox1=new OO.ui.CheckboxInputWidget( {
12385 * var checkbox2=new OO.ui.CheckboxInputWidget( {
12388 * var checkbox3=new OO.ui.CheckboxInputWidget( {
12392 * // Create a fieldset layout with fields for each checkbox.
12393 * var fieldset = new OO.ui.FieldsetLayout( {
12394 * label: 'Checkboxes'
12396 * fieldset.addItems( [
12397 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
12398 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
12399 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
12401 * $( 'body' ).append( fieldset.$element );
12403 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
12406 * @extends OO.ui.InputWidget
12409 * @param {Object} [config] Configuration options
12410 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
12412 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
12413 // Configuration initialization
12414 config
= config
|| {};
12416 // Parent constructor
12417 OO
.ui
.CheckboxInputWidget
.super.call( this, config
);
12420 this.$element
.addClass( 'oo-ui-checkboxInputWidget' );
12421 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
12426 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
12434 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
12435 return $( '<input type="checkbox" />' );
12441 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
12443 if ( !this.isDisabled() ) {
12444 // Allow the stack to clear so the value will be updated
12445 setTimeout( function () {
12446 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
12452 * Set selection state of this checkbox.
12454 * @param {boolean} state `true` for selected
12457 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
12459 if ( this.selected
!== state
) {
12460 this.selected
= state
;
12461 this.$input
.prop( 'checked', this.selected
);
12462 this.emit( 'change', this.selected
);
12468 * Check if this checkbox is selected.
12470 * @return {boolean} Checkbox is selected
12472 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
12473 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
12474 // it, and we won't know unless they're kind enough to trigger a 'change' event.
12475 var selected
= this.$input
.prop( 'checked' );
12476 if ( this.selected
!== selected
) {
12477 this.setSelected( selected
);
12479 return this.selected
;
12483 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
12484 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
12485 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
12486 * more information about input widgets.
12489 * // Example: A DropdownInputWidget with three options
12490 * var dropDown = new OO.ui.DropdownInputWidget( {
12491 * label: 'Dropdown menu: Select a menu option',
12493 * { data: 'a', label: 'First' } ,
12494 * { data: 'b', label: 'Second'} ,
12495 * { data: 'c', label: 'Third' }
12498 * $( 'body' ).append( dropDown.$element );
12500 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
12503 * @extends OO.ui.InputWidget
12506 * @param {Object} [config] Configuration options
12507 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
12509 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
12510 // Configuration initialization
12511 config
= config
|| {};
12513 // Properties (must be done before parent constructor which calls #setDisabled)
12514 this.dropdownWidget
= new OO
.ui
.DropdownWidget();
12516 // Parent constructor
12517 OO
.ui
.DropdownInputWidget
.super.call( this, config
);
12520 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
12523 this.setOptions( config
.options
|| [] );
12525 .addClass( 'oo-ui-dropdownInputWidget' )
12526 .append( this.dropdownWidget
.$element
);
12531 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
12539 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
12540 return $( '<input type="hidden">' );
12544 * Handles menu select events.
12547 * @param {OO.ui.MenuOptionWidget} item Selected menu item
12549 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
12550 this.setValue( item
.getData() );
12556 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
12557 this.dropdownWidget
.getMenu().selectItemByData( value
);
12558 OO
.ui
.DropdownInputWidget
.super.prototype.setValue
.call( this, value
);
12565 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
12566 this.dropdownWidget
.setDisabled( state
);
12567 OO
.ui
.DropdownInputWidget
.super.prototype.setDisabled
.call( this, state
);
12572 * Set the options available for this input.
12574 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
12577 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
12578 var value
= this.getValue();
12580 // Rebuild the dropdown menu
12581 this.dropdownWidget
.getMenu()
12583 .addItems( options
.map( function ( opt
) {
12584 return new OO
.ui
.MenuOptionWidget( {
12586 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
12590 // Restore the previous value, or reset to something sensible
12591 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
12592 // Previous value is still available, ensure consistency with the dropdown
12593 this.setValue( value
);
12595 // No longer valid, reset
12596 if ( options
.length
) {
12597 this.setValue( options
[ 0 ].data
);
12607 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
12608 this.dropdownWidget
.getMenu().toggle( true );
12615 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
12616 this.dropdownWidget
.getMenu().toggle( false );
12621 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
12622 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
12623 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
12624 * please see the [OOjs UI documentation on MediaWiki][1].
12626 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
12629 * // An example of selected, unselected, and disabled radio inputs
12630 * var radio1 = new OO.ui.RadioInputWidget( {
12634 * var radio2 = new OO.ui.RadioInputWidget( {
12637 * var radio3 = new OO.ui.RadioInputWidget( {
12641 * // Create a fieldset layout with fields for each radio button.
12642 * var fieldset = new OO.ui.FieldsetLayout( {
12643 * label: 'Radio inputs'
12645 * fieldset.addItems( [
12646 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
12647 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
12648 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
12650 * $( 'body' ).append( fieldset.$element );
12652 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
12655 * @extends OO.ui.InputWidget
12658 * @param {Object} [config] Configuration options
12659 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
12661 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
12662 // Configuration initialization
12663 config
= config
|| {};
12665 // Parent constructor
12666 OO
.ui
.RadioInputWidget
.super.call( this, config
);
12669 this.$element
.addClass( 'oo-ui-radioInputWidget' );
12670 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
12675 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
12683 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
12684 return $( '<input type="radio" />' );
12690 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
12691 // RadioInputWidget doesn't track its state.
12695 * Set selection state of this radio button.
12697 * @param {boolean} state `true` for selected
12700 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
12701 // RadioInputWidget doesn't track its state.
12702 this.$input
.prop( 'checked', state
);
12707 * Check if this radio button is selected.
12709 * @return {boolean} Radio is selected
12711 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
12712 return this.$input
.prop( 'checked' );
12716 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
12717 * size of the field as well as its presentation. In addition, these widgets can be configured
12718 * with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators}, an optional
12719 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
12720 * which modifies incoming values rather than validating them.
12721 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
12723 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
12726 * // Example of a text input widget
12727 * var textInput = new OO.ui.TextInputWidget( {
12728 * value: 'Text input'
12730 * $( 'body' ).append( textInput.$element );
12732 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
12735 * @extends OO.ui.InputWidget
12736 * @mixins OO.ui.IconElement
12737 * @mixins OO.ui.IndicatorElement
12738 * @mixins OO.ui.PendingElement
12739 * @mixins OO.ui.LabelElement
12742 * @param {Object} [config] Configuration options
12743 * @cfg {string} [type='text'] The value of the HTML `type` attribute
12744 * @cfg {string} [placeholder] Placeholder text
12745 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
12746 * instruct the browser to focus this widget.
12747 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
12748 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
12749 * @cfg {boolean} [multiline=false] Allow multiple lines of text
12750 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
12751 * Use the #maxRows config to specify a maximum number of displayed rows.
12752 * @cfg {boolean} [maxRows=10] Maximum number of rows to display when #autosize is set to true.
12753 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
12754 * the value or placeholder text: `'before'` or `'after'`
12755 * @cfg {boolean} [required=false] Mark the field as required
12756 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
12757 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
12758 * (the value must contain only numbers); when RegExp, a regular expression that must match the
12759 * value for it to be considered valid; when Function, a function receiving the value as parameter
12760 * that must return true, or promise resolving to true, for it to be considered valid.
12762 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
12763 // Configuration initialization
12764 config
= $.extend( {
12766 labelPosition
: 'after',
12770 // Parent constructor
12771 OO
.ui
.TextInputWidget
.super.call( this, config
);
12773 // Mixin constructors
12774 OO
.ui
.IconElement
.call( this, config
);
12775 OO
.ui
.IndicatorElement
.call( this, config
);
12776 OO
.ui
.PendingElement
.call( this, config
);
12777 OO
.ui
.LabelElement
.call( this, config
);
12780 this.readOnly
= false;
12781 this.multiline
= !!config
.multiline
;
12782 this.autosize
= !!config
.autosize
;
12783 this.maxRows
= config
.maxRows
;
12784 this.validate
= null;
12786 // Clone for resizing
12787 if ( this.autosize
) {
12788 this.$clone
= this.$input
12790 .insertAfter( this.$input
)
12791 .attr( 'aria-hidden', 'true' )
12792 .addClass( 'oo-ui-element-hidden' );
12795 this.setValidation( config
.validate
);
12796 this.setLabelPosition( config
.labelPosition
);
12800 keypress
: this.onKeyPress
.bind( this ),
12801 blur
: this.onBlur
.bind( this )
12804 focus
: this.onElementAttach
.bind( this )
12806 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
12807 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
12808 this.on( 'labelChange', this.updatePosition
.bind( this ) );
12809 this.connect( this, { change
: 'onChange' } );
12813 .addClass( 'oo-ui-textInputWidget' )
12814 .append( this.$icon
, this.$indicator
);
12815 this.setReadOnly( !!config
.readOnly
);
12816 if ( config
.placeholder
) {
12817 this.$input
.attr( 'placeholder', config
.placeholder
);
12819 if ( config
.maxLength
!== undefined ) {
12820 this.$input
.attr( 'maxlength', config
.maxLength
);
12822 if ( config
.autofocus
) {
12823 this.$input
.attr( 'autofocus', 'autofocus' );
12825 if ( config
.required
) {
12826 this.$input
.attr( 'required', 'required' );
12827 this.$input
.attr( 'aria-required', 'true' );
12829 if ( this.label
|| config
.autosize
) {
12830 this.installParentChangeDetector();
12836 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
12837 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.IconElement
);
12838 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.IndicatorElement
);
12839 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.PendingElement
);
12840 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.LabelElement
);
12842 /* Static properties */
12844 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
12852 * An `enter` event is emitted when the user presses 'enter' inside the text box.
12854 * Not emitted if the input is multiline.
12862 * Handle icon mouse down events.
12865 * @param {jQuery.Event} e Mouse down event
12868 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
12869 if ( e
.which
=== 1 ) {
12870 this.$input
[ 0 ].focus();
12876 * Handle indicator mouse down events.
12879 * @param {jQuery.Event} e Mouse down event
12882 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
12883 if ( e
.which
=== 1 ) {
12884 this.$input
[ 0 ].focus();
12890 * Handle key press events.
12893 * @param {jQuery.Event} e Key press event
12894 * @fires enter If enter key is pressed and input is not multiline
12896 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
12897 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
12898 this.emit( 'enter', e
);
12903 * Handle blur events.
12906 * @param {jQuery.Event} e Blur event
12908 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
12909 this.setValidityFlag();
12913 * Handle element attach events.
12916 * @param {jQuery.Event} e Element attach event
12918 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
12919 // Any previously calculated size is now probably invalid if we reattached elsewhere
12920 this.valCache
= null;
12922 this.positionLabel();
12926 * Handle change events.
12928 * @param {string} value
12931 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
12932 this.setValidityFlag();
12937 * Check if the input is {@link #readOnly read-only}.
12939 * @return {boolean}
12941 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
12942 return this.readOnly
;
12946 * Set the {@link #readOnly read-only} state of the input.
12948 * @param {boolean} state Make input read-only
12951 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
12952 this.readOnly
= !!state
;
12953 this.$input
.prop( 'readOnly', this.readOnly
);
12958 * Support function for making #onElementAttach work across browsers.
12960 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
12961 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
12963 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
12964 * first time that the element gets attached to the documented.
12966 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
12967 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
12968 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
12971 if ( MutationObserver
) {
12972 // The new way. If only it wasn't so ugly.
12974 if ( this.$element
.closest( 'html' ).length
) {
12975 // Widget is attached already, do nothing. This breaks the functionality of this function when
12976 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
12977 // would require observation of the whole document, which would hurt performance of other,
12978 // more important code.
12982 // Find topmost node in the tree
12983 topmostNode
= this.$element
[0];
12984 while ( topmostNode
.parentNode
) {
12985 topmostNode
= topmostNode
.parentNode
;
12988 // We have no way to detect the $element being attached somewhere without observing the entire
12989 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
12990 // parent node of $element, and instead detect when $element is removed from it (and thus
12991 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
12992 // doesn't get attached, we end up back here and create the parent.
12994 mutationObserver
= new MutationObserver( function ( mutations
) {
12995 var i
, j
, removedNodes
;
12996 for ( i
= 0; i
< mutations
.length
; i
++ ) {
12997 removedNodes
= mutations
[ i
].removedNodes
;
12998 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
12999 if ( removedNodes
[ j
] === topmostNode
) {
13000 setTimeout( onRemove
, 0 );
13007 onRemove = function () {
13008 // If the node was attached somewhere else, report it
13009 if ( widget
.$element
.closest( 'html' ).length
) {
13010 widget
.onElementAttach();
13012 mutationObserver
.disconnect();
13013 widget
.installParentChangeDetector();
13016 // Create a fake parent and observe it
13017 fakeParentNode
= $( '<div>' ).append( this.$element
)[0];
13018 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
13020 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
13021 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
13022 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
13027 * Automatically adjust the size of the text input.
13029 * This only affects #multiline inputs that are {@link #autosize autosized}.
13033 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
13034 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
, idealHeight
;
13036 if ( this.multiline
&& this.autosize
&& this.$input
.val() !== this.valCache
) {
13038 .val( this.$input
.val() )
13039 .attr( 'rows', '' )
13040 // Set inline height property to 0 to measure scroll height
13041 .css( 'height', 0 );
13043 this.$clone
.removeClass( 'oo-ui-element-hidden' );
13045 this.valCache
= this.$input
.val();
13047 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
13049 // Remove inline height property to measure natural heights
13050 this.$clone
.css( 'height', '' );
13051 innerHeight
= this.$clone
.innerHeight();
13052 outerHeight
= this.$clone
.outerHeight();
13054 // Measure max rows height
13056 .attr( 'rows', this.maxRows
)
13057 .css( 'height', 'auto' )
13059 maxInnerHeight
= this.$clone
.innerHeight();
13061 // Difference between reported innerHeight and scrollHeight with no scrollbars present
13062 // Equals 1 on Blink-based browsers and 0 everywhere else
13063 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
13064 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
13066 this.$clone
.addClass( 'oo-ui-element-hidden' );
13068 // Only apply inline height when expansion beyond natural height is needed
13069 if ( idealHeight
> innerHeight
) {
13070 // Use the difference between the inner and outer height as a buffer
13071 this.$input
.css( 'height', idealHeight
+ ( outerHeight
- innerHeight
) );
13073 this.$input
.css( 'height', '' );
13083 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
13084 return config
.multiline
? $( '<textarea>' ) : $( '<input type="' + config
.type
+ '" />' );
13088 * Check if the input supports multiple lines.
13090 * @return {boolean}
13092 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
13093 return !!this.multiline
;
13097 * Check if the input automatically adjusts its size.
13099 * @return {boolean}
13101 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
13102 return !!this.autosize
;
13106 * Select the entire text of the input.
13110 OO
.ui
.TextInputWidget
.prototype.select = function () {
13111 this.$input
.select();
13116 * Set the validation pattern.
13118 * The validation pattern is either a regular expression, a function, or the symbolic name of a
13119 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
13120 * value must contain only numbers).
13122 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
13123 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
13125 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
13126 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
13127 this.validate
= validate
;
13129 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
13134 * Sets the 'invalid' flag appropriately.
13136 * @param {boolean} [isValid] Optionally override validation result
13138 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
13140 setFlag = function ( valid
) {
13142 widget
.$input
.attr( 'aria-invalid', 'true' );
13144 widget
.$input
.removeAttr( 'aria-invalid' );
13146 widget
.setFlags( { invalid
: !valid
} );
13149 if ( isValid
!== undefined ) {
13150 setFlag( isValid
);
13152 this.isValid().done( setFlag
);
13157 * Check if a value is valid.
13159 * This method returns a promise that resolves with a boolean `true` if the current value is
13160 * considered valid according to the supplied {@link #validate validation pattern}.
13162 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
13164 OO
.ui
.TextInputWidget
.prototype.isValid = function () {
13165 if ( this.validate
instanceof Function
) {
13166 var result
= this.validate( this.getValue() );
13167 if ( $.isFunction( result
.promise
) ) {
13168 return result
.promise();
13170 return $.Deferred().resolve( !!result
).promise();
13173 return $.Deferred().resolve( !!this.getValue().match( this.validate
) ).promise();
13178 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
13180 * @param {string} labelPosition Label position, 'before' or 'after'
13183 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
13184 this.labelPosition
= labelPosition
;
13185 this.updatePosition();
13190 * Deprecated alias of #setLabelPosition
13192 * @deprecated Use setLabelPosition instead.
13194 OO
.ui
.TextInputWidget
.prototype.setPosition
=
13195 OO
.ui
.TextInputWidget
.prototype.setLabelPosition
;
13198 * Update the position of the inline label.
13200 * This method is called by #setLabelPosition, and can also be called on its own if
13201 * something causes the label to be mispositioned.
13206 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
13207 var after
= this.labelPosition
=== 'after';
13210 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
13211 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
13213 if ( this.label
) {
13214 this.positionLabel();
13221 * Position the label by setting the correct padding on the input.
13226 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
13227 // Clear old values
13229 // Clear old values if present
13231 'padding-right': '',
13235 if ( this.label
) {
13236 this.$element
.append( this.$label
);
13238 this.$label
.detach();
13242 var after
= this.labelPosition
=== 'after',
13243 rtl
= this.$element
.css( 'direction' ) === 'rtl',
13244 property
= after
=== rtl
? 'padding-left' : 'padding-right';
13246 this.$input
.css( property
, this.$label
.outerWidth( true ) );
13252 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
13253 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
13254 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
13256 * - by typing a value in the text input field. If the value exactly matches the value of a menu
13257 * option, that option will appear to be selected.
13258 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
13261 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
13264 * // Example: A ComboBoxWidget.
13265 * var comboBox = new OO.ui.ComboBoxWidget( {
13266 * label: 'ComboBoxWidget',
13267 * input: { value: 'Option One' },
13270 * new OO.ui.MenuOptionWidget( {
13271 * data: 'Option 1',
13272 * label: 'Option One'
13274 * new OO.ui.MenuOptionWidget( {
13275 * data: 'Option 2',
13276 * label: 'Option Two'
13278 * new OO.ui.MenuOptionWidget( {
13279 * data: 'Option 3',
13280 * label: 'Option Three'
13282 * new OO.ui.MenuOptionWidget( {
13283 * data: 'Option 4',
13284 * label: 'Option Four'
13286 * new OO.ui.MenuOptionWidget( {
13287 * data: 'Option 5',
13288 * label: 'Option Five'
13293 * $( 'body' ).append( comboBox.$element );
13295 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13298 * @extends OO.ui.Widget
13299 * @mixins OO.ui.TabIndexedElement
13302 * @param {Object} [config] Configuration options
13303 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
13304 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
13305 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
13306 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
13307 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
13309 OO
.ui
.ComboBoxWidget
= function OoUiComboBoxWidget( config
) {
13310 // Configuration initialization
13311 config
= config
|| {};
13313 // Parent constructor
13314 OO
.ui
.ComboBoxWidget
.super.call( this, config
);
13316 // Properties (must be set before TabIndexedElement constructor call)
13317 this.$indicator
= this.$( '<span>' );
13319 // Mixin constructors
13320 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
13323 this.$overlay
= config
.$overlay
|| this.$element
;
13324 this.input
= new OO
.ui
.TextInputWidget( $.extend(
13327 $indicator
: this.$indicator
,
13328 disabled
: this.isDisabled()
13332 this.input
.$input
.eq( 0 ).attr( {
13334 'aria-autocomplete': 'list'
13336 this.menu
= new OO
.ui
.TextInputMenuSelectWidget( this.input
, $.extend(
13340 disabled
: this.isDisabled()
13346 this.$indicator
.on( {
13347 click
: this.onClick
.bind( this ),
13348 keypress
: this.onKeyPress
.bind( this )
13350 this.input
.connect( this, {
13351 change
: 'onInputChange',
13352 enter
: 'onInputEnter'
13354 this.menu
.connect( this, {
13355 choose
: 'onMenuChoose',
13356 add
: 'onMenuItemsChange',
13357 remove
: 'onMenuItemsChange'
13361 this.$element
.addClass( 'oo-ui-comboBoxWidget' ).append( this.input
.$element
);
13362 this.$overlay
.append( this.menu
.$element
);
13363 this.onMenuItemsChange();
13368 OO
.inheritClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.Widget
);
13369 OO
.mixinClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.TabIndexedElement
);
13374 * Get the combobox's menu.
13375 * @return {OO.ui.TextInputMenuSelectWidget} Menu widget
13377 OO
.ui
.ComboBoxWidget
.prototype.getMenu = function () {
13382 * Handle input change events.
13385 * @param {string} value New value
13387 OO
.ui
.ComboBoxWidget
.prototype.onInputChange = function ( value
) {
13388 var match
= this.menu
.getItemFromData( value
);
13390 this.menu
.selectItem( match
);
13391 if ( this.menu
.getHighlightedItem() ) {
13392 this.menu
.highlightItem( match
);
13395 if ( !this.isDisabled() ) {
13396 this.menu
.toggle( true );
13401 * Handle mouse click events.
13405 * @param {jQuery.Event} e Mouse click event
13407 OO
.ui
.ComboBoxWidget
.prototype.onClick = function ( e
) {
13408 if ( !this.isDisabled() && e
.which
=== 1 ) {
13409 this.menu
.toggle();
13410 this.input
.$input
[ 0 ].focus();
13416 * Handle key press events.
13420 * @param {jQuery.Event} e Key press event
13422 OO
.ui
.ComboBoxWidget
.prototype.onKeyPress = function ( e
) {
13423 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
13424 this.menu
.toggle();
13425 this.input
.$input
[ 0 ].focus();
13431 * Handle input enter events.
13435 OO
.ui
.ComboBoxWidget
.prototype.onInputEnter = function () {
13436 if ( !this.isDisabled() ) {
13437 this.menu
.toggle( false );
13442 * Handle menu choose events.
13445 * @param {OO.ui.OptionWidget} item Chosen item
13447 OO
.ui
.ComboBoxWidget
.prototype.onMenuChoose = function ( item
) {
13448 this.input
.setValue( item
.getData() );
13452 * Handle menu item change events.
13456 OO
.ui
.ComboBoxWidget
.prototype.onMenuItemsChange = function () {
13457 var match
= this.menu
.getItemFromData( this.input
.getValue() );
13458 this.menu
.selectItem( match
);
13459 if ( this.menu
.getHighlightedItem() ) {
13460 this.menu
.highlightItem( match
);
13462 this.$element
.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu
.isEmpty() );
13468 OO
.ui
.ComboBoxWidget
.prototype.setDisabled = function ( disabled
) {
13470 OO
.ui
.ComboBoxWidget
.super.prototype.setDisabled
.call( this, disabled
);
13472 if ( this.input
) {
13473 this.input
.setDisabled( this.isDisabled() );
13476 this.menu
.setDisabled( this.isDisabled() );
13483 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
13484 * be configured with a `label` option that is set to a string, a label node, or a function:
13486 * - String: a plaintext string
13487 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
13488 * label that includes a link or special styling, such as a gray color or additional graphical elements.
13489 * - Function: a function that will produce a string in the future. Functions are used
13490 * in cases where the value of the label is not currently defined.
13492 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
13493 * will come into focus when the label is clicked.
13496 * // Examples of LabelWidgets
13497 * var label1 = new OO.ui.LabelWidget( {
13498 * label: 'plaintext label'
13500 * var label2 = new OO.ui.LabelWidget( {
13501 * label: $( '<a href="default.html">jQuery label</a>' )
13503 * // Create a fieldset layout with fields for each example
13504 * var fieldset = new OO.ui.FieldsetLayout();
13505 * fieldset.addItems( [
13506 * new OO.ui.FieldLayout( label1 ),
13507 * new OO.ui.FieldLayout( label2 )
13509 * $( 'body' ).append( fieldset.$element );
13513 * @extends OO.ui.Widget
13514 * @mixins OO.ui.LabelElement
13517 * @param {Object} [config] Configuration options
13518 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
13519 * Clicking the label will focus the specified input field.
13521 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
13522 // Configuration initialization
13523 config
= config
|| {};
13525 // Parent constructor
13526 OO
.ui
.LabelWidget
.super.call( this, config
);
13528 // Mixin constructors
13529 OO
.ui
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
13530 OO
.ui
.TitledElement
.call( this, config
);
13533 this.input
= config
.input
;
13536 if ( this.input
instanceof OO
.ui
.InputWidget
) {
13537 this.$element
.on( 'click', this.onClick
.bind( this ) );
13541 this.$element
.addClass( 'oo-ui-labelWidget' );
13546 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
13547 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.LabelElement
);
13548 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.TitledElement
);
13550 /* Static Properties */
13552 OO
.ui
.LabelWidget
.static.tagName
= 'span';
13557 * Handles label mouse click events.
13560 * @param {jQuery.Event} e Mouse click event
13562 OO
.ui
.LabelWidget
.prototype.onClick = function () {
13563 this.input
.simulateLabelClick();
13568 * OptionWidgets are special elements that can be selected and configured with data. The
13569 * data is often unique for each option, but it does not have to be. OptionWidgets are used
13570 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
13571 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
13573 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13576 * @extends OO.ui.Widget
13577 * @mixins OO.ui.LabelElement
13578 * @mixins OO.ui.FlaggedElement
13581 * @param {Object} [config] Configuration options
13583 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
13584 // Configuration initialization
13585 config
= config
|| {};
13587 // Parent constructor
13588 OO
.ui
.OptionWidget
.super.call( this, config
);
13590 // Mixin constructors
13591 OO
.ui
.ItemWidget
.call( this );
13592 OO
.ui
.LabelElement
.call( this, config
);
13593 OO
.ui
.FlaggedElement
.call( this, config
);
13596 this.selected
= false;
13597 this.highlighted
= false;
13598 this.pressed
= false;
13602 .data( 'oo-ui-optionWidget', this )
13603 .attr( 'role', 'option' )
13604 .addClass( 'oo-ui-optionWidget' )
13605 .append( this.$label
);
13610 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
13611 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.ItemWidget
);
13612 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.LabelElement
);
13613 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.FlaggedElement
);
13615 /* Static Properties */
13617 OO
.ui
.OptionWidget
.static.selectable
= true;
13619 OO
.ui
.OptionWidget
.static.highlightable
= true;
13621 OO
.ui
.OptionWidget
.static.pressable
= true;
13623 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
13628 * Check if the option can be selected.
13630 * @return {boolean} Item is selectable
13632 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
13633 return this.constructor.static.selectable
&& !this.isDisabled();
13637 * Check if the option can be highlighted. A highlight indicates that the option
13638 * may be selected when a user presses enter or clicks. Disabled items cannot
13641 * @return {boolean} Item is highlightable
13643 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
13644 return this.constructor.static.highlightable
&& !this.isDisabled();
13648 * Check if the option can be pressed. The pressed state occurs when a user mouses
13649 * down on an item, but has not yet let go of the mouse.
13651 * @return {boolean} Item is pressable
13653 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
13654 return this.constructor.static.pressable
&& !this.isDisabled();
13658 * Check if the option is selected.
13660 * @return {boolean} Item is selected
13662 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
13663 return this.selected
;
13667 * Check if the option is highlighted. A highlight indicates that the
13668 * item may be selected when a user presses enter or clicks.
13670 * @return {boolean} Item is highlighted
13672 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
13673 return this.highlighted
;
13677 * Check if the option is pressed. The pressed state occurs when a user mouses
13678 * down on an item, but has not yet let go of the mouse. The item may appear
13679 * selected, but it will not be selected until the user releases the mouse.
13681 * @return {boolean} Item is pressed
13683 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
13684 return this.pressed
;
13688 * Set the option’s selected state. In general, all modifications to the selection
13689 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
13690 * method instead of this method.
13692 * @param {boolean} [state=false] Select option
13695 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
13696 if ( this.constructor.static.selectable
) {
13697 this.selected
= !!state
;
13699 .toggleClass( 'oo-ui-optionWidget-selected', state
)
13700 .attr( 'aria-selected', state
.toString() );
13701 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
13702 this.scrollElementIntoView();
13704 this.updateThemeClasses();
13710 * Set the option’s highlighted state. In general, all programmatic
13711 * modifications to the highlight should be handled by the
13712 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
13713 * method instead of this method.
13715 * @param {boolean} [state=false] Highlight option
13718 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
13719 if ( this.constructor.static.highlightable
) {
13720 this.highlighted
= !!state
;
13721 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
13722 this.updateThemeClasses();
13728 * Set the option’s pressed state. In general, all
13729 * programmatic modifications to the pressed state should be handled by the
13730 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
13731 * method instead of this method.
13733 * @param {boolean} [state=false] Press option
13736 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
13737 if ( this.constructor.static.pressable
) {
13738 this.pressed
= !!state
;
13739 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
13740 this.updateThemeClasses();
13746 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
13747 * with an {@link OO.ui.IconElement icon} and/or {@link OO.ui.IndicatorElement indicator}.
13748 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
13749 * options. For more information about options and selects, please see the
13750 * [OOjs UI documentation on MediaWiki][1].
13753 * // Decorated options in a select widget
13754 * var select = new OO.ui.SelectWidget( {
13756 * new OO.ui.DecoratedOptionWidget( {
13758 * label: 'Option with icon',
13761 * new OO.ui.DecoratedOptionWidget( {
13763 * label: 'Option with indicator',
13764 * indicator: 'next'
13768 * $( 'body' ).append( select.$element );
13770 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13773 * @extends OO.ui.OptionWidget
13774 * @mixins OO.ui.IconElement
13775 * @mixins OO.ui.IndicatorElement
13778 * @param {Object} [config] Configuration options
13780 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
13781 // Parent constructor
13782 OO
.ui
.DecoratedOptionWidget
.super.call( this, config
);
13784 // Mixin constructors
13785 OO
.ui
.IconElement
.call( this, config
);
13786 OO
.ui
.IndicatorElement
.call( this, config
);
13790 .addClass( 'oo-ui-decoratedOptionWidget' )
13791 .prepend( this.$icon
)
13792 .append( this.$indicator
);
13797 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
13798 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.IconElement
);
13799 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.IndicatorElement
);
13802 * ButtonOptionWidget is a special type of {@link OO.ui.ButtonElement button element} that
13803 * can be selected and configured with data. The class is
13804 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
13805 * [OOjs UI documentation on MediaWiki] [1] for more information.
13807 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
13810 * @extends OO.ui.DecoratedOptionWidget
13811 * @mixins OO.ui.ButtonElement
13812 * @mixins OO.ui.TabIndexedElement
13815 * @param {Object} [config] Configuration options
13817 OO
.ui
.ButtonOptionWidget
= function OoUiButtonOptionWidget( config
) {
13818 // Configuration initialization
13819 config
= $.extend( { tabIndex
: -1 }, config
);
13821 // Parent constructor
13822 OO
.ui
.ButtonOptionWidget
.super.call( this, config
);
13824 // Mixin constructors
13825 OO
.ui
.ButtonElement
.call( this, config
);
13826 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
13829 this.$element
.addClass( 'oo-ui-buttonOptionWidget' );
13830 this.$button
.append( this.$element
.contents() );
13831 this.$element
.append( this.$button
);
13836 OO
.inheritClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
13837 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.ButtonElement
);
13838 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.TabIndexedElement
);
13840 /* Static Properties */
13842 // Allow button mouse down events to pass through so they can be handled by the parent select widget
13843 OO
.ui
.ButtonOptionWidget
.static.cancelButtonMouseDownEvents
= false;
13845 OO
.ui
.ButtonOptionWidget
.static.highlightable
= false;
13852 OO
.ui
.ButtonOptionWidget
.prototype.setSelected = function ( state
) {
13853 OO
.ui
.ButtonOptionWidget
.super.prototype.setSelected
.call( this, state
);
13855 if ( this.constructor.static.selectable
) {
13856 this.setActive( state
);
13863 * RadioOptionWidget is an option widget that looks like a radio button.
13864 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
13865 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
13867 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
13870 * @extends OO.ui.OptionWidget
13873 * @param {Object} [config] Configuration options
13875 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
13876 // Configuration initialization
13877 config
= config
|| {};
13879 // Properties (must be done before parent constructor which calls #setDisabled)
13880 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
13882 // Parent constructor
13883 OO
.ui
.RadioOptionWidget
.super.call( this, config
);
13887 .addClass( 'oo-ui-radioOptionWidget' )
13888 .prepend( this.radio
.$element
);
13893 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
13895 /* Static Properties */
13897 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
13899 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
13901 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
13903 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
13910 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
13911 OO
.ui
.RadioOptionWidget
.super.prototype.setSelected
.call( this, state
);
13913 this.radio
.setSelected( state
);
13921 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
13922 OO
.ui
.RadioOptionWidget
.super.prototype.setDisabled
.call( this, disabled
);
13924 this.radio
.setDisabled( this.isDisabled() );
13930 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
13931 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
13932 * the [OOjs UI documentation on MediaWiki] [1] for more information.
13934 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13937 * @extends OO.ui.DecoratedOptionWidget
13940 * @param {Object} [config] Configuration options
13942 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
13943 // Configuration initialization
13944 config
= $.extend( { icon
: 'check' }, config
);
13946 // Parent constructor
13947 OO
.ui
.MenuOptionWidget
.super.call( this, config
);
13951 .attr( 'role', 'menuitem' )
13952 .addClass( 'oo-ui-menuOptionWidget' );
13957 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
13959 /* Static Properties */
13961 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
13964 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
13965 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
13968 * var myDropdown = new OO.ui.DropdownWidget( {
13971 * new OO.ui.MenuSectionOptionWidget( {
13974 * new OO.ui.MenuOptionWidget( {
13976 * label: 'Welsh Corgi'
13978 * new OO.ui.MenuOptionWidget( {
13980 * label: 'Standard Poodle'
13982 * new OO.ui.MenuSectionOptionWidget( {
13985 * new OO.ui.MenuOptionWidget( {
13992 * $( 'body' ).append( myDropdown.$element );
13996 * @extends OO.ui.DecoratedOptionWidget
13999 * @param {Object} [config] Configuration options
14001 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
14002 // Parent constructor
14003 OO
.ui
.MenuSectionOptionWidget
.super.call( this, config
);
14006 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
14011 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
14013 /* Static Properties */
14015 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
14017 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
14020 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
14022 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
14023 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
14027 * @extends OO.ui.DecoratedOptionWidget
14030 * @param {Object} [config] Configuration options
14031 * @cfg {number} [level] Indentation level
14032 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
14034 OO
.ui
.OutlineOptionWidget
= function OoUiOutlineOptionWidget( config
) {
14035 // Configuration initialization
14036 config
= config
|| {};
14038 // Parent constructor
14039 OO
.ui
.OutlineOptionWidget
.super.call( this, config
);
14043 this.movable
= !!config
.movable
;
14044 this.removable
= !!config
.removable
;
14047 this.$element
.addClass( 'oo-ui-outlineOptionWidget' );
14048 this.setLevel( config
.level
);
14053 OO
.inheritClass( OO
.ui
.OutlineOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
14055 /* Static Properties */
14057 OO
.ui
.OutlineOptionWidget
.static.highlightable
= false;
14059 OO
.ui
.OutlineOptionWidget
.static.scrollIntoViewOnSelect
= true;
14061 OO
.ui
.OutlineOptionWidget
.static.levelClass
= 'oo-ui-outlineOptionWidget-level-';
14063 OO
.ui
.OutlineOptionWidget
.static.levels
= 3;
14068 * Check if item is movable.
14070 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
14072 * @return {boolean} Item is movable
14074 OO
.ui
.OutlineOptionWidget
.prototype.isMovable = function () {
14075 return this.movable
;
14079 * Check if item is removable.
14081 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
14083 * @return {boolean} Item is removable
14085 OO
.ui
.OutlineOptionWidget
.prototype.isRemovable = function () {
14086 return this.removable
;
14090 * Get indentation level.
14092 * @return {number} Indentation level
14094 OO
.ui
.OutlineOptionWidget
.prototype.getLevel = function () {
14101 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
14103 * @param {boolean} movable Item is movable
14106 OO
.ui
.OutlineOptionWidget
.prototype.setMovable = function ( movable
) {
14107 this.movable
= !!movable
;
14108 this.updateThemeClasses();
14113 * Set removability.
14115 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
14117 * @param {boolean} movable Item is removable
14120 OO
.ui
.OutlineOptionWidget
.prototype.setRemovable = function ( removable
) {
14121 this.removable
= !!removable
;
14122 this.updateThemeClasses();
14127 * Set indentation level.
14129 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
14132 OO
.ui
.OutlineOptionWidget
.prototype.setLevel = function ( level
) {
14133 var levels
= this.constructor.static.levels
,
14134 levelClass
= this.constructor.static.levelClass
,
14137 this.level
= level
? Math
.max( 0, Math
.min( levels
- 1, level
) ) : 0;
14139 if ( this.level
=== i
) {
14140 this.$element
.addClass( levelClass
+ i
);
14142 this.$element
.removeClass( levelClass
+ i
);
14145 this.updateThemeClasses();
14151 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
14153 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
14154 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
14158 * @extends OO.ui.OptionWidget
14161 * @param {Object} [config] Configuration options
14163 OO
.ui
.TabOptionWidget
= function OoUiTabOptionWidget( config
) {
14164 // Configuration initialization
14165 config
= config
|| {};
14167 // Parent constructor
14168 OO
.ui
.TabOptionWidget
.super.call( this, config
);
14171 this.$element
.addClass( 'oo-ui-tabOptionWidget' );
14176 OO
.inheritClass( OO
.ui
.TabOptionWidget
, OO
.ui
.OptionWidget
);
14178 /* Static Properties */
14180 OO
.ui
.TabOptionWidget
.static.highlightable
= false;
14183 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
14184 * By default, each popup has an anchor that points toward its origin.
14185 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
14188 * // A popup widget.
14189 * var popup = new OO.ui.PopupWidget( {
14190 * $content: $( '<p>Hi there!</p>' ),
14195 * $( 'body' ).append( popup.$element );
14196 * // To display the popup, toggle the visibility to 'true'.
14197 * popup.toggle( true );
14199 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
14202 * @extends OO.ui.Widget
14203 * @mixins OO.ui.LabelElement
14206 * @param {Object} [config] Configuration options
14207 * @cfg {number} [width=320] Width of popup in pixels
14208 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
14209 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
14210 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
14211 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
14212 * popup is leaning towards the right of the screen.
14213 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
14214 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
14215 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
14216 * sentence in the given language.
14217 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
14218 * See the [OOjs UI docs on MediaWiki][3] for an example.
14219 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
14220 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
14221 * @cfg {jQuery} [$content] Content to append to the popup's body
14222 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
14223 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
14224 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
14226 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
14227 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
14229 * @cfg {boolean} [padded] Add padding to the popup's body
14231 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
14232 // Configuration initialization
14233 config
= config
|| {};
14235 // Parent constructor
14236 OO
.ui
.PopupWidget
.super.call( this, config
);
14238 // Properties (must be set before ClippableElement constructor call)
14239 this.$body
= $( '<div>' );
14241 // Mixin constructors
14242 OO
.ui
.LabelElement
.call( this, config
);
14243 OO
.ui
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$body
} ) );
14246 this.$popup
= $( '<div>' );
14247 this.$head
= $( '<div>' );
14248 this.$anchor
= $( '<div>' );
14249 // If undefined, will be computed lazily in updateDimensions()
14250 this.$container
= config
.$container
;
14251 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
14252 this.autoClose
= !!config
.autoClose
;
14253 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
14254 this.transitionTimeout
= null;
14255 this.anchor
= null;
14256 this.width
= config
.width
!== undefined ? config
.width
: 320;
14257 this.height
= config
.height
!== undefined ? config
.height
: null;
14258 this.setAlignment( config
.align
);
14259 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
14260 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
14261 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
14264 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
14267 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
14268 this.$body
.addClass( 'oo-ui-popupWidget-body' );
14269 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
14271 .addClass( 'oo-ui-popupWidget-head' )
14272 .append( this.$label
, this.closeButton
.$element
);
14273 if ( !config
.head
) {
14274 this.$head
.addClass( 'oo-ui-element-hidden' );
14277 .addClass( 'oo-ui-popupWidget-popup' )
14278 .append( this.$head
, this.$body
);
14280 .addClass( 'oo-ui-popupWidget' )
14281 .append( this.$popup
, this.$anchor
);
14282 // Move content, which was added to #$element by OO.ui.Widget, to the body
14283 if ( config
.$content
instanceof jQuery
) {
14284 this.$body
.append( config
.$content
);
14286 if ( config
.padded
) {
14287 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
14290 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
14291 // that reference properties not initialized at that time of parent class construction
14292 // TODO: Find a better way to handle post-constructor setup
14293 this.visible
= false;
14294 this.$element
.addClass( 'oo-ui-element-hidden' );
14299 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
14300 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.LabelElement
);
14301 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.ClippableElement
);
14306 * Handles mouse down events.
14309 * @param {MouseEvent} e Mouse down event
14311 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
14313 this.isVisible() &&
14314 !$.contains( this.$element
[ 0 ], e
.target
) &&
14315 ( !this.$autoCloseIgnore
|| !this.$autoCloseIgnore
.has( e
.target
).length
)
14317 this.toggle( false );
14322 * Bind mouse down listener.
14326 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
14327 // Capture clicks outside popup
14328 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler
, true );
14332 * Handles close button click events.
14336 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
14337 if ( this.isVisible() ) {
14338 this.toggle( false );
14343 * Unbind mouse down listener.
14347 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
14348 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler
, true );
14352 * Handles key down events.
14355 * @param {KeyboardEvent} e Key down event
14357 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
14359 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
14362 this.toggle( false );
14363 e
.preventDefault();
14364 e
.stopPropagation();
14369 * Bind key down listener.
14373 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
14374 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
14378 * Unbind key down listener.
14382 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
14383 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
14387 * Show, hide, or toggle the visibility of the anchor.
14389 * @param {boolean} [show] Show anchor, omit to toggle
14391 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
14392 show
= show
=== undefined ? !this.anchored
: !!show
;
14394 if ( this.anchored
!== show
) {
14396 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
14398 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
14400 this.anchored
= show
;
14405 * Check if the anchor is visible.
14407 * @return {boolean} Anchor is visible
14409 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
14410 return this.anchor
;
14416 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
14417 show
= show
=== undefined ? !this.isVisible() : !!show
;
14419 var change
= show
!== this.isVisible();
14422 OO
.ui
.PopupWidget
.super.prototype.toggle
.call( this, show
);
14426 if ( this.autoClose
) {
14427 this.bindMouseDownListener();
14428 this.bindKeyDownListener();
14430 this.updateDimensions();
14431 this.toggleClipping( true );
14433 this.toggleClipping( false );
14434 if ( this.autoClose
) {
14435 this.unbindMouseDownListener();
14436 this.unbindKeyDownListener();
14445 * Set the size of the popup.
14447 * Changing the size may also change the popup's position depending on the alignment.
14449 * @param {number} width Width in pixels
14450 * @param {number} height Height in pixels
14451 * @param {boolean} [transition=false] Use a smooth transition
14454 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
14455 this.width
= width
;
14456 this.height
= height
!== undefined ? height
: null;
14457 if ( this.isVisible() ) {
14458 this.updateDimensions( transition
);
14463 * Update the size and position.
14465 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
14466 * be called automatically.
14468 * @param {boolean} [transition=false] Use a smooth transition
14471 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
14472 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
14473 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
14474 align
= this.align
,
14477 if ( !this.$container
) {
14478 // Lazy-initialize $container if not specified in constructor
14479 this.$container
= $( this.getClosestScrollableElementContainer() );
14482 // Set height and width before measuring things, since it might cause our measurements
14483 // to change (e.g. due to scrollbars appearing or disappearing)
14486 height
: this.height
!== null ? this.height
: 'auto'
14489 // If we are in RTL, we need to flip the alignment, unless it is center
14490 if ( align
=== 'forwards' || align
=== 'backwards' ) {
14491 if ( this.$container
.css( 'direction' ) === 'rtl' ) {
14492 align
= ( { forwards
: 'force-left', backwards
: 'force-right' } )[ this.align
];
14494 align
= ( { forwards
: 'force-right', backwards
: 'force-left' } )[ this.align
];
14499 // Compute initial popupOffset based on alignment
14500 popupOffset
= this.width
* ( { 'force-left': -1, center
: -0.5, 'force-right': 0 } )[ align
];
14502 // Figure out if this will cause the popup to go beyond the edge of the container
14503 originOffset
= this.$element
.offset().left
;
14504 containerLeft
= this.$container
.offset().left
;
14505 containerWidth
= this.$container
.innerWidth();
14506 containerRight
= containerLeft
+ containerWidth
;
14507 popupLeft
= popupOffset
- this.containerPadding
;
14508 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
14509 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
14510 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
14512 // Adjust offset to make the popup not go beyond the edge, if needed
14513 if ( overlapRight
< 0 ) {
14514 popupOffset
+= overlapRight
;
14515 } else if ( overlapLeft
< 0 ) {
14516 popupOffset
-= overlapLeft
;
14519 // Adjust offset to avoid anchor being rendered too close to the edge
14520 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
14521 // TODO: Find a measurement that works for CSS anchors and image anchors
14522 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
14523 if ( popupOffset
+ this.width
< anchorWidth
) {
14524 popupOffset
= anchorWidth
- this.width
;
14525 } else if ( -popupOffset
< anchorWidth
) {
14526 popupOffset
= -anchorWidth
;
14529 // Prevent transition from being interrupted
14530 clearTimeout( this.transitionTimeout
);
14531 if ( transition
) {
14532 // Enable transition
14533 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
14536 // Position body relative to anchor
14537 this.$popup
.css( 'margin-left', popupOffset
);
14539 if ( transition
) {
14540 // Prevent transitioning after transition is complete
14541 this.transitionTimeout
= setTimeout( function () {
14542 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
14545 // Prevent transitioning immediately
14546 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
14549 // Reevaluate clipping state since we've relocated and resized the popup
14556 * Set popup alignment
14557 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
14558 * `backwards` or `forwards`.
14560 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
14561 // Validate alignment and transform deprecated values
14562 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
14563 this.align
= { left
: 'force-right', right
: 'force-left' }[ align
] || align
;
14565 this.align
= 'center';
14570 * Get popup alignment
14571 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
14572 * `backwards` or `forwards`.
14574 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
14579 * Progress bars visually display the status of an operation, such as a download,
14580 * and can be either determinate or indeterminate:
14582 * - **determinate** process bars show the percent of an operation that is complete.
14584 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
14585 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
14586 * not use percentages.
14588 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
14591 * // Examples of determinate and indeterminate progress bars.
14592 * var progressBar1 = new OO.ui.ProgressBarWidget( {
14595 * var progressBar2 = new OO.ui.ProgressBarWidget();
14597 * // Create a FieldsetLayout to layout progress bars
14598 * var fieldset = new OO.ui.FieldsetLayout;
14599 * fieldset.addItems( [
14600 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
14601 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
14603 * $( 'body' ).append( fieldset.$element );
14606 * @extends OO.ui.Widget
14609 * @param {Object} [config] Configuration options
14610 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
14611 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
14612 * By default, the progress bar is indeterminate.
14614 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
14615 // Configuration initialization
14616 config
= config
|| {};
14618 // Parent constructor
14619 OO
.ui
.ProgressBarWidget
.super.call( this, config
);
14622 this.$bar
= $( '<div>' );
14623 this.progress
= null;
14626 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
14627 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
14630 role
: 'progressbar',
14631 'aria-valuemin': 0,
14632 'aria-valuemax': 100
14634 .addClass( 'oo-ui-progressBarWidget' )
14635 .append( this.$bar
);
14640 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
14642 /* Static Properties */
14644 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
14649 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
14651 * @return {number|boolean} Progress percent
14653 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
14654 return this.progress
;
14658 * Set the percent of the process completed or `false` for an indeterminate process.
14660 * @param {number|boolean} progress Progress percent or `false` for indeterminate
14662 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
14663 this.progress
= progress
;
14665 if ( progress
!== false ) {
14666 this.$bar
.css( 'width', this.progress
+ '%' );
14667 this.$element
.attr( 'aria-valuenow', this.progress
);
14669 this.$bar
.css( 'width', '' );
14670 this.$element
.removeAttr( 'aria-valuenow' );
14672 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress
);
14676 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
14677 * and a {@link OO.ui.TextInputMenuSelectWidget menu} of search results, which is displayed beneath the query
14678 * field. Unlike {@link OO.ui.LookupElement lookup menus}, search result menus are always visible to the user.
14679 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
14680 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
14682 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
14683 * the [OOjs UI demos][1] for an example.
14685 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
14688 * @extends OO.ui.Widget
14691 * @param {Object} [config] Configuration options
14692 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
14693 * @cfg {string} [value] Initial query value
14695 OO
.ui
.SearchWidget
= function OoUiSearchWidget( config
) {
14696 // Configuration initialization
14697 config
= config
|| {};
14699 // Parent constructor
14700 OO
.ui
.SearchWidget
.super.call( this, config
);
14703 this.query
= new OO
.ui
.TextInputWidget( {
14705 placeholder
: config
.placeholder
,
14706 value
: config
.value
14708 this.results
= new OO
.ui
.SelectWidget();
14709 this.$query
= $( '<div>' );
14710 this.$results
= $( '<div>' );
14713 this.query
.connect( this, {
14714 change
: 'onQueryChange',
14715 enter
: 'onQueryEnter'
14717 this.results
.connect( this, {
14718 highlight
: 'onResultsHighlight',
14719 select
: 'onResultsSelect'
14721 this.query
.$input
.on( 'keydown', this.onQueryKeydown
.bind( this ) );
14725 .addClass( 'oo-ui-searchWidget-query' )
14726 .append( this.query
.$element
);
14728 .addClass( 'oo-ui-searchWidget-results' )
14729 .append( this.results
.$element
);
14731 .addClass( 'oo-ui-searchWidget' )
14732 .append( this.$results
, this.$query
);
14737 OO
.inheritClass( OO
.ui
.SearchWidget
, OO
.ui
.Widget
);
14742 * A 'highlight' event is emitted when an item is highlighted. The highlight indicates which
14743 * item will be selected. When a user mouses over a menu item, it is highlighted. If a search
14744 * string is typed into the query field instead, the first menu item that matches the query
14745 * will be highlighted.
14748 * @deprecated Connect straight to getResults() events instead
14749 * @param {Object|null} item Item data or null if no item is highlighted
14753 * A 'select' event is emitted when an item is selected. A menu item is selected when it is clicked,
14754 * or when a user types a search query, a menu result is highlighted, and the user presses enter.
14757 * @deprecated Connect straight to getResults() events instead
14758 * @param {Object|null} item Item data or null if no item is selected
14764 * Handle query key down events.
14767 * @param {jQuery.Event} e Key down event
14769 OO
.ui
.SearchWidget
.prototype.onQueryKeydown = function ( e
) {
14770 var highlightedItem
, nextItem
,
14771 dir
= e
.which
=== OO
.ui
.Keys
.DOWN
? 1 : ( e
.which
=== OO
.ui
.Keys
.UP
? -1 : 0 );
14774 highlightedItem
= this.results
.getHighlightedItem();
14775 if ( !highlightedItem
) {
14776 highlightedItem
= this.results
.getSelectedItem();
14778 nextItem
= this.results
.getRelativeSelectableItem( highlightedItem
, dir
);
14779 this.results
.highlightItem( nextItem
);
14780 nextItem
.scrollElementIntoView();
14785 * Handle select widget select events.
14787 * Clears existing results. Subclasses should repopulate items according to new query.
14790 * @param {string} value New value
14792 OO
.ui
.SearchWidget
.prototype.onQueryChange = function () {
14794 this.results
.clearItems();
14798 * Handle select widget enter key events.
14800 * Selects highlighted item.
14803 * @param {string} value New value
14805 OO
.ui
.SearchWidget
.prototype.onQueryEnter = function () {
14807 this.results
.selectItem( this.results
.getHighlightedItem() );
14811 * Handle select widget highlight events.
14814 * @deprecated Connect straight to getResults() events instead
14815 * @param {OO.ui.OptionWidget} item Highlighted item
14818 OO
.ui
.SearchWidget
.prototype.onResultsHighlight = function ( item
) {
14819 this.emit( 'highlight', item
? item
.getData() : null );
14823 * Handle select widget select events.
14826 * @deprecated Connect straight to getResults() events instead
14827 * @param {OO.ui.OptionWidget} item Selected item
14830 OO
.ui
.SearchWidget
.prototype.onResultsSelect = function ( item
) {
14831 this.emit( 'select', item
? item
.getData() : null );
14835 * Get the query input.
14837 * @return {OO.ui.TextInputWidget} Query input
14839 OO
.ui
.SearchWidget
.prototype.getQuery = function () {
14844 * Get the search results menu.
14846 * @return {OO.ui.SelectWidget} Menu of search results
14848 OO
.ui
.SearchWidget
.prototype.getResults = function () {
14849 return this.results
;
14853 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
14854 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
14855 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
14858 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
14859 * information, please see the [OOjs UI documentation on MediaWiki][1].
14862 * // Example of a select widget with three options
14863 * var select = new OO.ui.SelectWidget( {
14865 * new OO.ui.OptionWidget( {
14867 * label: 'Option One',
14869 * new OO.ui.OptionWidget( {
14871 * label: 'Option Two',
14873 * new OO.ui.OptionWidget( {
14875 * label: 'Option Three',
14879 * $( 'body' ).append( select.$element );
14881 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14885 * @extends OO.ui.Widget
14886 * @mixins OO.ui.GroupElement
14889 * @param {Object} [config] Configuration options
14890 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
14891 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
14892 * the [OOjs UI documentation on MediaWiki] [2] for examples.
14893 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14895 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
14896 // Configuration initialization
14897 config
= config
|| {};
14899 // Parent constructor
14900 OO
.ui
.SelectWidget
.super.call( this, config
);
14902 // Mixin constructors
14903 OO
.ui
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
14906 this.pressed
= false;
14907 this.selecting
= null;
14908 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
14909 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
14910 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
14913 this.$element
.on( {
14914 mousedown
: this.onMouseDown
.bind( this ),
14915 mouseover
: this.onMouseOver
.bind( this ),
14916 mouseleave
: this.onMouseLeave
.bind( this )
14921 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
14922 .attr( 'role', 'listbox' );
14923 if ( Array
.isArray( config
.items
) ) {
14924 this.addItems( config
.items
);
14930 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
14932 // Need to mixin base class as well
14933 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.GroupElement
);
14934 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.GroupWidget
);
14941 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
14943 * @param {OO.ui.OptionWidget|null} item Highlighted item
14949 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
14950 * pressed state of an option.
14952 * @param {OO.ui.OptionWidget|null} item Pressed item
14958 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
14960 * @param {OO.ui.OptionWidget|null} item Selected item
14965 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
14966 * @param {OO.ui.OptionWidget} item Chosen item
14972 * An `add` event is emitted when options are added to the select with the #addItems method.
14974 * @param {OO.ui.OptionWidget[]} items Added items
14975 * @param {number} index Index of insertion point
14981 * A `remove` event is emitted when options are removed from the select with the #clearItems
14982 * or #removeItems methods.
14984 * @param {OO.ui.OptionWidget[]} items Removed items
14990 * Handle mouse down events.
14993 * @param {jQuery.Event} e Mouse down event
14995 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
14998 if ( !this.isDisabled() && e
.which
=== 1 ) {
14999 this.togglePressed( true );
15000 item
= this.getTargetItem( e
);
15001 if ( item
&& item
.isSelectable() ) {
15002 this.pressItem( item
);
15003 this.selecting
= item
;
15004 this.getElementDocument().addEventListener(
15006 this.onMouseUpHandler
,
15009 this.getElementDocument().addEventListener(
15011 this.onMouseMoveHandler
,
15020 * Handle mouse up events.
15023 * @param {jQuery.Event} e Mouse up event
15025 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
15028 this.togglePressed( false );
15029 if ( !this.selecting
) {
15030 item
= this.getTargetItem( e
);
15031 if ( item
&& item
.isSelectable() ) {
15032 this.selecting
= item
;
15035 if ( !this.isDisabled() && e
.which
=== 1 && this.selecting
) {
15036 this.pressItem( null );
15037 this.chooseItem( this.selecting
);
15038 this.selecting
= null;
15041 this.getElementDocument().removeEventListener(
15043 this.onMouseUpHandler
,
15046 this.getElementDocument().removeEventListener(
15048 this.onMouseMoveHandler
,
15056 * Handle mouse move events.
15059 * @param {jQuery.Event} e Mouse move event
15061 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
15064 if ( !this.isDisabled() && this.pressed
) {
15065 item
= this.getTargetItem( e
);
15066 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
15067 this.pressItem( item
);
15068 this.selecting
= item
;
15075 * Handle mouse over events.
15078 * @param {jQuery.Event} e Mouse over event
15080 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
15083 if ( !this.isDisabled() ) {
15084 item
= this.getTargetItem( e
);
15085 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
15091 * Handle mouse leave events.
15094 * @param {jQuery.Event} e Mouse over event
15096 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
15097 if ( !this.isDisabled() ) {
15098 this.highlightItem( null );
15104 * Handle key down events.
15107 * @param {jQuery.Event} e Key down event
15109 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
15112 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
15114 if ( !this.isDisabled() && this.isVisible() ) {
15115 switch ( e
.keyCode
) {
15116 case OO
.ui
.Keys
.ENTER
:
15117 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
15118 // Was only highlighted, now let's select it. No-op if already selected.
15119 this.chooseItem( currentItem
);
15123 case OO
.ui
.Keys
.UP
:
15124 case OO
.ui
.Keys
.LEFT
:
15125 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
15128 case OO
.ui
.Keys
.DOWN
:
15129 case OO
.ui
.Keys
.RIGHT
:
15130 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
15133 case OO
.ui
.Keys
.ESCAPE
:
15134 case OO
.ui
.Keys
.TAB
:
15135 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
15136 currentItem
.setHighlighted( false );
15138 this.unbindKeyDownListener();
15139 // Don't prevent tabbing away / defocusing
15145 if ( nextItem
.constructor.static.highlightable
) {
15146 this.highlightItem( nextItem
);
15148 this.chooseItem( nextItem
);
15150 nextItem
.scrollElementIntoView();
15154 // Can't just return false, because e is not always a jQuery event
15155 e
.preventDefault();
15156 e
.stopPropagation();
15162 * Bind key down listener.
15166 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
15167 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler
, true );
15171 * Unbind key down listener.
15175 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
15176 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler
, true );
15180 * Get the closest item to a jQuery.Event.
15183 * @param {jQuery.Event} e
15184 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
15186 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
15187 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
15191 * Get selected item.
15193 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
15195 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
15198 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
15199 if ( this.items
[ i
].isSelected() ) {
15200 return this.items
[ i
];
15207 * Get highlighted item.
15209 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
15211 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
15214 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
15215 if ( this.items
[ i
].isHighlighted() ) {
15216 return this.items
[ i
];
15223 * Toggle pressed state.
15225 * Press is a state that occurs when a user mouses down on an item, but
15226 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
15227 * until the user releases the mouse.
15229 * @param {boolean} pressed An option is being pressed
15231 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
15232 if ( pressed
=== undefined ) {
15233 pressed
= !this.pressed
;
15235 if ( pressed
!== this.pressed
) {
15237 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
15238 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
15239 this.pressed
= pressed
;
15244 * Highlight an option. If the `item` param is omitted, no options will be highlighted
15245 * and any existing highlight will be removed. The highlight is mutually exclusive.
15247 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
15251 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
15252 var i
, len
, highlighted
,
15255 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
15256 highlighted
= this.items
[ i
] === item
;
15257 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
15258 this.items
[ i
].setHighlighted( highlighted
);
15263 this.emit( 'highlight', item
);
15270 * Programmatically select an option by its data. If the `data` parameter is omitted,
15271 * or if the item does not exist, all options will be deselected.
15273 * @param {Object|string} [data] Value of the item to select, omit to deselect all
15277 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
15278 var itemFromData
= this.getItemFromData( data
);
15279 if ( data
=== undefined || !itemFromData
) {
15280 return this.selectItem();
15282 return this.selectItem( itemFromData
);
15286 * Programmatically select an option by its reference. If the `item` parameter is omitted,
15287 * all options will be deselected.
15289 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
15293 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
15294 var i
, len
, selected
,
15297 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
15298 selected
= this.items
[ i
] === item
;
15299 if ( this.items
[ i
].isSelected() !== selected
) {
15300 this.items
[ i
].setSelected( selected
);
15305 this.emit( 'select', item
);
15314 * Press is a state that occurs when a user mouses down on an item, but has not
15315 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
15316 * releases the mouse.
15318 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
15322 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
15323 var i
, len
, pressed
,
15326 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
15327 pressed
= this.items
[ i
] === item
;
15328 if ( this.items
[ i
].isPressed() !== pressed
) {
15329 this.items
[ i
].setPressed( pressed
);
15334 this.emit( 'press', item
);
15343 * Note that ‘choose’ should never be modified programmatically. A user can choose
15344 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
15345 * use the #selectItem method.
15347 * This method is identical to #selectItem, but may vary in subclasses that take additional action
15348 * when users choose an item with the keyboard or mouse.
15350 * @param {OO.ui.OptionWidget} item Item to choose
15354 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
15355 this.selectItem( item
);
15356 this.emit( 'choose', item
);
15362 * Get an option by its position relative to the specified item (or to the start of the option array,
15363 * if item is `null`). The direction in which to search through the option array is specified with a
15364 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
15365 * `null` if there are no options in the array.
15367 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
15368 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
15369 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
15371 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
) {
15372 var currentIndex
, nextIndex
, i
,
15373 increase
= direction
> 0 ? 1 : -1,
15374 len
= this.items
.length
;
15376 if ( item
instanceof OO
.ui
.OptionWidget
) {
15377 currentIndex
= $.inArray( item
, this.items
);
15378 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
15380 // If no item is selected and moving forward, start at the beginning.
15381 // If moving backward, start at the end.
15382 nextIndex
= direction
> 0 ? 0 : len
- 1;
15385 for ( i
= 0; i
< len
; i
++ ) {
15386 item
= this.items
[ nextIndex
];
15387 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
15390 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
15396 * Get the next selectable item or `null` if there are no selectable items.
15397 * Disabled options and menu-section markers and breaks are not selectable.
15399 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
15401 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
15404 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
15405 item
= this.items
[ i
];
15406 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
15415 * Add an array of options to the select. Optionally, an index number can be used to
15416 * specify an insertion point.
15418 * @param {OO.ui.OptionWidget[]} items Items to add
15419 * @param {number} [index] Index to insert items after
15423 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
15425 OO
.ui
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
15427 // Always provide an index, even if it was omitted
15428 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
15434 * Remove the specified array of options from the select. Options will be detached
15435 * from the DOM, not removed, so they can be reused later. To remove all options from
15436 * the select, you may wish to use the #clearItems method instead.
15438 * @param {OO.ui.OptionWidget[]} items Items to remove
15442 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
15445 // Deselect items being removed
15446 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
15448 if ( item
.isSelected() ) {
15449 this.selectItem( null );
15454 OO
.ui
.GroupWidget
.prototype.removeItems
.call( this, items
);
15456 this.emit( 'remove', items
);
15462 * Clear all options from the select. Options will be detached from the DOM, not removed,
15463 * so that they can be reused later. To remove a subset of options from the select, use
15464 * the #removeItems method.
15469 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
15470 var items
= this.items
.slice();
15473 OO
.ui
.GroupWidget
.prototype.clearItems
.call( this );
15476 this.selectItem( null );
15478 this.emit( 'remove', items
);
15484 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
15485 * button options and is used together with
15486 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
15487 * highlighting, choosing, and selecting mutually exclusive options. Please see
15488 * the [OOjs UI documentation on MediaWiki] [1] for more information.
15491 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
15492 * var option1 = new OO.ui.ButtonOptionWidget( {
15494 * label: 'Option 1',
15495 * title: 'Button option 1'
15498 * var option2 = new OO.ui.ButtonOptionWidget( {
15500 * label: 'Option 2',
15501 * title: 'Button option 2'
15504 * var option3 = new OO.ui.ButtonOptionWidget( {
15506 * label: 'Option 3',
15507 * title: 'Button option 3'
15510 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
15511 * items: [ option1, option2, option3 ]
15513 * $( 'body' ).append( buttonSelect.$element );
15515 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
15518 * @extends OO.ui.SelectWidget
15519 * @mixins OO.ui.TabIndexedElement
15522 * @param {Object} [config] Configuration options
15524 OO
.ui
.ButtonSelectWidget
= function OoUiButtonSelectWidget( config
) {
15525 // Parent constructor
15526 OO
.ui
.ButtonSelectWidget
.super.call( this, config
);
15528 // Mixin constructors
15529 OO
.ui
.TabIndexedElement
.call( this, config
);
15532 this.$element
.on( {
15533 focus
: this.bindKeyDownListener
.bind( this ),
15534 blur
: this.unbindKeyDownListener
.bind( this )
15538 this.$element
.addClass( 'oo-ui-buttonSelectWidget' );
15543 OO
.inheritClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.SelectWidget
);
15544 OO
.mixinClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.TabIndexedElement
);
15547 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
15548 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
15549 * an interface for adding, removing and selecting options.
15550 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
15553 * // A RadioSelectWidget with RadioOptions.
15554 * var option1 = new OO.ui.RadioOptionWidget( {
15556 * label: 'Selected radio option'
15559 * var option2 = new OO.ui.RadioOptionWidget( {
15561 * label: 'Unselected radio option'
15564 * var radioSelect=new OO.ui.RadioSelectWidget( {
15565 * items: [ option1, option2 ]
15568 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
15569 * radioSelect.selectItem( option1 );
15571 * $( 'body' ).append( radioSelect.$element );
15573 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
15577 * @extends OO.ui.SelectWidget
15578 * @mixins OO.ui.TabIndexedElement
15581 * @param {Object} [config] Configuration options
15583 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
15584 // Parent constructor
15585 OO
.ui
.RadioSelectWidget
.super.call( this, config
);
15587 // Mixin constructors
15588 OO
.ui
.TabIndexedElement
.call( this, config
);
15591 this.$element
.on( {
15592 focus
: this.bindKeyDownListener
.bind( this ),
15593 blur
: this.unbindKeyDownListener
.bind( this )
15597 this.$element
.addClass( 'oo-ui-radioSelectWidget' );
15602 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
15603 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.TabIndexedElement
);
15606 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
15607 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
15608 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
15609 * and {@link OO.ui.LookupElement LookupElement} for examples of widgets that contain menus.
15610 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
15611 * and customized to be opened, closed, and displayed as needed.
15613 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
15614 * mouse outside the menu.
15616 * Menus also have support for keyboard interaction:
15618 * - Enter/Return key: choose and select a menu option
15619 * - Up-arrow key: highlight the previous menu option
15620 * - Down-arrow key: highlight the next menu option
15621 * - Esc key: hide the menu
15623 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
15624 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
15627 * @extends OO.ui.SelectWidget
15628 * @mixins OO.ui.ClippableElement
15631 * @param {Object} [config] Configuration options
15632 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
15633 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
15634 * and {@link OO.ui.LookupElement LookupElement}
15635 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu’s active state. If the user clicks the mouse
15636 * anywhere on the page outside of this widget, the menu is hidden.
15637 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
15639 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
15640 // Configuration initialization
15641 config
= config
|| {};
15643 // Parent constructor
15644 OO
.ui
.MenuSelectWidget
.super.call( this, config
);
15646 // Mixin constructors
15647 OO
.ui
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
15650 this.newItems
= null;
15651 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
15652 this.$input
= config
.input
? config
.input
.$input
: null;
15653 this.$widget
= config
.widget
? config
.widget
.$element
: null;
15654 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
15658 .addClass( 'oo-ui-menuSelectWidget' )
15659 .attr( 'role', 'menu' );
15661 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
15662 // that reference properties not initialized at that time of parent class construction
15663 // TODO: Find a better way to handle post-constructor setup
15664 this.visible
= false;
15665 this.$element
.addClass( 'oo-ui-element-hidden' );
15670 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
15671 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.ClippableElement
);
15676 * Handles document mouse down events.
15679 * @param {jQuery.Event} e Key down event
15681 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
15683 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
15684 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
15686 this.toggle( false );
15693 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
15694 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
15696 if ( !this.isDisabled() && this.isVisible() ) {
15697 switch ( e
.keyCode
) {
15698 case OO
.ui
.Keys
.LEFT
:
15699 case OO
.ui
.Keys
.RIGHT
:
15700 // Do nothing if a text field is associated, arrow keys will be handled natively
15701 if ( !this.$input
) {
15702 OO
.ui
.MenuSelectWidget
.super.prototype.onKeyDown
.call( this, e
);
15705 case OO
.ui
.Keys
.ESCAPE
:
15706 case OO
.ui
.Keys
.TAB
:
15707 if ( currentItem
) {
15708 currentItem
.setHighlighted( false );
15710 this.toggle( false );
15711 // Don't prevent tabbing away, prevent defocusing
15712 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
15713 e
.preventDefault();
15714 e
.stopPropagation();
15718 OO
.ui
.MenuSelectWidget
.super.prototype.onKeyDown
.call( this, e
);
15727 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
15728 if ( this.$input
) {
15729 this.$input
.on( 'keydown', this.onKeyDownHandler
);
15731 OO
.ui
.MenuSelectWidget
.super.prototype.bindKeyDownListener
.call( this );
15738 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
15739 if ( this.$input
) {
15740 this.$input
.off( 'keydown', this.onKeyDownHandler
);
15742 OO
.ui
.MenuSelectWidget
.super.prototype.unbindKeyDownListener
.call( this );
15749 * When a user chooses an item, the menu is closed.
15751 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
15752 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
15753 * @param {OO.ui.OptionWidget} item Item to choose
15756 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
15757 OO
.ui
.MenuSelectWidget
.super.prototype.chooseItem
.call( this, item
);
15758 this.toggle( false );
15765 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
15769 OO
.ui
.MenuSelectWidget
.super.prototype.addItems
.call( this, items
, index
);
15772 if ( !this.newItems
) {
15773 this.newItems
= [];
15776 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
15778 if ( this.isVisible() ) {
15779 // Defer fitting label until item has been attached
15782 this.newItems
.push( item
);
15786 // Reevaluate clipping
15795 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
15797 OO
.ui
.MenuSelectWidget
.super.prototype.removeItems
.call( this, items
);
15799 // Reevaluate clipping
15808 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
15810 OO
.ui
.MenuSelectWidget
.super.prototype.clearItems
.call( this );
15812 // Reevaluate clipping
15821 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
15822 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
15825 change
= visible
!== this.isVisible();
15828 OO
.ui
.MenuSelectWidget
.super.prototype.toggle
.call( this, visible
);
15832 this.bindKeyDownListener();
15834 if ( this.newItems
&& this.newItems
.length
) {
15835 for ( i
= 0, len
= this.newItems
.length
; i
< len
; i
++ ) {
15836 this.newItems
[ i
].fitLabel();
15838 this.newItems
= null;
15840 this.toggleClipping( true );
15843 if ( this.autoHide
) {
15844 this.getElementDocument().addEventListener(
15845 'mousedown', this.onDocumentMouseDownHandler
, true
15849 this.unbindKeyDownListener();
15850 this.getElementDocument().removeEventListener(
15851 'mousedown', this.onDocumentMouseDownHandler
, true
15853 this.toggleClipping( false );
15861 * TextInputMenuSelectWidget is a menu that is specially designed to be positioned beneath
15862 * a {@link OO.ui.TextInputWidget text input} field. The menu's position is automatically
15863 * calculated and maintained when the menu is toggled or the window is resized.
15864 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
15867 * @extends OO.ui.MenuSelectWidget
15870 * @param {OO.ui.TextInputWidget} inputWidget Text input widget to provide menu for
15871 * @param {Object} [config] Configuration options
15872 * @cfg {jQuery} [$container=input.$element] Element to render menu under
15874 OO
.ui
.TextInputMenuSelectWidget
= function OoUiTextInputMenuSelectWidget( inputWidget
, config
) {
15875 // Allow passing positional parameters inside the config object
15876 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
15877 config
= inputWidget
;
15878 inputWidget
= config
.inputWidget
;
15881 // Configuration initialization
15882 config
= config
|| {};
15884 // Parent constructor
15885 OO
.ui
.TextInputMenuSelectWidget
.super.call( this, config
);
15888 this.inputWidget
= inputWidget
;
15889 this.$container
= config
.$container
|| this.inputWidget
.$element
;
15890 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
15893 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
15898 OO
.inheritClass( OO
.ui
.TextInputMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
15903 * Handle window resize event.
15906 * @param {jQuery.Event} e Window resize event
15908 OO
.ui
.TextInputMenuSelectWidget
.prototype.onWindowResize = function () {
15915 OO
.ui
.TextInputMenuSelectWidget
.prototype.toggle = function ( visible
) {
15916 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
15918 var change
= visible
!== this.isVisible();
15920 if ( change
&& visible
) {
15921 // Make sure the width is set before the parent method runs.
15922 // After this we have to call this.position(); again to actually
15923 // position ourselves correctly.
15928 OO
.ui
.TextInputMenuSelectWidget
.super.prototype.toggle
.call( this, visible
);
15931 if ( this.isVisible() ) {
15933 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
15935 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
15943 * Position the menu.
15948 OO
.ui
.TextInputMenuSelectWidget
.prototype.position = function () {
15949 var $container
= this.$container
,
15950 pos
= OO
.ui
.Element
.static.getRelativePosition( $container
, this.$element
.offsetParent() );
15952 // Position under input
15953 pos
.top
+= $container
.height();
15954 this.$element
.css( pos
);
15957 this.setIdealSize( $container
.width() );
15958 // We updated the position, so re-evaluate the clipping state
15965 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
15966 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
15968 * ####Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.####
15971 * @extends OO.ui.SelectWidget
15972 * @mixins OO.ui.TabIndexedElement
15975 * @param {Object} [config] Configuration options
15977 OO
.ui
.OutlineSelectWidget
= function OoUiOutlineSelectWidget( config
) {
15978 // Parent constructor
15979 OO
.ui
.OutlineSelectWidget
.super.call( this, config
);
15981 // Mixin constructors
15982 OO
.ui
.TabIndexedElement
.call( this, config
);
15985 this.$element
.on( {
15986 focus
: this.bindKeyDownListener
.bind( this ),
15987 blur
: this.unbindKeyDownListener
.bind( this )
15991 this.$element
.addClass( 'oo-ui-outlineSelectWidget' );
15996 OO
.inheritClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.SelectWidget
);
15997 OO
.mixinClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.TabIndexedElement
);
16000 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
16002 * ####Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.####
16005 * @extends OO.ui.SelectWidget
16006 * @mixins OO.ui.TabIndexedElement
16009 * @param {Object} [config] Configuration options
16011 OO
.ui
.TabSelectWidget
= function OoUiTabSelectWidget( config
) {
16012 // Parent constructor
16013 OO
.ui
.TabSelectWidget
.super.call( this, config
);
16015 // Mixin constructors
16016 OO
.ui
.TabIndexedElement
.call( this, config
);
16019 this.$element
.on( {
16020 focus
: this.bindKeyDownListener
.bind( this ),
16021 blur
: this.unbindKeyDownListener
.bind( this )
16025 this.$element
.addClass( 'oo-ui-tabSelectWidget' );
16030 OO
.inheritClass( OO
.ui
.TabSelectWidget
, OO
.ui
.SelectWidget
);
16031 OO
.mixinClass( OO
.ui
.TabSelectWidget
, OO
.ui
.TabIndexedElement
);
16034 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
16035 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
16036 * visually by a slider in the leftmost position.
16039 * // Toggle switches in the 'off' and 'on' position.
16040 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
16041 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
16045 * // Create a FieldsetLayout to layout and label switches
16046 * var fieldset = new OO.ui.FieldsetLayout( {
16047 * label: 'Toggle switches'
16049 * fieldset.addItems( [
16050 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
16051 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
16053 * $( 'body' ).append( fieldset.$element );
16056 * @extends OO.ui.ToggleWidget
16057 * @mixins OO.ui.TabIndexedElement
16060 * @param {Object} [config] Configuration options
16061 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
16062 * By default, the toggle switch is in the 'off' position.
16064 OO
.ui
.ToggleSwitchWidget
= function OoUiToggleSwitchWidget( config
) {
16065 // Parent constructor
16066 OO
.ui
.ToggleSwitchWidget
.super.call( this, config
);
16068 // Mixin constructors
16069 OO
.ui
.TabIndexedElement
.call( this, config
);
16072 this.dragging
= false;
16073 this.dragStart
= null;
16074 this.sliding
= false;
16075 this.$glow
= $( '<span>' );
16076 this.$grip
= $( '<span>' );
16079 this.$element
.on( {
16080 click
: this.onClick
.bind( this ),
16081 keypress
: this.onKeyPress
.bind( this )
16085 this.$glow
.addClass( 'oo-ui-toggleSwitchWidget-glow' );
16086 this.$grip
.addClass( 'oo-ui-toggleSwitchWidget-grip' );
16088 .addClass( 'oo-ui-toggleSwitchWidget' )
16089 .attr( 'role', 'checkbox' )
16090 .append( this.$glow
, this.$grip
);
16095 OO
.inheritClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.ToggleWidget
);
16096 OO
.mixinClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.TabIndexedElement
);
16101 * Handle mouse click events.
16104 * @param {jQuery.Event} e Mouse click event
16106 OO
.ui
.ToggleSwitchWidget
.prototype.onClick = function ( e
) {
16107 if ( !this.isDisabled() && e
.which
=== 1 ) {
16108 this.setValue( !this.value
);
16114 * Handle key press events.
16117 * @param {jQuery.Event} e Key press event
16119 OO
.ui
.ToggleSwitchWidget
.prototype.onKeyPress = function ( e
) {
16120 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
16121 this.setValue( !this.value
);