3 * https://www.mediawiki.org/wiki/OOjs_UI
5 * Copyright 2011–2015 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2015-08-19T02:10:17Z
16 * Namespace for all classes, static methods and static properties.
53 * Generate a unique ID for element
55 * @return {String} [id]
57 OO
.ui
.generateElementId = function () {
59 return 'oojsui-' + OO
.ui
.elementId
;
63 * Check if an element is focusable.
64 * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14
66 * @param {jQuery} element Element to test
67 * @return {Boolean} [description]
69 OO
.ui
.isFocusableElement = function ( $element
) {
70 var node
= $element
[0],
71 nodeName
= node
.nodeName
.toLowerCase(),
72 // Check if the element have tabindex set
73 isInElementGroup
= /^(input|select|textarea|button|object)$/.test( nodeName
),
74 // Check if the element is a link with href or if it has tabindex
76 ( nodeName
=== 'a' && node
.href
) ||
77 !isNaN( $element
.attr( 'tabindex' ) )
79 // Check if the element is visible
81 // This is quicker than calling $element.is( ':visible' )
82 $.expr
.filters
.visible( node
) &&
83 // Check that all parents are visible
84 !$element
.parents().addBack().filter( function () {
85 return $.css( this, 'visibility' ) === 'hidden';
88 isTabOk
= isNaN( $element
.attr( 'tabindex' ) ) || +$element
.attr( 'tabindex' ) >= 0;
91 ( isInElementGroup
? !node
.disabled
: isOtherElement
) &&
97 * Get the user's language and any fallback languages.
99 * These language codes are used to localize user interface elements in the user's language.
101 * In environments that provide a localization system, this function should be overridden to
102 * return the user's language(s). The default implementation returns English (en) only.
104 * @return {string[]} Language codes, in descending order of priority
106 OO
.ui
.getUserLanguages = function () {
111 * Get a value in an object keyed by language code.
113 * @param {Object.<string,Mixed>} obj Object keyed by language code
114 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
115 * @param {string} [fallback] Fallback code, used if no matching language can be found
116 * @return {Mixed} Local value
118 OO
.ui
.getLocalValue = function ( obj
, lang
, fallback
) {
121 // Requested language
125 // Known user language
126 langs
= OO
.ui
.getUserLanguages();
127 for ( i
= 0, len
= langs
.length
; i
< len
; i
++ ) {
134 if ( obj
[ fallback
] ) {
135 return obj
[ fallback
];
137 // First existing language
138 for ( lang
in obj
) {
146 * Check if a node is contained within another node
148 * Similar to jQuery#contains except a list of containers can be supplied
149 * and a boolean argument allows you to include the container in the match list
151 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
152 * @param {HTMLElement} contained Node to find
153 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
154 * @return {boolean} The node is in the list of target nodes
156 OO
.ui
.contains = function ( containers
, contained
, matchContainers
) {
158 if ( !Array
.isArray( containers
) ) {
159 containers
= [ containers
];
161 for ( i
= containers
.length
- 1; i
>= 0; i
-- ) {
162 if ( ( matchContainers
&& contained
=== containers
[ i
] ) || $.contains( containers
[ i
], contained
) ) {
170 * Return a function, that, as long as it continues to be invoked, will not
171 * be triggered. The function will be called after it stops being called for
172 * N milliseconds. If `immediate` is passed, trigger the function on the
173 * leading edge, instead of the trailing.
175 * Ported from: http://underscorejs.org/underscore.js
177 * @param {Function} func
178 * @param {number} wait
179 * @param {boolean} immediate
182 OO
.ui
.debounce = function ( func
, wait
, immediate
) {
187 later = function () {
190 func
.apply( context
, args
);
193 if ( immediate
&& !timeout
) {
194 func
.apply( context
, args
);
196 clearTimeout( timeout
);
197 timeout
= setTimeout( later
, wait
);
202 * Proxy for `node.addEventListener( eventName, handler, true )`, if the browser supports it.
203 * Otherwise falls back to non-capturing event listeners.
205 * @param {HTMLElement} node
206 * @param {string} eventName
207 * @param {Function} handler
209 OO
.ui
.addCaptureEventListener = function ( node
, eventName
, handler
) {
210 if ( node
.addEventListener
) {
211 node
.addEventListener( eventName
, handler
, true );
213 node
.attachEvent( 'on' + eventName
, handler
);
218 * Proxy for `node.removeEventListener( eventName, handler, true )`, if the browser supports it.
219 * Otherwise falls back to non-capturing event listeners.
221 * @param {HTMLElement} node
222 * @param {string} eventName
223 * @param {Function} handler
225 OO
.ui
.removeCaptureEventListener = function ( node
, eventName
, handler
) {
226 if ( node
.addEventListener
) {
227 node
.removeEventListener( eventName
, handler
, true );
229 node
.detachEvent( 'on' + eventName
, handler
);
234 * Reconstitute a JavaScript object corresponding to a widget created by
235 * the PHP implementation.
237 * This is an alias for `OO.ui.Element.static.infuse()`.
239 * @param {string|HTMLElement|jQuery} idOrNode
240 * A DOM id (if a string) or node for the widget to infuse.
241 * @return {OO.ui.Element}
242 * The `OO.ui.Element` corresponding to this (infusable) document node.
244 OO
.ui
.infuse = function ( idOrNode
) {
245 return OO
.ui
.Element
.static.infuse( idOrNode
);
250 * Message store for the default implementation of OO.ui.msg
252 * Environments that provide a localization system should not use this, but should override
253 * OO.ui.msg altogether.
258 // Tool tip for a button that moves items in a list down one place
259 'ooui-outline-control-move-down': 'Move item down',
260 // Tool tip for a button that moves items in a list up one place
261 'ooui-outline-control-move-up': 'Move item up',
262 // Tool tip for a button that removes items from a list
263 'ooui-outline-control-remove': 'Remove item',
264 // Label for the toolbar group that contains a list of all other available tools
265 'ooui-toolbar-more': 'More',
266 // Label for the fake tool that expands the full list of tools in a toolbar group
267 'ooui-toolgroup-expand': 'More',
268 // Label for the fake tool that collapses the full list of tools in a toolbar group
269 'ooui-toolgroup-collapse': 'Fewer',
270 // Default label for the accept button of a confirmation dialog
271 'ooui-dialog-message-accept': 'OK',
272 // Default label for the reject button of a confirmation dialog
273 'ooui-dialog-message-reject': 'Cancel',
274 // Title for process dialog error description
275 'ooui-dialog-process-error': 'Something went wrong',
276 // Label for process dialog dismiss error button, visible when describing errors
277 'ooui-dialog-process-dismiss': 'Dismiss',
278 // Label for process dialog retry action button, visible when describing only recoverable errors
279 'ooui-dialog-process-retry': 'Try again',
280 // Label for process dialog retry action button, visible when describing only warnings
281 'ooui-dialog-process-continue': 'Continue',
282 // Default placeholder for file selection widgets
283 'ooui-selectfile-not-supported': 'File selection is not supported',
284 // Default placeholder for file selection widgets
285 'ooui-selectfile-placeholder': 'No file is selected',
286 // Semicolon separator
287 'ooui-semicolon-separator': '; '
291 * Get a localized message.
293 * In environments that provide a localization system, this function should be overridden to
294 * return the message translated in the user's language. The default implementation always returns
297 * After the message key, message parameters may optionally be passed. In the default implementation,
298 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
299 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
300 * they support unnamed, ordered message parameters.
303 * @param {string} key Message key
304 * @param {Mixed...} [params] Message parameters
305 * @return {string} Translated message with parameters substituted
307 OO
.ui
.msg = function ( key
) {
308 var message
= messages
[ key
],
309 params
= Array
.prototype.slice
.call( arguments
, 1 );
310 if ( typeof message
=== 'string' ) {
311 // Perform $1 substitution
312 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
313 var i
= parseInt( n
, 10 );
314 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
317 // Return placeholder if message not found
318 message
= '[' + key
+ ']';
324 * Package a message and arguments for deferred resolution.
326 * Use this when you are statically specifying a message and the message may not yet be present.
328 * @param {string} key Message key
329 * @param {Mixed...} [params] Message parameters
330 * @return {Function} Function that returns the resolved message when executed
332 OO
.ui
.deferMsg = function () {
333 var args
= arguments
;
335 return OO
.ui
.msg
.apply( OO
.ui
, args
);
342 * If the message is a function it will be executed, otherwise it will pass through directly.
344 * @param {Function|string} msg Deferred message, or message text
345 * @return {string} Resolved message
347 OO
.ui
.resolveMsg = function ( msg
) {
348 if ( $.isFunction( msg
) ) {
355 * @param {string} url
358 OO
.ui
.isSafeUrl = function ( url
) {
360 // Keep in sync with php/Tag.php
362 'bitcoin:', 'ftp:', 'ftps:', 'geo:', 'git:', 'gopher:', 'http:', 'https:', 'irc:', 'ircs:',
363 'magnet:', 'mailto:', 'mms:', 'news:', 'nntp:', 'redis:', 'sftp:', 'sip:', 'sips:', 'sms:', 'ssh:',
364 'svn:', 'tel:', 'telnet:', 'urn:', 'worldwind:', 'xmpp:'
367 if ( url
.indexOf( ':' ) === -1 ) {
372 protocol
= url
.split( ':', 1 )[0] + ':';
373 if ( !protocol
.match( /^([A-za-z0-9\+\.\-])+:/ ) ) {
374 // Not a valid protocol, safe
378 // Safe if in the whitelist
379 return $.inArray( protocol
, whitelist
) !== -1;
389 * Namespace for OOjs UI mixins.
391 * Mixins are named according to the type of object they are intended to
392 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
393 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
394 * is intended to be mixed in to an instance of OO.ui.Widget.
402 * PendingElement is a mixin that is used to create elements that notify users that something is happening
403 * and that they should wait before proceeding. The pending state is visually represented with a pending
404 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
405 * field of a {@link OO.ui.TextInputWidget text input widget}.
407 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
408 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
409 * in process dialogs.
412 * function MessageDialog( config ) {
413 * MessageDialog.parent.call( this, config );
415 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
417 * MessageDialog.static.actions = [
418 * { action: 'save', label: 'Done', flags: 'primary' },
419 * { label: 'Cancel', flags: 'safe' }
422 * MessageDialog.prototype.initialize = function () {
423 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
424 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
425 * this.content.$element.append( '<p>Click the \'Done\' action widget to see its pending state. Note that action widgets can be marked pending in message dialogs but not process dialogs.</p>' );
426 * this.$body.append( this.content.$element );
428 * MessageDialog.prototype.getBodyHeight = function () {
431 * MessageDialog.prototype.getActionProcess = function ( action ) {
433 * if ( action === 'save' ) {
434 * dialog.getActions().get({actions: 'save'})[0].pushPending();
435 * return new OO.ui.Process()
437 * .next( function () {
438 * dialog.getActions().get({actions: 'save'})[0].popPending();
441 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
444 * var windowManager = new OO.ui.WindowManager();
445 * $( 'body' ).append( windowManager.$element );
447 * var dialog = new MessageDialog();
448 * windowManager.addWindows( [ dialog ] );
449 * windowManager.openWindow( dialog );
455 * @param {Object} [config] Configuration options
456 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
458 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
459 // Configuration initialization
460 config
= config
|| {};
464 this.$pending
= null;
467 this.setPendingElement( config
.$pending
|| this.$element
);
472 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
477 * Set the pending element (and clean up any existing one).
479 * @param {jQuery} $pending The element to set to pending.
481 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
482 if ( this.$pending
) {
483 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
486 this.$pending
= $pending
;
487 if ( this.pending
> 0 ) {
488 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
493 * Check if an element is pending.
495 * @return {boolean} Element is pending
497 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
498 return !!this.pending
;
502 * Increase the pending counter. The pending state will remain active until the counter is zero
503 * (i.e., the number of calls to #pushPending and #popPending is the same).
507 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
508 if ( this.pending
=== 0 ) {
509 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
510 this.updateThemeClasses();
518 * Decrease the pending counter. The pending state will remain active until the counter is zero
519 * (i.e., the number of calls to #pushPending and #popPending is the same).
523 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
524 if ( this.pending
=== 1 ) {
525 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
526 this.updateThemeClasses();
528 this.pending
= Math
.max( 0, this.pending
- 1 );
534 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
535 * Actions can be made available for specific contexts (modes) and circumstances
536 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
538 * ActionSets contain two types of actions:
540 * - 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.
541 * - Other: Other actions include all non-special visible actions.
543 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
546 * // Example: An action set used in a process dialog
547 * function MyProcessDialog( config ) {
548 * MyProcessDialog.parent.call( this, config );
550 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
551 * MyProcessDialog.static.title = 'An action set in a process dialog';
552 * // An action set that uses modes ('edit' and 'help' mode, in this example).
553 * MyProcessDialog.static.actions = [
554 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
555 * { action: 'help', modes: 'edit', label: 'Help' },
556 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
557 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
560 * MyProcessDialog.prototype.initialize = function () {
561 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
562 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
563 * 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>' );
564 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
565 * 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>' );
566 * this.stackLayout = new OO.ui.StackLayout( {
567 * items: [ this.panel1, this.panel2 ]
569 * this.$body.append( this.stackLayout.$element );
571 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
572 * return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
573 * .next( function () {
574 * this.actions.setMode( 'edit' );
577 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
578 * if ( action === 'help' ) {
579 * this.actions.setMode( 'help' );
580 * this.stackLayout.setItem( this.panel2 );
581 * } else if ( action === 'back' ) {
582 * this.actions.setMode( 'edit' );
583 * this.stackLayout.setItem( this.panel1 );
584 * } else if ( action === 'continue' ) {
586 * return new OO.ui.Process( function () {
590 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
592 * MyProcessDialog.prototype.getBodyHeight = function () {
593 * return this.panel1.$element.outerHeight( true );
595 * var windowManager = new OO.ui.WindowManager();
596 * $( 'body' ).append( windowManager.$element );
597 * var dialog = new MyProcessDialog( {
600 * windowManager.addWindows( [ dialog ] );
601 * windowManager.openWindow( dialog );
603 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
607 * @mixins OO.EventEmitter
610 * @param {Object} [config] Configuration options
612 OO
.ui
.ActionSet
= function OoUiActionSet( config
) {
613 // Configuration initialization
614 config
= config
|| {};
616 // Mixin constructors
617 OO
.EventEmitter
.call( this );
622 actions
: 'getAction',
626 this.categorized
= {};
629 this.organized
= false;
630 this.changing
= false;
631 this.changed
= false;
636 OO
.mixinClass( OO
.ui
.ActionSet
, OO
.EventEmitter
);
638 /* Static Properties */
641 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
642 * header of a {@link OO.ui.ProcessDialog process dialog}.
643 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
645 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
652 OO
.ui
.ActionSet
.static.specialFlags
= [ 'safe', 'primary' ];
659 * A 'click' event is emitted when an action is clicked.
661 * @param {OO.ui.ActionWidget} action Action that was clicked
667 * A 'resize' event is emitted when an action widget is resized.
669 * @param {OO.ui.ActionWidget} action Action that was resized
675 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
677 * @param {OO.ui.ActionWidget[]} added Actions added
683 * A 'remove' event is emitted when actions are {@link #method-remove removed}
684 * or {@link #clear cleared}.
686 * @param {OO.ui.ActionWidget[]} added Actions removed
692 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
693 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
700 * Handle action change events.
705 OO
.ui
.ActionSet
.prototype.onActionChange = function () {
706 this.organized
= false;
707 if ( this.changing
) {
710 this.emit( 'change' );
715 * Check if an action is one of the special actions.
717 * @param {OO.ui.ActionWidget} action Action to check
718 * @return {boolean} Action is special
720 OO
.ui
.ActionSet
.prototype.isSpecial = function ( action
) {
723 for ( flag
in this.special
) {
724 if ( action
=== this.special
[ flag
] ) {
733 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
736 * @param {Object} [filters] Filters to use, omit to get all actions
737 * @param {string|string[]} [filters.actions] Actions that action widgets must have
738 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
739 * @param {string|string[]} [filters.modes] Modes that action widgets must have
740 * @param {boolean} [filters.visible] Action widgets must be visible
741 * @param {boolean} [filters.disabled] Action widgets must be disabled
742 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
744 OO
.ui
.ActionSet
.prototype.get = function ( filters
) {
745 var i
, len
, list
, category
, actions
, index
, match
, matches
;
750 // Collect category candidates
752 for ( category
in this.categorized
) {
753 list
= filters
[ category
];
755 if ( !Array
.isArray( list
) ) {
758 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
759 actions
= this.categorized
[ category
][ list
[ i
] ];
760 if ( Array
.isArray( actions
) ) {
761 matches
.push
.apply( matches
, actions
);
766 // Remove by boolean filters
767 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
768 match
= matches
[ i
];
770 ( filters
.visible
!== undefined && match
.isVisible() !== filters
.visible
) ||
771 ( filters
.disabled
!== undefined && match
.isDisabled() !== filters
.disabled
)
773 matches
.splice( i
, 1 );
779 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
780 match
= matches
[ i
];
781 index
= matches
.lastIndexOf( match
);
782 while ( index
!== i
) {
783 matches
.splice( index
, 1 );
785 index
= matches
.lastIndexOf( match
);
790 return this.list
.slice();
794 * Get 'special' actions.
796 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
797 * Special flags can be configured in subclasses by changing the static #specialFlags property.
799 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
801 OO
.ui
.ActionSet
.prototype.getSpecial = function () {
803 return $.extend( {}, this.special
);
807 * Get 'other' actions.
809 * Other actions include all non-special visible action widgets.
811 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
813 OO
.ui
.ActionSet
.prototype.getOthers = function () {
815 return this.others
.slice();
819 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
820 * to be available in the specified mode will be made visible. All other actions will be hidden.
822 * @param {string} mode The mode. Only actions configured to be available in the specified
823 * mode will be made visible.
828 OO
.ui
.ActionSet
.prototype.setMode = function ( mode
) {
831 this.changing
= true;
832 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
833 action
= this.list
[ i
];
834 action
.toggle( action
.hasMode( mode
) );
837 this.organized
= false;
838 this.changing
= false;
839 this.emit( 'change' );
845 * Set the abilities of the specified actions.
847 * Action widgets that are configured with the specified actions will be enabled
848 * or disabled based on the boolean values specified in the `actions`
851 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
852 * values that indicate whether or not the action should be enabled.
855 OO
.ui
.ActionSet
.prototype.setAbilities = function ( actions
) {
856 var i
, len
, action
, item
;
858 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
859 item
= this.list
[ i
];
860 action
= item
.getAction();
861 if ( actions
[ action
] !== undefined ) {
862 item
.setDisabled( !actions
[ action
] );
870 * Executes a function once per action.
872 * When making changes to multiple actions, use this method instead of iterating over the actions
873 * manually to defer emitting a #change event until after all actions have been changed.
875 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
876 * @param {Function} callback Callback to run for each action; callback is invoked with three
877 * arguments: the action, the action's index, the list of actions being iterated over
880 OO
.ui
.ActionSet
.prototype.forEach = function ( filter
, callback
) {
881 this.changed
= false;
882 this.changing
= true;
883 this.get( filter
).forEach( callback
);
884 this.changing
= false;
885 if ( this.changed
) {
886 this.emit( 'change' );
893 * Add action widgets to the action set.
895 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
900 OO
.ui
.ActionSet
.prototype.add = function ( actions
) {
903 this.changing
= true;
904 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
905 action
= actions
[ i
];
906 action
.connect( this, {
907 click
: [ 'emit', 'click', action
],
908 resize
: [ 'emit', 'resize', action
],
909 toggle
: [ 'onActionChange' ]
911 this.list
.push( action
);
913 this.organized
= false;
914 this.emit( 'add', actions
);
915 this.changing
= false;
916 this.emit( 'change' );
922 * Remove action widgets from the set.
924 * To remove all actions, you may wish to use the #clear method instead.
926 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
931 OO
.ui
.ActionSet
.prototype.remove = function ( actions
) {
932 var i
, len
, index
, action
;
934 this.changing
= true;
935 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
936 action
= actions
[ i
];
937 index
= this.list
.indexOf( action
);
938 if ( index
!== -1 ) {
939 action
.disconnect( this );
940 this.list
.splice( index
, 1 );
943 this.organized
= false;
944 this.emit( 'remove', actions
);
945 this.changing
= false;
946 this.emit( 'change' );
952 * Remove all action widets from the set.
954 * To remove only specified actions, use the {@link #method-remove remove} method instead.
960 OO
.ui
.ActionSet
.prototype.clear = function () {
962 removed
= this.list
.slice();
964 this.changing
= true;
965 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
966 action
= this.list
[ i
];
967 action
.disconnect( this );
972 this.organized
= false;
973 this.emit( 'remove', removed
);
974 this.changing
= false;
975 this.emit( 'change' );
983 * This is called whenever organized information is requested. It will only reorganize the actions
984 * if something has changed since the last time it ran.
989 OO
.ui
.ActionSet
.prototype.organize = function () {
990 var i
, iLen
, j
, jLen
, flag
, action
, category
, list
, item
, special
,
991 specialFlags
= this.constructor.static.specialFlags
;
993 if ( !this.organized
) {
994 this.categorized
= {};
997 for ( i
= 0, iLen
= this.list
.length
; i
< iLen
; i
++ ) {
998 action
= this.list
[ i
];
999 if ( action
.isVisible() ) {
1000 // Populate categories
1001 for ( category
in this.categories
) {
1002 if ( !this.categorized
[ category
] ) {
1003 this.categorized
[ category
] = {};
1005 list
= action
[ this.categories
[ category
] ]();
1006 if ( !Array
.isArray( list
) ) {
1009 for ( j
= 0, jLen
= list
.length
; j
< jLen
; j
++ ) {
1011 if ( !this.categorized
[ category
][ item
] ) {
1012 this.categorized
[ category
][ item
] = [];
1014 this.categorized
[ category
][ item
].push( action
);
1017 // Populate special/others
1019 for ( j
= 0, jLen
= specialFlags
.length
; j
< jLen
; j
++ ) {
1020 flag
= specialFlags
[ j
];
1021 if ( !this.special
[ flag
] && action
.hasFlag( flag
) ) {
1022 this.special
[ flag
] = action
;
1028 this.others
.push( action
);
1032 this.organized
= true;
1039 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
1040 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
1041 * connected to them and can't be interacted with.
1047 * @param {Object} [config] Configuration options
1048 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
1049 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
1051 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
1052 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
1053 * @cfg {string} [text] Text to insert
1054 * @cfg {Array} [content] An array of content elements to append (after #text).
1055 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
1056 * Instances of OO.ui.Element will have their $element appended.
1057 * @cfg {jQuery} [$content] Content elements to append (after #text)
1058 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
1059 * Data can also be specified with the #setData method.
1061 OO
.ui
.Element
= function OoUiElement( config
) {
1062 // Configuration initialization
1063 config
= config
|| {};
1067 this.visible
= true;
1068 this.data
= config
.data
;
1069 this.$element
= config
.$element
||
1070 $( document
.createElement( this.getTagName() ) );
1071 this.elementGroup
= null;
1072 this.debouncedUpdateThemeClassesHandler
= this.debouncedUpdateThemeClasses
.bind( this );
1073 this.updateThemeClassesPending
= false;
1076 if ( Array
.isArray( config
.classes
) ) {
1077 this.$element
.addClass( config
.classes
.join( ' ' ) );
1080 this.$element
.attr( 'id', config
.id
);
1082 if ( config
.text
) {
1083 this.$element
.text( config
.text
);
1085 if ( config
.content
) {
1086 // The `content` property treats plain strings as text; use an
1087 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
1088 // appropriate $element appended.
1089 this.$element
.append( config
.content
.map( function ( v
) {
1090 if ( typeof v
=== 'string' ) {
1091 // Escape string so it is properly represented in HTML.
1092 return document
.createTextNode( v
);
1093 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
1095 return v
.toString();
1096 } else if ( v
instanceof OO
.ui
.Element
) {
1102 if ( config
.$content
) {
1103 // The `$content` property treats plain strings as HTML.
1104 this.$element
.append( config
.$content
);
1110 OO
.initClass( OO
.ui
.Element
);
1112 /* Static Properties */
1115 * The name of the HTML tag used by the element.
1117 * The static value may be ignored if the #getTagName method is overridden.
1121 * @property {string}
1123 OO
.ui
.Element
.static.tagName
= 'div';
1125 /* Static Methods */
1128 * Reconstitute a JavaScript object corresponding to a widget created
1129 * by the PHP implementation.
1131 * @param {string|HTMLElement|jQuery} idOrNode
1132 * A DOM id (if a string) or node for the widget to infuse.
1133 * @return {OO.ui.Element}
1134 * The `OO.ui.Element` corresponding to this (infusable) document node.
1135 * For `Tag` objects emitted on the HTML side (used occasionally for content)
1136 * the value returned is a newly-created Element wrapping around the existing
1139 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
1140 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, false );
1141 // Verify that the type matches up.
1142 // FIXME: uncomment after T89721 is fixed (see T90929)
1144 if ( !( obj instanceof this['class'] ) ) {
1145 throw new Error( 'Infusion type mismatch!' );
1152 * Implementation helper for `infuse`; skips the type check and has an
1153 * extra property so that only the top-level invocation touches the DOM.
1155 * @param {string|HTMLElement|jQuery} idOrNode
1156 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
1157 * when the top-level widget of this infusion is inserted into DOM,
1158 * replacing the original node; or false for top-level invocation.
1159 * @return {OO.ui.Element}
1161 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, domPromise
) {
1162 // look for a cached result of a previous infusion.
1163 var id
, $elem
, data
, cls
, parts
, parent
, obj
, top
, state
;
1164 if ( typeof idOrNode
=== 'string' ) {
1166 $elem
= $( document
.getElementById( id
) );
1168 $elem
= $( idOrNode
);
1169 id
= $elem
.attr( 'id' );
1171 if ( !$elem
.length
) {
1172 throw new Error( 'Widget not found: ' + id
);
1174 data
= $elem
.data( 'ooui-infused' ) || $elem
[0].oouiInfused
;
1177 if ( data
=== true ) {
1178 throw new Error( 'Circular dependency! ' + id
);
1182 data
= $elem
.attr( 'data-ooui' );
1184 throw new Error( 'No infusion data found: ' + id
);
1187 data
= $.parseJSON( data
);
1191 if ( !( data
&& data
._
) ) {
1192 throw new Error( 'No valid infusion data found: ' + id
);
1194 if ( data
._
=== 'Tag' ) {
1195 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1196 return new OO
.ui
.Element( { $element
: $elem
} );
1198 parts
= data
._
.split( '.' );
1199 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
1200 if ( cls
=== undefined ) {
1201 // The PHP output might be old and not including the "OO.ui" prefix
1202 // TODO: Remove this back-compat after next major release
1203 cls
= OO
.getProp
.apply( OO
, [ OO
.ui
].concat( parts
) );
1204 if ( cls
=== undefined ) {
1205 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
1209 // Verify that we're creating an OO.ui.Element instance
1210 parent
= cls
.parent
;
1212 while ( parent
!== undefined ) {
1213 if ( parent
=== OO
.ui
.Element
) {
1218 parent
= parent
.parent
;
1221 if ( parent
!== OO
.ui
.Element
) {
1222 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
1225 if ( domPromise
=== false ) {
1227 domPromise
= top
.promise();
1229 $elem
.data( 'ooui-infused', true ); // prevent loops
1230 data
.id
= id
; // implicit
1231 data
= OO
.copy( data
, null, function deserialize( value
) {
1232 if ( OO
.isPlainObject( value
) ) {
1234 return OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, domPromise
);
1237 return new OO
.ui
.HtmlSnippet( value
.html
);
1241 // jscs:disable requireCapitalizedConstructors
1242 obj
= new cls( data
); // rebuild widget
1243 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
1244 state
= obj
.gatherPreInfuseState( $elem
);
1245 // now replace old DOM with this new DOM.
1247 $elem
.replaceWith( obj
.$element
);
1248 // This element is now gone from the DOM, but if anyone is holding a reference to it,
1249 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
1250 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
1251 $elem
[0].oouiInfused
= obj
;
1254 obj
.$element
.data( 'ooui-infused', obj
);
1255 // set the 'data-ooui' attribute so we can identify infused widgets
1256 obj
.$element
.attr( 'data-ooui', '' );
1257 // restore dynamic state after the new element is inserted into DOM
1258 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
1263 * Get a jQuery function within a specific document.
1266 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1267 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1269 * @return {Function} Bound jQuery function
1271 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
1272 function wrapper( selector
) {
1273 return $( selector
, wrapper
.context
);
1276 wrapper
.context
= this.getDocument( context
);
1279 wrapper
.$iframe
= $iframe
;
1286 * Get the document of an element.
1289 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1290 * @return {HTMLDocument|null} Document object
1292 OO
.ui
.Element
.static.getDocument = function ( obj
) {
1293 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1294 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
1295 // Empty jQuery selections might have a context
1298 obj
.ownerDocument
||
1302 ( obj
.nodeType
=== 9 && obj
) ||
1307 * Get the window of an element or document.
1310 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1311 * @return {Window} Window object
1313 OO
.ui
.Element
.static.getWindow = function ( obj
) {
1314 var doc
= this.getDocument( obj
);
1315 return doc
.parentWindow
|| doc
.defaultView
;
1319 * Get the direction of an element or document.
1322 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1323 * @return {string} Text direction, either 'ltr' or 'rtl'
1325 OO
.ui
.Element
.static.getDir = function ( obj
) {
1328 if ( obj
instanceof jQuery
) {
1331 isDoc
= obj
.nodeType
=== 9;
1332 isWin
= obj
.document
!== undefined;
1333 if ( isDoc
|| isWin
) {
1339 return $( obj
).css( 'direction' );
1343 * Get the offset between two frames.
1345 * TODO: Make this function not use recursion.
1348 * @param {Window} from Window of the child frame
1349 * @param {Window} [to=window] Window of the parent frame
1350 * @param {Object} [offset] Offset to start with, used internally
1351 * @return {Object} Offset object, containing left and top properties
1353 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
1354 var i
, len
, frames
, frame
, rect
;
1360 offset
= { top
: 0, left
: 0 };
1362 if ( from.parent
=== from ) {
1366 // Get iframe element
1367 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
1368 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
1369 if ( frames
[ i
].contentWindow
=== from ) {
1370 frame
= frames
[ i
];
1375 // Recursively accumulate offset values
1377 rect
= frame
.getBoundingClientRect();
1378 offset
.left
+= rect
.left
;
1379 offset
.top
+= rect
.top
;
1380 if ( from !== to
) {
1381 this.getFrameOffset( from.parent
, offset
);
1388 * Get the offset between two elements.
1390 * The two elements may be in a different frame, but in that case the frame $element is in must
1391 * be contained in the frame $anchor is in.
1394 * @param {jQuery} $element Element whose position to get
1395 * @param {jQuery} $anchor Element to get $element's position relative to
1396 * @return {Object} Translated position coordinates, containing top and left properties
1398 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
1399 var iframe
, iframePos
,
1400 pos
= $element
.offset(),
1401 anchorPos
= $anchor
.offset(),
1402 elementDocument
= this.getDocument( $element
),
1403 anchorDocument
= this.getDocument( $anchor
);
1405 // If $element isn't in the same document as $anchor, traverse up
1406 while ( elementDocument
!== anchorDocument
) {
1407 iframe
= elementDocument
.defaultView
.frameElement
;
1409 throw new Error( '$element frame is not contained in $anchor frame' );
1411 iframePos
= $( iframe
).offset();
1412 pos
.left
+= iframePos
.left
;
1413 pos
.top
+= iframePos
.top
;
1414 elementDocument
= iframe
.ownerDocument
;
1416 pos
.left
-= anchorPos
.left
;
1417 pos
.top
-= anchorPos
.top
;
1422 * Get element border sizes.
1425 * @param {HTMLElement} el Element to measure
1426 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1428 OO
.ui
.Element
.static.getBorders = function ( el
) {
1429 var doc
= el
.ownerDocument
,
1430 win
= doc
.parentWindow
|| doc
.defaultView
,
1431 style
= win
&& win
.getComputedStyle
?
1432 win
.getComputedStyle( el
, null ) :
1435 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1436 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1437 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1438 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1449 * Get dimensions of an element or window.
1452 * @param {HTMLElement|Window} el Element to measure
1453 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1455 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1457 doc
= el
.ownerDocument
|| el
.document
,
1458 win
= doc
.parentWindow
|| doc
.defaultView
;
1460 if ( win
=== el
|| el
=== doc
.documentElement
) {
1463 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1465 top
: $win
.scrollTop(),
1466 left
: $win
.scrollLeft()
1468 scrollbar
: { right
: 0, bottom
: 0 },
1472 bottom
: $win
.innerHeight(),
1473 right
: $win
.innerWidth()
1479 borders
: this.getBorders( el
),
1481 top
: $el
.scrollTop(),
1482 left
: $el
.scrollLeft()
1485 right
: $el
.innerWidth() - el
.clientWidth
,
1486 bottom
: $el
.innerHeight() - el
.clientHeight
1488 rect
: el
.getBoundingClientRect()
1494 * Get scrollable object parent
1496 * documentElement can't be used to get or set the scrollTop
1497 * property on Blink. Changing and testing its value lets us
1498 * use 'body' or 'documentElement' based on what is working.
1500 * https://code.google.com/p/chromium/issues/detail?id=303131
1503 * @param {HTMLElement} el Element to find scrollable parent for
1504 * @return {HTMLElement} Scrollable parent
1506 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1507 var scrollTop
, body
;
1509 if ( OO
.ui
.scrollableElement
=== undefined ) {
1510 body
= el
.ownerDocument
.body
;
1511 scrollTop
= body
.scrollTop
;
1514 if ( body
.scrollTop
=== 1 ) {
1515 body
.scrollTop
= scrollTop
;
1516 OO
.ui
.scrollableElement
= 'body';
1518 OO
.ui
.scrollableElement
= 'documentElement';
1522 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1526 * Get closest scrollable container.
1528 * Traverses up until either a scrollable element or the root is reached, in which case the window
1532 * @param {HTMLElement} el Element to find scrollable container for
1533 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1534 * @return {HTMLElement} Closest scrollable container
1536 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1538 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1539 props
= [ 'overflow-x', 'overflow-y' ],
1540 $parent
= $( el
).parent();
1542 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1543 props
= [ 'overflow-' + dimension
];
1546 while ( $parent
.length
) {
1547 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1548 return $parent
[ 0 ];
1552 val
= $parent
.css( props
[ i
] );
1553 if ( val
=== 'auto' || val
=== 'scroll' ) {
1554 return $parent
[ 0 ];
1557 $parent
= $parent
.parent();
1559 return this.getDocument( el
).body
;
1563 * Scroll element into view.
1566 * @param {HTMLElement} el Element to scroll into view
1567 * @param {Object} [config] Configuration options
1568 * @param {string} [config.duration] jQuery animation duration value
1569 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1570 * to scroll in both directions
1571 * @param {Function} [config.complete] Function to call when scrolling completes
1573 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1574 // Configuration initialization
1575 config
= config
|| {};
1578 callback
= typeof config
.complete
=== 'function' && config
.complete
,
1579 sc
= this.getClosestScrollableContainer( el
, config
.direction
),
1581 eld
= this.getDimensions( el
),
1582 scd
= this.getDimensions( sc
),
1583 $win
= $( this.getWindow( el
) );
1585 // Compute the distances between the edges of el and the edges of the scroll viewport
1586 if ( $sc
.is( 'html, body' ) ) {
1587 // If the scrollable container is the root, this is easy
1590 bottom
: $win
.innerHeight() - eld
.rect
.bottom
,
1591 left
: eld
.rect
.left
,
1592 right
: $win
.innerWidth() - eld
.rect
.right
1595 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1597 top
: eld
.rect
.top
- ( scd
.rect
.top
+ scd
.borders
.top
),
1598 bottom
: scd
.rect
.bottom
- scd
.borders
.bottom
- scd
.scrollbar
.bottom
- eld
.rect
.bottom
,
1599 left
: eld
.rect
.left
- ( scd
.rect
.left
+ scd
.borders
.left
),
1600 right
: scd
.rect
.right
- scd
.borders
.right
- scd
.scrollbar
.right
- eld
.rect
.right
1604 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1605 if ( rel
.top
< 0 ) {
1606 anim
.scrollTop
= scd
.scroll
.top
+ rel
.top
;
1607 } else if ( rel
.top
> 0 && rel
.bottom
< 0 ) {
1608 anim
.scrollTop
= scd
.scroll
.top
+ Math
.min( rel
.top
, -rel
.bottom
);
1611 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1612 if ( rel
.left
< 0 ) {
1613 anim
.scrollLeft
= scd
.scroll
.left
+ rel
.left
;
1614 } else if ( rel
.left
> 0 && rel
.right
< 0 ) {
1615 anim
.scrollLeft
= scd
.scroll
.left
+ Math
.min( rel
.left
, -rel
.right
);
1618 if ( !$.isEmptyObject( anim
) ) {
1619 $sc
.stop( true ).animate( anim
, config
.duration
|| 'fast' );
1621 $sc
.queue( function ( next
) {
1634 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1635 * and reserve space for them, because it probably doesn't.
1637 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1638 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1639 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1640 * and then reattach (or show) them back.
1643 * @param {HTMLElement} el Element to reconsider the scrollbars on
1645 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1646 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1647 // Save scroll position
1648 scrollLeft
= el
.scrollLeft
;
1649 scrollTop
= el
.scrollTop
;
1650 // Detach all children
1651 while ( el
.firstChild
) {
1652 nodes
.push( el
.firstChild
);
1653 el
.removeChild( el
.firstChild
);
1656 void el
.offsetHeight
;
1657 // Reattach all children
1658 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1659 el
.appendChild( nodes
[ i
] );
1661 // Restore scroll position (no-op if scrollbars disappeared)
1662 el
.scrollLeft
= scrollLeft
;
1663 el
.scrollTop
= scrollTop
;
1669 * Toggle visibility of an element.
1671 * @param {boolean} [show] Make element visible, omit to toggle visibility
1675 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1676 show
= show
=== undefined ? !this.visible
: !!show
;
1678 if ( show
!== this.isVisible() ) {
1679 this.visible
= show
;
1680 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1681 this.emit( 'toggle', show
);
1688 * Check if element is visible.
1690 * @return {boolean} element is visible
1692 OO
.ui
.Element
.prototype.isVisible = function () {
1693 return this.visible
;
1699 * @return {Mixed} Element data
1701 OO
.ui
.Element
.prototype.getData = function () {
1708 * @param {Mixed} Element data
1711 OO
.ui
.Element
.prototype.setData = function ( data
) {
1717 * Check if element supports one or more methods.
1719 * @param {string|string[]} methods Method or list of methods to check
1720 * @return {boolean} All methods are supported
1722 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1726 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1727 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1728 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1733 return methods
.length
=== support
;
1737 * Update the theme-provided classes.
1739 * @localdoc This is called in element mixins and widget classes any time state changes.
1740 * Updating is debounced, minimizing overhead of changing multiple attributes and
1741 * guaranteeing that theme updates do not occur within an element's constructor
1743 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1744 if ( !this.updateThemeClassesPending
) {
1745 this.updateThemeClassesPending
= true;
1746 setTimeout( this.debouncedUpdateThemeClassesHandler
);
1753 OO
.ui
.Element
.prototype.debouncedUpdateThemeClasses = function () {
1754 OO
.ui
.theme
.updateElementClasses( this );
1755 this.updateThemeClassesPending
= false;
1759 * Get the HTML tag name.
1761 * Override this method to base the result on instance information.
1763 * @return {string} HTML tag name
1765 OO
.ui
.Element
.prototype.getTagName = function () {
1766 return this.constructor.static.tagName
;
1770 * Check if the element is attached to the DOM
1771 * @return {boolean} The element is attached to the DOM
1773 OO
.ui
.Element
.prototype.isElementAttached = function () {
1774 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1778 * Get the DOM document.
1780 * @return {HTMLDocument} Document object
1782 OO
.ui
.Element
.prototype.getElementDocument = function () {
1783 // Don't cache this in other ways either because subclasses could can change this.$element
1784 return OO
.ui
.Element
.static.getDocument( this.$element
);
1788 * Get the DOM window.
1790 * @return {Window} Window object
1792 OO
.ui
.Element
.prototype.getElementWindow = function () {
1793 return OO
.ui
.Element
.static.getWindow( this.$element
);
1797 * Get closest scrollable container.
1799 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1800 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1804 * Get group element is in.
1806 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1808 OO
.ui
.Element
.prototype.getElementGroup = function () {
1809 return this.elementGroup
;
1813 * Set group element is in.
1815 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1818 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1819 this.elementGroup
= group
;
1824 * Scroll element into view.
1826 * @param {Object} [config] Configuration options
1828 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1829 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1833 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
1834 * (and its children) that represent an Element of the same type and configuration as the current
1835 * one, generated by the PHP implementation.
1837 * This method is called just before `node` is detached from the DOM. The return value of this
1838 * function will be passed to #restorePreInfuseState after this widget's #$element is inserted into
1839 * DOM to replace `node`.
1842 * @param {HTMLElement} node
1845 OO
.ui
.Element
.prototype.gatherPreInfuseState = function () {
1850 * Restore the pre-infusion dynamic state for this widget.
1852 * This method is called after #$element has been inserted into DOM. The parameter is the return
1853 * value of #gatherPreInfuseState.
1856 * @param {Object} state
1858 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1862 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1863 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1864 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1865 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1866 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1870 * @extends OO.ui.Element
1871 * @mixins OO.EventEmitter
1874 * @param {Object} [config] Configuration options
1876 OO
.ui
.Layout
= function OoUiLayout( config
) {
1877 // Configuration initialization
1878 config
= config
|| {};
1880 // Parent constructor
1881 OO
.ui
.Layout
.parent
.call( this, config
);
1883 // Mixin constructors
1884 OO
.EventEmitter
.call( this );
1887 this.$element
.addClass( 'oo-ui-layout' );
1892 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1893 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1896 * Widgets are compositions of one or more OOjs UI elements that users can both view
1897 * and interact with. All widgets can be configured and modified via a standard API,
1898 * and their state can change dynamically according to a model.
1902 * @extends OO.ui.Element
1903 * @mixins OO.EventEmitter
1906 * @param {Object} [config] Configuration options
1907 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1908 * appearance reflects this state.
1910 OO
.ui
.Widget
= function OoUiWidget( config
) {
1911 // Initialize config
1912 config
= $.extend( { disabled
: false }, config
);
1914 // Parent constructor
1915 OO
.ui
.Widget
.parent
.call( this, config
);
1917 // Mixin constructors
1918 OO
.EventEmitter
.call( this );
1921 this.disabled
= null;
1922 this.wasDisabled
= null;
1925 this.$element
.addClass( 'oo-ui-widget' );
1926 this.setDisabled( !!config
.disabled
);
1931 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1932 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1934 /* Static Properties */
1937 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
1938 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
1943 * @property {boolean}
1945 OO
.ui
.Widget
.static.supportsSimpleLabel
= false;
1952 * A 'disable' event is emitted when a widget is disabled.
1954 * @param {boolean} disabled Widget is disabled
1960 * A 'toggle' event is emitted when the visibility of the widget changes.
1962 * @param {boolean} visible Widget is visible
1968 * Check if the widget is disabled.
1970 * @return {boolean} Widget is disabled
1972 OO
.ui
.Widget
.prototype.isDisabled = function () {
1973 return this.disabled
;
1977 * Set the 'disabled' state of the widget.
1979 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1981 * @param {boolean} disabled Disable widget
1984 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1987 this.disabled
= !!disabled
;
1988 isDisabled
= this.isDisabled();
1989 if ( isDisabled
!== this.wasDisabled
) {
1990 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1991 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1992 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1993 this.emit( 'disable', isDisabled
);
1994 this.updateThemeClasses();
1996 this.wasDisabled
= isDisabled
;
2002 * Update the disabled state, in case of changes in parent widget.
2006 OO
.ui
.Widget
.prototype.updateDisabled = function () {
2007 this.setDisabled( this.disabled
);
2012 * A window is a container for elements that are in a child frame. They are used with
2013 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
2014 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
2015 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
2016 * the window manager will choose a sensible fallback.
2018 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
2019 * different processes are executed:
2021 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
2022 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
2025 * - {@link #getSetupProcess} method is called and its result executed
2026 * - {@link #getReadyProcess} method is called and its result executed
2028 * **opened**: The window is now open
2030 * **closing**: The closing stage begins when the window manager's
2031 * {@link OO.ui.WindowManager#closeWindow closeWindow}
2032 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
2034 * - {@link #getHoldProcess} method is called and its result executed
2035 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
2037 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
2038 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
2039 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
2040 * processing can complete. Always assume window processes are executed asynchronously.
2042 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2044 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
2048 * @extends OO.ui.Element
2049 * @mixins OO.EventEmitter
2052 * @param {Object} [config] Configuration options
2053 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
2054 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
2056 OO
.ui
.Window
= function OoUiWindow( config
) {
2057 // Configuration initialization
2058 config
= config
|| {};
2060 // Parent constructor
2061 OO
.ui
.Window
.parent
.call( this, config
);
2063 // Mixin constructors
2064 OO
.EventEmitter
.call( this );
2067 this.manager
= null;
2068 this.size
= config
.size
|| this.constructor.static.size
;
2069 this.$frame
= $( '<div>' );
2070 this.$overlay
= $( '<div>' );
2071 this.$content
= $( '<div>' );
2074 this.$overlay
.addClass( 'oo-ui-window-overlay' );
2076 .addClass( 'oo-ui-window-content' )
2077 .attr( 'tabindex', 0 );
2079 .addClass( 'oo-ui-window-frame' )
2080 .append( this.$content
);
2083 .addClass( 'oo-ui-window' )
2084 .append( this.$frame
, this.$overlay
);
2086 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
2087 // that reference properties not initialized at that time of parent class construction
2088 // TODO: Find a better way to handle post-constructor setup
2089 this.visible
= false;
2090 this.$element
.addClass( 'oo-ui-element-hidden' );
2095 OO
.inheritClass( OO
.ui
.Window
, OO
.ui
.Element
);
2096 OO
.mixinClass( OO
.ui
.Window
, OO
.EventEmitter
);
2098 /* Static Properties */
2101 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
2103 * The static size is used if no #size is configured during construction.
2107 * @property {string}
2109 OO
.ui
.Window
.static.size
= 'medium';
2114 * Handle mouse down events.
2117 * @param {jQuery.Event} e Mouse down event
2119 OO
.ui
.Window
.prototype.onMouseDown = function ( e
) {
2120 // Prevent clicking on the click-block from stealing focus
2121 if ( e
.target
=== this.$element
[ 0 ] ) {
2127 * Check if the window has been initialized.
2129 * Initialization occurs when a window is added to a manager.
2131 * @return {boolean} Window has been initialized
2133 OO
.ui
.Window
.prototype.isInitialized = function () {
2134 return !!this.manager
;
2138 * Check if the window is visible.
2140 * @return {boolean} Window is visible
2142 OO
.ui
.Window
.prototype.isVisible = function () {
2143 return this.visible
;
2147 * Check if the window is opening.
2149 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2152 * @return {boolean} Window is opening
2154 OO
.ui
.Window
.prototype.isOpening = function () {
2155 return this.manager
.isOpening( this );
2159 * Check if the window is closing.
2161 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2163 * @return {boolean} Window is closing
2165 OO
.ui
.Window
.prototype.isClosing = function () {
2166 return this.manager
.isClosing( this );
2170 * Check if the window is opened.
2172 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2174 * @return {boolean} Window is opened
2176 OO
.ui
.Window
.prototype.isOpened = function () {
2177 return this.manager
.isOpened( this );
2181 * Get the window manager.
2183 * All windows must be attached to a window manager, which is used to open
2184 * and close the window and control its presentation.
2186 * @return {OO.ui.WindowManager} Manager of window
2188 OO
.ui
.Window
.prototype.getManager = function () {
2189 return this.manager
;
2193 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2195 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2197 OO
.ui
.Window
.prototype.getSize = function () {
2198 var viewport
= OO
.ui
.Element
.static.getDimensions( this.getElementWindow() ),
2199 sizes
= this.manager
.constructor.static.sizes
,
2202 if ( !sizes
[ size
] ) {
2203 size
= this.manager
.constructor.static.defaultSize
;
2205 if ( size
!== 'full' && viewport
.rect
.right
- viewport
.rect
.left
< sizes
[ size
].width
) {
2213 * Get the size properties associated with the current window size
2215 * @return {Object} Size properties
2217 OO
.ui
.Window
.prototype.getSizeProperties = function () {
2218 return this.manager
.constructor.static.sizes
[ this.getSize() ];
2222 * Disable transitions on window's frame for the duration of the callback function, then enable them
2226 * @param {Function} callback Function to call while transitions are disabled
2228 OO
.ui
.Window
.prototype.withoutSizeTransitions = function ( callback
) {
2229 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2230 // Disable transitions first, otherwise we'll get values from when the window was animating.
2232 styleObj
= this.$frame
[ 0 ].style
;
2233 oldTransition
= styleObj
.transition
|| styleObj
.OTransition
|| styleObj
.MsTransition
||
2234 styleObj
.MozTransition
|| styleObj
.WebkitTransition
;
2235 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
2236 styleObj
.MozTransition
= styleObj
.WebkitTransition
= 'none';
2238 // Force reflow to make sure the style changes done inside callback really are not transitioned
2239 this.$frame
.height();
2240 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
2241 styleObj
.MozTransition
= styleObj
.WebkitTransition
= oldTransition
;
2245 * Get the height of the full window contents (i.e., the window head, body and foot together).
2247 * What consistitutes the head, body, and foot varies depending on the window type.
2248 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2249 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2250 * and special actions in the head, and dialog content in the body.
2252 * To get just the height of the dialog body, use the #getBodyHeight method.
2254 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2256 OO
.ui
.Window
.prototype.getContentHeight = function () {
2259 bodyStyleObj
= this.$body
[ 0 ].style
,
2260 frameStyleObj
= this.$frame
[ 0 ].style
;
2262 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2263 // Disable transitions first, otherwise we'll get values from when the window was animating.
2264 this.withoutSizeTransitions( function () {
2265 var oldHeight
= frameStyleObj
.height
,
2266 oldPosition
= bodyStyleObj
.position
;
2267 frameStyleObj
.height
= '1px';
2268 // Force body to resize to new width
2269 bodyStyleObj
.position
= 'relative';
2270 bodyHeight
= win
.getBodyHeight();
2271 frameStyleObj
.height
= oldHeight
;
2272 bodyStyleObj
.position
= oldPosition
;
2276 // Add buffer for border
2277 ( this.$frame
.outerHeight() - this.$frame
.innerHeight() ) +
2278 // Use combined heights of children
2279 ( this.$head
.outerHeight( true ) + bodyHeight
+ this.$foot
.outerHeight( true ) )
2284 * Get the height of the window body.
2286 * To get the height of the full window contents (the window body, head, and foot together),
2287 * use #getContentHeight.
2289 * When this function is called, the window will temporarily have been resized
2290 * to height=1px, so .scrollHeight measurements can be taken accurately.
2292 * @return {number} Height of the window body in pixels
2294 OO
.ui
.Window
.prototype.getBodyHeight = function () {
2295 return this.$body
[ 0 ].scrollHeight
;
2299 * Get the directionality of the frame (right-to-left or left-to-right).
2301 * @return {string} Directionality: `'ltr'` or `'rtl'`
2303 OO
.ui
.Window
.prototype.getDir = function () {
2304 return OO
.ui
.Element
.static.getDir( this.$content
) || 'ltr';
2308 * Get the 'setup' process.
2310 * The setup process is used to set up a window for use in a particular context,
2311 * based on the `data` argument. This method is called during the opening phase of the window’s
2314 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2315 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2318 * To add window content that persists between openings, you may wish to use the #initialize method
2322 * @param {Object} [data] Window opening data
2323 * @return {OO.ui.Process} Setup process
2325 OO
.ui
.Window
.prototype.getSetupProcess = function () {
2326 return new OO
.ui
.Process();
2330 * Get the ‘ready’ process.
2332 * The ready process is used to ready a window for use in a particular
2333 * context, based on the `data` argument. This method is called during the opening phase of
2334 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2336 * Override this method to add additional steps to the ‘ready’ process the parent method
2337 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2338 * methods of OO.ui.Process.
2341 * @param {Object} [data] Window opening data
2342 * @return {OO.ui.Process} Ready process
2344 OO
.ui
.Window
.prototype.getReadyProcess = function () {
2345 return new OO
.ui
.Process();
2349 * Get the 'hold' process.
2351 * The hold proccess is used to keep a window from being used in a particular context,
2352 * based on the `data` argument. This method is called during the closing phase of the window’s
2355 * Override this method to add additional steps to the 'hold' process the parent method provides
2356 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2360 * @param {Object} [data] Window closing data
2361 * @return {OO.ui.Process} Hold process
2363 OO
.ui
.Window
.prototype.getHoldProcess = function () {
2364 return new OO
.ui
.Process();
2368 * Get the ‘teardown’ process.
2370 * The teardown process is used to teardown a window after use. During teardown,
2371 * user interactions within the window are conveyed and the window is closed, based on the `data`
2372 * argument. This method is called during the closing phase of the window’s lifecycle.
2374 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2375 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2379 * @param {Object} [data] Window closing data
2380 * @return {OO.ui.Process} Teardown process
2382 OO
.ui
.Window
.prototype.getTeardownProcess = function () {
2383 return new OO
.ui
.Process();
2387 * Set the window manager.
2389 * This will cause the window to initialize. Calling it more than once will cause an error.
2391 * @param {OO.ui.WindowManager} manager Manager for this window
2392 * @throws {Error} An error is thrown if the method is called more than once
2395 OO
.ui
.Window
.prototype.setManager = function ( manager
) {
2396 if ( this.manager
) {
2397 throw new Error( 'Cannot set window manager, window already has a manager' );
2400 this.manager
= manager
;
2407 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2409 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2413 OO
.ui
.Window
.prototype.setSize = function ( size
) {
2420 * Update the window size.
2422 * @throws {Error} An error is thrown if the window is not attached to a window manager
2425 OO
.ui
.Window
.prototype.updateSize = function () {
2426 if ( !this.manager
) {
2427 throw new Error( 'Cannot update window size, must be attached to a manager' );
2430 this.manager
.updateWindowSize( this );
2436 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2437 * when the window is opening. In general, setDimensions should not be called directly.
2439 * To set the size of the window, use the #setSize method.
2441 * @param {Object} dim CSS dimension properties
2442 * @param {string|number} [dim.width] Width
2443 * @param {string|number} [dim.minWidth] Minimum width
2444 * @param {string|number} [dim.maxWidth] Maximum width
2445 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2446 * @param {string|number} [dim.minWidth] Minimum height
2447 * @param {string|number} [dim.maxWidth] Maximum height
2450 OO
.ui
.Window
.prototype.setDimensions = function ( dim
) {
2453 styleObj
= this.$frame
[ 0 ].style
;
2455 // Calculate the height we need to set using the correct width
2456 if ( dim
.height
=== undefined ) {
2457 this.withoutSizeTransitions( function () {
2458 var oldWidth
= styleObj
.width
;
2459 win
.$frame
.css( 'width', dim
.width
|| '' );
2460 height
= win
.getContentHeight();
2461 styleObj
.width
= oldWidth
;
2464 height
= dim
.height
;
2468 width
: dim
.width
|| '',
2469 minWidth
: dim
.minWidth
|| '',
2470 maxWidth
: dim
.maxWidth
|| '',
2471 height
: height
|| '',
2472 minHeight
: dim
.minHeight
|| '',
2473 maxHeight
: dim
.maxHeight
|| ''
2480 * Initialize window contents.
2482 * Before the window is opened for the first time, #initialize is called so that content that
2483 * persists between openings can be added to the window.
2485 * To set up a window with new content each time the window opens, use #getSetupProcess.
2487 * @throws {Error} An error is thrown if the window is not attached to a window manager
2490 OO
.ui
.Window
.prototype.initialize = function () {
2491 if ( !this.manager
) {
2492 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2496 this.$head
= $( '<div>' );
2497 this.$body
= $( '<div>' );
2498 this.$foot
= $( '<div>' );
2499 this.$document
= $( this.getElementDocument() );
2502 this.$element
.on( 'mousedown', this.onMouseDown
.bind( this ) );
2505 this.$head
.addClass( 'oo-ui-window-head' );
2506 this.$body
.addClass( 'oo-ui-window-body' );
2507 this.$foot
.addClass( 'oo-ui-window-foot' );
2508 this.$content
.append( this.$head
, this.$body
, this.$foot
);
2516 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2517 * method, which returns a promise resolved when the window is done opening.
2519 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2521 * @param {Object} [data] Window opening data
2522 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2523 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2524 * value is a new promise, which is resolved when the window begins closing.
2525 * @throws {Error} An error is thrown if the window is not attached to a window manager
2527 OO
.ui
.Window
.prototype.open = function ( data
) {
2528 if ( !this.manager
) {
2529 throw new Error( 'Cannot open window, must be attached to a manager' );
2532 return this.manager
.openWindow( this, data
);
2538 * This method is a wrapper around a call to the window
2539 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2540 * which returns a closing promise resolved when the window is done closing.
2542 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2543 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2544 * the window closes.
2546 * @param {Object} [data] Window closing data
2547 * @return {jQuery.Promise} Promise resolved when window is closed
2548 * @throws {Error} An error is thrown if the window is not attached to a window manager
2550 OO
.ui
.Window
.prototype.close = function ( data
) {
2551 if ( !this.manager
) {
2552 throw new Error( 'Cannot close window, must be attached to a manager' );
2555 return this.manager
.closeWindow( this, data
);
2561 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2564 * @param {Object} [data] Window opening data
2565 * @return {jQuery.Promise} Promise resolved when window is setup
2567 OO
.ui
.Window
.prototype.setup = function ( data
) {
2569 deferred
= $.Deferred();
2571 this.toggle( true );
2573 this.getSetupProcess( data
).execute().done( function () {
2574 // Force redraw by asking the browser to measure the elements' widths
2575 win
.$element
.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2576 win
.$content
.addClass( 'oo-ui-window-content-setup' ).width();
2580 return deferred
.promise();
2586 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2589 * @param {Object} [data] Window opening data
2590 * @return {jQuery.Promise} Promise resolved when window is ready
2592 OO
.ui
.Window
.prototype.ready = function ( data
) {
2594 deferred
= $.Deferred();
2596 this.$content
.focus();
2597 this.getReadyProcess( data
).execute().done( function () {
2598 // Force redraw by asking the browser to measure the elements' widths
2599 win
.$element
.addClass( 'oo-ui-window-ready' ).width();
2600 win
.$content
.addClass( 'oo-ui-window-content-ready' ).width();
2604 return deferred
.promise();
2610 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2613 * @param {Object} [data] Window closing data
2614 * @return {jQuery.Promise} Promise resolved when window is held
2616 OO
.ui
.Window
.prototype.hold = function ( data
) {
2618 deferred
= $.Deferred();
2620 this.getHoldProcess( data
).execute().done( function () {
2621 // Get the focused element within the window's content
2622 var $focus
= win
.$content
.find( OO
.ui
.Element
.static.getDocument( win
.$content
).activeElement
);
2624 // Blur the focused element
2625 if ( $focus
.length
) {
2629 // Force redraw by asking the browser to measure the elements' widths
2630 win
.$element
.removeClass( 'oo-ui-window-ready' ).width();
2631 win
.$content
.removeClass( 'oo-ui-window-content-ready' ).width();
2635 return deferred
.promise();
2641 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2644 * @param {Object} [data] Window closing data
2645 * @return {jQuery.Promise} Promise resolved when window is torn down
2647 OO
.ui
.Window
.prototype.teardown = function ( data
) {
2650 return this.getTeardownProcess( data
).execute()
2651 .done( function () {
2652 // Force redraw by asking the browser to measure the elements' widths
2653 win
.$element
.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2654 win
.$content
.removeClass( 'oo-ui-window-content-setup' ).width();
2655 win
.toggle( false );
2660 * The Dialog class serves as the base class for the other types of dialogs.
2661 * Unless extended to include controls, the rendered dialog box is a simple window
2662 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2663 * which opens, closes, and controls the presentation of the window. See the
2664 * [OOjs UI documentation on MediaWiki] [1] for more information.
2667 * // A simple dialog window.
2668 * function MyDialog( config ) {
2669 * MyDialog.parent.call( this, config );
2671 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2672 * MyDialog.prototype.initialize = function () {
2673 * MyDialog.parent.prototype.initialize.call( this );
2674 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2675 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2676 * this.$body.append( this.content.$element );
2678 * MyDialog.prototype.getBodyHeight = function () {
2679 * return this.content.$element.outerHeight( true );
2681 * var myDialog = new MyDialog( {
2684 * // Create and append a window manager, which opens and closes the window.
2685 * var windowManager = new OO.ui.WindowManager();
2686 * $( 'body' ).append( windowManager.$element );
2687 * windowManager.addWindows( [ myDialog ] );
2688 * // Open the window!
2689 * windowManager.openWindow( myDialog );
2691 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2695 * @extends OO.ui.Window
2696 * @mixins OO.ui.mixin.PendingElement
2699 * @param {Object} [config] Configuration options
2701 OO
.ui
.Dialog
= function OoUiDialog( config
) {
2702 // Parent constructor
2703 OO
.ui
.Dialog
.parent
.call( this, config
);
2705 // Mixin constructors
2706 OO
.ui
.mixin
.PendingElement
.call( this );
2709 this.actions
= new OO
.ui
.ActionSet();
2710 this.attachedActions
= [];
2711 this.currentAction
= null;
2712 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
2715 this.actions
.connect( this, {
2716 click
: 'onActionClick',
2717 resize
: 'onActionResize',
2718 change
: 'onActionsChange'
2723 .addClass( 'oo-ui-dialog' )
2724 .attr( 'role', 'dialog' );
2729 OO
.inheritClass( OO
.ui
.Dialog
, OO
.ui
.Window
);
2730 OO
.mixinClass( OO
.ui
.Dialog
, OO
.ui
.mixin
.PendingElement
);
2732 /* Static Properties */
2735 * Symbolic name of dialog.
2737 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2738 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2740 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2745 * @property {string}
2747 OO
.ui
.Dialog
.static.name
= '';
2752 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2753 * that will produce a Label node or string. The title can also be specified with data passed to the
2754 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2759 * @property {jQuery|string|Function}
2761 OO
.ui
.Dialog
.static.title
= '';
2764 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2766 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2767 * value will be overriden.
2769 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2773 * @property {Object[]}
2775 OO
.ui
.Dialog
.static.actions
= [];
2778 * Close the dialog when the 'Esc' key is pressed.
2783 * @property {boolean}
2785 OO
.ui
.Dialog
.static.escapable
= true;
2790 * Handle frame document key down events.
2793 * @param {jQuery.Event} e Key down event
2795 OO
.ui
.Dialog
.prototype.onDocumentKeyDown = function ( e
) {
2796 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
2799 e
.stopPropagation();
2804 * Handle action resized events.
2807 * @param {OO.ui.ActionWidget} action Action that was resized
2809 OO
.ui
.Dialog
.prototype.onActionResize = function () {
2810 // Override in subclass
2814 * Handle action click events.
2817 * @param {OO.ui.ActionWidget} action Action that was clicked
2819 OO
.ui
.Dialog
.prototype.onActionClick = function ( action
) {
2820 if ( !this.isPending() ) {
2821 this.executeAction( action
.getAction() );
2826 * Handle actions change event.
2830 OO
.ui
.Dialog
.prototype.onActionsChange = function () {
2831 this.detachActions();
2832 if ( !this.isClosing() ) {
2833 this.attachActions();
2838 * Get the set of actions used by the dialog.
2840 * @return {OO.ui.ActionSet}
2842 OO
.ui
.Dialog
.prototype.getActions = function () {
2843 return this.actions
;
2847 * Get a process for taking action.
2849 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2850 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2851 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2854 * @param {string} [action] Symbolic name of action
2855 * @return {OO.ui.Process} Action process
2857 OO
.ui
.Dialog
.prototype.getActionProcess = function ( action
) {
2858 return new OO
.ui
.Process()
2859 .next( function () {
2861 // An empty action always closes the dialog without data, which should always be
2862 // safe and make no changes
2871 * @param {Object} [data] Dialog opening data
2872 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2873 * the {@link #static-title static title}
2874 * @param {Object[]} [data.actions] List of configuration options for each
2875 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2877 OO
.ui
.Dialog
.prototype.getSetupProcess = function ( data
) {
2881 return OO
.ui
.Dialog
.parent
.prototype.getSetupProcess
.call( this, data
)
2882 .next( function () {
2883 var config
= this.constructor.static,
2884 actions
= data
.actions
!== undefined ? data
.actions
: config
.actions
;
2886 this.title
.setLabel(
2887 data
.title
!== undefined ? data
.title
: this.constructor.static.title
2889 this.actions
.add( this.getActionWidgets( actions
) );
2891 if ( this.constructor.static.escapable
) {
2892 this.$document
.on( 'keydown', this.onDocumentKeyDownHandler
);
2900 OO
.ui
.Dialog
.prototype.getTeardownProcess = function ( data
) {
2902 return OO
.ui
.Dialog
.parent
.prototype.getTeardownProcess
.call( this, data
)
2903 .first( function () {
2904 if ( this.constructor.static.escapable
) {
2905 this.$document
.off( 'keydown', this.onDocumentKeyDownHandler
);
2908 this.actions
.clear();
2909 this.currentAction
= null;
2916 OO
.ui
.Dialog
.prototype.initialize = function () {
2918 OO
.ui
.Dialog
.parent
.prototype.initialize
.call( this );
2920 var titleId
= OO
.ui
.generateElementId();
2923 this.title
= new OO
.ui
.LabelWidget( {
2928 this.$content
.addClass( 'oo-ui-dialog-content' );
2929 this.$element
.attr( 'aria-labelledby', titleId
);
2930 this.setPendingElement( this.$head
);
2934 * Get action widgets from a list of configs
2936 * @param {Object[]} actions Action widget configs
2937 * @return {OO.ui.ActionWidget[]} Action widgets
2939 OO
.ui
.Dialog
.prototype.getActionWidgets = function ( actions
) {
2940 var i
, len
, widgets
= [];
2941 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
2943 new OO
.ui
.ActionWidget( actions
[ i
] )
2950 * Attach action actions.
2954 OO
.ui
.Dialog
.prototype.attachActions = function () {
2955 // Remember the list of potentially attached actions
2956 this.attachedActions
= this.actions
.get();
2960 * Detach action actions.
2965 OO
.ui
.Dialog
.prototype.detachActions = function () {
2968 // Detach all actions that may have been previously attached
2969 for ( i
= 0, len
= this.attachedActions
.length
; i
< len
; i
++ ) {
2970 this.attachedActions
[ i
].$element
.detach();
2972 this.attachedActions
= [];
2976 * Execute an action.
2978 * @param {string} action Symbolic name of action to execute
2979 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2981 OO
.ui
.Dialog
.prototype.executeAction = function ( action
) {
2983 this.currentAction
= action
;
2984 return this.getActionProcess( action
).execute()
2985 .always( this.popPending
.bind( this ) );
2989 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
2990 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
2991 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
2992 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
2993 * pertinent data and reused.
2995 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
2996 * `opened`, and `closing`, which represent the primary stages of the cycle:
2998 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
2999 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
3001 * - an `opening` event is emitted with an `opening` promise
3002 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
3003 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
3004 * window and its result executed
3005 * - a `setup` progress notification is emitted from the `opening` promise
3006 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
3007 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
3008 * window and its result executed
3009 * - a `ready` progress notification is emitted from the `opening` promise
3010 * - the `opening` promise is resolved with an `opened` promise
3012 * **Opened**: the window is now open.
3014 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
3015 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
3016 * to close the window.
3018 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
3019 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
3020 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
3021 * window and its result executed
3022 * - a `hold` progress notification is emitted from the `closing` promise
3023 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
3024 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
3025 * window and its result executed
3026 * - a `teardown` progress notification is emitted from the `closing` promise
3027 * - the `closing` promise is resolved. The window is now closed
3029 * See the [OOjs UI documentation on MediaWiki][1] for more information.
3031 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3034 * @extends OO.ui.Element
3035 * @mixins OO.EventEmitter
3038 * @param {Object} [config] Configuration options
3039 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
3040 * Note that window classes that are instantiated with a factory must have
3041 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
3042 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
3044 OO
.ui
.WindowManager
= function OoUiWindowManager( config
) {
3045 // Configuration initialization
3046 config
= config
|| {};
3048 // Parent constructor
3049 OO
.ui
.WindowManager
.parent
.call( this, config
);
3051 // Mixin constructors
3052 OO
.EventEmitter
.call( this );
3055 this.factory
= config
.factory
;
3056 this.modal
= config
.modal
=== undefined || !!config
.modal
;
3058 this.opening
= null;
3060 this.closing
= null;
3061 this.preparingToOpen
= null;
3062 this.preparingToClose
= null;
3063 this.currentWindow
= null;
3064 this.globalEvents
= false;
3065 this.$ariaHidden
= null;
3066 this.onWindowResizeTimeout
= null;
3067 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
3068 this.afterWindowResizeHandler
= this.afterWindowResize
.bind( this );
3072 .addClass( 'oo-ui-windowManager' )
3073 .toggleClass( 'oo-ui-windowManager-modal', this.modal
);
3078 OO
.inheritClass( OO
.ui
.WindowManager
, OO
.ui
.Element
);
3079 OO
.mixinClass( OO
.ui
.WindowManager
, OO
.EventEmitter
);
3084 * An 'opening' event is emitted when the window begins to be opened.
3087 * @param {OO.ui.Window} win Window that's being opened
3088 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
3089 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
3090 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
3091 * @param {Object} data Window opening data
3095 * A 'closing' event is emitted when the window begins to be closed.
3098 * @param {OO.ui.Window} win Window that's being closed
3099 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
3100 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
3101 * processes are complete. When the `closing` promise is resolved, the first argument of its value
3102 * is the closing data.
3103 * @param {Object} data Window closing data
3107 * A 'resize' event is emitted when a window is resized.
3110 * @param {OO.ui.Window} win Window that was resized
3113 /* Static Properties */
3116 * Map of the symbolic name of each window size and its CSS properties.
3120 * @property {Object}
3122 OO
.ui
.WindowManager
.static.sizes
= {
3136 // These can be non-numeric because they are never used in calculations
3143 * Symbolic name of the default window size.
3145 * The default size is used if the window's requested size is not recognized.
3149 * @property {string}
3151 OO
.ui
.WindowManager
.static.defaultSize
= 'medium';
3156 * Handle window resize events.
3159 * @param {jQuery.Event} e Window resize event
3161 OO
.ui
.WindowManager
.prototype.onWindowResize = function () {
3162 clearTimeout( this.onWindowResizeTimeout
);
3163 this.onWindowResizeTimeout
= setTimeout( this.afterWindowResizeHandler
, 200 );
3167 * Handle window resize events.
3170 * @param {jQuery.Event} e Window resize event
3172 OO
.ui
.WindowManager
.prototype.afterWindowResize = function () {
3173 if ( this.currentWindow
) {
3174 this.updateWindowSize( this.currentWindow
);
3179 * Check if window is opening.
3181 * @return {boolean} Window is opening
3183 OO
.ui
.WindowManager
.prototype.isOpening = function ( win
) {
3184 return win
=== this.currentWindow
&& !!this.opening
&& this.opening
.state() === 'pending';
3188 * Check if window is closing.
3190 * @return {boolean} Window is closing
3192 OO
.ui
.WindowManager
.prototype.isClosing = function ( win
) {
3193 return win
=== this.currentWindow
&& !!this.closing
&& this.closing
.state() === 'pending';
3197 * Check if window is opened.
3199 * @return {boolean} Window is opened
3201 OO
.ui
.WindowManager
.prototype.isOpened = function ( win
) {
3202 return win
=== this.currentWindow
&& !!this.opened
&& this.opened
.state() === 'pending';
3206 * Check if a window is being managed.
3208 * @param {OO.ui.Window} win Window to check
3209 * @return {boolean} Window is being managed
3211 OO
.ui
.WindowManager
.prototype.hasWindow = function ( win
) {
3214 for ( name
in this.windows
) {
3215 if ( this.windows
[ name
] === win
) {
3224 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
3226 * @param {OO.ui.Window} win Window being opened
3227 * @param {Object} [data] Window opening data
3228 * @return {number} Milliseconds to wait
3230 OO
.ui
.WindowManager
.prototype.getSetupDelay = function () {
3235 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3237 * @param {OO.ui.Window} win Window being opened
3238 * @param {Object} [data] Window opening data
3239 * @return {number} Milliseconds to wait
3241 OO
.ui
.WindowManager
.prototype.getReadyDelay = function () {
3246 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3248 * @param {OO.ui.Window} win Window being closed
3249 * @param {Object} [data] Window closing data
3250 * @return {number} Milliseconds to wait
3252 OO
.ui
.WindowManager
.prototype.getHoldDelay = function () {
3257 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3258 * executing the ‘teardown’ process.
3260 * @param {OO.ui.Window} win Window being closed
3261 * @param {Object} [data] Window closing data
3262 * @return {number} Milliseconds to wait
3264 OO
.ui
.WindowManager
.prototype.getTeardownDelay = function () {
3265 return this.modal
? 250 : 0;
3269 * Get a window by its symbolic name.
3271 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3272 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3273 * for more information about using factories.
3274 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3276 * @param {string} name Symbolic name of the window
3277 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3278 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3279 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3281 OO
.ui
.WindowManager
.prototype.getWindow = function ( name
) {
3282 var deferred
= $.Deferred(),
3283 win
= this.windows
[ name
];
3285 if ( !( win
instanceof OO
.ui
.Window
) ) {
3286 if ( this.factory
) {
3287 if ( !this.factory
.lookup( name
) ) {
3288 deferred
.reject( new OO
.ui
.Error(
3289 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3292 win
= this.factory
.create( name
);
3293 this.addWindows( [ win
] );
3294 deferred
.resolve( win
);
3297 deferred
.reject( new OO
.ui
.Error(
3298 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3302 deferred
.resolve( win
);
3305 return deferred
.promise();
3309 * Get current window.
3311 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3313 OO
.ui
.WindowManager
.prototype.getCurrentWindow = function () {
3314 return this.currentWindow
;
3320 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3321 * @param {Object} [data] Window opening data
3322 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3323 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3326 OO
.ui
.WindowManager
.prototype.openWindow = function ( win
, data
) {
3328 opening
= $.Deferred();
3330 // Argument handling
3331 if ( typeof win
=== 'string' ) {
3332 return this.getWindow( win
).then( function ( win
) {
3333 return manager
.openWindow( win
, data
);
3338 if ( !this.hasWindow( win
) ) {
3339 opening
.reject( new OO
.ui
.Error(
3340 'Cannot open window: window is not attached to manager'
3342 } else if ( this.preparingToOpen
|| this.opening
|| this.opened
) {
3343 opening
.reject( new OO
.ui
.Error(
3344 'Cannot open window: another window is opening or open'
3349 if ( opening
.state() !== 'rejected' ) {
3350 // If a window is currently closing, wait for it to complete
3351 this.preparingToOpen
= $.when( this.closing
);
3352 // Ensure handlers get called after preparingToOpen is set
3353 this.preparingToOpen
.done( function () {
3354 if ( manager
.modal
) {
3355 manager
.toggleGlobalEvents( true );
3356 manager
.toggleAriaIsolation( true );
3358 manager
.currentWindow
= win
;
3359 manager
.opening
= opening
;
3360 manager
.preparingToOpen
= null;
3361 manager
.emit( 'opening', win
, opening
, data
);
3362 setTimeout( function () {
3363 win
.setup( data
).then( function () {
3364 manager
.updateWindowSize( win
);
3365 manager
.opening
.notify( { state
: 'setup' } );
3366 setTimeout( function () {
3367 win
.ready( data
).then( function () {
3368 manager
.opening
.notify( { state
: 'ready' } );
3369 manager
.opening
= null;
3370 manager
.opened
= $.Deferred();
3371 opening
.resolve( manager
.opened
.promise(), data
);
3373 }, manager
.getReadyDelay() );
3375 }, manager
.getSetupDelay() );
3379 return opening
.promise();
3385 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3386 * @param {Object} [data] Window closing data
3387 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3388 * See {@link #event-closing 'closing' event} for more information about closing promises.
3389 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3392 OO
.ui
.WindowManager
.prototype.closeWindow = function ( win
, data
) {
3394 closing
= $.Deferred(),
3397 // Argument handling
3398 if ( typeof win
=== 'string' ) {
3399 win
= this.windows
[ win
];
3400 } else if ( !this.hasWindow( win
) ) {
3406 closing
.reject( new OO
.ui
.Error(
3407 'Cannot close window: window is not attached to manager'
3409 } else if ( win
!== this.currentWindow
) {
3410 closing
.reject( new OO
.ui
.Error(
3411 'Cannot close window: window already closed with different data'
3413 } else if ( this.preparingToClose
|| this.closing
) {
3414 closing
.reject( new OO
.ui
.Error(
3415 'Cannot close window: window already closing with different data'
3420 if ( closing
.state() !== 'rejected' ) {
3421 // If the window is currently opening, close it when it's done
3422 this.preparingToClose
= $.when( this.opening
);
3423 // Ensure handlers get called after preparingToClose is set
3424 this.preparingToClose
.done( function () {
3425 manager
.closing
= closing
;
3426 manager
.preparingToClose
= null;
3427 manager
.emit( 'closing', win
, closing
, data
);
3428 opened
= manager
.opened
;
3429 manager
.opened
= null;
3430 opened
.resolve( closing
.promise(), data
);
3431 setTimeout( function () {
3432 win
.hold( data
).then( function () {
3433 closing
.notify( { state
: 'hold' } );
3434 setTimeout( function () {
3435 win
.teardown( data
).then( function () {
3436 closing
.notify( { state
: 'teardown' } );
3437 if ( manager
.modal
) {
3438 manager
.toggleGlobalEvents( false );
3439 manager
.toggleAriaIsolation( false );
3441 manager
.closing
= null;
3442 manager
.currentWindow
= null;
3443 closing
.resolve( data
);
3445 }, manager
.getTeardownDelay() );
3447 }, manager
.getHoldDelay() );
3451 return closing
.promise();
3455 * Add windows to the window manager.
3457 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3458 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3459 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3461 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3462 * by reference, symbolic name, or explicitly defined symbolic names.
3463 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3464 * explicit nor a statically configured symbolic name.
3466 OO
.ui
.WindowManager
.prototype.addWindows = function ( windows
) {
3467 var i
, len
, win
, name
, list
;
3469 if ( Array
.isArray( windows
) ) {
3470 // Convert to map of windows by looking up symbolic names from static configuration
3472 for ( i
= 0, len
= windows
.length
; i
< len
; i
++ ) {
3473 name
= windows
[ i
].constructor.static.name
;
3474 if ( typeof name
!== 'string' ) {
3475 throw new Error( 'Cannot add window' );
3477 list
[ name
] = windows
[ i
];
3479 } else if ( OO
.isPlainObject( windows
) ) {
3484 for ( name
in list
) {
3486 this.windows
[ name
] = win
.toggle( false );
3487 this.$element
.append( win
.$element
);
3488 win
.setManager( this );
3493 * Remove the specified windows from the windows manager.
3495 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3496 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3497 * longer listens to events, use the #destroy method.
3499 * @param {string[]} names Symbolic names of windows to remove
3500 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3501 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3503 OO
.ui
.WindowManager
.prototype.removeWindows = function ( names
) {
3504 var i
, len
, win
, name
, cleanupWindow
,
3507 cleanup = function ( name
, win
) {
3508 delete manager
.windows
[ name
];
3509 win
.$element
.detach();
3512 for ( i
= 0, len
= names
.length
; i
< len
; i
++ ) {
3514 win
= this.windows
[ name
];
3516 throw new Error( 'Cannot remove window' );
3518 cleanupWindow
= cleanup
.bind( null, name
, win
);
3519 promises
.push( this.closeWindow( name
).then( cleanupWindow
, cleanupWindow
) );
3522 return $.when
.apply( $, promises
);
3526 * Remove all windows from the window manager.
3528 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3529 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3530 * To remove just a subset of windows, use the #removeWindows method.
3532 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3534 OO
.ui
.WindowManager
.prototype.clearWindows = function () {
3535 return this.removeWindows( Object
.keys( this.windows
) );
3539 * Set dialog size. In general, this method should not be called directly.
3541 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3545 OO
.ui
.WindowManager
.prototype.updateWindowSize = function ( win
) {
3546 // Bypass for non-current, and thus invisible, windows
3547 if ( win
!== this.currentWindow
) {
3551 var isFullscreen
= win
.getSize() === 'full';
3553 this.$element
.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen
);
3554 this.$element
.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen
);
3555 win
.setDimensions( win
.getSizeProperties() );
3557 this.emit( 'resize', win
);
3563 * Bind or unbind global events for scrolling.
3566 * @param {boolean} [on] Bind global events
3569 OO
.ui
.WindowManager
.prototype.toggleGlobalEvents = function ( on
) {
3570 on
= on
=== undefined ? !!this.globalEvents
: !!on
;
3572 var scrollWidth
, bodyMargin
,
3573 $body
= $( this.getElementDocument().body
),
3574 // We could have multiple window managers open so only modify
3575 // the body css at the bottom of the stack
3576 stackDepth
= $body
.data( 'windowManagerGlobalEvents' ) || 0 ;
3579 if ( !this.globalEvents
) {
3580 $( this.getElementWindow() ).on( {
3581 // Start listening for top-level window dimension changes
3582 'orientationchange resize': this.onWindowResizeHandler
3584 if ( stackDepth
=== 0 ) {
3585 scrollWidth
= window
.innerWidth
- document
.documentElement
.clientWidth
;
3586 bodyMargin
= parseFloat( $body
.css( 'margin-right' ) ) || 0;
3589 'margin-right': bodyMargin
+ scrollWidth
3593 this.globalEvents
= true;
3595 } else if ( this.globalEvents
) {
3596 $( this.getElementWindow() ).off( {
3597 // Stop listening for top-level window dimension changes
3598 'orientationchange resize': this.onWindowResizeHandler
3601 if ( stackDepth
=== 0 ) {
3607 this.globalEvents
= false;
3609 $body
.data( 'windowManagerGlobalEvents', stackDepth
);
3615 * Toggle screen reader visibility of content other than the window manager.
3618 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3621 OO
.ui
.WindowManager
.prototype.toggleAriaIsolation = function ( isolate
) {
3622 isolate
= isolate
=== undefined ? !this.$ariaHidden
: !!isolate
;
3625 if ( !this.$ariaHidden
) {
3626 // Hide everything other than the window manager from screen readers
3627 this.$ariaHidden
= $( 'body' )
3629 .not( this.$element
.parentsUntil( 'body' ).last() )
3630 .attr( 'aria-hidden', '' );
3632 } else if ( this.$ariaHidden
) {
3633 // Restore screen reader visibility
3634 this.$ariaHidden
.removeAttr( 'aria-hidden' );
3635 this.$ariaHidden
= null;
3642 * Destroy the window manager.
3644 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3645 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3648 OO
.ui
.WindowManager
.prototype.destroy = function () {
3649 this.toggleGlobalEvents( false );
3650 this.toggleAriaIsolation( false );
3651 this.clearWindows();
3652 this.$element
.remove();
3656 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3657 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3658 * appearance and functionality of the error interface.
3660 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3661 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3662 * that initiated the failed process will be disabled.
3664 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3667 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3669 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3674 * @param {string|jQuery} message Description of error
3675 * @param {Object} [config] Configuration options
3676 * @cfg {boolean} [recoverable=true] Error is recoverable.
3677 * By default, errors are recoverable, and users can try the process again.
3678 * @cfg {boolean} [warning=false] Error is a warning.
3679 * If the error is a warning, the error interface will include a
3680 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3681 * is not triggered a second time if the user chooses to continue.
3683 OO
.ui
.Error
= function OoUiError( message
, config
) {
3684 // Allow passing positional parameters inside the config object
3685 if ( OO
.isPlainObject( message
) && config
=== undefined ) {
3687 message
= config
.message
;
3690 // Configuration initialization
3691 config
= config
|| {};
3694 this.message
= message
instanceof jQuery
? message
: String( message
);
3695 this.recoverable
= config
.recoverable
=== undefined || !!config
.recoverable
;
3696 this.warning
= !!config
.warning
;
3701 OO
.initClass( OO
.ui
.Error
);
3706 * Check if the error is recoverable.
3708 * If the error is recoverable, users are able to try the process again.
3710 * @return {boolean} Error is recoverable
3712 OO
.ui
.Error
.prototype.isRecoverable = function () {
3713 return this.recoverable
;
3717 * Check if the error is a warning.
3719 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3721 * @return {boolean} Error is warning
3723 OO
.ui
.Error
.prototype.isWarning = function () {
3724 return this.warning
;
3728 * Get error message as DOM nodes.
3730 * @return {jQuery} Error message in DOM nodes
3732 OO
.ui
.Error
.prototype.getMessage = function () {
3733 return this.message
instanceof jQuery
?
3734 this.message
.clone() :
3735 $( '<div>' ).text( this.message
).contents();
3739 * Get the error message text.
3741 * @return {string} Error message
3743 OO
.ui
.Error
.prototype.getMessageText = function () {
3744 return this.message
instanceof jQuery
? this.message
.text() : this.message
;
3748 * Wraps an HTML snippet for use with configuration values which default
3749 * to strings. This bypasses the default html-escaping done to string
3755 * @param {string} [content] HTML content
3757 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
3759 this.content
= content
;
3764 OO
.initClass( OO
.ui
.HtmlSnippet
);
3771 * @return {string} Unchanged HTML snippet.
3773 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
3774 return this.content
;
3778 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3781 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3782 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3783 * or stop if the promise is rejected.
3784 * - **function**: the process will execute the function. The process will stop if the function returns
3785 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3786 * will wait for that number of milliseconds before proceeding.
3788 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3789 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3790 * its remaining steps will not be performed.
3795 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3796 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3797 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3798 * a number or promise.
3799 * @return {Object} Step object, with `callback` and `context` properties
3801 OO
.ui
.Process = function ( step
, context
) {
3806 if ( step
!== undefined ) {
3807 this.next( step
, context
);
3813 OO
.initClass( OO
.ui
.Process
);
3818 * Start the process.
3820 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3821 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3822 * and any remaining steps are not performed.
3824 OO
.ui
.Process
.prototype.execute = function () {
3825 var i
, len
, promise
;
3828 * Continue execution.
3831 * @param {Array} step A function and the context it should be called in
3832 * @return {Function} Function that continues the process
3834 function proceed( step
) {
3835 return function () {
3836 // Execute step in the correct context
3838 result
= step
.callback
.call( step
.context
);
3840 if ( result
=== false ) {
3841 // Use rejected promise for boolean false results
3842 return $.Deferred().reject( [] ).promise();
3844 if ( typeof result
=== 'number' ) {
3846 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3848 // Use a delayed promise for numbers, expecting them to be in milliseconds
3849 deferred
= $.Deferred();
3850 setTimeout( deferred
.resolve
, result
);
3851 return deferred
.promise();
3853 if ( result
instanceof OO
.ui
.Error
) {
3854 // Use rejected promise for error
3855 return $.Deferred().reject( [ result
] ).promise();
3857 if ( Array
.isArray( result
) && result
.length
&& result
[ 0 ] instanceof OO
.ui
.Error
) {
3858 // Use rejected promise for list of errors
3859 return $.Deferred().reject( result
).promise();
3861 // Duck-type the object to see if it can produce a promise
3862 if ( result
&& $.isFunction( result
.promise
) ) {
3863 // Use a promise generated from the result
3864 return result
.promise();
3866 // Use resolved promise for other results
3867 return $.Deferred().resolve().promise();
3871 if ( this.steps
.length
) {
3872 // Generate a chain reaction of promises
3873 promise
= proceed( this.steps
[ 0 ] )();
3874 for ( i
= 1, len
= this.steps
.length
; i
< len
; i
++ ) {
3875 promise
= promise
.then( proceed( this.steps
[ i
] ) );
3878 promise
= $.Deferred().resolve().promise();
3885 * Create a process step.
3888 * @param {number|jQuery.Promise|Function} step
3890 * - Number of milliseconds to wait before proceeding
3891 * - Promise that must be resolved before proceeding
3892 * - Function to execute
3893 * - If the function returns a boolean false the process will stop
3894 * - If the function returns a promise, the process will continue to the next
3895 * step when the promise is resolved or stop if the promise is rejected
3896 * - If the function returns a number, the process will wait for that number of
3897 * milliseconds before proceeding
3898 * @param {Object} [context=null] Execution context of the function. The context is
3899 * ignored if the step is a number or promise.
3900 * @return {Object} Step object, with `callback` and `context` properties
3902 OO
.ui
.Process
.prototype.createStep = function ( step
, context
) {
3903 if ( typeof step
=== 'number' || $.isFunction( step
.promise
) ) {
3905 callback: function () {
3911 if ( $.isFunction( step
) ) {
3917 throw new Error( 'Cannot create process step: number, promise or function expected' );
3921 * Add step to the beginning of the process.
3923 * @inheritdoc #createStep
3924 * @return {OO.ui.Process} this
3927 OO
.ui
.Process
.prototype.first = function ( step
, context
) {
3928 this.steps
.unshift( this.createStep( step
, context
) );
3933 * Add step to the end of the process.
3935 * @inheritdoc #createStep
3936 * @return {OO.ui.Process} this
3939 OO
.ui
.Process
.prototype.next = function ( step
, context
) {
3940 this.steps
.push( this.createStep( step
, context
) );
3945 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
3946 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
3947 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
3949 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
3951 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
3954 * @extends OO.Factory
3957 OO
.ui
.ToolFactory
= function OoUiToolFactory() {
3958 // Parent constructor
3959 OO
.ui
.ToolFactory
.parent
.call( this );
3964 OO
.inheritClass( OO
.ui
.ToolFactory
, OO
.Factory
);
3969 * Get tools from the factory
3971 * @param {Array} include Included tools
3972 * @param {Array} exclude Excluded tools
3973 * @param {Array} promote Promoted tools
3974 * @param {Array} demote Demoted tools
3975 * @return {string[]} List of tools
3977 OO
.ui
.ToolFactory
.prototype.getTools = function ( include
, exclude
, promote
, demote
) {
3978 var i
, len
, included
, promoted
, demoted
,
3982 // Collect included and not excluded tools
3983 included
= OO
.simpleArrayDifference( this.extract( include
), this.extract( exclude
) );
3986 promoted
= this.extract( promote
, used
);
3987 demoted
= this.extract( demote
, used
);
3990 for ( i
= 0, len
= included
.length
; i
< len
; i
++ ) {
3991 if ( !used
[ included
[ i
] ] ) {
3992 auto
.push( included
[ i
] );
3996 return promoted
.concat( auto
).concat( demoted
);
4000 * Get a flat list of names from a list of names or groups.
4002 * Tools can be specified in the following ways:
4004 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
4005 * - All tools in a group: `{ group: 'group-name' }`
4006 * - All tools: `'*'`
4009 * @param {Array|string} collection List of tools
4010 * @param {Object} [used] Object with names that should be skipped as properties; extracted
4011 * names will be added as properties
4012 * @return {string[]} List of extracted names
4014 OO
.ui
.ToolFactory
.prototype.extract = function ( collection
, used
) {
4015 var i
, len
, item
, name
, tool
,
4018 if ( collection
=== '*' ) {
4019 for ( name
in this.registry
) {
4020 tool
= this.registry
[ name
];
4022 // Only add tools by group name when auto-add is enabled
4023 tool
.static.autoAddToCatchall
&&
4024 // Exclude already used tools
4025 ( !used
|| !used
[ name
] )
4029 used
[ name
] = true;
4033 } else if ( Array
.isArray( collection
) ) {
4034 for ( i
= 0, len
= collection
.length
; i
< len
; i
++ ) {
4035 item
= collection
[ i
];
4036 // Allow plain strings as shorthand for named tools
4037 if ( typeof item
=== 'string' ) {
4038 item
= { name
: item
};
4040 if ( OO
.isPlainObject( item
) ) {
4042 for ( name
in this.registry
) {
4043 tool
= this.registry
[ name
];
4045 // Include tools with matching group
4046 tool
.static.group
=== item
.group
&&
4047 // Only add tools by group name when auto-add is enabled
4048 tool
.static.autoAddToGroup
&&
4049 // Exclude already used tools
4050 ( !used
|| !used
[ name
] )
4054 used
[ name
] = true;
4058 // Include tools with matching name and exclude already used tools
4059 } else if ( item
.name
&& ( !used
|| !used
[ item
.name
] ) ) {
4060 names
.push( item
.name
);
4062 used
[ item
.name
] = true;
4072 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
4073 * specify a symbolic name and be registered with the factory. The following classes are registered by
4076 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
4077 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
4078 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
4080 * See {@link OO.ui.Toolbar toolbars} for an example.
4082 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4084 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4086 * @extends OO.Factory
4089 OO
.ui
.ToolGroupFactory
= function OoUiToolGroupFactory() {
4090 // Parent constructor
4091 OO
.Factory
.call( this );
4094 defaultClasses
= this.constructor.static.getDefaultClasses();
4096 // Register default toolgroups
4097 for ( i
= 0, l
= defaultClasses
.length
; i
< l
; i
++ ) {
4098 this.register( defaultClasses
[ i
] );
4104 OO
.inheritClass( OO
.ui
.ToolGroupFactory
, OO
.Factory
);
4106 /* Static Methods */
4109 * Get a default set of classes to be registered on construction.
4111 * @return {Function[]} Default classes
4113 OO
.ui
.ToolGroupFactory
.static.getDefaultClasses = function () {
4116 OO
.ui
.ListToolGroup
,
4128 * @param {Object} [config] Configuration options
4130 OO
.ui
.Theme
= function OoUiTheme( config
) {
4131 // Configuration initialization
4132 config
= config
|| {};
4137 OO
.initClass( OO
.ui
.Theme
);
4142 * Get a list of classes to be applied to a widget.
4144 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4145 * otherwise state transitions will not work properly.
4147 * @param {OO.ui.Element} element Element for which to get classes
4148 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4150 OO
.ui
.Theme
.prototype.getElementClasses = function ( /* element */ ) {
4151 return { on
: [], off
: [] };
4155 * Update CSS classes provided by the theme.
4157 * For elements with theme logic hooks, this should be called any time there's a state change.
4159 * @param {OO.ui.Element} element Element for which to update classes
4160 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4162 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
4163 var classes
= this.getElementClasses( element
);
4166 .removeClass( classes
.off
.join( ' ' ) )
4167 .addClass( classes
.on
.join( ' ' ) );
4171 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4172 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4173 * order in which users will navigate through the focusable elements via the "tab" key.
4176 * // TabIndexedElement is mixed into the ButtonWidget class
4177 * // to provide a tabIndex property.
4178 * var button1 = new OO.ui.ButtonWidget( {
4182 * var button2 = new OO.ui.ButtonWidget( {
4186 * var button3 = new OO.ui.ButtonWidget( {
4190 * var button4 = new OO.ui.ButtonWidget( {
4194 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4200 * @param {Object} [config] Configuration options
4201 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4202 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4203 * functionality will be applied to it instead.
4204 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4205 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4206 * to remove the element from the tab-navigation flow.
4208 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
4209 // Configuration initialization
4210 config
= $.extend( { tabIndex
: 0 }, config
);
4213 this.$tabIndexed
= null;
4214 this.tabIndex
= null;
4217 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
4220 this.setTabIndex( config
.tabIndex
);
4221 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
4226 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
4231 * Set the element that should use the tabindex functionality.
4233 * This method is used to retarget a tabindex mixin so that its functionality applies
4234 * to the specified element. If an element is currently using the functionality, the mixin’s
4235 * effect on that element is removed before the new element is set up.
4237 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4240 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
4241 var tabIndex
= this.tabIndex
;
4242 // Remove attributes from old $tabIndexed
4243 this.setTabIndex( null );
4244 // Force update of new $tabIndexed
4245 this.$tabIndexed
= $tabIndexed
;
4246 this.tabIndex
= tabIndex
;
4247 return this.updateTabIndex();
4251 * Set the value of the tabindex.
4253 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4256 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
4257 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
4259 if ( this.tabIndex
!== tabIndex
) {
4260 this.tabIndex
= tabIndex
;
4261 this.updateTabIndex();
4268 * Update the `tabindex` attribute, in case of changes to tab index or
4274 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
4275 if ( this.$tabIndexed
) {
4276 if ( this.tabIndex
!== null ) {
4277 // Do not index over disabled elements
4278 this.$tabIndexed
.attr( {
4279 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
4280 // ChromeVox and NVDA do not seem to inherit this from parent elements
4281 'aria-disabled': this.isDisabled().toString()
4284 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
4291 * Handle disable events.
4294 * @param {boolean} disabled Element is disabled
4296 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
4297 this.updateTabIndex();
4301 * Get the value of the tabindex.
4303 * @return {number|null} Tabindex value
4305 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
4306 return this.tabIndex
;
4310 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4311 * interface element that can be configured with access keys for accessibility.
4312 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4314 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4319 * @param {Object} [config] Configuration options
4320 * @cfg {jQuery} [$button] The button element created by the class.
4321 * If this configuration is omitted, the button element will use a generated `<a>`.
4322 * @cfg {boolean} [framed=true] Render the button with a frame
4323 * @cfg {string} [accessKey] Button's access key
4325 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
4326 // Configuration initialization
4327 config
= config
|| {};
4330 this.$button
= null;
4332 this.accessKey
= null;
4333 this.active
= false;
4334 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
4335 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4336 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
4337 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
4338 this.onClickHandler
= this.onClick
.bind( this );
4339 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
4342 this.$element
.addClass( 'oo-ui-buttonElement' );
4343 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
4344 this.setAccessKey( config
.accessKey
);
4345 this.setButtonElement( config
.$button
|| $( '<a>' ) );
4350 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
4352 /* Static Properties */
4355 * Cancel mouse down events.
4357 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4358 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4359 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4364 * @property {boolean}
4366 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
4371 * A 'click' event is emitted when the button element is clicked.
4379 * Set the button element.
4381 * This method is used to retarget a button mixin so that its functionality applies to
4382 * the specified button element instead of the one created by the class. If a button element
4383 * is already set, the method will remove the mixin’s effect on that element.
4385 * @param {jQuery} $button Element to use as button
4387 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
4388 if ( this.$button
) {
4390 .removeClass( 'oo-ui-buttonElement-button' )
4391 .removeAttr( 'role accesskey' )
4393 mousedown
: this.onMouseDownHandler
,
4394 keydown
: this.onKeyDownHandler
,
4395 click
: this.onClickHandler
,
4396 keypress
: this.onKeyPressHandler
4400 this.$button
= $button
4401 .addClass( 'oo-ui-buttonElement-button' )
4402 .attr( { role
: 'button', accesskey
: this.accessKey
} )
4404 mousedown
: this.onMouseDownHandler
,
4405 keydown
: this.onKeyDownHandler
,
4406 click
: this.onClickHandler
,
4407 keypress
: this.onKeyPressHandler
4412 * Handles mouse down events.
4415 * @param {jQuery.Event} e Mouse down event
4417 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
4418 if ( this.isDisabled() || e
.which
!== 1 ) {
4421 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4422 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4423 // reliably remove the pressed class
4424 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler
);
4425 // Prevent change of focus unless specifically configured otherwise
4426 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
4432 * Handles mouse up events.
4435 * @param {jQuery.Event} e Mouse up event
4437 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
4438 if ( this.isDisabled() || e
.which
!== 1 ) {
4441 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4442 // Stop listening for mouseup, since we only needed this once
4443 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler
);
4447 * Handles mouse click events.
4450 * @param {jQuery.Event} e Mouse click event
4453 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
4454 if ( !this.isDisabled() && e
.which
=== 1 ) {
4455 if ( this.emit( 'click' ) ) {
4462 * Handles key down events.
4465 * @param {jQuery.Event} e Key down event
4467 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
4468 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4471 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4472 // Run the keyup handler no matter where the key is when the button is let go, so we can
4473 // reliably remove the pressed class
4474 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler
);
4478 * Handles key up events.
4481 * @param {jQuery.Event} e Key up event
4483 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
4484 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4487 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4488 // Stop listening for keyup, since we only needed this once
4489 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler
);
4493 * Handles key press events.
4496 * @param {jQuery.Event} e Key press event
4499 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
4500 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
4501 if ( this.emit( 'click' ) ) {
4508 * Check if button has a frame.
4510 * @return {boolean} Button is framed
4512 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
4517 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4519 * @param {boolean} [framed] Make button framed, omit to toggle
4522 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
4523 framed
= framed
=== undefined ? !this.framed
: !!framed
;
4524 if ( framed
!== this.framed
) {
4525 this.framed
= framed
;
4527 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
4528 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
4529 this.updateThemeClasses();
4536 * Set the button's access key.
4538 * @param {string} accessKey Button's access key, use empty string to remove
4541 OO
.ui
.mixin
.ButtonElement
.prototype.setAccessKey = function ( accessKey
) {
4542 accessKey
= typeof accessKey
=== 'string' && accessKey
.length
? accessKey
: null;
4544 if ( this.accessKey
!== accessKey
) {
4545 if ( this.$button
) {
4546 if ( accessKey
!== null ) {
4547 this.$button
.attr( 'accesskey', accessKey
);
4549 this.$button
.removeAttr( 'accesskey' );
4552 this.accessKey
= accessKey
;
4559 * Set the button to its 'active' state.
4561 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4562 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4563 * for other button types.
4565 * @param {boolean} [value] Make button active
4568 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
4569 this.$element
.toggleClass( 'oo-ui-buttonElement-active', !!value
);
4574 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4575 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4576 * items from the group is done through the interface the class provides.
4577 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4579 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4585 * @param {Object} [config] Configuration options
4586 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4587 * is omitted, the group element will use a generated `<div>`.
4589 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
4590 // Configuration initialization
4591 config
= config
|| {};
4596 this.aggregateItemEvents
= {};
4599 this.setGroupElement( config
.$group
|| $( '<div>' ) );
4605 * Set the group element.
4607 * If an element is already set, items will be moved to the new element.
4609 * @param {jQuery} $group Element to use as group
4611 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
4614 this.$group
= $group
;
4615 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4616 this.$group
.append( this.items
[ i
].$element
);
4621 * Check if a group contains no items.
4623 * @return {boolean} Group is empty
4625 OO
.ui
.mixin
.GroupElement
.prototype.isEmpty = function () {
4626 return !this.items
.length
;
4630 * Get all items in the group.
4632 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4633 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4636 * @return {OO.ui.Element[]} An array of items.
4638 OO
.ui
.mixin
.GroupElement
.prototype.getItems = function () {
4639 return this.items
.slice( 0 );
4643 * Get an item by its data.
4645 * Only the first item with matching data will be returned. To return all matching items,
4646 * use the #getItemsFromData method.
4648 * @param {Object} data Item data to search for
4649 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4651 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
4653 hash
= OO
.getHash( data
);
4655 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4656 item
= this.items
[ i
];
4657 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4666 * Get items by their data.
4668 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4670 * @param {Object} data Item data to search for
4671 * @return {OO.ui.Element[]} Items with equivalent data
4673 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
4675 hash
= OO
.getHash( data
),
4678 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4679 item
= this.items
[ i
];
4680 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4689 * Aggregate the events emitted by the group.
4691 * When events are aggregated, the group will listen to all contained items for the event,
4692 * and then emit the event under a new name. The new event will contain an additional leading
4693 * parameter containing the item that emitted the original event. Other arguments emitted from
4694 * the original event are passed through.
4696 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4697 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4698 * A `null` value will remove aggregated events.
4700 * @throws {Error} An error is thrown if aggregation already exists.
4702 OO
.ui
.mixin
.GroupElement
.prototype.aggregate = function ( events
) {
4703 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
4705 for ( itemEvent
in events
) {
4706 groupEvent
= events
[ itemEvent
];
4708 // Remove existing aggregated event
4709 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4710 // Don't allow duplicate aggregations
4712 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
4714 // Remove event aggregation from existing items
4715 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4716 item
= this.items
[ i
];
4717 if ( item
.connect
&& item
.disconnect
) {
4719 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[itemEvent
], item
];
4720 item
.disconnect( this, remove
);
4723 // Prevent future items from aggregating event
4724 delete this.aggregateItemEvents
[ itemEvent
];
4727 // Add new aggregate event
4729 // Make future items aggregate event
4730 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
4731 // Add event aggregation to existing items
4732 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4733 item
= this.items
[ i
];
4734 if ( item
.connect
&& item
.disconnect
) {
4736 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
4737 item
.connect( this, add
);
4745 * Add items to the group.
4747 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4748 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4750 * @param {OO.ui.Element[]} items An array of items to add to the group
4751 * @param {number} [index] Index of the insertion point
4754 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
4755 var i
, len
, item
, event
, events
, currentIndex
,
4758 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4761 // Check if item exists then remove it first, effectively "moving" it
4762 currentIndex
= $.inArray( item
, this.items
);
4763 if ( currentIndex
>= 0 ) {
4764 this.removeItems( [ item
] );
4765 // Adjust index to compensate for removal
4766 if ( currentIndex
< index
) {
4771 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
4773 for ( event
in this.aggregateItemEvents
) {
4774 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
4776 item
.connect( this, events
);
4778 item
.setElementGroup( this );
4779 itemElements
.push( item
.$element
.get( 0 ) );
4782 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
4783 this.$group
.append( itemElements
);
4784 this.items
.push
.apply( this.items
, items
);
4785 } else if ( index
=== 0 ) {
4786 this.$group
.prepend( itemElements
);
4787 this.items
.unshift
.apply( this.items
, items
);
4789 this.items
[ index
].$element
.before( itemElements
);
4790 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
4797 * Remove the specified items from a group.
4799 * Removed items are detached (not removed) from the DOM so that they may be reused.
4800 * To remove all items from a group, you may wish to use the #clearItems method instead.
4802 * @param {OO.ui.Element[]} items An array of items to remove
4805 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
4806 var i
, len
, item
, index
, remove
, itemEvent
;
4808 // Remove specific items
4809 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4811 index
= $.inArray( item
, this.items
);
4812 if ( index
!== -1 ) {
4814 item
.connect
&& item
.disconnect
&&
4815 !$.isEmptyObject( this.aggregateItemEvents
)
4818 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4819 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4821 item
.disconnect( this, remove
);
4823 item
.setElementGroup( null );
4824 this.items
.splice( index
, 1 );
4825 item
.$element
.detach();
4833 * Clear all items from the group.
4835 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4836 * To remove only a subset of items from a group, use the #removeItems method.
4840 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
4841 var i
, len
, item
, remove
, itemEvent
;
4844 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4845 item
= this.items
[ i
];
4847 item
.connect
&& item
.disconnect
&&
4848 !$.isEmptyObject( this.aggregateItemEvents
)
4851 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4852 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4854 item
.disconnect( this, remove
);
4856 item
.setElementGroup( null );
4857 item
.$element
.detach();
4865 * DraggableElement is a mixin class used to create elements that can be clicked
4866 * and dragged by a mouse to a new position within a group. This class must be used
4867 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
4868 * the draggable elements.
4875 OO
.ui
.mixin
.DraggableElement
= function OoUiMixinDraggableElement() {
4879 // Initialize and events
4881 .attr( 'draggable', true )
4882 .addClass( 'oo-ui-draggableElement' )
4884 dragstart
: this.onDragStart
.bind( this ),
4885 dragover
: this.onDragOver
.bind( this ),
4886 dragend
: this.onDragEnd
.bind( this ),
4887 drop
: this.onDrop
.bind( this )
4891 OO
.initClass( OO
.ui
.mixin
.DraggableElement
);
4898 * A dragstart event is emitted when the user clicks and begins dragging an item.
4899 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4904 * A dragend event is emitted when the user drags an item and releases the mouse,
4905 * thus terminating the drag operation.
4910 * A drop event is emitted when the user drags an item and then releases the mouse button
4911 * over a valid target.
4914 /* Static Properties */
4917 * @inheritdoc OO.ui.mixin.ButtonElement
4919 OO
.ui
.mixin
.DraggableElement
.static.cancelButtonMouseDownEvents
= false;
4924 * Respond to dragstart event.
4927 * @param {jQuery.Event} event jQuery event
4930 OO
.ui
.mixin
.DraggableElement
.prototype.onDragStart = function ( e
) {
4931 var dataTransfer
= e
.originalEvent
.dataTransfer
;
4932 // Define drop effect
4933 dataTransfer
.dropEffect
= 'none';
4934 dataTransfer
.effectAllowed
= 'move';
4935 // We must set up a dataTransfer data property or Firefox seems to
4936 // ignore the fact the element is draggable.
4938 dataTransfer
.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4940 // The above is only for firefox. No need to set a catch clause
4941 // if it fails, move on.
4943 // Add dragging class
4944 this.$element
.addClass( 'oo-ui-draggableElement-dragging' );
4946 this.emit( 'dragstart', this );
4951 * Respond to dragend event.
4956 OO
.ui
.mixin
.DraggableElement
.prototype.onDragEnd = function () {
4957 this.$element
.removeClass( 'oo-ui-draggableElement-dragging' );
4958 this.emit( 'dragend' );
4962 * Handle drop event.
4965 * @param {jQuery.Event} event jQuery event
4968 OO
.ui
.mixin
.DraggableElement
.prototype.onDrop = function ( e
) {
4970 this.emit( 'drop', e
);
4974 * In order for drag/drop to work, the dragover event must
4975 * return false and stop propogation.
4979 OO
.ui
.mixin
.DraggableElement
.prototype.onDragOver = function ( e
) {
4985 * Store it in the DOM so we can access from the widget drag event
4988 * @param {number} Item index
4990 OO
.ui
.mixin
.DraggableElement
.prototype.setIndex = function ( index
) {
4991 if ( this.index
!== index
) {
4993 this.$element
.data( 'index', index
);
5001 * @return {number} Item index
5003 OO
.ui
.mixin
.DraggableElement
.prototype.getIndex = function () {
5008 * DraggableGroupElement is a mixin class used to create a group element to
5009 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
5010 * The class is used with OO.ui.mixin.DraggableElement.
5014 * @mixins OO.ui.mixin.GroupElement
5017 * @param {Object} [config] Configuration options
5018 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
5019 * should match the layout of the items. Items displayed in a single row
5020 * or in several rows should use horizontal orientation. The vertical orientation should only be
5021 * used when the items are displayed in a single column. Defaults to 'vertical'
5023 OO
.ui
.mixin
.DraggableGroupElement
= function OoUiMixinDraggableGroupElement( config
) {
5024 // Configuration initialization
5025 config
= config
|| {};
5027 // Parent constructor
5028 OO
.ui
.mixin
.GroupElement
.call( this, config
);
5031 this.orientation
= config
.orientation
|| 'vertical';
5032 this.dragItem
= null;
5033 this.itemDragOver
= null;
5035 this.sideInsertion
= '';
5039 dragstart
: 'itemDragStart',
5040 dragend
: 'itemDragEnd',
5043 this.connect( this, {
5044 itemDragStart
: 'onItemDragStart',
5045 itemDrop
: 'onItemDrop',
5046 itemDragEnd
: 'onItemDragEnd'
5049 dragover
: $.proxy( this.onDragOver
, this ),
5050 dragleave
: $.proxy( this.onDragLeave
, this )
5054 if ( Array
.isArray( config
.items
) ) {
5055 this.addItems( config
.items
);
5057 this.$placeholder
= $( '<div>' )
5058 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
5060 .addClass( 'oo-ui-draggableGroupElement' )
5061 .append( this.$status
)
5062 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation
=== 'horizontal' )
5063 .prepend( this.$placeholder
);
5067 OO
.mixinClass( OO
.ui
.mixin
.DraggableGroupElement
, OO
.ui
.mixin
.GroupElement
);
5072 * A 'reorder' event is emitted when the order of items in the group changes.
5075 * @param {OO.ui.mixin.DraggableElement} item Reordered item
5076 * @param {number} [newIndex] New index for the item
5082 * Respond to item drag start event
5085 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5087 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDragStart = function ( item
) {
5090 // Map the index of each object
5091 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5092 this.items
[ i
].setIndex( i
);
5095 if ( this.orientation
=== 'horizontal' ) {
5096 // Set the height of the indicator
5097 this.$placeholder
.css( {
5098 height
: item
.$element
.outerHeight(),
5102 // Set the width of the indicator
5103 this.$placeholder
.css( {
5105 width
: item
.$element
.outerWidth()
5108 this.setDragItem( item
);
5112 * Respond to item drag end event
5116 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDragEnd = function () {
5117 this.unsetDragItem();
5122 * Handle drop event and switch the order of the items accordingly
5125 * @param {OO.ui.mixin.DraggableElement} item Dropped item
5128 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDrop = function ( item
) {
5129 var toIndex
= item
.getIndex();
5130 // Check if the dropped item is from the current group
5131 // TODO: Figure out a way to configure a list of legally droppable
5132 // elements even if they are not yet in the list
5133 if ( this.getDragItem() ) {
5134 // If the insertion point is 'after', the insertion index
5135 // is shifted to the right (or to the left in RTL, hence 'after')
5136 if ( this.sideInsertion
=== 'after' ) {
5139 // Emit change event
5140 this.emit( 'reorder', this.getDragItem(), toIndex
);
5142 this.unsetDragItem();
5143 // Return false to prevent propogation
5148 * Handle dragleave event.
5152 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onDragLeave = function () {
5153 // This means the item was dragged outside the widget
5156 .addClass( 'oo-ui-element-hidden' );
5160 * Respond to dragover event
5163 * @param {jQuery.Event} event Event details
5165 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onDragOver = function ( e
) {
5166 var dragOverObj
, $optionWidget
, itemOffset
, itemMidpoint
, itemBoundingRect
,
5167 itemSize
, cssOutput
, dragPosition
, itemIndex
, itemPosition
,
5168 clientX
= e
.originalEvent
.clientX
,
5169 clientY
= e
.originalEvent
.clientY
;
5171 // Get the OptionWidget item we are dragging over
5172 dragOverObj
= this.getElementDocument().elementFromPoint( clientX
, clientY
);
5173 $optionWidget
= $( dragOverObj
).closest( '.oo-ui-draggableElement' );
5174 if ( $optionWidget
[ 0 ] ) {
5175 itemOffset
= $optionWidget
.offset();
5176 itemBoundingRect
= $optionWidget
[ 0 ].getBoundingClientRect();
5177 itemPosition
= $optionWidget
.position();
5178 itemIndex
= $optionWidget
.data( 'index' );
5183 this.isDragging() &&
5184 itemIndex
!== this.getDragItem().getIndex()
5186 if ( this.orientation
=== 'horizontal' ) {
5187 // Calculate where the mouse is relative to the item width
5188 itemSize
= itemBoundingRect
.width
;
5189 itemMidpoint
= itemBoundingRect
.left
+ itemSize
/ 2;
5190 dragPosition
= clientX
;
5191 // Which side of the item we hover over will dictate
5192 // where the placeholder will appear, on the left or
5195 left
: dragPosition
< itemMidpoint
? itemPosition
.left
: itemPosition
.left
+ itemSize
,
5196 top
: itemPosition
.top
5199 // Calculate where the mouse is relative to the item height
5200 itemSize
= itemBoundingRect
.height
;
5201 itemMidpoint
= itemBoundingRect
.top
+ itemSize
/ 2;
5202 dragPosition
= clientY
;
5203 // Which side of the item we hover over will dictate
5204 // where the placeholder will appear, on the top or
5207 top
: dragPosition
< itemMidpoint
? itemPosition
.top
: itemPosition
.top
+ itemSize
,
5208 left
: itemPosition
.left
5211 // Store whether we are before or after an item to rearrange
5212 // For horizontal layout, we need to account for RTL, as this is flipped
5213 if ( this.orientation
=== 'horizontal' && this.$element
.css( 'direction' ) === 'rtl' ) {
5214 this.sideInsertion
= dragPosition
< itemMidpoint
? 'after' : 'before';
5216 this.sideInsertion
= dragPosition
< itemMidpoint
? 'before' : 'after';
5218 // Add drop indicator between objects
5221 .removeClass( 'oo-ui-element-hidden' );
5223 // This means the item was dragged outside the widget
5226 .addClass( 'oo-ui-element-hidden' );
5233 * Set a dragged item
5235 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5237 OO
.ui
.mixin
.DraggableGroupElement
.prototype.setDragItem = function ( item
) {
5238 this.dragItem
= item
;
5242 * Unset the current dragged item
5244 OO
.ui
.mixin
.DraggableGroupElement
.prototype.unsetDragItem = function () {
5245 this.dragItem
= null;
5246 this.itemDragOver
= null;
5247 this.$placeholder
.addClass( 'oo-ui-element-hidden' );
5248 this.sideInsertion
= '';
5252 * Get the item that is currently being dragged.
5254 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5256 OO
.ui
.mixin
.DraggableGroupElement
.prototype.getDragItem = function () {
5257 return this.dragItem
;
5261 * Check if an item in the group is currently being dragged.
5263 * @return {Boolean} Item is being dragged
5265 OO
.ui
.mixin
.DraggableGroupElement
.prototype.isDragging = function () {
5266 return this.getDragItem() !== null;
5270 * IconElement is often mixed into other classes to generate an icon.
5271 * Icons are graphics, about the size of normal text. They are used to aid the user
5272 * in locating a control or to convey information in a space-efficient way. See the
5273 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5274 * included in the library.
5276 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5282 * @param {Object} [config] Configuration options
5283 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5284 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5285 * the icon element be set to an existing icon instead of the one generated by this class, set a
5286 * value using a jQuery selection. For example:
5288 * // Use a <div> tag instead of a <span>
5290 * // Use an existing icon element instead of the one generated by the class
5291 * $icon: this.$element
5292 * // Use an icon element from a child widget
5293 * $icon: this.childwidget.$element
5294 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5295 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5296 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5297 * by the user's language.
5299 * Example of an i18n map:
5301 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5302 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5303 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5304 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5305 * text. The icon title is displayed when users move the mouse over the icon.
5307 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
5308 // Configuration initialization
5309 config
= config
|| {};
5314 this.iconTitle
= null;
5317 this.setIcon( config
.icon
|| this.constructor.static.icon
);
5318 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
5319 this.setIconElement( config
.$icon
|| $( '<span>' ) );
5324 OO
.initClass( OO
.ui
.mixin
.IconElement
);
5326 /* Static Properties */
5329 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5330 * for i18n purposes and contains a `default` icon name and additional names keyed by
5331 * language code. The `default` name is used when no icon is keyed by the user's language.
5333 * Example of an i18n map:
5335 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5337 * Note: the static property will be overridden if the #icon configuration is used.
5341 * @property {Object|string}
5343 OO
.ui
.mixin
.IconElement
.static.icon
= null;
5346 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5347 * function that returns title text, or `null` for no title.
5349 * The static property will be overridden if the #iconTitle configuration is used.
5353 * @property {string|Function|null}
5355 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
5360 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5361 * applies to the specified icon element instead of the one created by the class. If an icon
5362 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5363 * and mixin methods will no longer affect the element.
5365 * @param {jQuery} $icon Element to use as icon
5367 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
5370 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
5371 .removeAttr( 'title' );
5375 .addClass( 'oo-ui-iconElement-icon' )
5376 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
5377 if ( this.iconTitle
!== null ) {
5378 this.$icon
.attr( 'title', this.iconTitle
);
5383 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5384 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5387 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5388 * by language code, or `null` to remove the icon.
5391 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
5392 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
5393 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
5395 if ( this.icon
!== icon
) {
5397 if ( this.icon
!== null ) {
5398 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
5400 if ( icon
!== null ) {
5401 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
5407 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
5408 this.updateThemeClasses();
5414 * Set the icon title. Use `null` to remove the title.
5416 * @param {string|Function|null} iconTitle A text string used as the icon title,
5417 * a function that returns title text, or `null` for no title.
5420 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
5421 iconTitle
= typeof iconTitle
=== 'function' ||
5422 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
5423 OO
.ui
.resolveMsg( iconTitle
) : null;
5425 if ( this.iconTitle
!== iconTitle
) {
5426 this.iconTitle
= iconTitle
;
5428 if ( this.iconTitle
!== null ) {
5429 this.$icon
.attr( 'title', iconTitle
);
5431 this.$icon
.removeAttr( 'title' );
5440 * Get the symbolic name of the icon.
5442 * @return {string} Icon name
5444 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
5449 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5451 * @return {string} Icon title text
5453 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
5454 return this.iconTitle
;
5458 * IndicatorElement is often mixed into other classes to generate an indicator.
5459 * Indicators are small graphics that are generally used in two ways:
5461 * - To draw attention to the status of an item. For example, an indicator might be
5462 * used to show that an item in a list has errors that need to be resolved.
5463 * - To clarify the function of a control that acts in an exceptional way (a button
5464 * that opens a menu instead of performing an action directly, for example).
5466 * For a list of indicators included in the library, please see the
5467 * [OOjs UI documentation on MediaWiki] [1].
5469 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5475 * @param {Object} [config] Configuration options
5476 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5477 * configuration is omitted, the indicator element will use a generated `<span>`.
5478 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5479 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5481 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5482 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5483 * or a function that returns title text. The indicator title is displayed when users move
5484 * the mouse over the indicator.
5486 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
5487 // Configuration initialization
5488 config
= config
|| {};
5491 this.$indicator
= null;
5492 this.indicator
= null;
5493 this.indicatorTitle
= null;
5496 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
5497 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
5498 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
5503 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
5505 /* Static Properties */
5508 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5509 * The static property will be overridden if the #indicator configuration is used.
5513 * @property {string|null}
5515 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
5518 * A text string used as the indicator title, a function that returns title text, or `null`
5519 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5523 * @property {string|Function|null}
5525 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
5530 * Set the indicator element.
5532 * If an element is already set, it will be cleaned up before setting up the new element.
5534 * @param {jQuery} $indicator Element to use as indicator
5536 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
5537 if ( this.$indicator
) {
5539 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
5540 .removeAttr( 'title' );
5543 this.$indicator
= $indicator
5544 .addClass( 'oo-ui-indicatorElement-indicator' )
5545 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
5546 if ( this.indicatorTitle
!== null ) {
5547 this.$indicator
.attr( 'title', this.indicatorTitle
);
5552 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5554 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5557 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
5558 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
5560 if ( this.indicator
!== indicator
) {
5561 if ( this.$indicator
) {
5562 if ( this.indicator
!== null ) {
5563 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
5565 if ( indicator
!== null ) {
5566 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
5569 this.indicator
= indicator
;
5572 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
5573 this.updateThemeClasses();
5579 * Set the indicator title.
5581 * The title is displayed when a user moves the mouse over the indicator.
5583 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5584 * `null` for no indicator title
5587 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
5588 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
5589 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
5590 OO
.ui
.resolveMsg( indicatorTitle
) : null;
5592 if ( this.indicatorTitle
!== indicatorTitle
) {
5593 this.indicatorTitle
= indicatorTitle
;
5594 if ( this.$indicator
) {
5595 if ( this.indicatorTitle
!== null ) {
5596 this.$indicator
.attr( 'title', indicatorTitle
);
5598 this.$indicator
.removeAttr( 'title' );
5607 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5609 * @return {string} Symbolic name of indicator
5611 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
5612 return this.indicator
;
5616 * Get the indicator title.
5618 * The title is displayed when a user moves the mouse over the indicator.
5620 * @return {string} Indicator title text
5622 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
5623 return this.indicatorTitle
;
5627 * LabelElement is often mixed into other classes to generate a label, which
5628 * helps identify the function of an interface element.
5629 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5631 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5637 * @param {Object} [config] Configuration options
5638 * @cfg {jQuery} [$label] The label element created by the class. If this
5639 * configuration is omitted, the label element will use a generated `<span>`.
5640 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5641 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5642 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5643 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5644 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5645 * The label will be truncated to fit if necessary.
5647 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
5648 // Configuration initialization
5649 config
= config
|| {};
5654 this.autoFitLabel
= config
.autoFitLabel
=== undefined || !!config
.autoFitLabel
;
5657 this.setLabel( config
.label
|| this.constructor.static.label
);
5658 this.setLabelElement( config
.$label
|| $( '<span>' ) );
5663 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
5668 * @event labelChange
5669 * @param {string} value
5672 /* Static Properties */
5675 * The label text. The label can be specified as a plaintext string, a function that will
5676 * produce a string in the future, or `null` for no label. The static value will
5677 * be overridden if a label is specified with the #label config option.
5681 * @property {string|Function|null}
5683 OO
.ui
.mixin
.LabelElement
.static.label
= null;
5688 * Set the label element.
5690 * If an element is already set, it will be cleaned up before setting up the new element.
5692 * @param {jQuery} $label Element to use as label
5694 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
5695 if ( this.$label
) {
5696 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
5699 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
5700 this.setLabelContent( this.label
);
5706 * An empty string will result in the label being hidden. A string containing only whitespace will
5707 * be converted to a single ` `.
5709 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5710 * text; or null for no label
5713 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
5714 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
5715 label
= ( ( typeof label
=== 'string' && label
.length
) || label
instanceof jQuery
|| label
instanceof OO
.ui
.HtmlSnippet
) ? label
: null;
5717 this.$element
.toggleClass( 'oo-ui-labelElement', !!label
);
5719 if ( this.label
!== label
) {
5720 if ( this.$label
) {
5721 this.setLabelContent( label
);
5724 this.emit( 'labelChange' );
5733 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5734 * text; or null for no label
5736 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
5745 OO
.ui
.mixin
.LabelElement
.prototype.fitLabel = function () {
5746 if ( this.$label
&& this.$label
.autoEllipsis
&& this.autoFitLabel
) {
5747 this.$label
.autoEllipsis( { hasSpan
: false, tooltip
: true } );
5754 * Set the content of the label.
5756 * Do not call this method until after the label element has been set by #setLabelElement.
5759 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5760 * text; or null for no label
5762 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
5763 if ( typeof label
=== 'string' ) {
5764 if ( label
.match( /^\s*$/ ) ) {
5765 // Convert whitespace only string to a single non-breaking space
5766 this.$label
.html( ' ' );
5768 this.$label
.text( label
);
5770 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
5771 this.$label
.html( label
.toString() );
5772 } else if ( label
instanceof jQuery
) {
5773 this.$label
.empty().append( label
);
5775 this.$label
.empty();
5780 * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
5781 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5782 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5783 * from the lookup menu, that value becomes the value of the input field.
5785 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5786 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5787 * re-enable lookups.
5789 * See the [OOjs UI demos][1] for an example.
5791 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5797 * @param {Object} [config] Configuration options
5798 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5799 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5800 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5801 * By default, the lookup menu is not generated and displayed until the user begins to type.
5803 OO
.ui
.mixin
.LookupElement
= function OoUiMixinLookupElement( config
) {
5804 // Configuration initialization
5805 config
= config
|| {};
5808 this.$overlay
= config
.$overlay
|| this.$element
;
5809 this.lookupMenu
= new OO
.ui
.FloatingMenuSelectWidget( {
5812 $container
: config
.$container
|| this.$element
5815 this.allowSuggestionsWhenEmpty
= config
.allowSuggestionsWhenEmpty
|| false;
5817 this.lookupCache
= {};
5818 this.lookupQuery
= null;
5819 this.lookupRequest
= null;
5820 this.lookupsDisabled
= false;
5821 this.lookupInputFocused
= false;
5825 focus
: this.onLookupInputFocus
.bind( this ),
5826 blur
: this.onLookupInputBlur
.bind( this ),
5827 mousedown
: this.onLookupInputMouseDown
.bind( this )
5829 this.connect( this, { change
: 'onLookupInputChange' } );
5830 this.lookupMenu
.connect( this, {
5831 toggle
: 'onLookupMenuToggle',
5832 choose
: 'onLookupMenuItemChoose'
5836 this.$element
.addClass( 'oo-ui-lookupElement' );
5837 this.lookupMenu
.$element
.addClass( 'oo-ui-lookupElement-menu' );
5838 this.$overlay
.append( this.lookupMenu
.$element
);
5844 * Handle input focus event.
5847 * @param {jQuery.Event} e Input focus event
5849 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputFocus = function () {
5850 this.lookupInputFocused
= true;
5851 this.populateLookupMenu();
5855 * Handle input blur event.
5858 * @param {jQuery.Event} e Input blur event
5860 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputBlur = function () {
5861 this.closeLookupMenu();
5862 this.lookupInputFocused
= false;
5866 * Handle input mouse down event.
5869 * @param {jQuery.Event} e Input mouse down event
5871 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputMouseDown = function () {
5872 // Only open the menu if the input was already focused.
5873 // This way we allow the user to open the menu again after closing it with Esc
5874 // by clicking in the input. Opening (and populating) the menu when initially
5875 // clicking into the input is handled by the focus handler.
5876 if ( this.lookupInputFocused
&& !this.lookupMenu
.isVisible() ) {
5877 this.populateLookupMenu();
5882 * Handle input change event.
5885 * @param {string} value New input value
5887 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputChange = function () {
5888 if ( this.lookupInputFocused
) {
5889 this.populateLookupMenu();
5894 * Handle the lookup menu being shown/hidden.
5897 * @param {boolean} visible Whether the lookup menu is now visible.
5899 OO
.ui
.mixin
.LookupElement
.prototype.onLookupMenuToggle = function ( visible
) {
5901 // When the menu is hidden, abort any active request and clear the menu.
5902 // This has to be done here in addition to closeLookupMenu(), because
5903 // MenuSelectWidget will close itself when the user presses Esc.
5904 this.abortLookupRequest();
5905 this.lookupMenu
.clearItems();
5910 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5913 * @param {OO.ui.MenuOptionWidget} item Selected item
5915 OO
.ui
.mixin
.LookupElement
.prototype.onLookupMenuItemChoose = function ( item
) {
5916 this.setValue( item
.getData() );
5923 * @return {OO.ui.FloatingMenuSelectWidget}
5925 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenu = function () {
5926 return this.lookupMenu
;
5930 * Disable or re-enable lookups.
5932 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
5934 * @param {boolean} disabled Disable lookups
5936 OO
.ui
.mixin
.LookupElement
.prototype.setLookupsDisabled = function ( disabled
) {
5937 this.lookupsDisabled
= !!disabled
;
5941 * Open the menu. If there are no entries in the menu, this does nothing.
5946 OO
.ui
.mixin
.LookupElement
.prototype.openLookupMenu = function () {
5947 if ( !this.lookupMenu
.isEmpty() ) {
5948 this.lookupMenu
.toggle( true );
5954 * Close the menu, empty it, and abort any pending request.
5959 OO
.ui
.mixin
.LookupElement
.prototype.closeLookupMenu = function () {
5960 this.lookupMenu
.toggle( false );
5961 this.abortLookupRequest();
5962 this.lookupMenu
.clearItems();
5967 * Request menu items based on the input's current value, and when they arrive,
5968 * populate the menu with these items and show the menu.
5970 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
5975 OO
.ui
.mixin
.LookupElement
.prototype.populateLookupMenu = function () {
5977 value
= this.getValue();
5979 if ( this.lookupsDisabled
) {
5983 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
5984 if ( !this.allowSuggestionsWhenEmpty
&& value
=== '' ) {
5985 this.closeLookupMenu();
5986 // Skip population if there is already a request pending for the current value
5987 } else if ( value
!== this.lookupQuery
) {
5988 this.getLookupMenuItems()
5989 .done( function ( items
) {
5990 widget
.lookupMenu
.clearItems();
5991 if ( items
.length
) {
5995 widget
.initializeLookupMenuSelection();
5997 widget
.lookupMenu
.toggle( false );
6000 .fail( function () {
6001 widget
.lookupMenu
.clearItems();
6009 * Highlight the first selectable item in the menu.
6014 OO
.ui
.mixin
.LookupElement
.prototype.initializeLookupMenuSelection = function () {
6015 if ( !this.lookupMenu
.getSelectedItem() ) {
6016 this.lookupMenu
.highlightItem( this.lookupMenu
.getFirstSelectableItem() );
6021 * Get lookup menu items for the current query.
6024 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
6025 * the done event. If the request was aborted to make way for a subsequent request, this promise
6026 * will not be rejected: it will remain pending forever.
6028 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenuItems = function () {
6030 value
= this.getValue(),
6031 deferred
= $.Deferred(),
6034 this.abortLookupRequest();
6035 if ( Object
.prototype.hasOwnProperty
.call( this.lookupCache
, value
) ) {
6036 deferred
.resolve( this.getLookupMenuOptionsFromData( this.lookupCache
[ value
] ) );
6039 this.lookupQuery
= value
;
6040 ourRequest
= this.lookupRequest
= this.getLookupRequest();
6042 .always( function () {
6043 // We need to pop pending even if this is an old request, otherwise
6044 // the widget will remain pending forever.
6045 // TODO: this assumes that an aborted request will fail or succeed soon after
6046 // being aborted, or at least eventually. It would be nice if we could popPending()
6047 // at abort time, but only if we knew that we hadn't already called popPending()
6048 // for that request.
6049 widget
.popPending();
6051 .done( function ( response
) {
6052 // If this is an old request (and aborting it somehow caused it to still succeed),
6053 // ignore its success completely
6054 if ( ourRequest
=== widget
.lookupRequest
) {
6055 widget
.lookupQuery
= null;
6056 widget
.lookupRequest
= null;
6057 widget
.lookupCache
[ value
] = widget
.getLookupCacheDataFromResponse( response
);
6058 deferred
.resolve( widget
.getLookupMenuOptionsFromData( widget
.lookupCache
[ value
] ) );
6061 .fail( function () {
6062 // If this is an old request (or a request failing because it's being aborted),
6063 // ignore its failure completely
6064 if ( ourRequest
=== widget
.lookupRequest
) {
6065 widget
.lookupQuery
= null;
6066 widget
.lookupRequest
= null;
6071 return deferred
.promise();
6075 * Abort the currently pending lookup request, if any.
6079 OO
.ui
.mixin
.LookupElement
.prototype.abortLookupRequest = function () {
6080 var oldRequest
= this.lookupRequest
;
6082 // First unset this.lookupRequest to the fail handler will notice
6083 // that the request is no longer current
6084 this.lookupRequest
= null;
6085 this.lookupQuery
= null;
6091 * Get a new request object of the current lookup query value.
6095 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
6097 OO
.ui
.mixin
.LookupElement
.prototype.getLookupRequest = function () {
6098 // Stub, implemented in subclass
6103 * Pre-process data returned by the request from #getLookupRequest.
6105 * The return value of this function will be cached, and any further queries for the given value
6106 * will use the cache rather than doing API requests.
6110 * @param {Mixed} response Response from server
6111 * @return {Mixed} Cached result data
6113 OO
.ui
.mixin
.LookupElement
.prototype.getLookupCacheDataFromResponse = function () {
6114 // Stub, implemented in subclass
6119 * Get a list of menu option widgets from the (possibly cached) data returned by
6120 * #getLookupCacheDataFromResponse.
6124 * @param {Mixed} data Cached result data, usually an array
6125 * @return {OO.ui.MenuOptionWidget[]} Menu items
6127 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenuOptionsFromData = function () {
6128 // Stub, implemented in subclass
6133 * Set the read-only state of the widget.
6135 * This will also disable/enable the lookups functionality.
6137 * @param {boolean} readOnly Make input read-only
6140 OO
.ui
.mixin
.LookupElement
.prototype.setReadOnly = function ( readOnly
) {
6142 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
6143 OO
.ui
.TextInputWidget
.prototype.setReadOnly
.call( this, readOnly
);
6145 this.setLookupsDisabled( readOnly
);
6146 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
6147 if ( readOnly
&& this.lookupMenu
) {
6148 this.closeLookupMenu();
6155 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
6156 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
6157 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
6158 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
6164 * @param {Object} [config] Configuration options
6165 * @cfg {Object} [popup] Configuration to pass to popup
6166 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
6168 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
6169 // Configuration initialization
6170 config
= config
|| {};
6173 this.popup
= new OO
.ui
.PopupWidget( $.extend(
6174 { autoClose
: true },
6176 { $autoCloseIgnore
: this.$element
}
6185 * @return {OO.ui.PopupWidget} Popup widget
6187 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
6192 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
6193 * additional functionality to an element created by another class. The class provides
6194 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
6195 * which are used to customize the look and feel of a widget to better describe its
6196 * importance and functionality.
6198 * The library currently contains the following styling flags for general use:
6200 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
6201 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
6202 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
6204 * The flags affect the appearance of the buttons:
6207 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
6208 * var button1 = new OO.ui.ButtonWidget( {
6209 * label: 'Constructive',
6210 * flags: 'constructive'
6212 * var button2 = new OO.ui.ButtonWidget( {
6213 * label: 'Destructive',
6214 * flags: 'destructive'
6216 * var button3 = new OO.ui.ButtonWidget( {
6217 * label: 'Progressive',
6218 * flags: 'progressive'
6220 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
6222 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
6223 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6225 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6231 * @param {Object} [config] Configuration options
6232 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
6233 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
6234 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6235 * @cfg {jQuery} [$flagged] The flagged element. By default,
6236 * the flagged functionality is applied to the element created by the class ($element).
6237 * If a different element is specified, the flagged functionality will be applied to it instead.
6239 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
6240 // Configuration initialization
6241 config
= config
|| {};
6245 this.$flagged
= null;
6248 this.setFlags( config
.flags
);
6249 this.setFlaggedElement( config
.$flagged
|| this.$element
);
6256 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
6257 * parameter contains the name of each modified flag and indicates whether it was
6260 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
6261 * that the flag was added, `false` that the flag was removed.
6267 * Set the flagged element.
6269 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
6270 * If an element is already set, the method will remove the mixin’s effect on that element.
6272 * @param {jQuery} $flagged Element that should be flagged
6274 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
6275 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
6276 return 'oo-ui-flaggedElement-' + flag
;
6279 if ( this.$flagged
) {
6280 this.$flagged
.removeClass( classNames
);
6283 this.$flagged
= $flagged
.addClass( classNames
);
6287 * Check if the specified flag is set.
6289 * @param {string} flag Name of flag
6290 * @return {boolean} The flag is set
6292 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
6293 // This may be called before the constructor, thus before this.flags is set
6294 return this.flags
&& ( flag
in this.flags
);
6298 * Get the names of all flags set.
6300 * @return {string[]} Flag names
6302 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
6303 // This may be called before the constructor, thus before this.flags is set
6304 return Object
.keys( this.flags
|| {} );
6313 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
6314 var flag
, className
,
6317 classPrefix
= 'oo-ui-flaggedElement-';
6319 for ( flag
in this.flags
) {
6320 className
= classPrefix
+ flag
;
6321 changes
[ flag
] = false;
6322 delete this.flags
[ flag
];
6323 remove
.push( className
);
6326 if ( this.$flagged
) {
6327 this.$flagged
.removeClass( remove
.join( ' ' ) );
6330 this.updateThemeClasses();
6331 this.emit( 'flag', changes
);
6337 * Add one or more flags.
6339 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6340 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6341 * be added (`true`) or removed (`false`).
6345 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
6346 var i
, len
, flag
, className
,
6350 classPrefix
= 'oo-ui-flaggedElement-';
6352 if ( typeof flags
=== 'string' ) {
6353 className
= classPrefix
+ flags
;
6355 if ( !this.flags
[ flags
] ) {
6356 this.flags
[ flags
] = true;
6357 add
.push( className
);
6359 } else if ( Array
.isArray( flags
) ) {
6360 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
6362 className
= classPrefix
+ flag
;
6364 if ( !this.flags
[ flag
] ) {
6365 changes
[ flag
] = true;
6366 this.flags
[ flag
] = true;
6367 add
.push( className
);
6370 } else if ( OO
.isPlainObject( flags
) ) {
6371 for ( flag
in flags
) {
6372 className
= classPrefix
+ flag
;
6373 if ( flags
[ flag
] ) {
6375 if ( !this.flags
[ flag
] ) {
6376 changes
[ flag
] = true;
6377 this.flags
[ flag
] = true;
6378 add
.push( className
);
6382 if ( this.flags
[ flag
] ) {
6383 changes
[ flag
] = false;
6384 delete this.flags
[ flag
];
6385 remove
.push( className
);
6391 if ( this.$flagged
) {
6393 .addClass( add
.join( ' ' ) )
6394 .removeClass( remove
.join( ' ' ) );
6397 this.updateThemeClasses();
6398 this.emit( 'flag', changes
);
6404 * TitledElement is mixed into other classes to provide a `title` attribute.
6405 * Titles are rendered by the browser and are made visible when the user moves
6406 * the mouse over the element. Titles are not visible on touch devices.
6409 * // TitledElement provides a 'title' attribute to the
6410 * // ButtonWidget class
6411 * var button = new OO.ui.ButtonWidget( {
6412 * label: 'Button with Title',
6413 * title: 'I am a button'
6415 * $( 'body' ).append( button.$element );
6421 * @param {Object} [config] Configuration options
6422 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6423 * If this config is omitted, the title functionality is applied to $element, the
6424 * element created by the class.
6425 * @cfg {string|Function} [title] The title text or a function that returns text. If
6426 * this config is omitted, the value of the {@link #static-title static title} property is used.
6428 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
6429 // Configuration initialization
6430 config
= config
|| {};
6433 this.$titled
= null;
6437 this.setTitle( config
.title
|| this.constructor.static.title
);
6438 this.setTitledElement( config
.$titled
|| this.$element
);
6443 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
6445 /* Static Properties */
6448 * The title text, a function that returns text, or `null` for no title. The value of the static property
6449 * is overridden if the #title config option is used.
6453 * @property {string|Function|null}
6455 OO
.ui
.mixin
.TitledElement
.static.title
= null;
6460 * Set the titled element.
6462 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6463 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6465 * @param {jQuery} $titled Element that should use the 'titled' functionality
6467 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
6468 if ( this.$titled
) {
6469 this.$titled
.removeAttr( 'title' );
6472 this.$titled
= $titled
;
6474 this.$titled
.attr( 'title', this.title
);
6481 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6484 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
6485 title
= typeof title
=== 'string' ? OO
.ui
.resolveMsg( title
) : null;
6487 if ( this.title
!== title
) {
6488 if ( this.$titled
) {
6489 if ( title
!== null ) {
6490 this.$titled
.attr( 'title', title
);
6492 this.$titled
.removeAttr( 'title' );
6504 * @return {string} Title string
6506 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
6511 * Element that can be automatically clipped to visible boundaries.
6513 * Whenever the element's natural height changes, you have to call
6514 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
6515 * clipping correctly.
6521 * @param {Object} [config] Configuration options
6522 * @cfg {jQuery} [$clippable] Nodes to clip, assigned to #$clippable, omit to use #$element
6524 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
6525 // Configuration initialization
6526 config
= config
|| {};
6529 this.$clippable
= null;
6530 this.clipping
= false;
6531 this.clippedHorizontally
= false;
6532 this.clippedVertically
= false;
6533 this.$clippableContainer
= null;
6534 this.$clippableScroller
= null;
6535 this.$clippableWindow
= null;
6536 this.idealWidth
= null;
6537 this.idealHeight
= null;
6538 this.onClippableContainerScrollHandler
= this.clip
.bind( this );
6539 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
6542 this.setClippableElement( config
.$clippable
|| this.$element
);
6548 * Set clippable element.
6550 * If an element is already set, it will be cleaned up before setting up the new element.
6552 * @param {jQuery} $clippable Element to make clippable
6554 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
6555 if ( this.$clippable
) {
6556 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
6557 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6558 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6561 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
6568 * Do not turn clipping on until after the element is attached to the DOM and visible.
6570 * @param {boolean} [clipping] Enable clipping, omit to toggle
6573 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
6574 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
6576 if ( this.clipping
!== clipping
) {
6577 this.clipping
= clipping
;
6579 this.$clippableContainer
= $( this.getClosestScrollableElementContainer() );
6580 // If the clippable container is the root, we have to listen to scroll events and check
6581 // jQuery.scrollTop on the window because of browser inconsistencies
6582 this.$clippableScroller
= this.$clippableContainer
.is( 'html, body' ) ?
6583 $( OO
.ui
.Element
.static.getWindow( this.$clippableContainer
) ) :
6584 this.$clippableContainer
;
6585 this.$clippableScroller
.on( 'scroll', this.onClippableContainerScrollHandler
);
6586 this.$clippableWindow
= $( this.getElementWindow() )
6587 .on( 'resize', this.onClippableWindowResizeHandler
);
6588 // Initial clip after visible
6591 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6592 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6594 this.$clippableContainer
= null;
6595 this.$clippableScroller
.off( 'scroll', this.onClippableContainerScrollHandler
);
6596 this.$clippableScroller
= null;
6597 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
6598 this.$clippableWindow
= null;
6606 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6608 * @return {boolean} Element will be clipped to the visible area
6610 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
6611 return this.clipping
;
6615 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6617 * @return {boolean} Part of the element is being clipped
6619 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
6620 return this.clippedHorizontally
|| this.clippedVertically
;
6624 * Check if the right of the element is being clipped by the nearest scrollable container.
6626 * @return {boolean} Part of the element is being clipped
6628 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
6629 return this.clippedHorizontally
;
6633 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6635 * @return {boolean} Part of the element is being clipped
6637 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
6638 return this.clippedVertically
;
6642 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6644 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6645 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6647 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
6648 this.idealWidth
= width
;
6649 this.idealHeight
= height
;
6651 if ( !this.clipping
) {
6652 // Update dimensions
6653 this.$clippable
.css( { width
: width
, height
: height
} );
6655 // While clipping, idealWidth and idealHeight are not considered
6659 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6660 * the element's natural height changes.
6662 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6663 * overlapped by, the visible area of the nearest scrollable container.
6667 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
6668 if ( !this.clipping
) {
6669 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
6673 var buffer
= 7, // Chosen by fair dice roll
6674 cOffset
= this.$clippable
.offset(),
6675 $container
= this.$clippableContainer
.is( 'html, body' ) ?
6676 this.$clippableWindow
: this.$clippableContainer
,
6677 ccOffset
= $container
.offset() || { top
: 0, left
: 0 },
6678 ccHeight
= $container
.innerHeight() - buffer
,
6679 ccWidth
= $container
.innerWidth() - buffer
,
6680 cWidth
= this.$clippable
.outerWidth() + buffer
,
6681 scrollerIsWindow
= this.$clippableScroller
[0] === this.$clippableWindow
[0],
6682 scrollTop
= scrollerIsWindow
? this.$clippableScroller
.scrollTop() : 0,
6683 scrollLeft
= scrollerIsWindow
? this.$clippableScroller
.scrollLeft() : 0,
6684 desiredWidth
= cOffset
.left
< 0 ?
6685 cWidth
+ cOffset
.left
:
6686 ( ccOffset
.left
+ scrollLeft
+ ccWidth
) - cOffset
.left
,
6687 desiredHeight
= ( ccOffset
.top
+ scrollTop
+ ccHeight
) - cOffset
.top
,
6688 naturalWidth
= this.$clippable
.prop( 'scrollWidth' ),
6689 naturalHeight
= this.$clippable
.prop( 'scrollHeight' ),
6690 clipWidth
= desiredWidth
< naturalWidth
,
6691 clipHeight
= desiredHeight
< naturalHeight
;
6694 this.$clippable
.css( { overflowX
: 'scroll', width
: desiredWidth
} );
6696 this.$clippable
.css( { width
: this.idealWidth
|| '', overflowX
: '' } );
6699 this.$clippable
.css( { overflowY
: 'scroll', height
: desiredHeight
} );
6701 this.$clippable
.css( { height
: this.idealHeight
|| '', overflowY
: '' } );
6704 // If we stopped clipping in at least one of the dimensions
6705 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
6706 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6709 this.clippedHorizontally
= clipWidth
;
6710 this.clippedVertically
= clipHeight
;
6716 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
6717 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
6718 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
6719 * which creates the tools on demand.
6721 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
6722 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
6723 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
6725 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
6726 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
6730 * @extends OO.ui.Widget
6731 * @mixins OO.ui.mixin.IconElement
6732 * @mixins OO.ui.mixin.FlaggedElement
6733 * @mixins OO.ui.mixin.TabIndexedElement
6736 * @param {OO.ui.ToolGroup} toolGroup
6737 * @param {Object} [config] Configuration options
6738 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
6739 * the {@link #static-title static title} property is used.
6741 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
6742 * title is used as a tooltip if the tool is part of a {@link OO.ui.BarToolGroup bar} toolgroup, or as the label text if the tool is
6743 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
6745 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
6746 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
6747 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
6749 OO
.ui
.Tool
= function OoUiTool( toolGroup
, config
) {
6750 // Allow passing positional parameters inside the config object
6751 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
6753 toolGroup
= config
.toolGroup
;
6756 // Configuration initialization
6757 config
= config
|| {};
6759 // Parent constructor
6760 OO
.ui
.Tool
.parent
.call( this, config
);
6763 this.toolGroup
= toolGroup
;
6764 this.toolbar
= this.toolGroup
.getToolbar();
6765 this.active
= false;
6766 this.$title
= $( '<span>' );
6767 this.$accel
= $( '<span>' );
6768 this.$link
= $( '<a>' );
6771 // Mixin constructors
6772 OO
.ui
.mixin
.IconElement
.call( this, config
);
6773 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
6774 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$link
} ) );
6777 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
6780 this.$title
.addClass( 'oo-ui-tool-title' );
6782 .addClass( 'oo-ui-tool-accel' )
6784 // This may need to be changed if the key names are ever localized,
6785 // but for now they are essentially written in English
6790 .addClass( 'oo-ui-tool-link' )
6791 .append( this.$icon
, this.$title
, this.$accel
)
6792 .attr( 'role', 'button' );
6794 .data( 'oo-ui-tool', this )
6796 'oo-ui-tool ' + 'oo-ui-tool-name-' +
6797 this.constructor.static.name
.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
6799 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel
)
6800 .append( this.$link
);
6801 this.setTitle( config
.title
|| this.constructor.static.title
);
6806 OO
.inheritClass( OO
.ui
.Tool
, OO
.ui
.Widget
);
6807 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.IconElement
);
6808 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.FlaggedElement
);
6809 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.TabIndexedElement
);
6811 /* Static Properties */
6817 OO
.ui
.Tool
.static.tagName
= 'span';
6820 * Symbolic name of tool.
6822 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
6823 * also be used when adding tools to toolgroups.
6828 * @property {string}
6830 OO
.ui
.Tool
.static.name
= '';
6833 * Symbolic name of the group.
6835 * The group name is used to associate tools with each other so that they can be selected later by
6836 * a {@link OO.ui.ToolGroup toolgroup}.
6841 * @property {string}
6843 OO
.ui
.Tool
.static.group
= '';
6846 * Tool title text or a function that returns title text. The value of the static property is overridden if the #title config option is used.
6851 * @property {string|Function}
6853 OO
.ui
.Tool
.static.title
= '';
6856 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
6857 * Normally only the icon is displayed, or only the label if no icon is given.
6861 * @property {boolean}
6863 OO
.ui
.Tool
.static.displayBothIconAndLabel
= false;
6866 * Add tool to catch-all groups automatically.
6868 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
6869 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
6873 * @property {boolean}
6875 OO
.ui
.Tool
.static.autoAddToCatchall
= true;
6878 * Add tool to named groups automatically.
6880 * By default, tools that are configured with a static ‘group’ property are added
6881 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
6882 * toolgroups include tools by group name).
6885 * @property {boolean}
6888 OO
.ui
.Tool
.static.autoAddToGroup
= true;
6891 * Check if this tool is compatible with given data.
6893 * This is a stub that can be overriden to provide support for filtering tools based on an
6894 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
6895 * must also call this method so that the compatibility check can be performed.
6899 * @param {Mixed} data Data to check
6900 * @return {boolean} Tool can be used with data
6902 OO
.ui
.Tool
.static.isCompatibleWith = function () {
6909 * Handle the toolbar state being updated.
6911 * This is an abstract method that must be overridden in a concrete subclass.
6916 OO
.ui
.Tool
.prototype.onUpdateState = function () {
6918 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
6923 * Handle the tool being selected.
6925 * This is an abstract method that must be overridden in a concrete subclass.
6930 OO
.ui
.Tool
.prototype.onSelect = function () {
6932 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
6937 * Check if the tool is active.
6939 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
6940 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
6942 * @return {boolean} Tool is active
6944 OO
.ui
.Tool
.prototype.isActive = function () {
6949 * Make the tool appear active or inactive.
6951 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
6952 * appear pressed or not.
6954 * @param {boolean} state Make tool appear active
6956 OO
.ui
.Tool
.prototype.setActive = function ( state
) {
6957 this.active
= !!state
;
6958 if ( this.active
) {
6959 this.$element
.addClass( 'oo-ui-tool-active' );
6961 this.$element
.removeClass( 'oo-ui-tool-active' );
6966 * Set the tool #title.
6968 * @param {string|Function} title Title text or a function that returns text
6971 OO
.ui
.Tool
.prototype.setTitle = function ( title
) {
6972 this.title
= OO
.ui
.resolveMsg( title
);
6978 * Get the tool #title.
6980 * @return {string} Title text
6982 OO
.ui
.Tool
.prototype.getTitle = function () {
6987 * Get the tool's symbolic name.
6989 * @return {string} Symbolic name of tool
6991 OO
.ui
.Tool
.prototype.getName = function () {
6992 return this.constructor.static.name
;
6998 OO
.ui
.Tool
.prototype.updateTitle = function () {
6999 var titleTooltips
= this.toolGroup
.constructor.static.titleTooltips
,
7000 accelTooltips
= this.toolGroup
.constructor.static.accelTooltips
,
7001 accel
= this.toolbar
.getToolAccelerator( this.constructor.static.name
),
7004 this.$title
.text( this.title
);
7005 this.$accel
.text( accel
);
7007 if ( titleTooltips
&& typeof this.title
=== 'string' && this.title
.length
) {
7008 tooltipParts
.push( this.title
);
7010 if ( accelTooltips
&& typeof accel
=== 'string' && accel
.length
) {
7011 tooltipParts
.push( accel
);
7013 if ( tooltipParts
.length
) {
7014 this.$link
.attr( 'title', tooltipParts
.join( ' ' ) );
7016 this.$link
.removeAttr( 'title' );
7023 * Destroying the tool removes all event handlers and the tool’s DOM elements.
7024 * Call this method whenever you are done using a tool.
7026 OO
.ui
.Tool
.prototype.destroy = function () {
7027 this.toolbar
.disconnect( this );
7028 this.$element
.remove();
7032 * Toolbars are complex interface components that permit users to easily access a variety
7033 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
7034 * part of the toolbar, but not configured as tools.
7036 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
7037 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
7038 * picture’), and an icon.
7040 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
7041 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
7042 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
7043 * any order, but each can only appear once in the toolbar.
7045 * The following is an example of a basic toolbar.
7048 * // Example of a toolbar
7049 * // Create the toolbar
7050 * var toolFactory = new OO.ui.ToolFactory();
7051 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7052 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7054 * // We will be placing status text in this element when tools are used
7055 * var $area = $( '<p>' ).text( 'Toolbar example' );
7057 * // Define the tools that we're going to place in our toolbar
7059 * // Create a class inheriting from OO.ui.Tool
7060 * function PictureTool() {
7061 * PictureTool.parent.apply( this, arguments );
7063 * OO.inheritClass( PictureTool, OO.ui.Tool );
7064 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7065 * // of 'icon' and 'title' (displayed icon and text).
7066 * PictureTool.static.name = 'picture';
7067 * PictureTool.static.icon = 'picture';
7068 * PictureTool.static.title = 'Insert picture';
7069 * // Defines the action that will happen when this tool is selected (clicked).
7070 * PictureTool.prototype.onSelect = function () {
7071 * $area.text( 'Picture tool clicked!' );
7072 * // Never display this tool as "active" (selected).
7073 * this.setActive( false );
7075 * // Make this tool available in our toolFactory and thus our toolbar
7076 * toolFactory.register( PictureTool );
7078 * // Register two more tools, nothing interesting here
7079 * function SettingsTool() {
7080 * SettingsTool.parent.apply( this, arguments );
7082 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7083 * SettingsTool.static.name = 'settings';
7084 * SettingsTool.static.icon = 'settings';
7085 * SettingsTool.static.title = 'Change settings';
7086 * SettingsTool.prototype.onSelect = function () {
7087 * $area.text( 'Settings tool clicked!' );
7088 * this.setActive( false );
7090 * toolFactory.register( SettingsTool );
7092 * // Register two more tools, nothing interesting here
7093 * function StuffTool() {
7094 * StuffTool.parent.apply( this, arguments );
7096 * OO.inheritClass( StuffTool, OO.ui.Tool );
7097 * StuffTool.static.name = 'stuff';
7098 * StuffTool.static.icon = 'ellipsis';
7099 * StuffTool.static.title = 'More stuff';
7100 * StuffTool.prototype.onSelect = function () {
7101 * $area.text( 'More stuff tool clicked!' );
7102 * this.setActive( false );
7104 * toolFactory.register( StuffTool );
7106 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7107 * // little popup window (a PopupWidget).
7108 * function HelpTool( toolGroup, config ) {
7109 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7114 * this.popup.$body.append( '<p>I am helpful!</p>' );
7116 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7117 * HelpTool.static.name = 'help';
7118 * HelpTool.static.icon = 'help';
7119 * HelpTool.static.title = 'Help';
7120 * toolFactory.register( HelpTool );
7122 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7123 * // used once (but not all defined tools must be used).
7126 * // 'bar' tool groups display tools' icons only, side-by-side.
7128 * include: [ 'picture', 'help' ]
7131 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7133 * indicator: 'down',
7135 * include: [ 'settings', 'stuff' ]
7137 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7138 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7139 * // since it's more complicated to use. (See the next example snippet on this page.)
7142 * // Create some UI around the toolbar and place it in the document
7143 * var frame = new OO.ui.PanelLayout( {
7147 * var contentFrame = new OO.ui.PanelLayout( {
7151 * frame.$element.append(
7153 * contentFrame.$element.append( $area )
7155 * $( 'body' ).append( frame.$element );
7157 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7159 * toolbar.initialize();
7161 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7162 * 'updateState' event.
7165 * // Create the toolbar
7166 * var toolFactory = new OO.ui.ToolFactory();
7167 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7168 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7170 * // We will be placing status text in this element when tools are used
7171 * var $area = $( '<p>' ).text( 'Toolbar example' );
7173 * // Define the tools that we're going to place in our toolbar
7175 * // Create a class inheriting from OO.ui.Tool
7176 * function PictureTool() {
7177 * PictureTool.parent.apply( this, arguments );
7179 * OO.inheritClass( PictureTool, OO.ui.Tool );
7180 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7181 * // of 'icon' and 'title' (displayed icon and text).
7182 * PictureTool.static.name = 'picture';
7183 * PictureTool.static.icon = 'picture';
7184 * PictureTool.static.title = 'Insert picture';
7185 * // Defines the action that will happen when this tool is selected (clicked).
7186 * PictureTool.prototype.onSelect = function () {
7187 * $area.text( 'Picture tool clicked!' );
7188 * // Never display this tool as "active" (selected).
7189 * this.setActive( false );
7191 * // The toolbar can be synchronized with the state of some external stuff, like a text
7192 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
7193 * // when the text cursor was inside bolded text). Here we simply disable this feature.
7194 * PictureTool.prototype.onUpdateState = function () {
7196 * // Make this tool available in our toolFactory and thus our toolbar
7197 * toolFactory.register( PictureTool );
7199 * // Register two more tools, nothing interesting here
7200 * function SettingsTool() {
7201 * SettingsTool.parent.apply( this, arguments );
7202 * this.reallyActive = false;
7204 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7205 * SettingsTool.static.name = 'settings';
7206 * SettingsTool.static.icon = 'settings';
7207 * SettingsTool.static.title = 'Change settings';
7208 * SettingsTool.prototype.onSelect = function () {
7209 * $area.text( 'Settings tool clicked!' );
7210 * // Toggle the active state on each click
7211 * this.reallyActive = !this.reallyActive;
7212 * this.setActive( this.reallyActive );
7213 * // To update the menu label
7214 * this.toolbar.emit( 'updateState' );
7216 * SettingsTool.prototype.onUpdateState = function () {
7218 * toolFactory.register( SettingsTool );
7220 * // Register two more tools, nothing interesting here
7221 * function StuffTool() {
7222 * StuffTool.parent.apply( this, arguments );
7223 * this.reallyActive = false;
7225 * OO.inheritClass( StuffTool, OO.ui.Tool );
7226 * StuffTool.static.name = 'stuff';
7227 * StuffTool.static.icon = 'ellipsis';
7228 * StuffTool.static.title = 'More stuff';
7229 * StuffTool.prototype.onSelect = function () {
7230 * $area.text( 'More stuff tool clicked!' );
7231 * // Toggle the active state on each click
7232 * this.reallyActive = !this.reallyActive;
7233 * this.setActive( this.reallyActive );
7234 * // To update the menu label
7235 * this.toolbar.emit( 'updateState' );
7237 * StuffTool.prototype.onUpdateState = function () {
7239 * toolFactory.register( StuffTool );
7241 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7242 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7243 * function HelpTool( toolGroup, config ) {
7244 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7249 * this.popup.$body.append( '<p>I am helpful!</p>' );
7251 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7252 * HelpTool.static.name = 'help';
7253 * HelpTool.static.icon = 'help';
7254 * HelpTool.static.title = 'Help';
7255 * toolFactory.register( HelpTool );
7257 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7258 * // used once (but not all defined tools must be used).
7261 * // 'bar' tool groups display tools' icons only, side-by-side.
7263 * include: [ 'picture', 'help' ]
7266 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7267 * // Menu label indicates which items are selected.
7269 * indicator: 'down',
7270 * include: [ 'settings', 'stuff' ]
7274 * // Create some UI around the toolbar and place it in the document
7275 * var frame = new OO.ui.PanelLayout( {
7279 * var contentFrame = new OO.ui.PanelLayout( {
7283 * frame.$element.append(
7285 * contentFrame.$element.append( $area )
7287 * $( 'body' ).append( frame.$element );
7289 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7291 * toolbar.initialize();
7292 * toolbar.emit( 'updateState' );
7295 * @extends OO.ui.Element
7296 * @mixins OO.EventEmitter
7297 * @mixins OO.ui.mixin.GroupElement
7300 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7301 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7302 * @param {Object} [config] Configuration options
7303 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7304 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7306 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7308 OO
.ui
.Toolbar
= function OoUiToolbar( toolFactory
, toolGroupFactory
, config
) {
7309 // Allow passing positional parameters inside the config object
7310 if ( OO
.isPlainObject( toolFactory
) && config
=== undefined ) {
7311 config
= toolFactory
;
7312 toolFactory
= config
.toolFactory
;
7313 toolGroupFactory
= config
.toolGroupFactory
;
7316 // Configuration initialization
7317 config
= config
|| {};
7319 // Parent constructor
7320 OO
.ui
.Toolbar
.parent
.call( this, config
);
7322 // Mixin constructors
7323 OO
.EventEmitter
.call( this );
7324 OO
.ui
.mixin
.GroupElement
.call( this, config
);
7327 this.toolFactory
= toolFactory
;
7328 this.toolGroupFactory
= toolGroupFactory
;
7331 this.$bar
= $( '<div>' );
7332 this.$actions
= $( '<div>' );
7333 this.initialized
= false;
7334 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
7338 .add( this.$bar
).add( this.$group
).add( this.$actions
)
7339 .on( 'mousedown keydown', this.onPointerDown
.bind( this ) );
7342 this.$group
.addClass( 'oo-ui-toolbar-tools' );
7343 if ( config
.actions
) {
7344 this.$bar
.append( this.$actions
.addClass( 'oo-ui-toolbar-actions' ) );
7347 .addClass( 'oo-ui-toolbar-bar' )
7348 .append( this.$group
, '<div style="clear:both"></div>' );
7349 if ( config
.shadow
) {
7350 this.$bar
.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7352 this.$element
.addClass( 'oo-ui-toolbar' ).append( this.$bar
);
7357 OO
.inheritClass( OO
.ui
.Toolbar
, OO
.ui
.Element
);
7358 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.EventEmitter
);
7359 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.ui
.mixin
.GroupElement
);
7364 * Get the tool factory.
7366 * @return {OO.ui.ToolFactory} Tool factory
7368 OO
.ui
.Toolbar
.prototype.getToolFactory = function () {
7369 return this.toolFactory
;
7373 * Get the toolgroup factory.
7375 * @return {OO.Factory} Toolgroup factory
7377 OO
.ui
.Toolbar
.prototype.getToolGroupFactory = function () {
7378 return this.toolGroupFactory
;
7382 * Handles mouse down events.
7385 * @param {jQuery.Event} e Mouse down event
7387 OO
.ui
.Toolbar
.prototype.onPointerDown = function ( e
) {
7388 var $closestWidgetToEvent
= $( e
.target
).closest( '.oo-ui-widget' ),
7389 $closestWidgetToToolbar
= this.$element
.closest( '.oo-ui-widget' );
7390 if ( !$closestWidgetToEvent
.length
|| $closestWidgetToEvent
[ 0 ] === $closestWidgetToToolbar
[ 0 ] ) {
7396 * Handle window resize event.
7399 * @param {jQuery.Event} e Window resize event
7401 OO
.ui
.Toolbar
.prototype.onWindowResize = function () {
7402 this.$element
.toggleClass(
7403 'oo-ui-toolbar-narrow',
7404 this.$bar
.width() <= this.narrowThreshold
7409 * Sets up handles and preloads required information for the toolbar to work.
7410 * This must be called after it is attached to a visible document and before doing anything else.
7412 OO
.ui
.Toolbar
.prototype.initialize = function () {
7413 this.initialized
= true;
7414 this.narrowThreshold
= this.$group
.width() + this.$actions
.width();
7415 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
7416 this.onWindowResize();
7420 * Set up the toolbar.
7422 * The toolbar is set up with a list of toolgroup configurations that specify the type of
7423 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
7424 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
7425 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
7427 * @param {Object.<string,Array>} groups List of toolgroup configurations
7428 * @param {Array|string} [groups.include] Tools to include in the toolgroup
7429 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
7430 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
7431 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
7433 OO
.ui
.Toolbar
.prototype.setup = function ( groups
) {
7434 var i
, len
, type
, group
,
7436 defaultType
= 'bar';
7438 // Cleanup previous groups
7441 // Build out new groups
7442 for ( i
= 0, len
= groups
.length
; i
< len
; i
++ ) {
7443 group
= groups
[ i
];
7444 if ( group
.include
=== '*' ) {
7445 // Apply defaults to catch-all groups
7446 if ( group
.type
=== undefined ) {
7447 group
.type
= 'list';
7449 if ( group
.label
=== undefined ) {
7450 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
7453 // Check type has been registered
7454 type
= this.getToolGroupFactory().lookup( group
.type
) ? group
.type
: defaultType
;
7456 this.getToolGroupFactory().create( type
, this, group
)
7459 this.addItems( items
);
7463 * Remove all tools and toolgroups from the toolbar.
7465 OO
.ui
.Toolbar
.prototype.reset = function () {
7470 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7471 this.items
[ i
].destroy();
7477 * Destroy the toolbar.
7479 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
7480 * this method whenever you are done using a toolbar.
7482 OO
.ui
.Toolbar
.prototype.destroy = function () {
7483 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
7485 this.$element
.remove();
7489 * Check if the tool is available.
7491 * Available tools are ones that have not yet been added to the toolbar.
7493 * @param {string} name Symbolic name of tool
7494 * @return {boolean} Tool is available
7496 OO
.ui
.Toolbar
.prototype.isToolAvailable = function ( name
) {
7497 return !this.tools
[ name
];
7501 * Prevent tool from being used again.
7503 * @param {OO.ui.Tool} tool Tool to reserve
7505 OO
.ui
.Toolbar
.prototype.reserveTool = function ( tool
) {
7506 this.tools
[ tool
.getName() ] = tool
;
7510 * Allow tool to be used again.
7512 * @param {OO.ui.Tool} tool Tool to release
7514 OO
.ui
.Toolbar
.prototype.releaseTool = function ( tool
) {
7515 delete this.tools
[ tool
.getName() ];
7519 * Get accelerator label for tool.
7521 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
7522 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
7523 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
7525 * @param {string} name Symbolic name of tool
7526 * @return {string|undefined} Tool accelerator label if available
7528 OO
.ui
.Toolbar
.prototype.getToolAccelerator = function () {
7533 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
7534 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
7535 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
7536 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
7538 * Toolgroups can contain individual tools, groups of tools, or all available tools:
7540 * To include an individual tool (or array of individual tools), specify tools by symbolic name:
7542 * include: [ 'tool-name' ] or [ { name: 'tool-name' }]
7544 * To include a group of tools, specify the group name. (The tool's static ‘group’ config is used to assign the tool to a group.)
7546 * include: [ { group: 'group-name' } ]
7548 * To include all tools that are not yet assigned to a toolgroup, use the catch-all selector, an asterisk (*):
7552 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
7553 * please see the [OOjs UI documentation on MediaWiki][1].
7555 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7559 * @extends OO.ui.Widget
7560 * @mixins OO.ui.mixin.GroupElement
7563 * @param {OO.ui.Toolbar} toolbar
7564 * @param {Object} [config] Configuration options
7565 * @cfg {Array|string} [include=[]] List of tools to include in the toolgroup.
7566 * @cfg {Array|string} [exclude=[]] List of tools to exclude from the toolgroup.
7567 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning of the toolgroup.
7568 * @cfg {Array|string} [demote=[]] List of tools to demote to the end of the toolgroup.
7569 * This setting is particularly useful when tools have been added to the toolgroup
7570 * en masse (e.g., via the catch-all selector).
7572 OO
.ui
.ToolGroup
= function OoUiToolGroup( toolbar
, config
) {
7573 // Allow passing positional parameters inside the config object
7574 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
7576 toolbar
= config
.toolbar
;
7579 // Configuration initialization
7580 config
= config
|| {};
7582 // Parent constructor
7583 OO
.ui
.ToolGroup
.parent
.call( this, config
);
7585 // Mixin constructors
7586 OO
.ui
.mixin
.GroupElement
.call( this, config
);
7589 this.toolbar
= toolbar
;
7591 this.pressed
= null;
7592 this.autoDisabled
= false;
7593 this.include
= config
.include
|| [];
7594 this.exclude
= config
.exclude
|| [];
7595 this.promote
= config
.promote
|| [];
7596 this.demote
= config
.demote
|| [];
7597 this.onCapturedMouseKeyUpHandler
= this.onCapturedMouseKeyUp
.bind( this );
7601 mousedown
: this.onMouseKeyDown
.bind( this ),
7602 mouseup
: this.onMouseKeyUp
.bind( this ),
7603 keydown
: this.onMouseKeyDown
.bind( this ),
7604 keyup
: this.onMouseKeyUp
.bind( this ),
7605 focus
: this.onMouseOverFocus
.bind( this ),
7606 blur
: this.onMouseOutBlur
.bind( this ),
7607 mouseover
: this.onMouseOverFocus
.bind( this ),
7608 mouseout
: this.onMouseOutBlur
.bind( this )
7610 this.toolbar
.getToolFactory().connect( this, { register
: 'onToolFactoryRegister' } );
7611 this.aggregate( { disable
: 'itemDisable' } );
7612 this.connect( this, { itemDisable
: 'updateDisabled' } );
7615 this.$group
.addClass( 'oo-ui-toolGroup-tools' );
7617 .addClass( 'oo-ui-toolGroup' )
7618 .append( this.$group
);
7624 OO
.inheritClass( OO
.ui
.ToolGroup
, OO
.ui
.Widget
);
7625 OO
.mixinClass( OO
.ui
.ToolGroup
, OO
.ui
.mixin
.GroupElement
);
7633 /* Static Properties */
7636 * Show labels in tooltips.
7640 * @property {boolean}
7642 OO
.ui
.ToolGroup
.static.titleTooltips
= false;
7645 * Show acceleration labels in tooltips.
7647 * Note: The OOjs UI library does not include an accelerator system, but does contain
7648 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
7649 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
7650 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
7654 * @property {boolean}
7656 OO
.ui
.ToolGroup
.static.accelTooltips
= false;
7659 * Automatically disable the toolgroup when all tools are disabled
7663 * @property {boolean}
7665 OO
.ui
.ToolGroup
.static.autoDisable
= true;
7672 OO
.ui
.ToolGroup
.prototype.isDisabled = function () {
7673 return this.autoDisabled
|| OO
.ui
.ToolGroup
.parent
.prototype.isDisabled
.apply( this, arguments
);
7679 OO
.ui
.ToolGroup
.prototype.updateDisabled = function () {
7680 var i
, item
, allDisabled
= true;
7682 if ( this.constructor.static.autoDisable
) {
7683 for ( i
= this.items
.length
- 1; i
>= 0; i
-- ) {
7684 item
= this.items
[ i
];
7685 if ( !item
.isDisabled() ) {
7686 allDisabled
= false;
7690 this.autoDisabled
= allDisabled
;
7692 OO
.ui
.ToolGroup
.parent
.prototype.updateDisabled
.apply( this, arguments
);
7696 * Handle mouse down and key down events.
7699 * @param {jQuery.Event} e Mouse down or key down event
7701 OO
.ui
.ToolGroup
.prototype.onMouseKeyDown = function ( e
) {
7703 !this.isDisabled() &&
7704 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
7706 this.pressed
= this.getTargetTool( e
);
7707 if ( this.pressed
) {
7708 this.pressed
.setActive( true );
7709 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler
);
7710 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler
);
7717 * Handle captured mouse up and key up events.
7720 * @param {Event} e Mouse up or key up event
7722 OO
.ui
.ToolGroup
.prototype.onCapturedMouseKeyUp = function ( e
) {
7723 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler
);
7724 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler
);
7725 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
7726 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
7727 this.onMouseKeyUp( e
);
7731 * Handle mouse up and key up events.
7734 * @param {jQuery.Event} e Mouse up or key up event
7736 OO
.ui
.ToolGroup
.prototype.onMouseKeyUp = function ( e
) {
7737 var tool
= this.getTargetTool( e
);
7740 !this.isDisabled() && this.pressed
&& this.pressed
=== tool
&&
7741 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
7743 this.pressed
.onSelect();
7744 this.pressed
= null;
7748 this.pressed
= null;
7752 * Handle mouse over and focus events.
7755 * @param {jQuery.Event} e Mouse over or focus event
7757 OO
.ui
.ToolGroup
.prototype.onMouseOverFocus = function ( e
) {
7758 var tool
= this.getTargetTool( e
);
7760 if ( this.pressed
&& this.pressed
=== tool
) {
7761 this.pressed
.setActive( true );
7766 * Handle mouse out and blur events.
7769 * @param {jQuery.Event} e Mouse out or blur event
7771 OO
.ui
.ToolGroup
.prototype.onMouseOutBlur = function ( e
) {
7772 var tool
= this.getTargetTool( e
);
7774 if ( this.pressed
&& this.pressed
=== tool
) {
7775 this.pressed
.setActive( false );
7780 * Get the closest tool to a jQuery.Event.
7782 * Only tool links are considered, which prevents other elements in the tool such as popups from
7783 * triggering tool group interactions.
7786 * @param {jQuery.Event} e
7787 * @return {OO.ui.Tool|null} Tool, `null` if none was found
7789 OO
.ui
.ToolGroup
.prototype.getTargetTool = function ( e
) {
7791 $item
= $( e
.target
).closest( '.oo-ui-tool-link' );
7793 if ( $item
.length
) {
7794 tool
= $item
.parent().data( 'oo-ui-tool' );
7797 return tool
&& !tool
.isDisabled() ? tool
: null;
7801 * Handle tool registry register events.
7803 * If a tool is registered after the group is created, we must repopulate the list to account for:
7805 * - a tool being added that may be included
7806 * - a tool already included being overridden
7809 * @param {string} name Symbolic name of tool
7811 OO
.ui
.ToolGroup
.prototype.onToolFactoryRegister = function () {
7816 * Get the toolbar that contains the toolgroup.
7818 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
7820 OO
.ui
.ToolGroup
.prototype.getToolbar = function () {
7821 return this.toolbar
;
7825 * Add and remove tools based on configuration.
7827 OO
.ui
.ToolGroup
.prototype.populate = function () {
7828 var i
, len
, name
, tool
,
7829 toolFactory
= this.toolbar
.getToolFactory(),
7833 list
= this.toolbar
.getToolFactory().getTools(
7834 this.include
, this.exclude
, this.promote
, this.demote
7837 // Build a list of needed tools
7838 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
7842 toolFactory
.lookup( name
) &&
7843 // Tool is available or is already in this group
7844 ( this.toolbar
.isToolAvailable( name
) || this.tools
[ name
] )
7846 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
7847 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
7848 this.toolbar
.tools
[ name
] = true;
7849 tool
= this.tools
[ name
];
7851 // Auto-initialize tools on first use
7852 this.tools
[ name
] = tool
= toolFactory
.create( name
, this );
7855 this.toolbar
.reserveTool( tool
);
7857 names
[ name
] = true;
7860 // Remove tools that are no longer needed
7861 for ( name
in this.tools
) {
7862 if ( !names
[ name
] ) {
7863 this.tools
[ name
].destroy();
7864 this.toolbar
.releaseTool( this.tools
[ name
] );
7865 remove
.push( this.tools
[ name
] );
7866 delete this.tools
[ name
];
7869 if ( remove
.length
) {
7870 this.removeItems( remove
);
7872 // Update emptiness state
7874 this.$element
.removeClass( 'oo-ui-toolGroup-empty' );
7876 this.$element
.addClass( 'oo-ui-toolGroup-empty' );
7878 // Re-add tools (moving existing ones to new locations)
7879 this.addItems( add
);
7880 // Disabled state may depend on items
7881 this.updateDisabled();
7885 * Destroy toolgroup.
7887 OO
.ui
.ToolGroup
.prototype.destroy = function () {
7891 this.toolbar
.getToolFactory().disconnect( this );
7892 for ( name
in this.tools
) {
7893 this.toolbar
.releaseTool( this.tools
[ name
] );
7894 this.tools
[ name
].disconnect( this ).destroy();
7895 delete this.tools
[ name
];
7897 this.$element
.remove();
7901 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
7902 * consists of a header that contains the dialog title, a body with the message, and a footer that
7903 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
7904 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
7906 * There are two basic types of message dialogs, confirmation and alert:
7908 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
7909 * more details about the consequences.
7910 * - **alert**: the dialog title describes which event occurred and the message provides more information
7911 * about why the event occurred.
7913 * The MessageDialog class specifies two actions: ‘accept’, the primary
7914 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
7915 * passing along the selected action.
7917 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
7920 * // Example: Creating and opening a message dialog window.
7921 * var messageDialog = new OO.ui.MessageDialog();
7923 * // Create and append a window manager.
7924 * var windowManager = new OO.ui.WindowManager();
7925 * $( 'body' ).append( windowManager.$element );
7926 * windowManager.addWindows( [ messageDialog ] );
7927 * // Open the window.
7928 * windowManager.openWindow( messageDialog, {
7929 * title: 'Basic message dialog',
7930 * message: 'This is the message'
7933 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
7936 * @extends OO.ui.Dialog
7939 * @param {Object} [config] Configuration options
7941 OO
.ui
.MessageDialog
= function OoUiMessageDialog( config
) {
7942 // Parent constructor
7943 OO
.ui
.MessageDialog
.parent
.call( this, config
);
7946 this.verticalActionLayout
= null;
7949 this.$element
.addClass( 'oo-ui-messageDialog' );
7954 OO
.inheritClass( OO
.ui
.MessageDialog
, OO
.ui
.Dialog
);
7956 /* Static Properties */
7958 OO
.ui
.MessageDialog
.static.name
= 'message';
7960 OO
.ui
.MessageDialog
.static.size
= 'small';
7962 OO
.ui
.MessageDialog
.static.verbose
= false;
7967 * The title of a confirmation dialog describes what a progressive action will do. The
7968 * title of an alert dialog describes which event occurred.
7972 * @property {jQuery|string|Function|null}
7974 OO
.ui
.MessageDialog
.static.title
= null;
7977 * The message displayed in the dialog body.
7979 * A confirmation message describes the consequences of a progressive action. An alert
7980 * message describes why an event occurred.
7984 * @property {jQuery|string|Function|null}
7986 OO
.ui
.MessageDialog
.static.message
= null;
7988 OO
.ui
.MessageDialog
.static.actions
= [
7989 { action
: 'accept', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-accept' ), flags
: 'primary' },
7990 { action
: 'reject', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-reject' ), flags
: 'safe' }
7998 OO
.ui
.MessageDialog
.prototype.setManager = function ( manager
) {
7999 OO
.ui
.MessageDialog
.parent
.prototype.setManager
.call( this, manager
);
8002 this.manager
.connect( this, {
8012 OO
.ui
.MessageDialog
.prototype.onActionResize = function ( action
) {
8014 return OO
.ui
.MessageDialog
.parent
.prototype.onActionResize
.call( this, action
);
8018 * Handle window resized events.
8022 OO
.ui
.MessageDialog
.prototype.onResize = function () {
8024 dialog
.fitActions();
8025 // Wait for CSS transition to finish and do it again :(
8026 setTimeout( function () {
8027 dialog
.fitActions();
8032 * Toggle action layout between vertical and horizontal.
8036 * @param {boolean} [value] Layout actions vertically, omit to toggle
8039 OO
.ui
.MessageDialog
.prototype.toggleVerticalActionLayout = function ( value
) {
8040 value
= value
=== undefined ? !this.verticalActionLayout
: !!value
;
8042 if ( value
!== this.verticalActionLayout
) {
8043 this.verticalActionLayout
= value
;
8045 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value
)
8046 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value
);
8055 OO
.ui
.MessageDialog
.prototype.getActionProcess = function ( action
) {
8057 return new OO
.ui
.Process( function () {
8058 this.close( { action
: action
} );
8061 return OO
.ui
.MessageDialog
.parent
.prototype.getActionProcess
.call( this, action
);
8067 * @param {Object} [data] Dialog opening data
8068 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8069 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8070 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8071 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8074 OO
.ui
.MessageDialog
.prototype.getSetupProcess = function ( data
) {
8078 return OO
.ui
.MessageDialog
.parent
.prototype.getSetupProcess
.call( this, data
)
8079 .next( function () {
8080 this.title
.setLabel(
8081 data
.title
!== undefined ? data
.title
: this.constructor.static.title
8083 this.message
.setLabel(
8084 data
.message
!== undefined ? data
.message
: this.constructor.static.message
8086 this.message
.$element
.toggleClass(
8087 'oo-ui-messageDialog-message-verbose',
8088 data
.verbose
!== undefined ? data
.verbose
: this.constructor.static.verbose
8096 OO
.ui
.MessageDialog
.prototype.getReadyProcess = function ( data
) {
8100 return OO
.ui
.MessageDialog
.parent
.prototype.getReadyProcess
.call( this, data
)
8101 .next( function () {
8102 // Focus the primary action button
8103 var actions
= this.actions
.get();
8104 actions
= actions
.filter( function ( action
) {
8105 return action
.getFlags().indexOf( 'primary' ) > -1;
8107 if ( actions
.length
> 0 ) {
8108 actions
[0].$button
.focus();
8116 OO
.ui
.MessageDialog
.prototype.getBodyHeight = function () {
8117 var bodyHeight
, oldOverflow
,
8118 $scrollable
= this.container
.$element
;
8120 oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
8121 $scrollable
[ 0 ].style
.overflow
= 'hidden';
8123 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
8125 bodyHeight
= this.text
.$element
.outerHeight( true );
8126 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
8134 OO
.ui
.MessageDialog
.prototype.setDimensions = function ( dim
) {
8135 var $scrollable
= this.container
.$element
;
8136 OO
.ui
.MessageDialog
.parent
.prototype.setDimensions
.call( this, dim
);
8138 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8139 // Need to do it after transition completes (250ms), add 50ms just in case.
8140 setTimeout( function () {
8141 var oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
8142 $scrollable
[ 0 ].style
.overflow
= 'hidden';
8144 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
8146 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
8155 OO
.ui
.MessageDialog
.prototype.initialize = function () {
8157 OO
.ui
.MessageDialog
.parent
.prototype.initialize
.call( this );
8160 this.$actions
= $( '<div>' );
8161 this.container
= new OO
.ui
.PanelLayout( {
8162 scrollable
: true, classes
: [ 'oo-ui-messageDialog-container' ]
8164 this.text
= new OO
.ui
.PanelLayout( {
8165 padded
: true, expanded
: false, classes
: [ 'oo-ui-messageDialog-text' ]
8167 this.message
= new OO
.ui
.LabelWidget( {
8168 classes
: [ 'oo-ui-messageDialog-message' ]
8172 this.title
.$element
.addClass( 'oo-ui-messageDialog-title' );
8173 this.$content
.addClass( 'oo-ui-messageDialog-content' );
8174 this.container
.$element
.append( this.text
.$element
);
8175 this.text
.$element
.append( this.title
.$element
, this.message
.$element
);
8176 this.$body
.append( this.container
.$element
);
8177 this.$actions
.addClass( 'oo-ui-messageDialog-actions' );
8178 this.$foot
.append( this.$actions
);
8184 OO
.ui
.MessageDialog
.prototype.attachActions = function () {
8185 var i
, len
, other
, special
, others
;
8188 OO
.ui
.MessageDialog
.parent
.prototype.attachActions
.call( this );
8190 special
= this.actions
.getSpecial();
8191 others
= this.actions
.getOthers();
8193 if ( special
.safe
) {
8194 this.$actions
.append( special
.safe
.$element
);
8195 special
.safe
.toggleFramed( false );
8197 if ( others
.length
) {
8198 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
8199 other
= others
[ i
];
8200 this.$actions
.append( other
.$element
);
8201 other
.toggleFramed( false );
8204 if ( special
.primary
) {
8205 this.$actions
.append( special
.primary
.$element
);
8206 special
.primary
.toggleFramed( false );
8209 if ( !this.isOpening() ) {
8210 // If the dialog is currently opening, this will be called automatically soon.
8211 // This also calls #fitActions.
8217 * Fit action actions into columns or rows.
8219 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8223 OO
.ui
.MessageDialog
.prototype.fitActions = function () {
8225 previous
= this.verticalActionLayout
,
8226 actions
= this.actions
.get();
8229 this.toggleVerticalActionLayout( false );
8230 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
8231 action
= actions
[ i
];
8232 if ( action
.$element
.innerWidth() < action
.$label
.outerWidth( true ) ) {
8233 this.toggleVerticalActionLayout( true );
8238 // Move the body out of the way of the foot
8239 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
8241 if ( this.verticalActionLayout
!== previous
) {
8242 // We changed the layout, window height might need to be updated.
8248 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8249 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8250 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8251 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8252 * required for each process.
8254 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8255 * processes with an animation. The header contains the dialog title as well as
8256 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8257 * a ‘primary’ action on the right (e.g., ‘Done’).
8259 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8260 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8263 * // Example: Creating and opening a process dialog window.
8264 * function MyProcessDialog( config ) {
8265 * MyProcessDialog.parent.call( this, config );
8267 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8269 * MyProcessDialog.static.title = 'Process dialog';
8270 * MyProcessDialog.static.actions = [
8271 * { action: 'save', label: 'Done', flags: 'primary' },
8272 * { label: 'Cancel', flags: 'safe' }
8275 * MyProcessDialog.prototype.initialize = function () {
8276 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8277 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8278 * 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>' );
8279 * this.$body.append( this.content.$element );
8281 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8282 * var dialog = this;
8284 * return new OO.ui.Process( function () {
8285 * dialog.close( { action: action } );
8288 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8291 * var windowManager = new OO.ui.WindowManager();
8292 * $( 'body' ).append( windowManager.$element );
8294 * var dialog = new MyProcessDialog();
8295 * windowManager.addWindows( [ dialog ] );
8296 * windowManager.openWindow( dialog );
8298 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8302 * @extends OO.ui.Dialog
8305 * @param {Object} [config] Configuration options
8307 OO
.ui
.ProcessDialog
= function OoUiProcessDialog( config
) {
8308 // Parent constructor
8309 OO
.ui
.ProcessDialog
.parent
.call( this, config
);
8312 this.fitOnOpen
= false;
8315 this.$element
.addClass( 'oo-ui-processDialog' );
8320 OO
.inheritClass( OO
.ui
.ProcessDialog
, OO
.ui
.Dialog
);
8325 * Handle dismiss button click events.
8331 OO
.ui
.ProcessDialog
.prototype.onDismissErrorButtonClick = function () {
8336 * Handle retry button click events.
8338 * Hides errors and then tries again.
8342 OO
.ui
.ProcessDialog
.prototype.onRetryButtonClick = function () {
8344 this.executeAction( this.currentAction
);
8350 OO
.ui
.ProcessDialog
.prototype.onActionResize = function ( action
) {
8351 if ( this.actions
.isSpecial( action
) ) {
8354 return OO
.ui
.ProcessDialog
.parent
.prototype.onActionResize
.call( this, action
);
8360 OO
.ui
.ProcessDialog
.prototype.initialize = function () {
8362 OO
.ui
.ProcessDialog
.parent
.prototype.initialize
.call( this );
8365 this.$navigation
= $( '<div>' );
8366 this.$location
= $( '<div>' );
8367 this.$safeActions
= $( '<div>' );
8368 this.$primaryActions
= $( '<div>' );
8369 this.$otherActions
= $( '<div>' );
8370 this.dismissButton
= new OO
.ui
.ButtonWidget( {
8371 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' )
8373 this.retryButton
= new OO
.ui
.ButtonWidget();
8374 this.$errors
= $( '<div>' );
8375 this.$errorsTitle
= $( '<div>' );
8378 this.dismissButton
.connect( this, { click
: 'onDismissErrorButtonClick' } );
8379 this.retryButton
.connect( this, { click
: 'onRetryButtonClick' } );
8382 this.title
.$element
.addClass( 'oo-ui-processDialog-title' );
8384 .append( this.title
.$element
)
8385 .addClass( 'oo-ui-processDialog-location' );
8386 this.$safeActions
.addClass( 'oo-ui-processDialog-actions-safe' );
8387 this.$primaryActions
.addClass( 'oo-ui-processDialog-actions-primary' );
8388 this.$otherActions
.addClass( 'oo-ui-processDialog-actions-other' );
8390 .addClass( 'oo-ui-processDialog-errors-title' )
8391 .text( OO
.ui
.msg( 'ooui-dialog-process-error' ) );
8393 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8394 .append( this.$errorsTitle
, this.dismissButton
.$element
, this.retryButton
.$element
);
8396 .addClass( 'oo-ui-processDialog-content' )
8397 .append( this.$errors
);
8399 .addClass( 'oo-ui-processDialog-navigation' )
8400 .append( this.$safeActions
, this.$location
, this.$primaryActions
);
8401 this.$head
.append( this.$navigation
);
8402 this.$foot
.append( this.$otherActions
);
8408 OO
.ui
.ProcessDialog
.prototype.getActionWidgets = function ( actions
) {
8409 var i
, len
, widgets
= [];
8410 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
8412 new OO
.ui
.ActionWidget( $.extend( { framed
: true }, actions
[ i
] ) )
8421 OO
.ui
.ProcessDialog
.prototype.attachActions = function () {
8422 var i
, len
, other
, special
, others
;
8425 OO
.ui
.ProcessDialog
.parent
.prototype.attachActions
.call( this );
8427 special
= this.actions
.getSpecial();
8428 others
= this.actions
.getOthers();
8429 if ( special
.primary
) {
8430 this.$primaryActions
.append( special
.primary
.$element
);
8432 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
8433 other
= others
[ i
];
8434 this.$otherActions
.append( other
.$element
);
8436 if ( special
.safe
) {
8437 this.$safeActions
.append( special
.safe
.$element
);
8441 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
8447 OO
.ui
.ProcessDialog
.prototype.executeAction = function ( action
) {
8449 return OO
.ui
.ProcessDialog
.parent
.prototype.executeAction
.call( this, action
)
8450 .fail( function ( errors
) {
8451 process
.showErrors( errors
|| [] );
8458 OO
.ui
.ProcessDialog
.prototype.setDimensions = function () {
8460 OO
.ui
.ProcessDialog
.parent
.prototype.setDimensions
.apply( this, arguments
);
8466 * Fit label between actions.
8471 OO
.ui
.ProcessDialog
.prototype.fitLabel = function () {
8472 var safeWidth
, primaryWidth
, biggerWidth
, labelWidth
, navigationWidth
, leftWidth
, rightWidth
,
8473 size
= this.getSizeProperties();
8475 if ( typeof size
.width
!== 'number' ) {
8476 if ( this.isOpened() ) {
8477 navigationWidth
= this.$head
.width() - 20;
8478 } else if ( this.isOpening() ) {
8479 if ( !this.fitOnOpen
) {
8480 // Size is relative and the dialog isn't open yet, so wait.
8481 this.manager
.opening
.done( this.fitLabel
.bind( this ) );
8482 this.fitOnOpen
= true;
8489 navigationWidth
= size
.width
- 20;
8492 safeWidth
= this.$safeActions
.is( ':visible' ) ? this.$safeActions
.width() : 0;
8493 primaryWidth
= this.$primaryActions
.is( ':visible' ) ? this.$primaryActions
.width() : 0;
8494 biggerWidth
= Math
.max( safeWidth
, primaryWidth
);
8496 labelWidth
= this.title
.$element
.width();
8498 if ( 2 * biggerWidth
+ labelWidth
< navigationWidth
) {
8499 // We have enough space to center the label
8500 leftWidth
= rightWidth
= biggerWidth
;
8502 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
8503 if ( this.getDir() === 'ltr' ) {
8504 leftWidth
= safeWidth
;
8505 rightWidth
= primaryWidth
;
8507 leftWidth
= primaryWidth
;
8508 rightWidth
= safeWidth
;
8512 this.$location
.css( { paddingLeft
: leftWidth
, paddingRight
: rightWidth
} );
8518 * Handle errors that occurred during accept or reject processes.
8521 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
8523 OO
.ui
.ProcessDialog
.prototype.showErrors = function ( errors
) {
8524 var i
, len
, $item
, actions
,
8530 if ( errors
instanceof OO
.ui
.Error
) {
8531 errors
= [ errors
];
8534 for ( i
= 0, len
= errors
.length
; i
< len
; i
++ ) {
8535 if ( !errors
[ i
].isRecoverable() ) {
8536 recoverable
= false;
8538 if ( errors
[ i
].isWarning() ) {
8541 $item
= $( '<div>' )
8542 .addClass( 'oo-ui-processDialog-error' )
8543 .append( errors
[ i
].getMessage() );
8544 items
.push( $item
[ 0 ] );
8546 this.$errorItems
= $( items
);
8547 if ( recoverable
) {
8548 abilities
[this.currentAction
] = true;
8549 // Copy the flags from the first matching action
8550 actions
= this.actions
.get( { actions
: this.currentAction
} );
8551 if ( actions
.length
) {
8552 this.retryButton
.clearFlags().setFlags( actions
[0].getFlags() );
8555 abilities
[this.currentAction
] = false;
8556 this.actions
.setAbilities( abilities
);
8559 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-continue' ) );
8561 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-retry' ) );
8563 this.retryButton
.toggle( recoverable
);
8564 this.$errorsTitle
.after( this.$errorItems
);
8565 this.$errors
.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
8573 OO
.ui
.ProcessDialog
.prototype.hideErrors = function () {
8574 this.$errors
.addClass( 'oo-ui-element-hidden' );
8575 if ( this.$errorItems
) {
8576 this.$errorItems
.remove();
8577 this.$errorItems
= null;
8584 OO
.ui
.ProcessDialog
.prototype.getTeardownProcess = function ( data
) {
8586 return OO
.ui
.ProcessDialog
.parent
.prototype.getTeardownProcess
.call( this, data
)
8587 .first( function () {
8588 // Make sure to hide errors
8590 this.fitOnOpen
= false;
8595 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8596 * which is a widget that is specified by reference before any optional configuration settings.
8598 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8600 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8601 * A left-alignment is used for forms with many fields.
8602 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8603 * A right-alignment is used for long but familiar forms which users tab through,
8604 * verifying the current field with a quick glance at the label.
8605 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8606 * that users fill out from top to bottom.
8607 * - **inline**: The label is placed after the field-widget and aligned to the left.
8608 * An inline-alignment is best used with checkboxes or radio buttons.
8610 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
8611 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
8613 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8615 * @extends OO.ui.Layout
8616 * @mixins OO.ui.mixin.LabelElement
8617 * @mixins OO.ui.mixin.TitledElement
8620 * @param {OO.ui.Widget} fieldWidget Field widget
8621 * @param {Object} [config] Configuration options
8622 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8623 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
8624 * The array may contain strings or OO.ui.HtmlSnippet instances.
8625 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
8626 * The array may contain strings or OO.ui.HtmlSnippet instances.
8627 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
8628 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
8629 * For important messages, you are advised to use `notices`, as they are always shown.
8631 * @throws {Error} An error is thrown if no widget is specified
8633 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
8634 // Allow passing positional parameters inside the config object
8635 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
8636 config
= fieldWidget
;
8637 fieldWidget
= config
.fieldWidget
;
8640 // Make sure we have required constructor arguments
8641 if ( fieldWidget
=== undefined ) {
8642 throw new Error( 'Widget not found' );
8645 var hasInputWidget
= fieldWidget
.constructor.static.supportsSimpleLabel
,
8648 // Configuration initialization
8649 config
= $.extend( { align
: 'left' }, config
);
8651 // Parent constructor
8652 OO
.ui
.FieldLayout
.parent
.call( this, config
);
8654 // Mixin constructors
8655 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8656 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
8659 this.fieldWidget
= fieldWidget
;
8660 this.errors
= config
.errors
|| [];
8661 this.notices
= config
.notices
|| [];
8662 this.$field
= $( '<div>' );
8663 this.$messages
= $( '<ul>' );
8664 this.$body
= $( '<' + ( hasInputWidget
? 'label' : 'div' ) + '>' );
8666 if ( config
.help
) {
8667 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
8668 classes
: [ 'oo-ui-fieldLayout-help' ],
8674 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
8675 div
.html( config
.help
.toString() );
8677 div
.text( config
.help
);
8679 this.popupButtonWidget
.getPopup().$body
.append(
8680 div
.addClass( 'oo-ui-fieldLayout-help-content' )
8682 this.$help
= this.popupButtonWidget
.$element
;
8684 this.$help
= $( [] );
8688 if ( hasInputWidget
) {
8689 this.$label
.on( 'click', this.onLabelClick
.bind( this ) );
8691 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
8695 .addClass( 'oo-ui-fieldLayout' )
8696 .append( this.$help
, this.$body
);
8697 if ( this.errors
.length
|| this.notices
.length
) {
8698 this.$element
.append( this.$messages
);
8700 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
8701 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
8703 .addClass( 'oo-ui-fieldLayout-field' )
8704 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget
.isDisabled() )
8705 .append( this.fieldWidget
.$element
);
8707 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
8708 this.$messages
.append( this.makeMessage( 'notice', this.notices
[i
] ) );
8710 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
8711 this.$messages
.append( this.makeMessage( 'error', this.errors
[i
] ) );
8714 this.setAlignment( config
.align
);
8719 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
8720 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
8721 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
8726 * Handle field disable events.
8729 * @param {boolean} value Field is disabled
8731 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
8732 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
8736 * Handle label mouse click events.
8739 * @param {jQuery.Event} e Mouse click event
8741 OO
.ui
.FieldLayout
.prototype.onLabelClick = function () {
8742 this.fieldWidget
.simulateLabelClick();
8747 * Get the widget contained by the field.
8749 * @return {OO.ui.Widget} Field widget
8751 OO
.ui
.FieldLayout
.prototype.getField = function () {
8752 return this.fieldWidget
;
8756 * @param {string} kind 'error' or 'notice'
8757 * @param {string|OO.ui.HtmlSnippet} text
8760 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
8761 var $listItem
, $icon
, message
;
8762 $listItem
= $( '<li>' );
8763 if ( kind
=== 'error' ) {
8764 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
8765 } else if ( kind
=== 'notice' ) {
8766 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
8770 message
= new OO
.ui
.LabelWidget( { label
: text
} );
8772 .append( $icon
, message
.$element
)
8773 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
8778 * Set the field alignment mode.
8781 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
8784 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
8785 if ( value
!== this.align
) {
8786 // Default to 'left'
8787 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
8791 if ( value
=== 'inline' ) {
8792 this.$body
.append( this.$field
, this.$label
);
8794 this.$body
.append( this.$label
, this.$field
);
8796 // Set classes. The following classes can be used here:
8797 // * oo-ui-fieldLayout-align-left
8798 // * oo-ui-fieldLayout-align-right
8799 // * oo-ui-fieldLayout-align-top
8800 // * oo-ui-fieldLayout-align-inline
8802 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
8804 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
8812 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
8813 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
8814 * is required and is specified before any optional configuration settings.
8816 * Labels can be aligned in one of four ways:
8818 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8819 * A left-alignment is used for forms with many fields.
8820 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8821 * A right-alignment is used for long but familiar forms which users tab through,
8822 * verifying the current field with a quick glance at the label.
8823 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8824 * that users fill out from top to bottom.
8825 * - **inline**: The label is placed after the field-widget and aligned to the left.
8826 * An inline-alignment is best used with checkboxes or radio buttons.
8828 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
8829 * text is specified.
8832 * // Example of an ActionFieldLayout
8833 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
8834 * new OO.ui.TextInputWidget( {
8835 * placeholder: 'Field widget'
8837 * new OO.ui.ButtonWidget( {
8841 * label: 'An ActionFieldLayout. This label is aligned top',
8843 * help: 'This is help text'
8847 * $( 'body' ).append( actionFieldLayout.$element );
8851 * @extends OO.ui.FieldLayout
8854 * @param {OO.ui.Widget} fieldWidget Field widget
8855 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
8857 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
8858 // Allow passing positional parameters inside the config object
8859 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
8860 config
= fieldWidget
;
8861 fieldWidget
= config
.fieldWidget
;
8862 buttonWidget
= config
.buttonWidget
;
8865 // Parent constructor
8866 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
8869 this.buttonWidget
= buttonWidget
;
8870 this.$button
= $( '<div>' );
8871 this.$input
= $( '<div>' );
8875 .addClass( 'oo-ui-actionFieldLayout' );
8877 .addClass( 'oo-ui-actionFieldLayout-button' )
8878 .append( this.buttonWidget
.$element
);
8880 .addClass( 'oo-ui-actionFieldLayout-input' )
8881 .append( this.fieldWidget
.$element
);
8883 .append( this.$input
, this.$button
);
8888 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
8891 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
8892 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
8893 * configured with a label as well. For more information and examples,
8894 * please see the [OOjs UI documentation on MediaWiki][1].
8897 * // Example of a fieldset layout
8898 * var input1 = new OO.ui.TextInputWidget( {
8899 * placeholder: 'A text input field'
8902 * var input2 = new OO.ui.TextInputWidget( {
8903 * placeholder: 'A text input field'
8906 * var fieldset = new OO.ui.FieldsetLayout( {
8907 * label: 'Example of a fieldset layout'
8910 * fieldset.addItems( [
8911 * new OO.ui.FieldLayout( input1, {
8912 * label: 'Field One'
8914 * new OO.ui.FieldLayout( input2, {
8915 * label: 'Field Two'
8918 * $( 'body' ).append( fieldset.$element );
8920 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8923 * @extends OO.ui.Layout
8924 * @mixins OO.ui.mixin.IconElement
8925 * @mixins OO.ui.mixin.LabelElement
8926 * @mixins OO.ui.mixin.GroupElement
8929 * @param {Object} [config] Configuration options
8930 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
8932 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
8933 // Configuration initialization
8934 config
= config
|| {};
8936 // Parent constructor
8937 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
8939 // Mixin constructors
8940 OO
.ui
.mixin
.IconElement
.call( this, config
);
8941 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8942 OO
.ui
.mixin
.GroupElement
.call( this, config
);
8944 if ( config
.help
) {
8945 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
8946 classes
: [ 'oo-ui-fieldsetLayout-help' ],
8951 this.popupButtonWidget
.getPopup().$body
.append(
8953 .text( config
.help
)
8954 .addClass( 'oo-ui-fieldsetLayout-help-content' )
8956 this.$help
= this.popupButtonWidget
.$element
;
8958 this.$help
= $( [] );
8963 .addClass( 'oo-ui-fieldsetLayout' )
8964 .prepend( this.$help
, this.$icon
, this.$label
, this.$group
);
8965 if ( Array
.isArray( config
.items
) ) {
8966 this.addItems( config
.items
);
8972 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
8973 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
8974 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
8975 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
8978 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
8979 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
8980 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
8981 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
8983 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
8984 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
8985 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
8986 * some fancier controls. Some controls have both regular and InputWidget variants, for example
8987 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
8988 * often have simplified APIs to match the capabilities of HTML forms.
8989 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
8991 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
8992 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8995 * // Example of a form layout that wraps a fieldset layout
8996 * var input1 = new OO.ui.TextInputWidget( {
8997 * placeholder: 'Username'
8999 * var input2 = new OO.ui.TextInputWidget( {
9000 * placeholder: 'Password',
9003 * var submit = new OO.ui.ButtonInputWidget( {
9007 * var fieldset = new OO.ui.FieldsetLayout( {
9008 * label: 'A form layout'
9010 * fieldset.addItems( [
9011 * new OO.ui.FieldLayout( input1, {
9012 * label: 'Username',
9015 * new OO.ui.FieldLayout( input2, {
9016 * label: 'Password',
9019 * new OO.ui.FieldLayout( submit )
9021 * var form = new OO.ui.FormLayout( {
9022 * items: [ fieldset ],
9023 * action: '/api/formhandler',
9026 * $( 'body' ).append( form.$element );
9029 * @extends OO.ui.Layout
9030 * @mixins OO.ui.mixin.GroupElement
9033 * @param {Object} [config] Configuration options
9034 * @cfg {string} [method] HTML form `method` attribute
9035 * @cfg {string} [action] HTML form `action` attribute
9036 * @cfg {string} [enctype] HTML form `enctype` attribute
9037 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9039 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
9040 // Configuration initialization
9041 config
= config
|| {};
9043 // Parent constructor
9044 OO
.ui
.FormLayout
.parent
.call( this, config
);
9046 // Mixin constructors
9047 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
9050 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
9052 // Make sure the action is safe
9053 if ( config
.action
!== undefined && !OO
.ui
.isSafeUrl( config
.action
) ) {
9054 throw new Error( 'Potentially unsafe action provided: ' + config
.action
);
9059 .addClass( 'oo-ui-formLayout' )
9061 method
: config
.method
,
9062 action
: config
.action
,
9063 enctype
: config
.enctype
9065 if ( Array
.isArray( config
.items
) ) {
9066 this.addItems( config
.items
);
9072 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
9073 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
9078 * A 'submit' event is emitted when the form is submitted.
9083 /* Static Properties */
9085 OO
.ui
.FormLayout
.static.tagName
= 'form';
9090 * Handle form submit events.
9093 * @param {jQuery.Event} e Submit event
9096 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
9097 if ( this.emit( 'submit' ) ) {
9103 * 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)
9104 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9107 * var menuLayout = new OO.ui.MenuLayout( {
9110 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9111 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9112 * select = new OO.ui.SelectWidget( {
9114 * new OO.ui.OptionWidget( {
9118 * new OO.ui.OptionWidget( {
9122 * new OO.ui.OptionWidget( {
9126 * new OO.ui.OptionWidget( {
9131 * } ).on( 'select', function ( item ) {
9132 * menuLayout.setMenuPosition( item.getData() );
9135 * menuLayout.$menu.append(
9136 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9138 * menuLayout.$content.append(
9139 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9141 * $( 'body' ).append( menuLayout.$element );
9143 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9144 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9145 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9148 * .oo-ui-menuLayout-menu {
9152 * .oo-ui-menuLayout-content {
9160 * @extends OO.ui.Layout
9163 * @param {Object} [config] Configuration options
9164 * @cfg {boolean} [showMenu=true] Show menu
9165 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9167 OO
.ui
.MenuLayout
= function OoUiMenuLayout( config
) {
9168 // Configuration initialization
9169 config
= $.extend( {
9171 menuPosition
: 'before'
9174 // Parent constructor
9175 OO
.ui
.MenuLayout
.parent
.call( this, config
);
9180 * @property {jQuery}
9182 this.$menu
= $( '<div>' );
9186 * @property {jQuery}
9188 this.$content
= $( '<div>' );
9192 .addClass( 'oo-ui-menuLayout-menu' );
9193 this.$content
.addClass( 'oo-ui-menuLayout-content' );
9195 .addClass( 'oo-ui-menuLayout' )
9196 .append( this.$content
, this.$menu
);
9197 this.setMenuPosition( config
.menuPosition
);
9198 this.toggleMenu( config
.showMenu
);
9203 OO
.inheritClass( OO
.ui
.MenuLayout
, OO
.ui
.Layout
);
9210 * @param {boolean} showMenu Show menu, omit to toggle
9213 OO
.ui
.MenuLayout
.prototype.toggleMenu = function ( showMenu
) {
9214 showMenu
= showMenu
=== undefined ? !this.showMenu
: !!showMenu
;
9216 if ( this.showMenu
!== showMenu
) {
9217 this.showMenu
= showMenu
;
9219 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu
)
9220 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu
);
9227 * Check if menu is visible
9229 * @return {boolean} Menu is visible
9231 OO
.ui
.MenuLayout
.prototype.isMenuVisible = function () {
9232 return this.showMenu
;
9236 * Set menu position.
9238 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9239 * @throws {Error} If position value is not supported
9242 OO
.ui
.MenuLayout
.prototype.setMenuPosition = function ( position
) {
9243 this.$element
.removeClass( 'oo-ui-menuLayout-' + this.menuPosition
);
9244 this.menuPosition
= position
;
9245 this.$element
.addClass( 'oo-ui-menuLayout-' + position
);
9251 * Get menu position.
9253 * @return {string} Menu position
9255 OO
.ui
.MenuLayout
.prototype.getMenuPosition = function () {
9256 return this.menuPosition
;
9260 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9261 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9262 * through the pages and select which one to display. By default, only one page is
9263 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9264 * the booklet layout automatically focuses on the first focusable element, unless the
9265 * default setting is changed. Optionally, booklets can be configured to show
9266 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9269 * // Example of a BookletLayout that contains two PageLayouts.
9271 * function PageOneLayout( name, config ) {
9272 * PageOneLayout.parent.call( this, name, config );
9273 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9275 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9276 * PageOneLayout.prototype.setupOutlineItem = function () {
9277 * this.outlineItem.setLabel( 'Page One' );
9280 * function PageTwoLayout( name, config ) {
9281 * PageTwoLayout.parent.call( this, name, config );
9282 * this.$element.append( '<p>Second page</p>' );
9284 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9285 * PageTwoLayout.prototype.setupOutlineItem = function () {
9286 * this.outlineItem.setLabel( 'Page Two' );
9289 * var page1 = new PageOneLayout( 'one' ),
9290 * page2 = new PageTwoLayout( 'two' );
9292 * var booklet = new OO.ui.BookletLayout( {
9296 * booklet.addPages ( [ page1, page2 ] );
9297 * $( 'body' ).append( booklet.$element );
9300 * @extends OO.ui.MenuLayout
9303 * @param {Object} [config] Configuration options
9304 * @cfg {boolean} [continuous=false] Show all pages, one after another
9305 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9306 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9307 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9309 OO
.ui
.BookletLayout
= function OoUiBookletLayout( config
) {
9310 // Configuration initialization
9311 config
= config
|| {};
9313 // Parent constructor
9314 OO
.ui
.BookletLayout
.parent
.call( this, config
);
9317 this.currentPageName
= null;
9319 this.ignoreFocus
= false;
9320 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
9321 this.$content
.append( this.stackLayout
.$element
);
9322 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
9323 this.outlineVisible
= false;
9324 this.outlined
= !!config
.outlined
;
9325 if ( this.outlined
) {
9326 this.editable
= !!config
.editable
;
9327 this.outlineControlsWidget
= null;
9328 this.outlineSelectWidget
= new OO
.ui
.OutlineSelectWidget();
9329 this.outlinePanel
= new OO
.ui
.PanelLayout( { scrollable
: true } );
9330 this.$menu
.append( this.outlinePanel
.$element
);
9331 this.outlineVisible
= true;
9332 if ( this.editable
) {
9333 this.outlineControlsWidget
= new OO
.ui
.OutlineControlsWidget(
9334 this.outlineSelectWidget
9338 this.toggleMenu( this.outlined
);
9341 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
9342 if ( this.outlined
) {
9343 this.outlineSelectWidget
.connect( this, { select
: 'onOutlineSelectWidgetSelect' } );
9345 if ( this.autoFocus
) {
9346 // Event 'focus' does not bubble, but 'focusin' does
9347 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
9351 this.$element
.addClass( 'oo-ui-bookletLayout' );
9352 this.stackLayout
.$element
.addClass( 'oo-ui-bookletLayout-stackLayout' );
9353 if ( this.outlined
) {
9354 this.outlinePanel
.$element
9355 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
9356 .append( this.outlineSelectWidget
.$element
);
9357 if ( this.editable
) {
9358 this.outlinePanel
.$element
9359 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
9360 .append( this.outlineControlsWidget
.$element
);
9367 OO
.inheritClass( OO
.ui
.BookletLayout
, OO
.ui
.MenuLayout
);
9372 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
9374 * @param {OO.ui.PageLayout} page Current page
9378 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
9381 * @param {OO.ui.PageLayout[]} page Added pages
9382 * @param {number} index Index pages were added at
9386 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
9387 * {@link #removePages removed} from the booklet.
9390 * @param {OO.ui.PageLayout[]} pages Removed pages
9396 * Handle stack layout focus.
9399 * @param {jQuery.Event} e Focusin event
9401 OO
.ui
.BookletLayout
.prototype.onStackLayoutFocus = function ( e
) {
9404 // Find the page that an element was focused within
9405 $target
= $( e
.target
).closest( '.oo-ui-pageLayout' );
9406 for ( name
in this.pages
) {
9407 // Check for page match, exclude current page to find only page changes
9408 if ( this.pages
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentPageName
) {
9409 this.setPage( name
);
9416 * Handle stack layout set events.
9419 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
9421 OO
.ui
.BookletLayout
.prototype.onStackLayoutSet = function ( page
) {
9424 page
.scrollElementIntoView( { complete: function () {
9425 if ( layout
.autoFocus
) {
9433 * Focus the first input in the current page.
9435 * If no page is selected, the first selectable page will be selected.
9436 * If the focus is already in an element on the current page, nothing will happen.
9437 * @param {number} [itemIndex] A specific item to focus on
9439 OO
.ui
.BookletLayout
.prototype.focus = function ( itemIndex
) {
9441 items
= this.stackLayout
.getItems();
9443 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
9444 page
= items
[ itemIndex
];
9446 page
= this.stackLayout
.getCurrentItem();
9449 if ( !page
&& this.outlined
) {
9450 this.selectFirstSelectablePage();
9451 page
= this.stackLayout
.getCurrentItem();
9456 // Only change the focus if is not already in the current page
9457 if ( !page
.$element
.find( ':focus' ).length
) {
9458 $input
= page
.$element
.find( ':input:first' );
9459 if ( $input
.length
) {
9460 $input
[ 0 ].focus();
9466 * Find the first focusable input in the booklet layout and focus
9469 OO
.ui
.BookletLayout
.prototype.focusFirstFocusable = function () {
9472 items
= this.stackLayout
.getItems(),
9473 checkAndFocus = function () {
9474 if ( OO
.ui
.isFocusableElement( $( this ) ) ) {
9481 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
9485 // Find all potentially focusable elements in the item
9486 // and check if they are focusable
9488 .find( 'input, select, textarea, button, object' )
9489 /* jshint loopfunc:true */
9490 .each( checkAndFocus
);
9495 * Handle outline widget select events.
9498 * @param {OO.ui.OptionWidget|null} item Selected item
9500 OO
.ui
.BookletLayout
.prototype.onOutlineSelectWidgetSelect = function ( item
) {
9502 this.setPage( item
.getData() );
9507 * Check if booklet has an outline.
9509 * @return {boolean} Booklet has an outline
9511 OO
.ui
.BookletLayout
.prototype.isOutlined = function () {
9512 return this.outlined
;
9516 * Check if booklet has editing controls.
9518 * @return {boolean} Booklet is editable
9520 OO
.ui
.BookletLayout
.prototype.isEditable = function () {
9521 return this.editable
;
9525 * Check if booklet has a visible outline.
9527 * @return {boolean} Outline is visible
9529 OO
.ui
.BookletLayout
.prototype.isOutlineVisible = function () {
9530 return this.outlined
&& this.outlineVisible
;
9534 * Hide or show the outline.
9536 * @param {boolean} [show] Show outline, omit to invert current state
9539 OO
.ui
.BookletLayout
.prototype.toggleOutline = function ( show
) {
9540 if ( this.outlined
) {
9541 show
= show
=== undefined ? !this.outlineVisible
: !!show
;
9542 this.outlineVisible
= show
;
9543 this.toggleMenu( show
);
9550 * Get the page closest to the specified page.
9552 * @param {OO.ui.PageLayout} page Page to use as a reference point
9553 * @return {OO.ui.PageLayout|null} Page closest to the specified page
9555 OO
.ui
.BookletLayout
.prototype.getClosestPage = function ( page
) {
9556 var next
, prev
, level
,
9557 pages
= this.stackLayout
.getItems(),
9558 index
= $.inArray( page
, pages
);
9560 if ( index
!== -1 ) {
9561 next
= pages
[ index
+ 1 ];
9562 prev
= pages
[ index
- 1 ];
9563 // Prefer adjacent pages at the same level
9564 if ( this.outlined
) {
9565 level
= this.outlineSelectWidget
.getItemFromData( page
.getName() ).getLevel();
9568 level
=== this.outlineSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
9574 level
=== this.outlineSelectWidget
.getItemFromData( next
.getName() ).getLevel()
9580 return prev
|| next
|| null;
9584 * Get the outline widget.
9586 * If the booklet is not outlined, the method will return `null`.
9588 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
9590 OO
.ui
.BookletLayout
.prototype.getOutline = function () {
9591 return this.outlineSelectWidget
;
9595 * Get the outline controls widget.
9597 * If the outline is not editable, the method will return `null`.
9599 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
9601 OO
.ui
.BookletLayout
.prototype.getOutlineControls = function () {
9602 return this.outlineControlsWidget
;
9606 * Get a page by its symbolic name.
9608 * @param {string} name Symbolic name of page
9609 * @return {OO.ui.PageLayout|undefined} Page, if found
9611 OO
.ui
.BookletLayout
.prototype.getPage = function ( name
) {
9612 return this.pages
[ name
];
9616 * Get the current page.
9618 * @return {OO.ui.PageLayout|undefined} Current page, if found
9620 OO
.ui
.BookletLayout
.prototype.getCurrentPage = function () {
9621 var name
= this.getCurrentPageName();
9622 return name
? this.getPage( name
) : undefined;
9626 * Get the symbolic name of the current page.
9628 * @return {string|null} Symbolic name of the current page
9630 OO
.ui
.BookletLayout
.prototype.getCurrentPageName = function () {
9631 return this.currentPageName
;
9635 * Add pages to the booklet layout
9637 * When pages are added with the same names as existing pages, the existing pages will be
9638 * automatically removed before the new pages are added.
9640 * @param {OO.ui.PageLayout[]} pages Pages to add
9641 * @param {number} index Index of the insertion point
9645 OO
.ui
.BookletLayout
.prototype.addPages = function ( pages
, index
) {
9646 var i
, len
, name
, page
, item
, currentIndex
,
9647 stackLayoutPages
= this.stackLayout
.getItems(),
9651 // Remove pages with same names
9652 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9654 name
= page
.getName();
9656 if ( Object
.prototype.hasOwnProperty
.call( this.pages
, name
) ) {
9657 // Correct the insertion index
9658 currentIndex
= $.inArray( this.pages
[ name
], stackLayoutPages
);
9659 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
9662 remove
.push( this.pages
[ name
] );
9665 if ( remove
.length
) {
9666 this.removePages( remove
);
9670 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9672 name
= page
.getName();
9673 this.pages
[ page
.getName() ] = page
;
9674 if ( this.outlined
) {
9675 item
= new OO
.ui
.OutlineOptionWidget( { data
: name
} );
9676 page
.setOutlineItem( item
);
9681 if ( this.outlined
&& items
.length
) {
9682 this.outlineSelectWidget
.addItems( items
, index
);
9683 this.selectFirstSelectablePage();
9685 this.stackLayout
.addItems( pages
, index
);
9686 this.emit( 'add', pages
, index
);
9692 * Remove the specified pages from the booklet layout.
9694 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
9696 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
9700 OO
.ui
.BookletLayout
.prototype.removePages = function ( pages
) {
9701 var i
, len
, name
, page
,
9704 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9706 name
= page
.getName();
9707 delete this.pages
[ name
];
9708 if ( this.outlined
) {
9709 items
.push( this.outlineSelectWidget
.getItemFromData( name
) );
9710 page
.setOutlineItem( null );
9713 if ( this.outlined
&& items
.length
) {
9714 this.outlineSelectWidget
.removeItems( items
);
9715 this.selectFirstSelectablePage();
9717 this.stackLayout
.removeItems( pages
);
9718 this.emit( 'remove', pages
);
9724 * Clear all pages from the booklet layout.
9726 * To remove only a subset of pages from the booklet, use the #removePages method.
9731 OO
.ui
.BookletLayout
.prototype.clearPages = function () {
9733 pages
= this.stackLayout
.getItems();
9736 this.currentPageName
= null;
9737 if ( this.outlined
) {
9738 this.outlineSelectWidget
.clearItems();
9739 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9740 pages
[ i
].setOutlineItem( null );
9743 this.stackLayout
.clearItems();
9745 this.emit( 'remove', pages
);
9751 * Set the current page by symbolic name.
9754 * @param {string} name Symbolic name of page
9756 OO
.ui
.BookletLayout
.prototype.setPage = function ( name
) {
9759 page
= this.pages
[ name
];
9761 if ( name
!== this.currentPageName
) {
9762 if ( this.outlined
) {
9763 selectedItem
= this.outlineSelectWidget
.getSelectedItem();
9764 if ( selectedItem
&& selectedItem
.getData() !== name
) {
9765 this.outlineSelectWidget
.selectItemByData( name
);
9769 if ( this.currentPageName
&& this.pages
[ this.currentPageName
] ) {
9770 this.pages
[ this.currentPageName
].setActive( false );
9771 // Blur anything focused if the next page doesn't have anything focusable - this
9772 // is not needed if the next page has something focusable because once it is focused
9773 // this blur happens automatically
9774 if ( this.autoFocus
&& !page
.$element
.find( ':input' ).length
) {
9775 $focused
= this.pages
[ this.currentPageName
].$element
.find( ':focus' );
9776 if ( $focused
.length
) {
9777 $focused
[ 0 ].blur();
9781 this.currentPageName
= name
;
9782 this.stackLayout
.setItem( page
);
9783 page
.setActive( true );
9784 this.emit( 'set', page
);
9790 * Select the first selectable page.
9794 OO
.ui
.BookletLayout
.prototype.selectFirstSelectablePage = function () {
9795 if ( !this.outlineSelectWidget
.getSelectedItem() ) {
9796 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getFirstSelectableItem() );
9803 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
9804 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
9805 * select which one to display. By default, only one card is displayed at a time. When a user
9806 * navigates to a new card, the index layout automatically focuses on the first focusable element,
9807 * unless the default setting is changed.
9809 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
9812 * // Example of a IndexLayout that contains two CardLayouts.
9814 * function CardOneLayout( name, config ) {
9815 * CardOneLayout.parent.call( this, name, config );
9816 * this.$element.append( '<p>First card</p>' );
9818 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
9819 * CardOneLayout.prototype.setupTabItem = function () {
9820 * this.tabItem.setLabel( 'Card One' );
9823 * function CardTwoLayout( name, config ) {
9824 * CardTwoLayout.parent.call( this, name, config );
9825 * this.$element.append( '<p>Second card</p>' );
9827 * OO.inheritClass( CardTwoLayout, OO.ui.CardLayout );
9828 * CardTwoLayout.prototype.setupTabItem = function () {
9829 * this.tabItem.setLabel( 'Card Two' );
9832 * var card1 = new CardOneLayout( 'one' ),
9833 * card2 = new CardTwoLayout( 'two' );
9835 * var index = new OO.ui.IndexLayout();
9837 * index.addCards ( [ card1, card2 ] );
9838 * $( 'body' ).append( index.$element );
9841 * @extends OO.ui.MenuLayout
9844 * @param {Object} [config] Configuration options
9845 * @cfg {boolean} [continuous=false] Show all cards, one after another
9846 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
9848 OO
.ui
.IndexLayout
= function OoUiIndexLayout( config
) {
9849 // Configuration initialization
9850 config
= $.extend( {}, config
, { menuPosition
: 'top' } );
9852 // Parent constructor
9853 OO
.ui
.IndexLayout
.parent
.call( this, config
);
9856 this.currentCardName
= null;
9858 this.ignoreFocus
= false;
9859 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
9860 this.$content
.append( this.stackLayout
.$element
);
9861 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
9863 this.tabSelectWidget
= new OO
.ui
.TabSelectWidget();
9864 this.tabPanel
= new OO
.ui
.PanelLayout();
9865 this.$menu
.append( this.tabPanel
.$element
);
9867 this.toggleMenu( true );
9870 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
9871 this.tabSelectWidget
.connect( this, { select
: 'onTabSelectWidgetSelect' } );
9872 if ( this.autoFocus
) {
9873 // Event 'focus' does not bubble, but 'focusin' does
9874 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
9878 this.$element
.addClass( 'oo-ui-indexLayout' );
9879 this.stackLayout
.$element
.addClass( 'oo-ui-indexLayout-stackLayout' );
9880 this.tabPanel
.$element
9881 .addClass( 'oo-ui-indexLayout-tabPanel' )
9882 .append( this.tabSelectWidget
.$element
);
9887 OO
.inheritClass( OO
.ui
.IndexLayout
, OO
.ui
.MenuLayout
);
9892 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
9894 * @param {OO.ui.CardLayout} card Current card
9898 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
9901 * @param {OO.ui.CardLayout[]} card Added cards
9902 * @param {number} index Index cards were added at
9906 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
9907 * {@link #removeCards removed} from the index.
9910 * @param {OO.ui.CardLayout[]} cards Removed cards
9916 * Handle stack layout focus.
9919 * @param {jQuery.Event} e Focusin event
9921 OO
.ui
.IndexLayout
.prototype.onStackLayoutFocus = function ( e
) {
9924 // Find the card that an element was focused within
9925 $target
= $( e
.target
).closest( '.oo-ui-cardLayout' );
9926 for ( name
in this.cards
) {
9927 // Check for card match, exclude current card to find only card changes
9928 if ( this.cards
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentCardName
) {
9929 this.setCard( name
);
9936 * Handle stack layout set events.
9939 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
9941 OO
.ui
.IndexLayout
.prototype.onStackLayoutSet = function ( card
) {
9944 card
.scrollElementIntoView( { complete: function () {
9945 if ( layout
.autoFocus
) {
9953 * Focus the first input in the current card.
9955 * If no card is selected, the first selectable card will be selected.
9956 * If the focus is already in an element on the current card, nothing will happen.
9957 * @param {number} [itemIndex] A specific item to focus on
9959 OO
.ui
.IndexLayout
.prototype.focus = function ( itemIndex
) {
9961 items
= this.stackLayout
.getItems();
9963 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
9964 card
= items
[ itemIndex
];
9966 card
= this.stackLayout
.getCurrentItem();
9970 this.selectFirstSelectableCard();
9971 card
= this.stackLayout
.getCurrentItem();
9976 // Only change the focus if is not already in the current card
9977 if ( !card
.$element
.find( ':focus' ).length
) {
9978 $input
= card
.$element
.find( ':input:first' );
9979 if ( $input
.length
) {
9980 $input
[ 0 ].focus();
9986 * Find the first focusable input in the index layout and focus
9989 OO
.ui
.IndexLayout
.prototype.focusFirstFocusable = function () {
9992 items
= this.stackLayout
.getItems(),
9993 checkAndFocus = function () {
9994 if ( OO
.ui
.isFocusableElement( $( this ) ) ) {
10001 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
10005 // Find all potentially focusable elements in the item
10006 // and check if they are focusable
10008 .find( 'input, select, textarea, button, object' )
10009 .each( checkAndFocus
);
10014 * Handle tab widget select events.
10017 * @param {OO.ui.OptionWidget|null} item Selected item
10019 OO
.ui
.IndexLayout
.prototype.onTabSelectWidgetSelect = function ( item
) {
10021 this.setCard( item
.getData() );
10026 * Get the card closest to the specified card.
10028 * @param {OO.ui.CardLayout} card Card to use as a reference point
10029 * @return {OO.ui.CardLayout|null} Card closest to the specified card
10031 OO
.ui
.IndexLayout
.prototype.getClosestCard = function ( card
) {
10032 var next
, prev
, level
,
10033 cards
= this.stackLayout
.getItems(),
10034 index
= $.inArray( card
, cards
);
10036 if ( index
!== -1 ) {
10037 next
= cards
[ index
+ 1 ];
10038 prev
= cards
[ index
- 1 ];
10039 // Prefer adjacent cards at the same level
10040 level
= this.tabSelectWidget
.getItemFromData( card
.getName() ).getLevel();
10043 level
=== this.tabSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
10049 level
=== this.tabSelectWidget
.getItemFromData( next
.getName() ).getLevel()
10054 return prev
|| next
|| null;
10058 * Get the tabs widget.
10060 * @return {OO.ui.TabSelectWidget} Tabs widget
10062 OO
.ui
.IndexLayout
.prototype.getTabs = function () {
10063 return this.tabSelectWidget
;
10067 * Get a card by its symbolic name.
10069 * @param {string} name Symbolic name of card
10070 * @return {OO.ui.CardLayout|undefined} Card, if found
10072 OO
.ui
.IndexLayout
.prototype.getCard = function ( name
) {
10073 return this.cards
[ name
];
10077 * Get the current card.
10079 * @return {OO.ui.CardLayout|undefined} Current card, if found
10081 OO
.ui
.IndexLayout
.prototype.getCurrentCard = function () {
10082 var name
= this.getCurrentCardName();
10083 return name
? this.getCard( name
) : undefined;
10087 * Get the symbolic name of the current card.
10089 * @return {string|null} Symbolic name of the current card
10091 OO
.ui
.IndexLayout
.prototype.getCurrentCardName = function () {
10092 return this.currentCardName
;
10096 * Add cards to the index layout
10098 * When cards are added with the same names as existing cards, the existing cards will be
10099 * automatically removed before the new cards are added.
10101 * @param {OO.ui.CardLayout[]} cards Cards to add
10102 * @param {number} index Index of the insertion point
10106 OO
.ui
.IndexLayout
.prototype.addCards = function ( cards
, index
) {
10107 var i
, len
, name
, card
, item
, currentIndex
,
10108 stackLayoutCards
= this.stackLayout
.getItems(),
10112 // Remove cards with same names
10113 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10115 name
= card
.getName();
10117 if ( Object
.prototype.hasOwnProperty
.call( this.cards
, name
) ) {
10118 // Correct the insertion index
10119 currentIndex
= $.inArray( this.cards
[ name
], stackLayoutCards
);
10120 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
10123 remove
.push( this.cards
[ name
] );
10126 if ( remove
.length
) {
10127 this.removeCards( remove
);
10131 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10133 name
= card
.getName();
10134 this.cards
[ card
.getName() ] = card
;
10135 item
= new OO
.ui
.TabOptionWidget( { data
: name
} );
10136 card
.setTabItem( item
);
10137 items
.push( item
);
10140 if ( items
.length
) {
10141 this.tabSelectWidget
.addItems( items
, index
);
10142 this.selectFirstSelectableCard();
10144 this.stackLayout
.addItems( cards
, index
);
10145 this.emit( 'add', cards
, index
);
10151 * Remove the specified cards from the index layout.
10153 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10155 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10159 OO
.ui
.IndexLayout
.prototype.removeCards = function ( cards
) {
10160 var i
, len
, name
, card
,
10163 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10165 name
= card
.getName();
10166 delete this.cards
[ name
];
10167 items
.push( this.tabSelectWidget
.getItemFromData( name
) );
10168 card
.setTabItem( null );
10170 if ( items
.length
) {
10171 this.tabSelectWidget
.removeItems( items
);
10172 this.selectFirstSelectableCard();
10174 this.stackLayout
.removeItems( cards
);
10175 this.emit( 'remove', cards
);
10181 * Clear all cards from the index layout.
10183 * To remove only a subset of cards from the index, use the #removeCards method.
10188 OO
.ui
.IndexLayout
.prototype.clearCards = function () {
10190 cards
= this.stackLayout
.getItems();
10193 this.currentCardName
= null;
10194 this.tabSelectWidget
.clearItems();
10195 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10196 cards
[ i
].setTabItem( null );
10198 this.stackLayout
.clearItems();
10200 this.emit( 'remove', cards
);
10206 * Set the current card by symbolic name.
10209 * @param {string} name Symbolic name of card
10211 OO
.ui
.IndexLayout
.prototype.setCard = function ( name
) {
10214 card
= this.cards
[ name
];
10216 if ( name
!== this.currentCardName
) {
10217 selectedItem
= this.tabSelectWidget
.getSelectedItem();
10218 if ( selectedItem
&& selectedItem
.getData() !== name
) {
10219 this.tabSelectWidget
.selectItemByData( name
);
10222 if ( this.currentCardName
&& this.cards
[ this.currentCardName
] ) {
10223 this.cards
[ this.currentCardName
].setActive( false );
10224 // Blur anything focused if the next card doesn't have anything focusable - this
10225 // is not needed if the next card has something focusable because once it is focused
10226 // this blur happens automatically
10227 if ( this.autoFocus
&& !card
.$element
.find( ':input' ).length
) {
10228 $focused
= this.cards
[ this.currentCardName
].$element
.find( ':focus' );
10229 if ( $focused
.length
) {
10230 $focused
[ 0 ].blur();
10234 this.currentCardName
= name
;
10235 this.stackLayout
.setItem( card
);
10236 card
.setActive( true );
10237 this.emit( 'set', card
);
10243 * Select the first selectable card.
10247 OO
.ui
.IndexLayout
.prototype.selectFirstSelectableCard = function () {
10248 if ( !this.tabSelectWidget
.getSelectedItem() ) {
10249 this.tabSelectWidget
.selectItem( this.tabSelectWidget
.getFirstSelectableItem() );
10256 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10257 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10260 * // Example of a panel layout
10261 * var panel = new OO.ui.PanelLayout( {
10265 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10267 * $( 'body' ).append( panel.$element );
10270 * @extends OO.ui.Layout
10273 * @param {Object} [config] Configuration options
10274 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10275 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10276 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10277 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10279 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
10280 // Configuration initialization
10281 config
= $.extend( {
10288 // Parent constructor
10289 OO
.ui
.PanelLayout
.parent
.call( this, config
);
10292 this.$element
.addClass( 'oo-ui-panelLayout' );
10293 if ( config
.scrollable
) {
10294 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
10296 if ( config
.padded
) {
10297 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
10299 if ( config
.expanded
) {
10300 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
10302 if ( config
.framed
) {
10303 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
10309 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
10312 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10313 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10314 * rather extended to include the required content and functionality.
10316 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10317 * item is customized (with a label) using the #setupTabItem method. See
10318 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10321 * @extends OO.ui.PanelLayout
10324 * @param {string} name Unique symbolic name of card
10325 * @param {Object} [config] Configuration options
10327 OO
.ui
.CardLayout
= function OoUiCardLayout( name
, config
) {
10328 // Allow passing positional parameters inside the config object
10329 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
10331 name
= config
.name
;
10334 // Configuration initialization
10335 config
= $.extend( { scrollable
: true }, config
);
10337 // Parent constructor
10338 OO
.ui
.CardLayout
.parent
.call( this, config
);
10342 this.tabItem
= null;
10343 this.active
= false;
10346 this.$element
.addClass( 'oo-ui-cardLayout' );
10351 OO
.inheritClass( OO
.ui
.CardLayout
, OO
.ui
.PanelLayout
);
10356 * An 'active' event is emitted when the card becomes active. Cards become active when they are
10357 * shown in a index layout that is configured to display only one card at a time.
10360 * @param {boolean} active Card is active
10366 * Get the symbolic name of the card.
10368 * @return {string} Symbolic name of card
10370 OO
.ui
.CardLayout
.prototype.getName = function () {
10375 * Check if card is active.
10377 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
10378 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
10380 * @return {boolean} Card is active
10382 OO
.ui
.CardLayout
.prototype.isActive = function () {
10383 return this.active
;
10389 * The tab item allows users to access the card from the index's tab
10390 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
10392 * @return {OO.ui.TabOptionWidget|null} Tab option widget
10394 OO
.ui
.CardLayout
.prototype.getTabItem = function () {
10395 return this.tabItem
;
10399 * Set or unset the tab item.
10401 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
10402 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
10403 * level), use #setupTabItem instead of this method.
10405 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
10408 OO
.ui
.CardLayout
.prototype.setTabItem = function ( tabItem
) {
10409 this.tabItem
= tabItem
|| null;
10411 this.setupTabItem();
10417 * Set up the tab item.
10419 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
10420 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
10421 * the #setTabItem method instead.
10423 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
10426 OO
.ui
.CardLayout
.prototype.setupTabItem = function () {
10431 * Set the card to its 'active' state.
10433 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
10434 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
10435 * context, setting the active state on a card does nothing.
10437 * @param {boolean} value Card is active
10440 OO
.ui
.CardLayout
.prototype.setActive = function ( active
) {
10443 if ( active
!== this.active
) {
10444 this.active
= active
;
10445 this.$element
.toggleClass( 'oo-ui-cardLayout-active', this.active
);
10446 this.emit( 'active', this.active
);
10451 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
10452 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
10453 * rather extended to include the required content and functionality.
10455 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
10456 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
10457 * {@link OO.ui.BookletLayout BookletLayout} for an example.
10460 * @extends OO.ui.PanelLayout
10463 * @param {string} name Unique symbolic name of page
10464 * @param {Object} [config] Configuration options
10466 OO
.ui
.PageLayout
= function OoUiPageLayout( name
, config
) {
10467 // Allow passing positional parameters inside the config object
10468 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
10470 name
= config
.name
;
10473 // Configuration initialization
10474 config
= $.extend( { scrollable
: true }, config
);
10476 // Parent constructor
10477 OO
.ui
.PageLayout
.parent
.call( this, config
);
10481 this.outlineItem
= null;
10482 this.active
= false;
10485 this.$element
.addClass( 'oo-ui-pageLayout' );
10490 OO
.inheritClass( OO
.ui
.PageLayout
, OO
.ui
.PanelLayout
);
10495 * An 'active' event is emitted when the page becomes active. Pages become active when they are
10496 * shown in a booklet layout that is configured to display only one page at a time.
10499 * @param {boolean} active Page is active
10505 * Get the symbolic name of the page.
10507 * @return {string} Symbolic name of page
10509 OO
.ui
.PageLayout
.prototype.getName = function () {
10514 * Check if page is active.
10516 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
10517 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
10519 * @return {boolean} Page is active
10521 OO
.ui
.PageLayout
.prototype.isActive = function () {
10522 return this.active
;
10526 * Get outline item.
10528 * The outline item allows users to access the page from the booklet's outline
10529 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
10531 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
10533 OO
.ui
.PageLayout
.prototype.getOutlineItem = function () {
10534 return this.outlineItem
;
10538 * Set or unset the outline item.
10540 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
10541 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
10542 * level), use #setupOutlineItem instead of this method.
10544 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
10547 OO
.ui
.PageLayout
.prototype.setOutlineItem = function ( outlineItem
) {
10548 this.outlineItem
= outlineItem
|| null;
10549 if ( outlineItem
) {
10550 this.setupOutlineItem();
10556 * Set up the outline item.
10558 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
10559 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
10560 * the #setOutlineItem method instead.
10562 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
10565 OO
.ui
.PageLayout
.prototype.setupOutlineItem = function () {
10570 * Set the page to its 'active' state.
10572 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
10573 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
10574 * context, setting the active state on a page does nothing.
10576 * @param {boolean} value Page is active
10579 OO
.ui
.PageLayout
.prototype.setActive = function ( active
) {
10582 if ( active
!== this.active
) {
10583 this.active
= active
;
10584 this.$element
.toggleClass( 'oo-ui-pageLayout-active', active
);
10585 this.emit( 'active', this.active
);
10590 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
10591 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
10592 * by setting the #continuous option to 'true'.
10595 * // A stack layout with two panels, configured to be displayed continously
10596 * var myStack = new OO.ui.StackLayout( {
10598 * new OO.ui.PanelLayout( {
10599 * $content: $( '<p>Panel One</p>' ),
10603 * new OO.ui.PanelLayout( {
10604 * $content: $( '<p>Panel Two</p>' ),
10611 * $( 'body' ).append( myStack.$element );
10614 * @extends OO.ui.PanelLayout
10615 * @mixins OO.ui.mixin.GroupElement
10618 * @param {Object} [config] Configuration options
10619 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
10620 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
10622 OO
.ui
.StackLayout
= function OoUiStackLayout( config
) {
10623 // Configuration initialization
10624 config
= $.extend( { scrollable
: true }, config
);
10626 // Parent constructor
10627 OO
.ui
.StackLayout
.parent
.call( this, config
);
10629 // Mixin constructors
10630 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
10633 this.currentItem
= null;
10634 this.continuous
= !!config
.continuous
;
10637 this.$element
.addClass( 'oo-ui-stackLayout' );
10638 if ( this.continuous
) {
10639 this.$element
.addClass( 'oo-ui-stackLayout-continuous' );
10641 if ( Array
.isArray( config
.items
) ) {
10642 this.addItems( config
.items
);
10648 OO
.inheritClass( OO
.ui
.StackLayout
, OO
.ui
.PanelLayout
);
10649 OO
.mixinClass( OO
.ui
.StackLayout
, OO
.ui
.mixin
.GroupElement
);
10654 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
10655 * {@link #clearItems cleared} or {@link #setItem displayed}.
10658 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
10664 * Get the current panel.
10666 * @return {OO.ui.Layout|null}
10668 OO
.ui
.StackLayout
.prototype.getCurrentItem = function () {
10669 return this.currentItem
;
10673 * Unset the current item.
10676 * @param {OO.ui.StackLayout} layout
10679 OO
.ui
.StackLayout
.prototype.unsetCurrentItem = function () {
10680 var prevItem
= this.currentItem
;
10681 if ( prevItem
=== null ) {
10685 this.currentItem
= null;
10686 this.emit( 'set', null );
10690 * Add panel layouts to the stack layout.
10692 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
10693 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
10696 * @param {OO.ui.Layout[]} items Panels to add
10697 * @param {number} [index] Index of the insertion point
10700 OO
.ui
.StackLayout
.prototype.addItems = function ( items
, index
) {
10701 // Update the visibility
10702 this.updateHiddenState( items
, this.currentItem
);
10705 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
, index
);
10707 if ( !this.currentItem
&& items
.length
) {
10708 this.setItem( items
[ 0 ] );
10715 * Remove the specified panels from the stack layout.
10717 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
10718 * you may wish to use the #clearItems method instead.
10720 * @param {OO.ui.Layout[]} items Panels to remove
10724 OO
.ui
.StackLayout
.prototype.removeItems = function ( items
) {
10726 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
10728 if ( $.inArray( this.currentItem
, items
) !== -1 ) {
10729 if ( this.items
.length
) {
10730 this.setItem( this.items
[ 0 ] );
10732 this.unsetCurrentItem();
10740 * Clear all panels from the stack layout.
10742 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
10743 * a subset of panels, use the #removeItems method.
10748 OO
.ui
.StackLayout
.prototype.clearItems = function () {
10749 this.unsetCurrentItem();
10750 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
10756 * Show the specified panel.
10758 * If another panel is currently displayed, it will be hidden.
10760 * @param {OO.ui.Layout} item Panel to show
10764 OO
.ui
.StackLayout
.prototype.setItem = function ( item
) {
10765 if ( item
!== this.currentItem
) {
10766 this.updateHiddenState( this.items
, item
);
10768 if ( $.inArray( item
, this.items
) !== -1 ) {
10769 this.currentItem
= item
;
10770 this.emit( 'set', item
);
10772 this.unsetCurrentItem();
10780 * Update the visibility of all items in case of non-continuous view.
10782 * Ensure all items are hidden except for the selected one.
10783 * This method does nothing when the stack is continuous.
10786 * @param {OO.ui.Layout[]} items Item list iterate over
10787 * @param {OO.ui.Layout} [selectedItem] Selected item to show
10789 OO
.ui
.StackLayout
.prototype.updateHiddenState = function ( items
, selectedItem
) {
10792 if ( !this.continuous
) {
10793 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
10794 if ( !selectedItem
|| selectedItem
!== items
[ i
] ) {
10795 items
[ i
].$element
.addClass( 'oo-ui-element-hidden' );
10798 if ( selectedItem
) {
10799 selectedItem
.$element
.removeClass( 'oo-ui-element-hidden' );
10805 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
10806 * items), with small margins between them. Convenient when you need to put a number of block-level
10807 * widgets on a single line next to each other.
10809 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
10812 * // HorizontalLayout with a text input and a label
10813 * var layout = new OO.ui.HorizontalLayout( {
10815 * new OO.ui.LabelWidget( { label: 'Label' } ),
10816 * new OO.ui.TextInputWidget( { value: 'Text' } )
10819 * $( 'body' ).append( layout.$element );
10822 * @extends OO.ui.Layout
10823 * @mixins OO.ui.mixin.GroupElement
10826 * @param {Object} [config] Configuration options
10827 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
10829 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
10830 // Configuration initialization
10831 config
= config
|| {};
10833 // Parent constructor
10834 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
10836 // Mixin constructors
10837 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
10840 this.$element
.addClass( 'oo-ui-horizontalLayout' );
10841 if ( Array
.isArray( config
.items
) ) {
10842 this.addItems( config
.items
);
10848 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
10849 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);
10852 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
10853 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
10854 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
10855 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
10858 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
10862 * // Example of a BarToolGroup with two tools
10863 * var toolFactory = new OO.ui.ToolFactory();
10864 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
10865 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
10867 * // We will be placing status text in this element when tools are used
10868 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
10870 * // Define the tools that we're going to place in our toolbar
10872 * // Create a class inheriting from OO.ui.Tool
10873 * function PictureTool() {
10874 * PictureTool.parent.apply( this, arguments );
10876 * OO.inheritClass( PictureTool, OO.ui.Tool );
10877 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
10878 * // of 'icon' and 'title' (displayed icon and text).
10879 * PictureTool.static.name = 'picture';
10880 * PictureTool.static.icon = 'picture';
10881 * PictureTool.static.title = 'Insert picture';
10882 * // Defines the action that will happen when this tool is selected (clicked).
10883 * PictureTool.prototype.onSelect = function () {
10884 * $area.text( 'Picture tool clicked!' );
10885 * // Never display this tool as "active" (selected).
10886 * this.setActive( false );
10888 * // Make this tool available in our toolFactory and thus our toolbar
10889 * toolFactory.register( PictureTool );
10891 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
10892 * // little popup window (a PopupWidget).
10893 * function HelpTool( toolGroup, config ) {
10894 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
10899 * this.popup.$body.append( '<p>I am helpful!</p>' );
10901 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
10902 * HelpTool.static.name = 'help';
10903 * HelpTool.static.icon = 'help';
10904 * HelpTool.static.title = 'Help';
10905 * toolFactory.register( HelpTool );
10907 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
10908 * // used once (but not all defined tools must be used).
10911 * // 'bar' tool groups display tools by icon only
10913 * include: [ 'picture', 'help' ]
10917 * // Create some UI around the toolbar and place it in the document
10918 * var frame = new OO.ui.PanelLayout( {
10922 * var contentFrame = new OO.ui.PanelLayout( {
10926 * frame.$element.append(
10927 * toolbar.$element,
10928 * contentFrame.$element.append( $area )
10930 * $( 'body' ).append( frame.$element );
10932 * // Here is where the toolbar is actually built. This must be done after inserting it into the
10934 * toolbar.initialize();
10936 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
10937 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
10939 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
10942 * @extends OO.ui.ToolGroup
10945 * @param {OO.ui.Toolbar} toolbar
10946 * @param {Object} [config] Configuration options
10948 OO
.ui
.BarToolGroup
= function OoUiBarToolGroup( toolbar
, config
) {
10949 // Allow passing positional parameters inside the config object
10950 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
10952 toolbar
= config
.toolbar
;
10955 // Parent constructor
10956 OO
.ui
.BarToolGroup
.parent
.call( this, toolbar
, config
);
10959 this.$element
.addClass( 'oo-ui-barToolGroup' );
10964 OO
.inheritClass( OO
.ui
.BarToolGroup
, OO
.ui
.ToolGroup
);
10966 /* Static Properties */
10968 OO
.ui
.BarToolGroup
.static.titleTooltips
= true;
10970 OO
.ui
.BarToolGroup
.static.accelTooltips
= true;
10972 OO
.ui
.BarToolGroup
.static.name
= 'bar';
10975 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
10976 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
10977 * optional icon and label. This class can be used for other base classes that also use this functionality.
10981 * @extends OO.ui.ToolGroup
10982 * @mixins OO.ui.mixin.IconElement
10983 * @mixins OO.ui.mixin.IndicatorElement
10984 * @mixins OO.ui.mixin.LabelElement
10985 * @mixins OO.ui.mixin.TitledElement
10986 * @mixins OO.ui.mixin.ClippableElement
10987 * @mixins OO.ui.mixin.TabIndexedElement
10990 * @param {OO.ui.Toolbar} toolbar
10991 * @param {Object} [config] Configuration options
10992 * @cfg {string} [header] Text to display at the top of the popup
10994 OO
.ui
.PopupToolGroup
= function OoUiPopupToolGroup( toolbar
, config
) {
10995 // Allow passing positional parameters inside the config object
10996 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
10998 toolbar
= config
.toolbar
;
11001 // Configuration initialization
11002 config
= config
|| {};
11004 // Parent constructor
11005 OO
.ui
.PopupToolGroup
.parent
.call( this, toolbar
, config
);
11008 this.active
= false;
11009 this.dragging
= false;
11010 this.onBlurHandler
= this.onBlur
.bind( this );
11011 this.$handle
= $( '<span>' );
11013 // Mixin constructors
11014 OO
.ui
.mixin
.IconElement
.call( this, config
);
11015 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
11016 OO
.ui
.mixin
.LabelElement
.call( this, config
);
11017 OO
.ui
.mixin
.TitledElement
.call( this, config
);
11018 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
11019 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
11023 keydown
: this.onHandleMouseKeyDown
.bind( this ),
11024 keyup
: this.onHandleMouseKeyUp
.bind( this ),
11025 mousedown
: this.onHandleMouseKeyDown
.bind( this ),
11026 mouseup
: this.onHandleMouseKeyUp
.bind( this )
11031 .addClass( 'oo-ui-popupToolGroup-handle' )
11032 .append( this.$icon
, this.$label
, this.$indicator
);
11033 // If the pop-up should have a header, add it to the top of the toolGroup.
11034 // Note: If this feature is useful for other widgets, we could abstract it into an
11035 // OO.ui.HeaderedElement mixin constructor.
11036 if ( config
.header
!== undefined ) {
11038 .prepend( $( '<span>' )
11039 .addClass( 'oo-ui-popupToolGroup-header' )
11040 .text( config
.header
)
11044 .addClass( 'oo-ui-popupToolGroup' )
11045 .prepend( this.$handle
);
11050 OO
.inheritClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ToolGroup
);
11051 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.IconElement
);
11052 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.IndicatorElement
);
11053 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.LabelElement
);
11054 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.TitledElement
);
11055 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.ClippableElement
);
11056 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.TabIndexedElement
);
11063 OO
.ui
.PopupToolGroup
.prototype.setDisabled = function () {
11065 OO
.ui
.PopupToolGroup
.parent
.prototype.setDisabled
.apply( this, arguments
);
11067 if ( this.isDisabled() && this.isElementAttached() ) {
11068 this.setActive( false );
11073 * Handle focus being lost.
11075 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11078 * @param {jQuery.Event} e Mouse up or key up event
11080 OO
.ui
.PopupToolGroup
.prototype.onBlur = function ( e
) {
11081 // Only deactivate when clicking outside the dropdown element
11082 if ( $( e
.target
).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element
[ 0 ] ) {
11083 this.setActive( false );
11090 OO
.ui
.PopupToolGroup
.prototype.onMouseKeyUp = function ( e
) {
11091 // Only close toolgroup when a tool was actually selected
11093 !this.isDisabled() && this.pressed
&& this.pressed
=== this.getTargetTool( e
) &&
11094 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11096 this.setActive( false );
11098 return OO
.ui
.PopupToolGroup
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11102 * Handle mouse up and key up events.
11105 * @param {jQuery.Event} e Mouse up or key up event
11107 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyUp = function ( e
) {
11109 !this.isDisabled() &&
11110 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11117 * Handle mouse down and key down events.
11120 * @param {jQuery.Event} e Mouse down or key down event
11122 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyDown = function ( e
) {
11124 !this.isDisabled() &&
11125 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11127 this.setActive( !this.active
);
11133 * Switch into 'active' mode.
11135 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11138 OO
.ui
.PopupToolGroup
.prototype.setActive = function ( value
) {
11139 var containerWidth
, containerLeft
;
11141 if ( this.active
!== value
) {
11142 this.active
= value
;
11144 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler
);
11145 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler
);
11147 this.$clippable
.css( 'left', '' );
11148 // Try anchoring the popup to the left first
11149 this.$element
.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11150 this.toggleClipping( true );
11151 if ( this.isClippedHorizontally() ) {
11152 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11153 this.toggleClipping( false );
11155 .removeClass( 'oo-ui-popupToolGroup-left' )
11156 .addClass( 'oo-ui-popupToolGroup-right' );
11157 this.toggleClipping( true );
11159 if ( this.isClippedHorizontally() ) {
11160 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11161 containerWidth
= this.$clippableContainer
.width();
11162 containerLeft
= this.$clippableContainer
.offset().left
;
11164 this.toggleClipping( false );
11165 this.$element
.removeClass( 'oo-ui-popupToolGroup-right' );
11167 this.$clippable
.css( {
11168 left
: -( this.$element
.offset().left
- containerLeft
),
11169 width
: containerWidth
11173 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler
);
11174 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler
);
11175 this.$element
.removeClass(
11176 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11178 this.toggleClipping( false );
11184 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11185 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11186 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11187 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11188 * with a label, icon, indicator, header, and title.
11190 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11191 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11192 * users to collapse the list again.
11194 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11195 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11196 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11199 * // Example of a ListToolGroup
11200 * var toolFactory = new OO.ui.ToolFactory();
11201 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11202 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11204 * // Configure and register two tools
11205 * function SettingsTool() {
11206 * SettingsTool.parent.apply( this, arguments );
11208 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11209 * SettingsTool.static.name = 'settings';
11210 * SettingsTool.static.icon = 'settings';
11211 * SettingsTool.static.title = 'Change settings';
11212 * SettingsTool.prototype.onSelect = function () {
11213 * this.setActive( false );
11215 * toolFactory.register( SettingsTool );
11216 * // Register two more tools, nothing interesting here
11217 * function StuffTool() {
11218 * StuffTool.parent.apply( this, arguments );
11220 * OO.inheritClass( StuffTool, OO.ui.Tool );
11221 * StuffTool.static.name = 'stuff';
11222 * StuffTool.static.icon = 'ellipsis';
11223 * StuffTool.static.title = 'Change the world';
11224 * StuffTool.prototype.onSelect = function () {
11225 * this.setActive( false );
11227 * toolFactory.register( StuffTool );
11230 * // Configurations for list toolgroup.
11232 * label: 'ListToolGroup',
11233 * indicator: 'down',
11235 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11236 * header: 'This is the header',
11237 * include: [ 'settings', 'stuff' ],
11238 * allowCollapse: ['stuff']
11242 * // Create some UI around the toolbar and place it in the document
11243 * var frame = new OO.ui.PanelLayout( {
11247 * frame.$element.append(
11250 * $( 'body' ).append( frame.$element );
11251 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11252 * toolbar.initialize();
11254 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11256 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11259 * @extends OO.ui.PopupToolGroup
11262 * @param {OO.ui.Toolbar} toolbar
11263 * @param {Object} [config] Configuration options
11264 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11265 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11266 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11267 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11268 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11269 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11270 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11271 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11272 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11273 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
11275 OO
.ui
.ListToolGroup
= function OoUiListToolGroup( toolbar
, config
) {
11276 // Allow passing positional parameters inside the config object
11277 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11279 toolbar
= config
.toolbar
;
11282 // Configuration initialization
11283 config
= config
|| {};
11285 // Properties (must be set before parent constructor, which calls #populate)
11286 this.allowCollapse
= config
.allowCollapse
;
11287 this.forceExpand
= config
.forceExpand
;
11288 this.expanded
= config
.expanded
!== undefined ? config
.expanded
: false;
11289 this.collapsibleTools
= [];
11291 // Parent constructor
11292 OO
.ui
.ListToolGroup
.parent
.call( this, toolbar
, config
);
11295 this.$element
.addClass( 'oo-ui-listToolGroup' );
11300 OO
.inheritClass( OO
.ui
.ListToolGroup
, OO
.ui
.PopupToolGroup
);
11302 /* Static Properties */
11304 OO
.ui
.ListToolGroup
.static.name
= 'list';
11311 OO
.ui
.ListToolGroup
.prototype.populate = function () {
11312 var i
, len
, allowCollapse
= [];
11314 OO
.ui
.ListToolGroup
.parent
.prototype.populate
.call( this );
11316 // Update the list of collapsible tools
11317 if ( this.allowCollapse
!== undefined ) {
11318 allowCollapse
= this.allowCollapse
;
11319 } else if ( this.forceExpand
!== undefined ) {
11320 allowCollapse
= OO
.simpleArrayDifference( Object
.keys( this.tools
), this.forceExpand
);
11323 this.collapsibleTools
= [];
11324 for ( i
= 0, len
= allowCollapse
.length
; i
< len
; i
++ ) {
11325 if ( this.tools
[ allowCollapse
[ i
] ] !== undefined ) {
11326 this.collapsibleTools
.push( this.tools
[ allowCollapse
[ i
] ] );
11330 // Keep at the end, even when tools are added
11331 this.$group
.append( this.getExpandCollapseTool().$element
);
11333 this.getExpandCollapseTool().toggle( this.collapsibleTools
.length
!== 0 );
11334 this.updateCollapsibleState();
11337 OO
.ui
.ListToolGroup
.prototype.getExpandCollapseTool = function () {
11338 if ( this.expandCollapseTool
=== undefined ) {
11339 var ExpandCollapseTool = function () {
11340 ExpandCollapseTool
.parent
.apply( this, arguments
);
11343 OO
.inheritClass( ExpandCollapseTool
, OO
.ui
.Tool
);
11345 ExpandCollapseTool
.prototype.onSelect = function () {
11346 this.toolGroup
.expanded
= !this.toolGroup
.expanded
;
11347 this.toolGroup
.updateCollapsibleState();
11348 this.setActive( false );
11350 ExpandCollapseTool
.prototype.onUpdateState = function () {
11351 // Do nothing. Tool interface requires an implementation of this function.
11354 ExpandCollapseTool
.static.name
= 'more-fewer';
11356 this.expandCollapseTool
= new ExpandCollapseTool( this );
11358 return this.expandCollapseTool
;
11364 OO
.ui
.ListToolGroup
.prototype.onMouseKeyUp = function ( e
) {
11365 // Do not close the popup when the user wants to show more/fewer tools
11367 $( e
.target
).closest( '.oo-ui-tool-name-more-fewer' ).length
&&
11368 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11370 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
11371 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
11372 return OO
.ui
.ListToolGroup
.parent
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11374 return OO
.ui
.ListToolGroup
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11378 OO
.ui
.ListToolGroup
.prototype.updateCollapsibleState = function () {
11381 this.getExpandCollapseTool()
11382 .setIcon( this.expanded
? 'collapse' : 'expand' )
11383 .setTitle( OO
.ui
.msg( this.expanded
? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
11385 for ( i
= 0, len
= this.collapsibleTools
.length
; i
< len
; i
++ ) {
11386 this.collapsibleTools
[ i
].toggle( this.expanded
);
11391 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11392 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
11393 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
11394 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
11395 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
11396 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
11398 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
11399 * is set up. Note that all tools must define an {@link OO.ui.Tool#onUpdateState onUpdateState} method if
11400 * a MenuToolGroup is used.
11403 * // Example of a MenuToolGroup
11404 * var toolFactory = new OO.ui.ToolFactory();
11405 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11406 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11408 * // We will be placing status text in this element when tools are used
11409 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
11411 * // Define the tools that we're going to place in our toolbar
11413 * function SettingsTool() {
11414 * SettingsTool.parent.apply( this, arguments );
11415 * this.reallyActive = false;
11417 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11418 * SettingsTool.static.name = 'settings';
11419 * SettingsTool.static.icon = 'settings';
11420 * SettingsTool.static.title = 'Change settings';
11421 * SettingsTool.prototype.onSelect = function () {
11422 * $area.text( 'Settings tool clicked!' );
11423 * // Toggle the active state on each click
11424 * this.reallyActive = !this.reallyActive;
11425 * this.setActive( this.reallyActive );
11426 * // To update the menu label
11427 * this.toolbar.emit( 'updateState' );
11429 * SettingsTool.prototype.onUpdateState = function () {
11431 * toolFactory.register( SettingsTool );
11433 * function StuffTool() {
11434 * StuffTool.parent.apply( this, arguments );
11435 * this.reallyActive = false;
11437 * OO.inheritClass( StuffTool, OO.ui.Tool );
11438 * StuffTool.static.name = 'stuff';
11439 * StuffTool.static.icon = 'ellipsis';
11440 * StuffTool.static.title = 'More stuff';
11441 * StuffTool.prototype.onSelect = function () {
11442 * $area.text( 'More stuff tool clicked!' );
11443 * // Toggle the active state on each click
11444 * this.reallyActive = !this.reallyActive;
11445 * this.setActive( this.reallyActive );
11446 * // To update the menu label
11447 * this.toolbar.emit( 'updateState' );
11449 * StuffTool.prototype.onUpdateState = function () {
11451 * toolFactory.register( StuffTool );
11453 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11454 * // used once (but not all defined tools must be used).
11458 * header: 'This is the (optional) header',
11459 * title: 'This is the (optional) title',
11460 * indicator: 'down',
11461 * include: [ 'settings', 'stuff' ]
11465 * // Create some UI around the toolbar and place it in the document
11466 * var frame = new OO.ui.PanelLayout( {
11470 * var contentFrame = new OO.ui.PanelLayout( {
11474 * frame.$element.append(
11475 * toolbar.$element,
11476 * contentFrame.$element.append( $area )
11478 * $( 'body' ).append( frame.$element );
11480 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11482 * toolbar.initialize();
11483 * toolbar.emit( 'updateState' );
11485 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11486 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
11488 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11491 * @extends OO.ui.PopupToolGroup
11494 * @param {OO.ui.Toolbar} toolbar
11495 * @param {Object} [config] Configuration options
11497 OO
.ui
.MenuToolGroup
= function OoUiMenuToolGroup( toolbar
, config
) {
11498 // Allow passing positional parameters inside the config object
11499 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11501 toolbar
= config
.toolbar
;
11504 // Configuration initialization
11505 config
= config
|| {};
11507 // Parent constructor
11508 OO
.ui
.MenuToolGroup
.parent
.call( this, toolbar
, config
);
11511 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
11514 this.$element
.addClass( 'oo-ui-menuToolGroup' );
11519 OO
.inheritClass( OO
.ui
.MenuToolGroup
, OO
.ui
.PopupToolGroup
);
11521 /* Static Properties */
11523 OO
.ui
.MenuToolGroup
.static.name
= 'menu';
11528 * Handle the toolbar state being updated.
11530 * When the state changes, the title of each active item in the menu will be joined together and
11531 * used as a label for the group. The label will be empty if none of the items are active.
11535 OO
.ui
.MenuToolGroup
.prototype.onUpdateState = function () {
11539 for ( name
in this.tools
) {
11540 if ( this.tools
[ name
].isActive() ) {
11541 labelTexts
.push( this.tools
[ name
].getTitle() );
11545 this.setLabel( labelTexts
.join( ', ' ) || ' ' );
11549 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
11550 * with a static name, title, and icon, as well with as any popup configurations. Unlike other tools, popup tools do not require that developers specify
11551 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
11553 * // Example of a popup tool. When selected, a popup tool displays
11554 * // a popup window.
11555 * function HelpTool( toolGroup, config ) {
11556 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11561 * this.popup.$body.append( '<p>I am helpful!</p>' );
11563 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11564 * HelpTool.static.name = 'help';
11565 * HelpTool.static.icon = 'help';
11566 * HelpTool.static.title = 'Help';
11567 * toolFactory.register( HelpTool );
11569 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
11570 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
11572 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11576 * @extends OO.ui.Tool
11577 * @mixins OO.ui.mixin.PopupElement
11580 * @param {OO.ui.ToolGroup} toolGroup
11581 * @param {Object} [config] Configuration options
11583 OO
.ui
.PopupTool
= function OoUiPopupTool( toolGroup
, config
) {
11584 // Allow passing positional parameters inside the config object
11585 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
11586 config
= toolGroup
;
11587 toolGroup
= config
.toolGroup
;
11590 // Parent constructor
11591 OO
.ui
.PopupTool
.parent
.call( this, toolGroup
, config
);
11593 // Mixin constructors
11594 OO
.ui
.mixin
.PopupElement
.call( this, config
);
11598 .addClass( 'oo-ui-popupTool' )
11599 .append( this.popup
.$element
);
11604 OO
.inheritClass( OO
.ui
.PopupTool
, OO
.ui
.Tool
);
11605 OO
.mixinClass( OO
.ui
.PopupTool
, OO
.ui
.mixin
.PopupElement
);
11610 * Handle the tool being selected.
11614 OO
.ui
.PopupTool
.prototype.onSelect = function () {
11615 if ( !this.isDisabled() ) {
11616 this.popup
.toggle();
11618 this.setActive( false );
11623 * Handle the toolbar state being updated.
11627 OO
.ui
.PopupTool
.prototype.onUpdateState = function () {
11628 this.setActive( false );
11632 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
11633 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
11634 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
11635 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
11636 * when the ToolGroupTool is selected.
11638 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
11640 * function SettingsTool() {
11641 * SettingsTool.parent.apply( this, arguments );
11643 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
11644 * SettingsTool.static.name = 'settings';
11645 * SettingsTool.static.title = 'Change settings';
11646 * SettingsTool.static.groupConfig = {
11647 * icon: 'settings',
11648 * label: 'ToolGroupTool',
11649 * include: [ 'setting1', 'setting2' ]
11651 * toolFactory.register( SettingsTool );
11653 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
11655 * Please note that this implementation is subject to change per [T74159] [2].
11657 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
11658 * [2]: https://phabricator.wikimedia.org/T74159
11662 * @extends OO.ui.Tool
11665 * @param {OO.ui.ToolGroup} toolGroup
11666 * @param {Object} [config] Configuration options
11668 OO
.ui
.ToolGroupTool
= function OoUiToolGroupTool( toolGroup
, config
) {
11669 // Allow passing positional parameters inside the config object
11670 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
11671 config
= toolGroup
;
11672 toolGroup
= config
.toolGroup
;
11675 // Parent constructor
11676 OO
.ui
.ToolGroupTool
.parent
.call( this, toolGroup
, config
);
11679 this.innerToolGroup
= this.createGroup( this.constructor.static.groupConfig
);
11682 this.innerToolGroup
.connect( this, { disable
: 'onToolGroupDisable' } );
11685 this.$link
.remove();
11687 .addClass( 'oo-ui-toolGroupTool' )
11688 .append( this.innerToolGroup
.$element
);
11693 OO
.inheritClass( OO
.ui
.ToolGroupTool
, OO
.ui
.Tool
);
11695 /* Static Properties */
11698 * Toolgroup configuration.
11700 * The toolgroup configuration consists of the tools to include, as well as an icon and label
11701 * to use for the bar item. Tools can be included by symbolic name, group, or with the
11702 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
11704 * @property {Object.<string,Array>}
11706 OO
.ui
.ToolGroupTool
.static.groupConfig
= {};
11711 * Handle the tool being selected.
11715 OO
.ui
.ToolGroupTool
.prototype.onSelect = function () {
11716 this.innerToolGroup
.setActive( !this.innerToolGroup
.active
);
11721 * Synchronize disabledness state of the tool with the inner toolgroup.
11724 * @param {boolean} disabled Element is disabled
11726 OO
.ui
.ToolGroupTool
.prototype.onToolGroupDisable = function ( disabled
) {
11727 this.setDisabled( disabled
);
11731 * Handle the toolbar state being updated.
11735 OO
.ui
.ToolGroupTool
.prototype.onUpdateState = function () {
11736 this.setActive( false );
11740 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
11742 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
11743 * more information.
11744 * @return {OO.ui.ListToolGroup}
11746 OO
.ui
.ToolGroupTool
.prototype.createGroup = function ( group
) {
11747 if ( group
.include
=== '*' ) {
11748 // Apply defaults to catch-all groups
11749 if ( group
.label
=== undefined ) {
11750 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
11754 return this.toolbar
.getToolGroupFactory().create( 'list', this.toolbar
, group
);
11758 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
11760 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
11765 * @extends OO.ui.mixin.GroupElement
11768 * @param {Object} [config] Configuration options
11770 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
11771 // Parent constructor
11772 OO
.ui
.mixin
.GroupWidget
.parent
.call( this, config
);
11777 OO
.inheritClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
11782 * Set the disabled state of the widget.
11784 * This will also update the disabled state of child widgets.
11786 * @param {boolean} disabled Disable widget
11789 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
11793 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
11794 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
11796 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
11797 if ( this.items
) {
11798 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
11799 this.items
[ i
].updateDisabled();
11807 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
11809 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
11810 * allows bidirectional communication.
11812 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
11820 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
11827 * Check if widget is disabled.
11829 * Checks parent if present, making disabled state inheritable.
11831 * @return {boolean} Widget is disabled
11833 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
11834 return this.disabled
||
11835 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
11839 * Set group element is in.
11841 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
11844 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
11846 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
11847 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
11849 // Initialize item disabled states
11850 this.updateDisabled();
11856 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
11857 * Controls include moving items up and down, removing items, and adding different kinds of items.
11859 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
11862 * @extends OO.ui.Widget
11863 * @mixins OO.ui.mixin.GroupElement
11864 * @mixins OO.ui.mixin.IconElement
11867 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
11868 * @param {Object} [config] Configuration options
11869 * @cfg {Object} [abilities] List of abilties
11870 * @cfg {boolean} [abilities.move=true] Allow moving movable items
11871 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
11873 OO
.ui
.OutlineControlsWidget
= function OoUiOutlineControlsWidget( outline
, config
) {
11874 // Allow passing positional parameters inside the config object
11875 if ( OO
.isPlainObject( outline
) && config
=== undefined ) {
11877 outline
= config
.outline
;
11880 // Configuration initialization
11881 config
= $.extend( { icon
: 'add' }, config
);
11883 // Parent constructor
11884 OO
.ui
.OutlineControlsWidget
.parent
.call( this, config
);
11886 // Mixin constructors
11887 OO
.ui
.mixin
.GroupElement
.call( this, config
);
11888 OO
.ui
.mixin
.IconElement
.call( this, config
);
11891 this.outline
= outline
;
11892 this.$movers
= $( '<div>' );
11893 this.upButton
= new OO
.ui
.ButtonWidget( {
11896 title
: OO
.ui
.msg( 'ooui-outline-control-move-up' )
11898 this.downButton
= new OO
.ui
.ButtonWidget( {
11901 title
: OO
.ui
.msg( 'ooui-outline-control-move-down' )
11903 this.removeButton
= new OO
.ui
.ButtonWidget( {
11906 title
: OO
.ui
.msg( 'ooui-outline-control-remove' )
11908 this.abilities
= { move: true, remove
: true };
11911 outline
.connect( this, {
11912 select
: 'onOutlineChange',
11913 add
: 'onOutlineChange',
11914 remove
: 'onOutlineChange'
11916 this.upButton
.connect( this, { click
: [ 'emit', 'move', -1 ] } );
11917 this.downButton
.connect( this, { click
: [ 'emit', 'move', 1 ] } );
11918 this.removeButton
.connect( this, { click
: [ 'emit', 'remove' ] } );
11921 this.$element
.addClass( 'oo-ui-outlineControlsWidget' );
11922 this.$group
.addClass( 'oo-ui-outlineControlsWidget-items' );
11924 .addClass( 'oo-ui-outlineControlsWidget-movers' )
11925 .append( this.removeButton
.$element
, this.upButton
.$element
, this.downButton
.$element
);
11926 this.$element
.append( this.$icon
, this.$group
, this.$movers
);
11927 this.setAbilities( config
.abilities
|| {} );
11932 OO
.inheritClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.Widget
);
11933 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.GroupElement
);
11934 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.IconElement
);
11940 * @param {number} places Number of places to move
11952 * @param {Object} abilities List of abilties
11953 * @param {boolean} [abilities.move] Allow moving movable items
11954 * @param {boolean} [abilities.remove] Allow removing removable items
11956 OO
.ui
.OutlineControlsWidget
.prototype.setAbilities = function ( abilities
) {
11959 for ( ability
in this.abilities
) {
11960 if ( abilities
[ability
] !== undefined ) {
11961 this.abilities
[ability
] = !!abilities
[ability
];
11965 this.onOutlineChange();
11971 * Handle outline change events.
11973 OO
.ui
.OutlineControlsWidget
.prototype.onOutlineChange = function () {
11974 var i
, len
, firstMovable
, lastMovable
,
11975 items
= this.outline
.getItems(),
11976 selectedItem
= this.outline
.getSelectedItem(),
11977 movable
= this.abilities
.move && selectedItem
&& selectedItem
.isMovable(),
11978 removable
= this.abilities
.remove
&& selectedItem
&& selectedItem
.isRemovable();
11982 len
= items
.length
;
11983 while ( ++i
< len
) {
11984 if ( items
[ i
].isMovable() ) {
11985 firstMovable
= items
[ i
];
11991 if ( items
[ i
].isMovable() ) {
11992 lastMovable
= items
[ i
];
11997 this.upButton
.setDisabled( !movable
|| selectedItem
=== firstMovable
);
11998 this.downButton
.setDisabled( !movable
|| selectedItem
=== lastMovable
);
11999 this.removeButton
.setDisabled( !removable
);
12003 * ToggleWidget implements basic behavior of widgets with an on/off state.
12004 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
12008 * @extends OO.ui.Widget
12011 * @param {Object} [config] Configuration options
12012 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
12013 * By default, the toggle is in the 'off' state.
12015 OO
.ui
.ToggleWidget
= function OoUiToggleWidget( config
) {
12016 // Configuration initialization
12017 config
= config
|| {};
12019 // Parent constructor
12020 OO
.ui
.ToggleWidget
.parent
.call( this, config
);
12026 this.$element
.addClass( 'oo-ui-toggleWidget' );
12027 this.setValue( !!config
.value
);
12032 OO
.inheritClass( OO
.ui
.ToggleWidget
, OO
.ui
.Widget
);
12039 * A change event is emitted when the on/off state of the toggle changes.
12041 * @param {boolean} value Value representing the new state of the toggle
12047 * Get the value representing the toggle’s state.
12049 * @return {boolean} The on/off state of the toggle
12051 OO
.ui
.ToggleWidget
.prototype.getValue = function () {
12056 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
12058 * @param {boolean} value The state of the toggle
12062 OO
.ui
.ToggleWidget
.prototype.setValue = function ( value
) {
12064 if ( this.value
!== value
) {
12065 this.value
= value
;
12066 this.emit( 'change', value
);
12067 this.$element
.toggleClass( 'oo-ui-toggleWidget-on', value
);
12068 this.$element
.toggleClass( 'oo-ui-toggleWidget-off', !value
);
12069 this.$element
.attr( 'aria-checked', value
.toString() );
12075 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12076 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12077 * removed, and cleared from the group.
12080 * // Example: A ButtonGroupWidget with two buttons
12081 * var button1 = new OO.ui.PopupButtonWidget( {
12082 * label: 'Select a category',
12085 * $content: $( '<p>List of categories...</p>' ),
12090 * var button2 = new OO.ui.ButtonWidget( {
12091 * label: 'Add item'
12093 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12094 * items: [button1, button2]
12096 * $( 'body' ).append( buttonGroup.$element );
12099 * @extends OO.ui.Widget
12100 * @mixins OO.ui.mixin.GroupElement
12103 * @param {Object} [config] Configuration options
12104 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12106 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
12107 // Configuration initialization
12108 config
= config
|| {};
12110 // Parent constructor
12111 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
12113 // Mixin constructors
12114 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
12117 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
12118 if ( Array
.isArray( config
.items
) ) {
12119 this.addItems( config
.items
);
12125 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
12126 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
12129 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12130 * feels, and functionality can be customized via the class’s configuration options
12131 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12134 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12137 * // A button widget
12138 * var button = new OO.ui.ButtonWidget( {
12139 * label: 'Button with Icon',
12141 * iconTitle: 'Remove'
12143 * $( 'body' ).append( button.$element );
12145 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12148 * @extends OO.ui.Widget
12149 * @mixins OO.ui.mixin.ButtonElement
12150 * @mixins OO.ui.mixin.IconElement
12151 * @mixins OO.ui.mixin.IndicatorElement
12152 * @mixins OO.ui.mixin.LabelElement
12153 * @mixins OO.ui.mixin.TitledElement
12154 * @mixins OO.ui.mixin.FlaggedElement
12155 * @mixins OO.ui.mixin.TabIndexedElement
12158 * @param {Object} [config] Configuration options
12159 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12160 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12161 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12163 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
12164 // Configuration initialization
12165 config
= config
|| {};
12167 // Parent constructor
12168 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
12170 // Mixin constructors
12171 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
12172 OO
.ui
.mixin
.IconElement
.call( this, config
);
12173 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12174 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12175 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
12176 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
12177 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
12181 this.target
= null;
12182 this.noFollow
= false;
12185 this.connect( this, { disable
: 'onDisable' } );
12188 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
12190 .addClass( 'oo-ui-buttonWidget' )
12191 .append( this.$button
);
12192 this.setHref( config
.href
);
12193 this.setTarget( config
.target
);
12194 this.setNoFollow( config
.noFollow
);
12199 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
12200 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
12201 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
12202 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
12203 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
12204 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
12205 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
12206 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
12213 OO
.ui
.ButtonWidget
.prototype.onMouseDown = function ( e
) {
12214 if ( !this.isDisabled() ) {
12215 // Remove the tab-index while the button is down to prevent the button from stealing focus
12216 this.$button
.removeAttr( 'tabindex' );
12219 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown
.call( this, e
);
12225 OO
.ui
.ButtonWidget
.prototype.onMouseUp = function ( e
) {
12226 if ( !this.isDisabled() ) {
12227 // Restore the tab-index after the button is up to restore the button's accessibility
12228 this.$button
.attr( 'tabindex', this.tabIndex
);
12231 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp
.call( this, e
);
12235 * Get hyperlink location.
12237 * @return {string} Hyperlink location
12239 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
12244 * Get hyperlink target.
12246 * @return {string} Hyperlink target
12248 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
12249 return this.target
;
12253 * Get search engine traversal hint.
12255 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12257 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
12258 return this.noFollow
;
12262 * Set hyperlink location.
12264 * @param {string|null} href Hyperlink location, null to remove
12266 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
12267 href
= typeof href
=== 'string' ? href
: null;
12268 if ( href
!== null ) {
12269 if ( !OO
.ui
.isSafeUrl( href
) ) {
12270 throw new Error( 'Potentially unsafe href provided: ' + href
);
12275 if ( href
!== this.href
) {
12284 * Update the `href` attribute, in case of changes to href or
12290 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
12291 if ( this.href
!== null && !this.isDisabled() ) {
12292 this.$button
.attr( 'href', this.href
);
12294 this.$button
.removeAttr( 'href' );
12301 * Handle disable events.
12304 * @param {boolean} disabled Element is disabled
12306 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
12311 * Set hyperlink target.
12313 * @param {string|null} target Hyperlink target, null to remove
12315 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
12316 target
= typeof target
=== 'string' ? target
: null;
12318 if ( target
!== this.target
) {
12319 this.target
= target
;
12320 if ( target
!== null ) {
12321 this.$button
.attr( 'target', target
);
12323 this.$button
.removeAttr( 'target' );
12331 * Set search engine traversal hint.
12333 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
12335 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
12336 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
12338 if ( noFollow
!== this.noFollow
) {
12339 this.noFollow
= noFollow
;
12341 this.$button
.attr( 'rel', 'nofollow' );
12343 this.$button
.removeAttr( 'rel' );
12351 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
12352 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
12355 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
12356 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12359 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
12362 * @extends OO.ui.ButtonWidget
12363 * @mixins OO.ui.mixin.PendingElement
12366 * @param {Object} [config] Configuration options
12367 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12368 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
12369 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
12370 * for more information about setting modes.
12371 * @cfg {boolean} [framed=false] Render the action button with a frame
12373 OO
.ui
.ActionWidget
= function OoUiActionWidget( config
) {
12374 // Configuration initialization
12375 config
= $.extend( { framed
: false }, config
);
12377 // Parent constructor
12378 OO
.ui
.ActionWidget
.parent
.call( this, config
);
12380 // Mixin constructors
12381 OO
.ui
.mixin
.PendingElement
.call( this, config
);
12384 this.action
= config
.action
|| '';
12385 this.modes
= config
.modes
|| [];
12390 this.$element
.addClass( 'oo-ui-actionWidget' );
12395 OO
.inheritClass( OO
.ui
.ActionWidget
, OO
.ui
.ButtonWidget
);
12396 OO
.mixinClass( OO
.ui
.ActionWidget
, OO
.ui
.mixin
.PendingElement
);
12401 * A resize event is emitted when the size of the widget changes.
12409 * Check if the action is configured to be available in the specified `mode`.
12411 * @param {string} mode Name of mode
12412 * @return {boolean} The action is configured with the mode
12414 OO
.ui
.ActionWidget
.prototype.hasMode = function ( mode
) {
12415 return this.modes
.indexOf( mode
) !== -1;
12419 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12423 OO
.ui
.ActionWidget
.prototype.getAction = function () {
12424 return this.action
;
12428 * Get the symbolic name of the mode or modes for which the action is configured to be available.
12430 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
12431 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
12434 * @return {string[]}
12436 OO
.ui
.ActionWidget
.prototype.getModes = function () {
12437 return this.modes
.slice();
12441 * Emit a resize event if the size has changed.
12446 OO
.ui
.ActionWidget
.prototype.propagateResize = function () {
12449 if ( this.isElementAttached() ) {
12450 width
= this.$element
.width();
12451 height
= this.$element
.height();
12453 if ( width
!== this.width
|| height
!== this.height
) {
12454 this.width
= width
;
12455 this.height
= height
;
12456 this.emit( 'resize' );
12466 OO
.ui
.ActionWidget
.prototype.setIcon = function () {
12468 OO
.ui
.mixin
.IconElement
.prototype.setIcon
.apply( this, arguments
);
12469 this.propagateResize();
12477 OO
.ui
.ActionWidget
.prototype.setLabel = function () {
12479 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.apply( this, arguments
);
12480 this.propagateResize();
12488 OO
.ui
.ActionWidget
.prototype.setFlags = function () {
12490 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags
.apply( this, arguments
);
12491 this.propagateResize();
12499 OO
.ui
.ActionWidget
.prototype.clearFlags = function () {
12501 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags
.apply( this, arguments
);
12502 this.propagateResize();
12508 * Toggle the visibility of the action button.
12510 * @param {boolean} [show] Show button, omit to toggle visibility
12513 OO
.ui
.ActionWidget
.prototype.toggle = function () {
12515 OO
.ui
.ActionWidget
.parent
.prototype.toggle
.apply( this, arguments
);
12516 this.propagateResize();
12522 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
12523 * which is used to display additional information or options.
12526 * // Example of a popup button.
12527 * var popupButton = new OO.ui.PopupButtonWidget( {
12528 * label: 'Popup button with options',
12531 * $content: $( '<p>Additional options here.</p>' ),
12533 * align: 'force-left'
12536 * // Append the button to the DOM.
12537 * $( 'body' ).append( popupButton.$element );
12540 * @extends OO.ui.ButtonWidget
12541 * @mixins OO.ui.mixin.PopupElement
12544 * @param {Object} [config] Configuration options
12546 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
12547 // Parent constructor
12548 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
12550 // Mixin constructors
12551 OO
.ui
.mixin
.PopupElement
.call( this, config
);
12554 this.connect( this, { click
: 'onAction' } );
12558 .addClass( 'oo-ui-popupButtonWidget' )
12559 .attr( 'aria-haspopup', 'true' )
12560 .append( this.popup
.$element
);
12565 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
12566 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
12571 * Handle the button action being triggered.
12575 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
12576 this.popup
.toggle();
12580 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
12581 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
12582 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
12583 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
12584 * and {@link OO.ui.mixin.LabelElement labels}. Please see
12585 * the [OOjs UI documentation][1] on MediaWiki for more information.
12588 * // Toggle buttons in the 'off' and 'on' state.
12589 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
12590 * label: 'Toggle Button off'
12592 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
12593 * label: 'Toggle Button on',
12596 * // Append the buttons to the DOM.
12597 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
12599 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
12602 * @extends OO.ui.ToggleWidget
12603 * @mixins OO.ui.mixin.ButtonElement
12604 * @mixins OO.ui.mixin.IconElement
12605 * @mixins OO.ui.mixin.IndicatorElement
12606 * @mixins OO.ui.mixin.LabelElement
12607 * @mixins OO.ui.mixin.TitledElement
12608 * @mixins OO.ui.mixin.FlaggedElement
12609 * @mixins OO.ui.mixin.TabIndexedElement
12612 * @param {Object} [config] Configuration options
12613 * @cfg {boolean} [value=false] The toggle button’s initial on/off
12614 * state. By default, the button is in the 'off' state.
12616 OO
.ui
.ToggleButtonWidget
= function OoUiToggleButtonWidget( config
) {
12617 // Configuration initialization
12618 config
= config
|| {};
12620 // Parent constructor
12621 OO
.ui
.ToggleButtonWidget
.parent
.call( this, config
);
12623 // Mixin constructors
12624 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
12625 OO
.ui
.mixin
.IconElement
.call( this, config
);
12626 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12627 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12628 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
12629 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
12630 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
12633 this.connect( this, { click
: 'onAction' } );
12636 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
12638 .addClass( 'oo-ui-toggleButtonWidget' )
12639 .append( this.$button
);
12644 OO
.inheritClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ToggleWidget
);
12645 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
12646 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IconElement
);
12647 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
12648 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.LabelElement
);
12649 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TitledElement
);
12650 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
12651 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
12656 * Handle the button action being triggered.
12660 OO
.ui
.ToggleButtonWidget
.prototype.onAction = function () {
12661 this.setValue( !this.value
);
12667 OO
.ui
.ToggleButtonWidget
.prototype.setValue = function ( value
) {
12669 if ( value
!== this.value
) {
12670 // Might be called from parent constructor before ButtonElement constructor
12671 if ( this.$button
) {
12672 this.$button
.attr( 'aria-pressed', value
.toString() );
12674 this.setActive( value
);
12678 OO
.ui
.ToggleButtonWidget
.parent
.prototype.setValue
.call( this, value
);
12686 OO
.ui
.ToggleButtonWidget
.prototype.setButtonElement = function ( $button
) {
12687 if ( this.$button
) {
12688 this.$button
.removeAttr( 'aria-pressed' );
12690 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement
.call( this, $button
);
12691 this.$button
.attr( 'aria-pressed', this.value
.toString() );
12695 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxWidget combo box widget}
12696 * that allows for selecting multiple values.
12698 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
12701 * // Example: A CapsuleMultiSelectWidget.
12702 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
12703 * label: 'CapsuleMultiSelectWidget',
12704 * selected: [ 'Option 1', 'Option 3' ],
12707 * new OO.ui.MenuOptionWidget( {
12708 * data: 'Option 1',
12709 * label: 'Option One'
12711 * new OO.ui.MenuOptionWidget( {
12712 * data: 'Option 2',
12713 * label: 'Option Two'
12715 * new OO.ui.MenuOptionWidget( {
12716 * data: 'Option 3',
12717 * label: 'Option Three'
12719 * new OO.ui.MenuOptionWidget( {
12720 * data: 'Option 4',
12721 * label: 'Option Four'
12723 * new OO.ui.MenuOptionWidget( {
12724 * data: 'Option 5',
12725 * label: 'Option Five'
12730 * $( 'body' ).append( capsule.$element );
12732 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12735 * @extends OO.ui.Widget
12736 * @mixins OO.ui.mixin.TabIndexedElement
12737 * @mixins OO.ui.mixin.GroupElement
12740 * @param {Object} [config] Configuration options
12741 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
12742 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
12743 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
12744 * If specified, this popup will be shown instead of the menu (but the menu
12745 * will still be used for item labels and allowArbitrary=false). The widgets
12746 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
12747 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
12748 * This configuration is useful in cases where the expanded menu is larger than
12749 * its containing `<div>`. The specified overlay layer is usually on top of
12750 * the containing `<div>` and has a larger area. By default, the menu uses
12751 * relative positioning.
12753 OO
.ui
.CapsuleMultiSelectWidget
= function OoUiCapsuleMultiSelectWidget( config
) {
12756 // Configuration initialization
12757 config
= config
|| {};
12759 // Parent constructor
12760 OO
.ui
.CapsuleMultiSelectWidget
.parent
.call( this, config
);
12762 // Properties (must be set before mixin constructor calls)
12763 this.$input
= config
.popup
? null : $( '<input>' );
12764 this.$handle
= $( '<div>' );
12766 // Mixin constructors
12767 OO
.ui
.mixin
.GroupElement
.call( this, config
);
12768 if ( config
.popup
) {
12769 config
.popup
= $.extend( {}, config
.popup
, {
12773 OO
.ui
.mixin
.PopupElement
.call( this, config
);
12774 $tabFocus
= $( '<span>' );
12775 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: $tabFocus
} ) );
12779 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
12781 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12782 OO
.ui
.mixin
.IconElement
.call( this, config
);
12785 this.allowArbitrary
= !!config
.allowArbitrary
;
12786 this.$overlay
= config
.$overlay
|| this.$element
;
12787 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
12790 $input
: this.$input
,
12791 $container
: this.$element
,
12792 filterFromInput
: true,
12793 disabled
: this.isDisabled()
12799 if ( this.popup
) {
12801 focus
: this.onFocusForPopup
.bind( this )
12803 this.popup
.$element
.on( 'focusout', this.onPopupFocusOut
.bind( this ) );
12804 if ( this.popup
.$autoCloseIgnore
) {
12805 this.popup
.$autoCloseIgnore
.on( 'focusout', this.onPopupFocusOut
.bind( this ) );
12807 this.popup
.connect( this, {
12808 toggle: function ( visible
) {
12809 $tabFocus
.toggle( !visible
);
12814 focus
: this.onInputFocus
.bind( this ),
12815 blur
: this.onInputBlur
.bind( this ),
12816 'propertychange change click mouseup keydown keyup input cut paste select': this.onInputChange
.bind( this ),
12817 keydown
: this.onKeyDown
.bind( this ),
12818 keypress
: this.onKeyPress
.bind( this )
12821 this.menu
.connect( this, {
12822 choose
: 'onMenuChoose',
12823 add
: 'onMenuItemsChange',
12824 remove
: 'onMenuItemsChange'
12827 click
: this.onClick
.bind( this )
12831 if ( this.$input
) {
12832 this.$input
.prop( 'disabled', this.isDisabled() );
12833 this.$input
.attr( {
12835 'aria-autocomplete': 'list'
12837 this.$input
.width( '1em' );
12839 if ( config
.data
) {
12840 this.setItemsFromData( config
.data
);
12842 this.$group
.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
12843 this.$handle
.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
12844 .append( this.$indicator
, this.$icon
, this.$group
);
12845 this.$element
.addClass( 'oo-ui-capsuleMultiSelectWidget' )
12846 .append( this.$handle
);
12847 if ( this.popup
) {
12848 this.$handle
.append( $tabFocus
);
12849 this.$overlay
.append( this.popup
.$element
);
12851 this.$handle
.append( this.$input
);
12852 this.$overlay
.append( this.menu
.$element
);
12854 this.onMenuItemsChange();
12859 OO
.inheritClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.Widget
);
12860 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.GroupElement
);
12861 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.PopupElement
);
12862 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
12863 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.IndicatorElement
);
12864 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.IconElement
);
12871 * A change event is emitted when the set of selected items changes.
12873 * @param {Mixed[]} datas Data of the now-selected items
12879 * Get the data of the items in the capsule
12880 * @return {Mixed[]}
12882 OO
.ui
.CapsuleMultiSelectWidget
.prototype.getItemsData = function () {
12883 return $.map( this.getItems(), function ( e
) { return e
.data
; } );
12887 * Set the items in the capsule by providing data
12889 * @param {Mixed[]} datas
12890 * @return {OO.ui.CapsuleMultiSelectWidget}
12892 OO
.ui
.CapsuleMultiSelectWidget
.prototype.setItemsFromData = function ( datas
) {
12895 items
= this.getItems();
12897 $.each( datas
, function ( i
, data
) {
12899 item
= menu
.getItemFromData( data
);
12902 label
= item
.label
;
12903 } else if ( widget
.allowArbitrary
) {
12904 label
= String( data
);
12910 for ( j
= 0; j
< items
.length
; j
++ ) {
12911 if ( items
[j
].data
=== data
&& items
[j
].label
=== label
) {
12913 items
.splice( j
, 1 );
12918 item
= new OO
.ui
.CapsuleItemWidget( { data
: data
, label
: label
} );
12920 widget
.addItems( [ item
], i
);
12923 if ( items
.length
) {
12924 widget
.removeItems( items
);
12931 * Add items to the capsule by providing their data
12933 * @param {Mixed[]} datas
12934 * @return {OO.ui.CapsuleMultiSelectWidget}
12936 OO
.ui
.CapsuleMultiSelectWidget
.prototype.addItemsFromData = function ( datas
) {
12941 $.each( datas
, function ( i
, data
) {
12944 if ( !widget
.getItemFromData( data
) ) {
12945 item
= menu
.getItemFromData( data
);
12947 items
.push( new OO
.ui
.CapsuleItemWidget( { data
: data
, label
: item
.label
} ) );
12948 } else if ( widget
.allowArbitrary
) {
12949 items
.push( new OO
.ui
.CapsuleItemWidget( { data
: data
, label
: String( data
) } ) );
12954 if ( items
.length
) {
12955 this.addItems( items
);
12962 * Remove items by data
12964 * @param {Mixed[]} datas
12965 * @return {OO.ui.CapsuleMultiSelectWidget}
12967 OO
.ui
.CapsuleMultiSelectWidget
.prototype.removeItemsFromData = function ( datas
) {
12971 $.each( datas
, function ( i
, data
) {
12972 var item
= widget
.getItemFromData( data
);
12974 items
.push( item
);
12978 if ( items
.length
) {
12979 this.removeItems( items
);
12988 OO
.ui
.CapsuleMultiSelectWidget
.prototype.addItems = function ( items
) {
12990 oldItems
= this.items
.slice();
12992 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
);
12994 if ( this.items
.length
!== oldItems
.length
) {
12998 for ( i
= 0, l
= oldItems
.length
; same
&& i
< l
; i
++ ) {
12999 same
= same
&& this.items
[i
] === oldItems
[i
];
13003 this.emit( 'change', this.getItemsData() );
13012 OO
.ui
.CapsuleMultiSelectWidget
.prototype.removeItems = function ( items
) {
13014 oldItems
= this.items
.slice();
13016 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
13018 if ( this.items
.length
!== oldItems
.length
) {
13022 for ( i
= 0, l
= oldItems
.length
; same
&& i
< l
; i
++ ) {
13023 same
= same
&& this.items
[i
] === oldItems
[i
];
13027 this.emit( 'change', this.getItemsData() );
13036 OO
.ui
.CapsuleMultiSelectWidget
.prototype.clearItems = function () {
13037 if ( this.items
.length
) {
13038 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
13039 this.emit( 'change', this.getItemsData() );
13045 * Get the capsule widget's menu.
13046 * @return {OO.ui.MenuSelectWidget} Menu widget
13048 OO
.ui
.CapsuleMultiSelectWidget
.prototype.getMenu = function () {
13053 * Handle focus events
13056 * @param {jQuery.Event} event
13058 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputFocus = function () {
13059 if ( !this.isDisabled() ) {
13060 this.menu
.toggle( true );
13065 * Handle blur events
13068 * @param {jQuery.Event} event
13070 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputBlur = function () {
13075 * Handle focus events
13078 * @param {jQuery.Event} event
13080 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onFocusForPopup = function () {
13081 if ( !this.isDisabled() ) {
13082 this.popup
.setSize( this.$handle
.width() );
13083 this.popup
.toggle( true );
13084 this.popup
.$element
.find( '*' )
13085 .filter( function () { return OO
.ui
.isFocusableElement( $( this ), true ); } )
13092 * Handles popup focus out events.
13095 * @param {Event} e Focus out event
13097 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onPopupFocusOut = function () {
13098 var widget
= this.popup
;
13100 setTimeout( function () {
13102 widget
.isVisible() &&
13103 !OO
.ui
.contains( widget
.$element
[0], document
.activeElement
, true ) &&
13104 ( !widget
.$autoCloseIgnore
|| !widget
.$autoCloseIgnore
.has( document
.activeElement
).length
)
13106 widget
.toggle( false );
13112 * Handle mouse click events.
13115 * @param {jQuery.Event} e Mouse click event
13117 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onClick = function ( e
) {
13118 if ( e
.which
=== 1 ) {
13125 * Handle key press events.
13128 * @param {jQuery.Event} e Key press event
13130 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onKeyPress = function ( e
) {
13133 if ( !this.isDisabled() ) {
13134 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
13139 if ( !this.popup
) {
13140 this.menu
.toggle( true );
13141 if ( e
.which
=== OO
.ui
.Keys
.ENTER
) {
13142 item
= this.menu
.getItemFromLabel( this.$input
.val(), true );
13144 this.addItemsFromData( [ item
.data
] );
13146 } else if ( this.allowArbitrary
&& this.$input
.val().trim() !== '' ) {
13147 this.addItemsFromData( [ this.$input
.val() ] );
13153 // Make sure the input gets resized.
13154 setTimeout( this.onInputChange
.bind( this ), 0 );
13160 * Handle key down events.
13163 * @param {jQuery.Event} e Key down event
13165 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onKeyDown = function ( e
) {
13166 if ( !this.isDisabled() ) {
13167 // 'keypress' event is not triggered for Backspace
13168 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.$input
.val() === '' ) {
13169 if ( this.items
.length
) {
13170 this.removeItems( this.items
.slice( -1 ) );
13178 * Handle input change events.
13181 * @param {jQuery.Event} e Event of some sort
13183 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputChange = function () {
13184 if ( !this.isDisabled() ) {
13185 this.$input
.width( this.$input
.val().length
+ 'em' );
13190 * Handle menu choose events.
13193 * @param {OO.ui.OptionWidget} item Chosen item
13195 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onMenuChoose = function ( item
) {
13196 if ( item
&& item
.isVisible() ) {
13197 this.addItemsFromData( [ item
.getData() ] );
13203 * Handle menu item change events.
13207 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onMenuItemsChange = function () {
13208 this.setItemsFromData( this.getItemsData() );
13209 this.$element
.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu
.isEmpty() );
13213 * Clear the input field
13216 OO
.ui
.CapsuleMultiSelectWidget
.prototype.clearInput = function () {
13217 if ( this.$input
) {
13218 this.$input
.val( '' );
13219 this.$input
.width( '1em' );
13221 if ( this.popup
) {
13222 this.popup
.toggle( false );
13224 this.menu
.toggle( false );
13225 this.menu
.selectItem();
13226 this.menu
.highlightItem();
13232 OO
.ui
.CapsuleMultiSelectWidget
.prototype.setDisabled = function ( disabled
) {
13236 OO
.ui
.CapsuleMultiSelectWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
13238 if ( this.$input
) {
13239 this.$input
.prop( 'disabled', this.isDisabled() );
13242 this.menu
.setDisabled( this.isDisabled() );
13244 if ( this.popup
) {
13245 this.popup
.setDisabled( this.isDisabled() );
13248 if ( this.items
) {
13249 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
13250 this.items
[i
].updateDisabled();
13260 * @return {OO.ui.CapsuleMultiSelectWidget}
13262 OO
.ui
.CapsuleMultiSelectWidget
.prototype.focus = function () {
13263 if ( !this.isDisabled() ) {
13264 if ( this.popup
) {
13265 this.popup
.setSize( this.$handle
.width() );
13266 this.popup
.toggle( true );
13267 this.popup
.$element
.find( '*' )
13268 .filter( function () { return OO
.ui
.isFocusableElement( $( this ), true ); } )
13272 this.menu
.toggle( true );
13273 this.$input
.focus();
13280 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
13281 * CapsuleMultiSelectWidget} to display the selected items.
13284 * @extends OO.ui.Widget
13285 * @mixins OO.ui.mixin.ItemWidget
13286 * @mixins OO.ui.mixin.IndicatorElement
13287 * @mixins OO.ui.mixin.LabelElement
13288 * @mixins OO.ui.mixin.FlaggedElement
13289 * @mixins OO.ui.mixin.TabIndexedElement
13292 * @param {Object} [config] Configuration options
13294 OO
.ui
.CapsuleItemWidget
= function OoUiCapsuleItemWidget( config
) {
13295 // Configuration initialization
13296 config
= config
|| {};
13298 // Parent constructor
13299 OO
.ui
.CapsuleItemWidget
.parent
.call( this, config
);
13301 // Properties (must be set before mixin constructor calls)
13302 this.$indicator
= $( '<span>' );
13304 // Mixin constructors
13305 OO
.ui
.mixin
.ItemWidget
.call( this );
13306 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$indicator
, indicator
: 'clear' } ) );
13307 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13308 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
13309 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
13312 this.$indicator
.on( {
13313 keydown
: this.onCloseKeyDown
.bind( this ),
13314 click
: this.onCloseClick
.bind( this )
13316 this.$element
.on( 'click', false );
13320 .addClass( 'oo-ui-capsuleItemWidget' )
13321 .append( this.$indicator
, this.$label
);
13326 OO
.inheritClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.Widget
);
13327 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.ItemWidget
);
13328 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.IndicatorElement
);
13329 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.LabelElement
);
13330 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.FlaggedElement
);
13331 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13336 * Handle close icon clicks
13337 * @param {jQuery.Event} event
13339 OO
.ui
.CapsuleItemWidget
.prototype.onCloseClick = function () {
13340 var element
= this.getElementGroup();
13342 if ( !this.isDisabled() && element
&& $.isFunction( element
.removeItems
) ) {
13343 element
.removeItems( [ this ] );
13349 * Handle close keyboard events
13350 * @param {jQuery.Event} event Key down event
13352 OO
.ui
.CapsuleItemWidget
.prototype.onCloseKeyDown = function ( e
) {
13353 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems
) ) {
13354 switch ( e
.which
) {
13355 case OO
.ui
.Keys
.ENTER
:
13356 case OO
.ui
.Keys
.BACKSPACE
:
13357 case OO
.ui
.Keys
.SPACE
:
13358 this.getElementGroup().removeItems( [ this ] );
13365 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
13366 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
13367 * users can interact with it.
13369 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
13370 * OO.ui.DropdownInputWidget instead.
13373 * // Example: A DropdownWidget with a menu that contains three options
13374 * var dropDown = new OO.ui.DropdownWidget( {
13375 * label: 'Dropdown menu: Select a menu option',
13378 * new OO.ui.MenuOptionWidget( {
13382 * new OO.ui.MenuOptionWidget( {
13386 * new OO.ui.MenuOptionWidget( {
13394 * $( 'body' ).append( dropDown.$element );
13396 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
13398 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13401 * @extends OO.ui.Widget
13402 * @mixins OO.ui.mixin.IconElement
13403 * @mixins OO.ui.mixin.IndicatorElement
13404 * @mixins OO.ui.mixin.LabelElement
13405 * @mixins OO.ui.mixin.TitledElement
13406 * @mixins OO.ui.mixin.TabIndexedElement
13409 * @param {Object} [config] Configuration options
13410 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
13411 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
13412 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
13413 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
13415 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
13416 // Configuration initialization
13417 config
= $.extend( { indicator
: 'down' }, config
);
13419 // Parent constructor
13420 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
13422 // Properties (must be set before TabIndexedElement constructor call)
13423 this.$handle
= this.$( '<span>' );
13424 this.$overlay
= config
.$overlay
|| this.$element
;
13426 // Mixin constructors
13427 OO
.ui
.mixin
.IconElement
.call( this, config
);
13428 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13429 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13430 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
13431 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
13434 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend( {
13436 $container
: this.$element
13437 }, config
.menu
) );
13441 click
: this.onClick
.bind( this ),
13442 keypress
: this.onKeyPress
.bind( this )
13444 this.menu
.connect( this, { select
: 'onMenuSelect' } );
13448 .addClass( 'oo-ui-dropdownWidget-handle' )
13449 .append( this.$icon
, this.$label
, this.$indicator
);
13451 .addClass( 'oo-ui-dropdownWidget' )
13452 .append( this.$handle
);
13453 this.$overlay
.append( this.menu
.$element
);
13458 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
13459 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
13460 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
13461 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
13462 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
13463 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13470 * @return {OO.ui.MenuSelectWidget} Menu of widget
13472 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
13477 * Handles menu select events.
13480 * @param {OO.ui.MenuOptionWidget} item Selected menu item
13482 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
13486 this.setLabel( null );
13490 selectedLabel
= item
.getLabel();
13492 // If the label is a DOM element, clone it, because setLabel will append() it
13493 if ( selectedLabel
instanceof jQuery
) {
13494 selectedLabel
= selectedLabel
.clone();
13497 this.setLabel( selectedLabel
);
13501 * Handle mouse click events.
13504 * @param {jQuery.Event} e Mouse click event
13506 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
13507 if ( !this.isDisabled() && e
.which
=== 1 ) {
13508 this.menu
.toggle();
13514 * Handle key press events.
13517 * @param {jQuery.Event} e Key press event
13519 OO
.ui
.DropdownWidget
.prototype.onKeyPress = function ( e
) {
13520 if ( !this.isDisabled() &&
13521 ( ( e
.which
=== OO
.ui
.Keys
.SPACE
&& !this.menu
.isVisible() ) || e
.which
=== OO
.ui
.Keys
.ENTER
)
13523 this.menu
.toggle();
13529 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
13530 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
13531 * OO.ui.mixin.IndicatorElement indicators}.
13532 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
13535 * // Example of a file select widget
13536 * var selectFile = new OO.ui.SelectFileWidget();
13537 * $( 'body' ).append( selectFile.$element );
13539 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
13542 * @extends OO.ui.Widget
13543 * @mixins OO.ui.mixin.IconElement
13544 * @mixins OO.ui.mixin.IndicatorElement
13545 * @mixins OO.ui.mixin.PendingElement
13546 * @mixins OO.ui.mixin.LabelElement
13547 * @mixins OO.ui.mixin.TabIndexedElement
13550 * @param {Object} [config] Configuration options
13551 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
13552 * @cfg {string} [placeholder] Text to display when no file is selected.
13553 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
13554 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
13556 OO
.ui
.SelectFileWidget
= function OoUiSelectFileWidget( config
) {
13559 // Configuration initialization
13560 config
= $.extend( {
13562 placeholder
: OO
.ui
.msg( 'ooui-selectfile-placeholder' ),
13563 notsupported
: OO
.ui
.msg( 'ooui-selectfile-not-supported' ),
13567 // Parent constructor
13568 OO
.ui
.SelectFileWidget
.parent
.call( this, config
);
13570 // Properties (must be set before TabIndexedElement constructor call)
13571 this.$handle
= $( '<span>' );
13573 // Mixin constructors
13574 OO
.ui
.mixin
.IconElement
.call( this, config
);
13575 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13576 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$handle
} ) );
13577 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { autoFitLabel
: true } ) );
13578 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
13581 this.isSupported
= this.constructor.static.isSupported();
13582 this.currentFile
= null;
13583 if ( Array
.isArray( config
.accept
) ) {
13584 this.accept
= config
.accept
;
13586 this.accept
= null;
13588 this.placeholder
= config
.placeholder
;
13589 this.notsupported
= config
.notsupported
;
13590 this.onFileSelectedHandler
= this.onFileSelected
.bind( this );
13592 this.clearButton
= new OO
.ui
.ButtonWidget( {
13593 classes
: [ 'oo-ui-selectFileWidget-clearButton' ],
13596 disabled
: this.disabled
13601 keypress
: this.onKeyPress
.bind( this )
13603 this.clearButton
.connect( this, {
13604 click
: 'onClearClick'
13606 if ( config
.droppable
) {
13607 dragHandler
= this.onDragEnterOrOver
.bind( this );
13609 dragenter
: dragHandler
,
13610 dragover
: dragHandler
,
13611 dragleave
: this.onDragLeave
.bind( this ),
13612 drop
: this.onDrop
.bind( this )
13619 this.$label
.addClass( 'oo-ui-selectFileWidget-label' );
13621 .addClass( 'oo-ui-selectFileWidget-handle' )
13622 .append( this.$icon
, this.$label
, this.clearButton
.$element
, this.$indicator
);
13624 .addClass( 'oo-ui-selectFileWidget' )
13625 .append( this.$handle
);
13626 if ( config
.droppable
) {
13627 this.$element
.addClass( 'oo-ui-selectFileWidget-droppable' );
13633 OO
.inheritClass( OO
.ui
.SelectFileWidget
, OO
.ui
.Widget
);
13634 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IconElement
);
13635 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IndicatorElement
);
13636 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.PendingElement
);
13637 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.LabelElement
);
13638 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13640 /* Static Properties */
13643 * Check if this widget is supported
13646 * @return {boolean}
13648 OO
.ui
.SelectFileWidget
.static.isSupported = function () {
13650 if ( OO
.ui
.SelectFileWidget
.static.isSupportedCache
=== null ) {
13651 $input
= $( '<input type="file">' );
13652 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= $input
[0].files
!== undefined;
13654 return OO
.ui
.SelectFileWidget
.static.isSupportedCache
;
13657 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= null;
13664 * A change event is emitted when the on/off state of the toggle changes.
13666 * @param {File|null} value New value
13672 * Get the current value of the field
13674 * @return {File|null}
13676 OO
.ui
.SelectFileWidget
.prototype.getValue = function () {
13677 return this.currentFile
;
13681 * Set the current value of the field
13683 * @param {File|null} file File to select
13685 OO
.ui
.SelectFileWidget
.prototype.setValue = function ( file
) {
13686 if ( this.currentFile
!== file
) {
13687 this.currentFile
= file
;
13689 this.emit( 'change', this.currentFile
);
13694 * Update the user interface when a file is selected or unselected
13698 OO
.ui
.SelectFileWidget
.prototype.updateUI = function () {
13699 if ( !this.isSupported
) {
13700 this.$element
.addClass( 'oo-ui-selectFileWidget-notsupported' );
13701 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
13702 this.setLabel( this.notsupported
);
13703 } else if ( this.currentFile
) {
13704 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
13705 this.setLabel( this.currentFile
.name
+
13706 ( this.currentFile
.type
!== '' ? OO
.ui
.msg( 'ooui-semicolon-separator' ) + this.currentFile
.type
: '' )
13709 this.$element
.addClass( 'oo-ui-selectFileWidget-empty' );
13710 this.setLabel( this.placeholder
);
13713 if ( this.$input
) {
13714 this.$input
.attr( 'title', this.getLabel() );
13719 * Add the input to the handle
13723 OO
.ui
.SelectFileWidget
.prototype.addInput = function () {
13724 if ( this.$input
) {
13725 this.$input
.remove();
13728 if ( !this.isSupported
) {
13729 this.$input
= null;
13733 this.$input
= $( '<input type="file">' );
13734 this.$input
.on( 'change', this.onFileSelectedHandler
);
13735 this.$input
.attr( {
13737 title
: this.getLabel()
13739 if ( this.accept
) {
13740 this.$input
.attr( 'accept', this.accept
.join( ', ' ) );
13742 this.$handle
.append( this.$input
);
13746 * Determine if we should accept this file
13749 * @param {File} file
13750 * @return {boolean}
13752 OO
.ui
.SelectFileWidget
.prototype.isFileAcceptable = function ( file
) {
13753 var i
, mime
, mimeTest
;
13755 if ( !this.accept
|| file
.type
=== '' ) {
13760 for ( i
= 0; i
< this.accept
.length
; i
++ ) {
13761 mimeTest
= this.accept
[i
];
13762 if ( mimeTest
=== mime
) {
13764 } else if ( mimeTest
.substr( -2 ) === '/*' ) {
13765 mimeTest
= mimeTest
.substr( 0, mimeTest
.length
- 1 );
13766 if ( mime
.substr( 0, mimeTest
.length
) === mimeTest
) {
13776 * Handle file selection from the input
13779 * @param {jQuery.Event} e
13781 OO
.ui
.SelectFileWidget
.prototype.onFileSelected = function ( e
) {
13784 if ( e
.target
.files
&& e
.target
.files
[0] ) {
13785 file
= e
.target
.files
[0];
13786 if ( !this.isFileAcceptable( file
) ) {
13791 this.setValue( file
);
13796 * Handle clear button click events.
13800 OO
.ui
.SelectFileWidget
.prototype.onClearClick = function () {
13801 this.setValue( null );
13806 * Handle key press events.
13809 * @param {jQuery.Event} e Key press event
13811 OO
.ui
.SelectFileWidget
.prototype.onKeyPress = function ( e
) {
13812 if ( this.isSupported
&& !this.isDisabled() && this.$input
&&
13813 ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
13815 this.$input
.click();
13821 * Handle drag enter and over events
13824 * @param {jQuery.Event} e Drag event
13826 OO
.ui
.SelectFileWidget
.prototype.onDragEnterOrOver = function ( e
) {
13828 dt
= e
.originalEvent
.dataTransfer
;
13830 e
.preventDefault();
13831 e
.stopPropagation();
13833 if ( this.isDisabled() || !this.isSupported
) {
13834 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
13835 dt
.dropEffect
= 'none';
13839 if ( dt
&& dt
.files
&& dt
.files
[0] ) {
13840 file
= dt
.files
[0];
13841 if ( !this.isFileAcceptable( file
) ) {
13844 } else if ( dt
&& dt
.types
&& $.inArray( 'Files', dt
.types
) ) {
13845 // We know we have files so set 'file' to something truthy, we just
13846 // can't know any details about them.
13847 // * https://bugzilla.mozilla.org/show_bug.cgi?id=640534
13848 file
= 'Files exist, but details are unknown';
13851 this.$element
.addClass( 'oo-ui-selectFileWidget-canDrop' );
13853 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
13854 dt
.dropEffect
= 'none';
13861 * Handle drag leave events
13864 * @param {jQuery.Event} e Drag event
13866 OO
.ui
.SelectFileWidget
.prototype.onDragLeave = function () {
13867 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
13871 * Handle drop events
13874 * @param {jQuery.Event} e Drop event
13876 OO
.ui
.SelectFileWidget
.prototype.onDrop = function ( e
) {
13878 dt
= e
.originalEvent
.dataTransfer
;
13880 e
.preventDefault();
13881 e
.stopPropagation();
13882 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
13884 if ( this.isDisabled() || !this.isSupported
) {
13888 if ( dt
&& dt
.files
&& dt
.files
[0] ) {
13889 file
= dt
.files
[0];
13890 if ( !this.isFileAcceptable( file
) ) {
13895 this.setValue( file
);
13904 OO
.ui
.SelectFileWidget
.prototype.setDisabled = function ( state
) {
13905 OO
.ui
.SelectFileWidget
.parent
.prototype.setDisabled
.call( this, state
);
13906 if ( this.clearButton
) {
13907 this.clearButton
.setDisabled( state
);
13913 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
13914 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
13915 * for a list of icons included in the library.
13918 * // An icon widget with a label
13919 * var myIcon = new OO.ui.IconWidget( {
13921 * iconTitle: 'Help'
13923 * // Create a label.
13924 * var iconLabel = new OO.ui.LabelWidget( {
13927 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
13929 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
13932 * @extends OO.ui.Widget
13933 * @mixins OO.ui.mixin.IconElement
13934 * @mixins OO.ui.mixin.TitledElement
13935 * @mixins OO.ui.mixin.FlaggedElement
13938 * @param {Object} [config] Configuration options
13940 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
13941 // Configuration initialization
13942 config
= config
|| {};
13944 // Parent constructor
13945 OO
.ui
.IconWidget
.parent
.call( this, config
);
13947 // Mixin constructors
13948 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
13949 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
13950 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
13953 this.$element
.addClass( 'oo-ui-iconWidget' );
13958 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
13959 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
13960 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
13961 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
13963 /* Static Properties */
13965 OO
.ui
.IconWidget
.static.tagName
= 'span';
13968 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
13969 * attention to the status of an item or to clarify the function of a control. For a list of
13970 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
13973 * // Example of an indicator widget
13974 * var indicator1 = new OO.ui.IndicatorWidget( {
13975 * indicator: 'alert'
13978 * // Create a fieldset layout to add a label
13979 * var fieldset = new OO.ui.FieldsetLayout();
13980 * fieldset.addItems( [
13981 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
13983 * $( 'body' ).append( fieldset.$element );
13985 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
13988 * @extends OO.ui.Widget
13989 * @mixins OO.ui.mixin.IndicatorElement
13990 * @mixins OO.ui.mixin.TitledElement
13993 * @param {Object} [config] Configuration options
13995 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
13996 // Configuration initialization
13997 config
= config
|| {};
13999 // Parent constructor
14000 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
14002 // Mixin constructors
14003 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
14004 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
14007 this.$element
.addClass( 'oo-ui-indicatorWidget' );
14012 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
14013 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
14014 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
14016 /* Static Properties */
14018 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
14021 * InputWidget is the base class for all input widgets, which
14022 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
14023 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
14024 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14026 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14030 * @extends OO.ui.Widget
14031 * @mixins OO.ui.mixin.FlaggedElement
14032 * @mixins OO.ui.mixin.TabIndexedElement
14035 * @param {Object} [config] Configuration options
14036 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
14037 * @cfg {string} [value=''] The value of the input.
14038 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
14039 * before it is accepted.
14041 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
14042 // Configuration initialization
14043 config
= config
|| {};
14045 // Parent constructor
14046 OO
.ui
.InputWidget
.parent
.call( this, config
);
14049 this.$input
= this.getInputElement( config
);
14051 this.inputFilter
= config
.inputFilter
;
14053 // Mixin constructors
14054 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
14055 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
14058 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
14062 .addClass( 'oo-ui-inputWidget-input' )
14063 .attr( 'name', config
.name
)
14064 .prop( 'disabled', this.isDisabled() );
14066 .addClass( 'oo-ui-inputWidget' )
14067 .append( this.$input
);
14068 this.setValue( config
.value
);
14073 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
14074 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
14075 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
14077 /* Static Properties */
14079 OO
.ui
.InputWidget
.static.supportsSimpleLabel
= true;
14086 * A change event is emitted when the value of the input changes.
14088 * @param {string} value
14094 * Get input element.
14096 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14097 * different circumstances. The element must have a `value` property (like form elements).
14100 * @param {Object} config Configuration options
14101 * @return {jQuery} Input element
14103 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
14104 return $( '<input>' );
14108 * Handle potentially value-changing events.
14111 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14113 OO
.ui
.InputWidget
.prototype.onEdit = function () {
14115 if ( !this.isDisabled() ) {
14116 // Allow the stack to clear so the value will be updated
14117 setTimeout( function () {
14118 widget
.setValue( widget
.$input
.val() );
14124 * Get the value of the input.
14126 * @return {string} Input value
14128 OO
.ui
.InputWidget
.prototype.getValue = function () {
14129 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14130 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14131 var value
= this.$input
.val();
14132 if ( this.value
!== value
) {
14133 this.setValue( value
);
14139 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
14141 * @param {boolean} isRTL
14142 * Direction is right-to-left
14144 OO
.ui
.InputWidget
.prototype.setRTL = function ( isRTL
) {
14145 this.$input
.prop( 'dir', isRTL
? 'rtl' : 'ltr' );
14149 * Set the value of the input.
14151 * @param {string} value New value
14155 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
14156 value
= this.cleanUpValue( value
);
14157 // Update the DOM if it has changed. Note that with cleanUpValue, it
14158 // is possible for the DOM value to change without this.value changing.
14159 if ( this.$input
.val() !== value
) {
14160 this.$input
.val( value
);
14162 if ( this.value
!== value
) {
14163 this.value
= value
;
14164 this.emit( 'change', this.value
);
14170 * Clean up incoming value.
14172 * Ensures value is a string, and converts undefined and null to empty string.
14175 * @param {string} value Original value
14176 * @return {string} Cleaned up value
14178 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
14179 if ( value
=== undefined || value
=== null ) {
14181 } else if ( this.inputFilter
) {
14182 return this.inputFilter( String( value
) );
14184 return String( value
);
14189 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
14190 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
14193 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
14194 if ( !this.isDisabled() ) {
14195 if ( this.$input
.is( ':checkbox, :radio' ) ) {
14196 this.$input
.click();
14198 if ( this.$input
.is( ':input' ) ) {
14199 this.$input
[ 0 ].focus();
14207 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
14208 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
14209 if ( this.$input
) {
14210 this.$input
.prop( 'disabled', this.isDisabled() );
14220 OO
.ui
.InputWidget
.prototype.focus = function () {
14221 this.$input
[ 0 ].focus();
14230 OO
.ui
.InputWidget
.prototype.blur = function () {
14231 this.$input
[ 0 ].blur();
14238 OO
.ui
.InputWidget
.prototype.gatherPreInfuseState = function ( node
) {
14240 state
= OO
.ui
.InputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
),
14241 $input
= state
.$input
|| $( node
).find( '.oo-ui-inputWidget-input' );
14242 state
.value
= $input
.val();
14243 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14244 state
.focus
= $input
.is( ':focus' );
14251 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
14252 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
14253 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
14254 this.setValue( state
.value
);
14256 if ( state
.focus
) {
14262 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
14263 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
14264 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
14265 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
14266 * [OOjs UI documentation on MediaWiki] [1] for more information.
14269 * // A ButtonInputWidget rendered as an HTML button, the default.
14270 * var button = new OO.ui.ButtonInputWidget( {
14271 * label: 'Input button',
14275 * $( 'body' ).append( button.$element );
14277 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
14280 * @extends OO.ui.InputWidget
14281 * @mixins OO.ui.mixin.ButtonElement
14282 * @mixins OO.ui.mixin.IconElement
14283 * @mixins OO.ui.mixin.IndicatorElement
14284 * @mixins OO.ui.mixin.LabelElement
14285 * @mixins OO.ui.mixin.TitledElement
14288 * @param {Object} [config] Configuration options
14289 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
14290 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
14291 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
14292 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
14293 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
14295 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
14296 // Configuration initialization
14297 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
14299 // Properties (must be set before parent constructor, which calls #setValue)
14300 this.useInputTag
= config
.useInputTag
;
14302 // Parent constructor
14303 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
14305 // Mixin constructors
14306 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
14307 OO
.ui
.mixin
.IconElement
.call( this, config
);
14308 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
14309 OO
.ui
.mixin
.LabelElement
.call( this, config
);
14310 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
14313 if ( !config
.useInputTag
) {
14314 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
14316 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
14321 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
14322 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
14323 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
14324 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
14325 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
14326 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
14328 /* Static Properties */
14331 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
14332 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
14334 OO
.ui
.ButtonInputWidget
.static.supportsSimpleLabel
= false;
14342 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
14343 var type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ?
14346 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
14352 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
14354 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
14355 * text, or `null` for no label
14358 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
14359 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
14361 if ( this.useInputTag
) {
14362 if ( typeof label
=== 'function' ) {
14363 label
= OO
.ui
.resolveMsg( label
);
14365 if ( label
instanceof jQuery
) {
14366 label
= label
.text();
14371 this.$input
.val( label
);
14378 * Set the value of the input.
14380 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
14381 * they do not support {@link #value values}.
14383 * @param {string} value New value
14386 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
14387 if ( !this.useInputTag
) {
14388 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
14394 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
14395 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
14396 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
14397 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
14399 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14402 * // An example of selected, unselected, and disabled checkbox inputs
14403 * var checkbox1=new OO.ui.CheckboxInputWidget( {
14407 * var checkbox2=new OO.ui.CheckboxInputWidget( {
14410 * var checkbox3=new OO.ui.CheckboxInputWidget( {
14414 * // Create a fieldset layout with fields for each checkbox.
14415 * var fieldset = new OO.ui.FieldsetLayout( {
14416 * label: 'Checkboxes'
14418 * fieldset.addItems( [
14419 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
14420 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
14421 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
14423 * $( 'body' ).append( fieldset.$element );
14425 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14428 * @extends OO.ui.InputWidget
14431 * @param {Object} [config] Configuration options
14432 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
14434 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
14435 // Configuration initialization
14436 config
= config
|| {};
14438 // Parent constructor
14439 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
14443 .addClass( 'oo-ui-checkboxInputWidget' )
14444 // Required for pretty styling in MediaWiki theme
14445 .append( $( '<span>' ) );
14446 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
14451 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
14459 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
14460 return $( '<input type="checkbox" />' );
14466 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
14468 if ( !this.isDisabled() ) {
14469 // Allow the stack to clear so the value will be updated
14470 setTimeout( function () {
14471 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
14477 * Set selection state of this checkbox.
14479 * @param {boolean} state `true` for selected
14482 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
14484 if ( this.selected
!== state
) {
14485 this.selected
= state
;
14486 this.$input
.prop( 'checked', this.selected
);
14487 this.emit( 'change', this.selected
);
14493 * Check if this checkbox is selected.
14495 * @return {boolean} Checkbox is selected
14497 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
14498 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14499 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14500 var selected
= this.$input
.prop( 'checked' );
14501 if ( this.selected
!== selected
) {
14502 this.setSelected( selected
);
14504 return this.selected
;
14510 OO
.ui
.CheckboxInputWidget
.prototype.gatherPreInfuseState = function ( node
) {
14512 state
= OO
.ui
.CheckboxInputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
),
14513 $input
= $( node
).find( '.oo-ui-inputWidget-input' );
14514 state
.$input
= $input
; // shortcut for performance, used in InputWidget
14515 state
.checked
= $input
.prop( 'checked' );
14522 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
14523 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
14524 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
14525 this.setSelected( state
.checked
);
14530 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
14531 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
14532 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
14533 * more information about input widgets.
14535 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
14536 * are no options. If no `value` configuration option is provided, the first option is selected.
14537 * If you need a state representing no value (no option being selected), use a DropdownWidget.
14539 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
14542 * // Example: A DropdownInputWidget with three options
14543 * var dropdownInput = new OO.ui.DropdownInputWidget( {
14545 * { data: 'a', label: 'First' },
14546 * { data: 'b', label: 'Second'},
14547 * { data: 'c', label: 'Third' }
14550 * $( 'body' ).append( dropdownInput.$element );
14552 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14555 * @extends OO.ui.InputWidget
14556 * @mixins OO.ui.mixin.TitledElement
14559 * @param {Object} [config] Configuration options
14560 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
14562 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
14563 // Configuration initialization
14564 config
= config
|| {};
14566 // Properties (must be done before parent constructor which calls #setDisabled)
14567 this.dropdownWidget
= new OO
.ui
.DropdownWidget();
14569 // Parent constructor
14570 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
14572 // Mixin constructors
14573 OO
.ui
.mixin
.TitledElement
.call( this, config
);
14576 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
14579 this.setOptions( config
.options
|| [] );
14581 .addClass( 'oo-ui-dropdownInputWidget' )
14582 .append( this.dropdownWidget
.$element
);
14587 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
14588 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
14596 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
14597 return $( '<input type="hidden">' );
14601 * Handles menu select events.
14604 * @param {OO.ui.MenuOptionWidget} item Selected menu item
14606 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
14607 this.setValue( item
.getData() );
14613 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
14614 value
= this.cleanUpValue( value
);
14615 this.dropdownWidget
.getMenu().selectItemByData( value
);
14616 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
14623 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
14624 this.dropdownWidget
.setDisabled( state
);
14625 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
14630 * Set the options available for this input.
14632 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
14635 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
14637 value
= this.getValue(),
14640 // Rebuild the dropdown menu
14641 this.dropdownWidget
.getMenu()
14643 .addItems( options
.map( function ( opt
) {
14644 var optValue
= widget
.cleanUpValue( opt
.data
);
14645 return new OO
.ui
.MenuOptionWidget( {
14647 label
: opt
.label
!== undefined ? opt
.label
: optValue
14651 // Restore the previous value, or reset to something sensible
14652 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
14653 // Previous value is still available, ensure consistency with the dropdown
14654 this.setValue( value
);
14656 // No longer valid, reset
14657 if ( options
.length
) {
14658 this.setValue( options
[ 0 ].data
);
14668 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
14669 this.dropdownWidget
.getMenu().toggle( true );
14676 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
14677 this.dropdownWidget
.getMenu().toggle( false );
14682 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
14683 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
14684 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
14685 * please see the [OOjs UI documentation on MediaWiki][1].
14687 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14690 * // An example of selected, unselected, and disabled radio inputs
14691 * var radio1 = new OO.ui.RadioInputWidget( {
14695 * var radio2 = new OO.ui.RadioInputWidget( {
14698 * var radio3 = new OO.ui.RadioInputWidget( {
14702 * // Create a fieldset layout with fields for each radio button.
14703 * var fieldset = new OO.ui.FieldsetLayout( {
14704 * label: 'Radio inputs'
14706 * fieldset.addItems( [
14707 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
14708 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
14709 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
14711 * $( 'body' ).append( fieldset.$element );
14713 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14716 * @extends OO.ui.InputWidget
14719 * @param {Object} [config] Configuration options
14720 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
14722 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
14723 // Configuration initialization
14724 config
= config
|| {};
14726 // Parent constructor
14727 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
14731 .addClass( 'oo-ui-radioInputWidget' )
14732 // Required for pretty styling in MediaWiki theme
14733 .append( $( '<span>' ) );
14734 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
14739 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
14747 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
14748 return $( '<input type="radio" />' );
14754 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
14755 // RadioInputWidget doesn't track its state.
14759 * Set selection state of this radio button.
14761 * @param {boolean} state `true` for selected
14764 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
14765 // RadioInputWidget doesn't track its state.
14766 this.$input
.prop( 'checked', state
);
14771 * Check if this radio button is selected.
14773 * @return {boolean} Radio is selected
14775 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
14776 return this.$input
.prop( 'checked' );
14782 OO
.ui
.RadioInputWidget
.prototype.gatherPreInfuseState = function ( node
) {
14784 state
= OO
.ui
.RadioInputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
),
14785 $input
= $( node
).find( '.oo-ui-inputWidget-input' );
14786 state
.$input
= $input
; // shortcut for performance, used in InputWidget
14787 state
.checked
= $input
.prop( 'checked' );
14794 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
14795 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
14796 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
14797 this.setSelected( state
.checked
);
14802 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
14803 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
14804 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
14805 * more information about input widgets.
14807 * This and OO.ui.DropdownInputWidget support the same configuration options.
14810 * // Example: A RadioSelectInputWidget with three options
14811 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
14813 * { data: 'a', label: 'First' },
14814 * { data: 'b', label: 'Second'},
14815 * { data: 'c', label: 'Third' }
14818 * $( 'body' ).append( radioSelectInput.$element );
14820 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14823 * @extends OO.ui.InputWidget
14826 * @param {Object} [config] Configuration options
14827 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
14829 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
14830 // Configuration initialization
14831 config
= config
|| {};
14833 // Properties (must be done before parent constructor which calls #setDisabled)
14834 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
14836 // Parent constructor
14837 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
14840 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
14843 this.setOptions( config
.options
|| [] );
14845 .addClass( 'oo-ui-radioSelectInputWidget' )
14846 .append( this.radioSelectWidget
.$element
);
14851 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
14853 /* Static Properties */
14855 OO
.ui
.RadioSelectInputWidget
.static.supportsSimpleLabel
= false;
14863 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
14864 return $( '<input type="hidden">' );
14868 * Handles menu select events.
14871 * @param {OO.ui.RadioOptionWidget} item Selected menu item
14873 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
14874 this.setValue( item
.getData() );
14880 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
14881 value
= this.cleanUpValue( value
);
14882 this.radioSelectWidget
.selectItemByData( value
);
14883 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
14890 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
14891 this.radioSelectWidget
.setDisabled( state
);
14892 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
14897 * Set the options available for this input.
14899 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
14902 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
14904 value
= this.getValue(),
14907 // Rebuild the radioSelect menu
14908 this.radioSelectWidget
14910 .addItems( options
.map( function ( opt
) {
14911 var optValue
= widget
.cleanUpValue( opt
.data
);
14912 return new OO
.ui
.RadioOptionWidget( {
14914 label
: opt
.label
!== undefined ? opt
.label
: optValue
14918 // Restore the previous value, or reset to something sensible
14919 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
14920 // Previous value is still available, ensure consistency with the radioSelect
14921 this.setValue( value
);
14923 // No longer valid, reset
14924 if ( options
.length
) {
14925 this.setValue( options
[ 0 ].data
);
14935 OO
.ui
.RadioSelectInputWidget
.prototype.gatherPreInfuseState = function ( node
) {
14936 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
);
14937 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
14942 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
14943 * size of the field as well as its presentation. In addition, these widgets can be configured
14944 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
14945 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
14946 * which modifies incoming values rather than validating them.
14947 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14949 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14952 * // Example of a text input widget
14953 * var textInput = new OO.ui.TextInputWidget( {
14954 * value: 'Text input'
14956 * $( 'body' ).append( textInput.$element );
14958 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14961 * @extends OO.ui.InputWidget
14962 * @mixins OO.ui.mixin.IconElement
14963 * @mixins OO.ui.mixin.IndicatorElement
14964 * @mixins OO.ui.mixin.PendingElement
14965 * @mixins OO.ui.mixin.LabelElement
14968 * @param {Object} [config] Configuration options
14969 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
14970 * 'email' or 'url'. Ignored if `multiline` is true.
14972 * Some values of `type` result in additional behaviors:
14974 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
14975 * empties the text field
14976 * @cfg {string} [placeholder] Placeholder text
14977 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
14978 * instruct the browser to focus this widget.
14979 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
14980 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
14981 * @cfg {boolean} [multiline=false] Allow multiple lines of text
14982 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
14983 * specifies minimum number of rows to display.
14984 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
14985 * Use the #maxRows config to specify a maximum number of displayed rows.
14986 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
14987 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
14988 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
14989 * the value or placeholder text: `'before'` or `'after'`
14990 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
14991 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
14992 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
14993 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
14994 * (the value must contain only numbers); when RegExp, a regular expression that must match the
14995 * value for it to be considered valid; when Function, a function receiving the value as parameter
14996 * that must return true, or promise resolving to true, for it to be considered valid.
14998 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
14999 // Configuration initialization
15000 config
= $.extend( {
15002 labelPosition
: 'after'
15004 if ( config
.type
=== 'search' ) {
15005 if ( config
.icon
=== undefined ) {
15006 config
.icon
= 'search';
15008 // indicator: 'clear' is set dynamically later, depending on value
15010 if ( config
.required
) {
15011 if ( config
.indicator
=== undefined ) {
15012 config
.indicator
= 'required';
15016 // Parent constructor
15017 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
15019 // Mixin constructors
15020 OO
.ui
.mixin
.IconElement
.call( this, config
);
15021 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
15022 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
15023 OO
.ui
.mixin
.LabelElement
.call( this, config
);
15026 this.type
= this.getSaneType( config
);
15027 this.readOnly
= false;
15028 this.multiline
= !!config
.multiline
;
15029 this.autosize
= !!config
.autosize
;
15030 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
15031 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
15032 this.validate
= null;
15034 // Clone for resizing
15035 if ( this.autosize
) {
15036 this.$clone
= this.$input
15038 .insertAfter( this.$input
)
15039 .attr( 'aria-hidden', 'true' )
15040 .addClass( 'oo-ui-element-hidden' );
15043 this.setValidation( config
.validate
);
15044 this.setLabelPosition( config
.labelPosition
);
15048 keypress
: this.onKeyPress
.bind( this ),
15049 blur
: this.onBlur
.bind( this )
15052 focus
: this.onElementAttach
.bind( this )
15054 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
15055 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
15056 this.on( 'labelChange', this.updatePosition
.bind( this ) );
15057 this.connect( this, {
15058 change
: 'onChange',
15059 disable
: 'onDisable'
15064 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
15065 .append( this.$icon
, this.$indicator
);
15066 this.setReadOnly( !!config
.readOnly
);
15067 this.updateSearchIndicator();
15068 if ( config
.placeholder
) {
15069 this.$input
.attr( 'placeholder', config
.placeholder
);
15071 if ( config
.maxLength
!== undefined ) {
15072 this.$input
.attr( 'maxlength', config
.maxLength
);
15074 if ( config
.autofocus
) {
15075 this.$input
.attr( 'autofocus', 'autofocus' );
15077 if ( config
.required
) {
15078 this.$input
.attr( 'required', 'required' );
15079 this.$input
.attr( 'aria-required', 'true' );
15081 if ( config
.autocomplete
=== false ) {
15082 this.$input
.attr( 'autocomplete', 'off' );
15084 if ( this.multiline
&& config
.rows
) {
15085 this.$input
.attr( 'rows', config
.rows
);
15087 if ( this.label
|| config
.autosize
) {
15088 this.installParentChangeDetector();
15094 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
15095 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
15096 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
15097 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
15098 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
15100 /* Static Properties */
15102 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
15110 * An `enter` event is emitted when the user presses 'enter' inside the text box.
15112 * Not emitted if the input is multiline.
15120 * Handle icon mouse down events.
15123 * @param {jQuery.Event} e Mouse down event
15126 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
15127 if ( e
.which
=== 1 ) {
15128 this.$input
[ 0 ].focus();
15134 * Handle indicator mouse down events.
15137 * @param {jQuery.Event} e Mouse down event
15140 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
15141 if ( e
.which
=== 1 ) {
15142 if ( this.type
=== 'search' ) {
15143 // Clear the text field
15144 this.setValue( '' );
15146 this.$input
[ 0 ].focus();
15152 * Handle key press events.
15155 * @param {jQuery.Event} e Key press event
15156 * @fires enter If enter key is pressed and input is not multiline
15158 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
15159 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
15160 this.emit( 'enter', e
);
15165 * Handle blur events.
15168 * @param {jQuery.Event} e Blur event
15170 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
15171 this.setValidityFlag();
15175 * Handle element attach events.
15178 * @param {jQuery.Event} e Element attach event
15180 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
15181 // Any previously calculated size is now probably invalid if we reattached elsewhere
15182 this.valCache
= null;
15184 this.positionLabel();
15188 * Handle change events.
15190 * @param {string} value
15193 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
15194 this.updateSearchIndicator();
15195 this.setValidityFlag();
15200 * Handle disable events.
15202 * @param {boolean} disabled Element is disabled
15205 OO
.ui
.TextInputWidget
.prototype.onDisable = function () {
15206 this.updateSearchIndicator();
15210 * Check if the input is {@link #readOnly read-only}.
15212 * @return {boolean}
15214 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
15215 return this.readOnly
;
15219 * Set the {@link #readOnly read-only} state of the input.
15221 * @param {boolean} state Make input read-only
15224 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
15225 this.readOnly
= !!state
;
15226 this.$input
.prop( 'readOnly', this.readOnly
);
15227 this.updateSearchIndicator();
15232 * Support function for making #onElementAttach work across browsers.
15234 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
15235 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
15237 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
15238 * first time that the element gets attached to the documented.
15240 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
15241 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
15242 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
15245 if ( MutationObserver
) {
15246 // The new way. If only it wasn't so ugly.
15248 if ( this.$element
.closest( 'html' ).length
) {
15249 // Widget is attached already, do nothing. This breaks the functionality of this function when
15250 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
15251 // would require observation of the whole document, which would hurt performance of other,
15252 // more important code.
15256 // Find topmost node in the tree
15257 topmostNode
= this.$element
[0];
15258 while ( topmostNode
.parentNode
) {
15259 topmostNode
= topmostNode
.parentNode
;
15262 // We have no way to detect the $element being attached somewhere without observing the entire
15263 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
15264 // parent node of $element, and instead detect when $element is removed from it (and thus
15265 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
15266 // doesn't get attached, we end up back here and create the parent.
15268 mutationObserver
= new MutationObserver( function ( mutations
) {
15269 var i
, j
, removedNodes
;
15270 for ( i
= 0; i
< mutations
.length
; i
++ ) {
15271 removedNodes
= mutations
[ i
].removedNodes
;
15272 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
15273 if ( removedNodes
[ j
] === topmostNode
) {
15274 setTimeout( onRemove
, 0 );
15281 onRemove = function () {
15282 // If the node was attached somewhere else, report it
15283 if ( widget
.$element
.closest( 'html' ).length
) {
15284 widget
.onElementAttach();
15286 mutationObserver
.disconnect();
15287 widget
.installParentChangeDetector();
15290 // Create a fake parent and observe it
15291 fakeParentNode
= $( '<div>' ).append( topmostNode
)[0];
15292 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
15294 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
15295 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
15296 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
15301 * Automatically adjust the size of the text input.
15303 * This only affects #multiline inputs that are {@link #autosize autosized}.
15307 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
15308 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
, idealHeight
;
15310 if ( this.multiline
&& this.autosize
&& this.$input
.val() !== this.valCache
) {
15312 .val( this.$input
.val() )
15313 .attr( 'rows', this.minRows
)
15314 // Set inline height property to 0 to measure scroll height
15315 .css( 'height', 0 );
15317 this.$clone
.removeClass( 'oo-ui-element-hidden' );
15319 this.valCache
= this.$input
.val();
15321 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
15323 // Remove inline height property to measure natural heights
15324 this.$clone
.css( 'height', '' );
15325 innerHeight
= this.$clone
.innerHeight();
15326 outerHeight
= this.$clone
.outerHeight();
15328 // Measure max rows height
15330 .attr( 'rows', this.maxRows
)
15331 .css( 'height', 'auto' )
15333 maxInnerHeight
= this.$clone
.innerHeight();
15335 // Difference between reported innerHeight and scrollHeight with no scrollbars present
15336 // Equals 1 on Blink-based browsers and 0 everywhere else
15337 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
15338 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
15340 this.$clone
.addClass( 'oo-ui-element-hidden' );
15342 // Only apply inline height when expansion beyond natural height is needed
15343 if ( idealHeight
> innerHeight
) {
15344 // Use the difference between the inner and outer height as a buffer
15345 this.$input
.css( 'height', idealHeight
+ ( outerHeight
- innerHeight
) );
15347 this.$input
.css( 'height', '' );
15357 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
15358 return config
.multiline
?
15359 $( '<textarea>' ) :
15360 $( '<input type="' + this.getSaneType( config
) + '" />' );
15364 * Get sanitized value for 'type' for given config.
15366 * @param {Object} config Configuration options
15367 * @return {string|null}
15370 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
15371 var type
= [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config
.type
) !== -1 ?
15374 return config
.multiline
? 'multiline' : type
;
15378 * Check if the input supports multiple lines.
15380 * @return {boolean}
15382 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
15383 return !!this.multiline
;
15387 * Check if the input automatically adjusts its size.
15389 * @return {boolean}
15391 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
15392 return !!this.autosize
;
15396 * Select the entire text of the input.
15400 OO
.ui
.TextInputWidget
.prototype.select = function () {
15401 this.$input
.select();
15406 * Set the validation pattern.
15408 * The validation pattern is either a regular expression, a function, or the symbolic name of a
15409 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
15410 * value must contain only numbers).
15412 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
15413 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
15415 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
15416 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
15417 this.validate
= validate
;
15419 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
15424 * Sets the 'invalid' flag appropriately.
15426 * @param {boolean} [isValid] Optionally override validation result
15428 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
15430 setFlag = function ( valid
) {
15432 widget
.$input
.attr( 'aria-invalid', 'true' );
15434 widget
.$input
.removeAttr( 'aria-invalid' );
15436 widget
.setFlags( { invalid
: !valid
} );
15439 if ( isValid
!== undefined ) {
15440 setFlag( isValid
);
15442 this.getValidity().then( function () {
15451 * Check if a value is valid.
15453 * This method returns a promise that resolves with a boolean `true` if the current value is
15454 * considered valid according to the supplied {@link #validate validation pattern}.
15457 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
15459 OO
.ui
.TextInputWidget
.prototype.isValid = function () {
15460 if ( this.validate
instanceof Function
) {
15461 var result
= this.validate( this.getValue() );
15462 if ( $.isFunction( result
.promise
) ) {
15463 return result
.promise();
15465 return $.Deferred().resolve( !!result
).promise();
15468 return $.Deferred().resolve( !!this.getValue().match( this.validate
) ).promise();
15473 * Get the validity of current value.
15475 * This method returns a promise that resolves if the value is valid and rejects if
15476 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
15478 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
15480 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
15481 var result
, promise
;
15483 function rejectOrResolve( valid
) {
15485 return $.Deferred().resolve().promise();
15487 return $.Deferred().reject().promise();
15491 if ( this.validate
instanceof Function
) {
15492 result
= this.validate( this.getValue() );
15494 if ( $.isFunction( result
.promise
) ) {
15495 promise
= $.Deferred();
15497 result
.then( function ( valid
) {
15507 return promise
.promise();
15509 return rejectOrResolve( result
);
15512 return rejectOrResolve( this.getValue().match( this.validate
) );
15517 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
15519 * @param {string} labelPosition Label position, 'before' or 'after'
15522 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
15523 this.labelPosition
= labelPosition
;
15524 this.updatePosition();
15529 * Deprecated alias of #setLabelPosition
15531 * @deprecated Use setLabelPosition instead.
15533 OO
.ui
.TextInputWidget
.prototype.setPosition
=
15534 OO
.ui
.TextInputWidget
.prototype.setLabelPosition
;
15537 * Update the position of the inline label.
15539 * This method is called by #setLabelPosition, and can also be called on its own if
15540 * something causes the label to be mispositioned.
15544 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
15545 var after
= this.labelPosition
=== 'after';
15548 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
15549 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
15551 this.positionLabel();
15557 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
15558 * already empty or when it's not editable.
15560 OO
.ui
.TextInputWidget
.prototype.updateSearchIndicator = function () {
15561 if ( this.type
=== 'search' ) {
15562 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
15563 this.setIndicator( null );
15565 this.setIndicator( 'clear' );
15571 * Position the label by setting the correct padding on the input.
15576 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
15577 // Clear old values
15579 // Clear old values if present
15581 'padding-right': '',
15585 if ( this.label
) {
15586 this.$element
.append( this.$label
);
15588 this.$label
.detach();
15592 var after
= this.labelPosition
=== 'after',
15593 rtl
= this.$element
.css( 'direction' ) === 'rtl',
15594 property
= after
=== rtl
? 'padding-left' : 'padding-right';
15596 this.$input
.css( property
, this.$label
.outerWidth( true ) );
15604 OO
.ui
.TextInputWidget
.prototype.gatherPreInfuseState = function ( node
) {
15606 state
= OO
.ui
.TextInputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
),
15607 $input
= $( node
).find( '.oo-ui-inputWidget-input' );
15608 state
.$input
= $input
; // shortcut for performance, used in InputWidget
15609 if ( this.multiline
) {
15610 state
.scrollTop
= $input
.scrollTop();
15618 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
15619 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
15620 if ( state
.scrollTop
!== undefined ) {
15621 this.$input
.scrollTop( state
.scrollTop
);
15626 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
15627 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
15628 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
15630 * - by typing a value in the text input field. If the value exactly matches the value of a menu
15631 * option, that option will appear to be selected.
15632 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
15635 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
15638 * // Example: A ComboBoxWidget.
15639 * var comboBox = new OO.ui.ComboBoxWidget( {
15640 * label: 'ComboBoxWidget',
15641 * input: { value: 'Option One' },
15644 * new OO.ui.MenuOptionWidget( {
15645 * data: 'Option 1',
15646 * label: 'Option One'
15648 * new OO.ui.MenuOptionWidget( {
15649 * data: 'Option 2',
15650 * label: 'Option Two'
15652 * new OO.ui.MenuOptionWidget( {
15653 * data: 'Option 3',
15654 * label: 'Option Three'
15656 * new OO.ui.MenuOptionWidget( {
15657 * data: 'Option 4',
15658 * label: 'Option Four'
15660 * new OO.ui.MenuOptionWidget( {
15661 * data: 'Option 5',
15662 * label: 'Option Five'
15667 * $( 'body' ).append( comboBox.$element );
15669 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
15672 * @extends OO.ui.Widget
15673 * @mixins OO.ui.mixin.TabIndexedElement
15676 * @param {Object} [config] Configuration options
15677 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
15678 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
15679 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
15680 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
15681 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
15683 OO
.ui
.ComboBoxWidget
= function OoUiComboBoxWidget( config
) {
15684 // Configuration initialization
15685 config
= config
|| {};
15687 // Parent constructor
15688 OO
.ui
.ComboBoxWidget
.parent
.call( this, config
);
15690 // Properties (must be set before TabIndexedElement constructor call)
15691 this.$indicator
= this.$( '<span>' );
15693 // Mixin constructors
15694 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
15697 this.$overlay
= config
.$overlay
|| this.$element
;
15698 this.input
= new OO
.ui
.TextInputWidget( $.extend(
15701 $indicator
: this.$indicator
,
15702 disabled
: this.isDisabled()
15706 this.input
.$input
.eq( 0 ).attr( {
15708 'aria-autocomplete': 'list'
15710 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
15714 $container
: this.input
.$element
,
15715 disabled
: this.isDisabled()
15721 this.$indicator
.on( {
15722 click
: this.onClick
.bind( this ),
15723 keypress
: this.onKeyPress
.bind( this )
15725 this.input
.connect( this, {
15726 change
: 'onInputChange',
15727 enter
: 'onInputEnter'
15729 this.menu
.connect( this, {
15730 choose
: 'onMenuChoose',
15731 add
: 'onMenuItemsChange',
15732 remove
: 'onMenuItemsChange'
15736 this.$element
.addClass( 'oo-ui-comboBoxWidget' ).append( this.input
.$element
);
15737 this.$overlay
.append( this.menu
.$element
);
15738 this.onMenuItemsChange();
15743 OO
.inheritClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.Widget
);
15744 OO
.mixinClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.mixin
.TabIndexedElement
);
15749 * Get the combobox's menu.
15750 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
15752 OO
.ui
.ComboBoxWidget
.prototype.getMenu = function () {
15757 * Get the combobox's text input widget.
15758 * @return {OO.ui.TextInputWidget} Text input widget
15760 OO
.ui
.ComboBoxWidget
.prototype.getInput = function () {
15765 * Handle input change events.
15768 * @param {string} value New value
15770 OO
.ui
.ComboBoxWidget
.prototype.onInputChange = function ( value
) {
15771 var match
= this.menu
.getItemFromData( value
);
15773 this.menu
.selectItem( match
);
15774 if ( this.menu
.getHighlightedItem() ) {
15775 this.menu
.highlightItem( match
);
15778 if ( !this.isDisabled() ) {
15779 this.menu
.toggle( true );
15784 * Handle mouse click events.
15788 * @param {jQuery.Event} e Mouse click event
15790 OO
.ui
.ComboBoxWidget
.prototype.onClick = function ( e
) {
15791 if ( !this.isDisabled() && e
.which
=== 1 ) {
15792 this.menu
.toggle();
15793 this.input
.$input
[ 0 ].focus();
15799 * Handle key press events.
15803 * @param {jQuery.Event} e Key press event
15805 OO
.ui
.ComboBoxWidget
.prototype.onKeyPress = function ( e
) {
15806 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
15807 this.menu
.toggle();
15808 this.input
.$input
[ 0 ].focus();
15814 * Handle input enter events.
15818 OO
.ui
.ComboBoxWidget
.prototype.onInputEnter = function () {
15819 if ( !this.isDisabled() ) {
15820 this.menu
.toggle( false );
15825 * Handle menu choose events.
15828 * @param {OO.ui.OptionWidget} item Chosen item
15830 OO
.ui
.ComboBoxWidget
.prototype.onMenuChoose = function ( item
) {
15831 this.input
.setValue( item
.getData() );
15835 * Handle menu item change events.
15839 OO
.ui
.ComboBoxWidget
.prototype.onMenuItemsChange = function () {
15840 var match
= this.menu
.getItemFromData( this.input
.getValue() );
15841 this.menu
.selectItem( match
);
15842 if ( this.menu
.getHighlightedItem() ) {
15843 this.menu
.highlightItem( match
);
15845 this.$element
.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu
.isEmpty() );
15851 OO
.ui
.ComboBoxWidget
.prototype.setDisabled = function ( disabled
) {
15853 OO
.ui
.ComboBoxWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
15855 if ( this.input
) {
15856 this.input
.setDisabled( this.isDisabled() );
15859 this.menu
.setDisabled( this.isDisabled() );
15866 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
15867 * be configured with a `label` option that is set to a string, a label node, or a function:
15869 * - String: a plaintext string
15870 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
15871 * label that includes a link or special styling, such as a gray color or additional graphical elements.
15872 * - Function: a function that will produce a string in the future. Functions are used
15873 * in cases where the value of the label is not currently defined.
15875 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
15876 * will come into focus when the label is clicked.
15879 * // Examples of LabelWidgets
15880 * var label1 = new OO.ui.LabelWidget( {
15881 * label: 'plaintext label'
15883 * var label2 = new OO.ui.LabelWidget( {
15884 * label: $( '<a href="default.html">jQuery label</a>' )
15886 * // Create a fieldset layout with fields for each example
15887 * var fieldset = new OO.ui.FieldsetLayout();
15888 * fieldset.addItems( [
15889 * new OO.ui.FieldLayout( label1 ),
15890 * new OO.ui.FieldLayout( label2 )
15892 * $( 'body' ).append( fieldset.$element );
15896 * @extends OO.ui.Widget
15897 * @mixins OO.ui.mixin.LabelElement
15900 * @param {Object} [config] Configuration options
15901 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
15902 * Clicking the label will focus the specified input field.
15904 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
15905 // Configuration initialization
15906 config
= config
|| {};
15908 // Parent constructor
15909 OO
.ui
.LabelWidget
.parent
.call( this, config
);
15911 // Mixin constructors
15912 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
15913 OO
.ui
.mixin
.TitledElement
.call( this, config
);
15916 this.input
= config
.input
;
15919 if ( this.input
instanceof OO
.ui
.InputWidget
) {
15920 this.$element
.on( 'click', this.onClick
.bind( this ) );
15924 this.$element
.addClass( 'oo-ui-labelWidget' );
15929 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
15930 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
15931 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
15933 /* Static Properties */
15935 OO
.ui
.LabelWidget
.static.tagName
= 'span';
15940 * Handles label mouse click events.
15943 * @param {jQuery.Event} e Mouse click event
15945 OO
.ui
.LabelWidget
.prototype.onClick = function () {
15946 this.input
.simulateLabelClick();
15951 * OptionWidgets are special elements that can be selected and configured with data. The
15952 * data is often unique for each option, but it does not have to be. OptionWidgets are used
15953 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
15954 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
15956 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
15959 * @extends OO.ui.Widget
15960 * @mixins OO.ui.mixin.LabelElement
15961 * @mixins OO.ui.mixin.FlaggedElement
15964 * @param {Object} [config] Configuration options
15966 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
15967 // Configuration initialization
15968 config
= config
|| {};
15970 // Parent constructor
15971 OO
.ui
.OptionWidget
.parent
.call( this, config
);
15973 // Mixin constructors
15974 OO
.ui
.mixin
.ItemWidget
.call( this );
15975 OO
.ui
.mixin
.LabelElement
.call( this, config
);
15976 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
15979 this.selected
= false;
15980 this.highlighted
= false;
15981 this.pressed
= false;
15985 .data( 'oo-ui-optionWidget', this )
15986 .attr( 'role', 'option' )
15987 .attr( 'aria-selected', 'false' )
15988 .addClass( 'oo-ui-optionWidget' )
15989 .append( this.$label
);
15994 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
15995 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
15996 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
15997 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
15999 /* Static Properties */
16001 OO
.ui
.OptionWidget
.static.selectable
= true;
16003 OO
.ui
.OptionWidget
.static.highlightable
= true;
16005 OO
.ui
.OptionWidget
.static.pressable
= true;
16007 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
16012 * Check if the option can be selected.
16014 * @return {boolean} Item is selectable
16016 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
16017 return this.constructor.static.selectable
&& !this.isDisabled() && this.isVisible();
16021 * Check if the option can be highlighted. A highlight indicates that the option
16022 * may be selected when a user presses enter or clicks. Disabled items cannot
16025 * @return {boolean} Item is highlightable
16027 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
16028 return this.constructor.static.highlightable
&& !this.isDisabled() && this.isVisible();
16032 * Check if the option can be pressed. The pressed state occurs when a user mouses
16033 * down on an item, but has not yet let go of the mouse.
16035 * @return {boolean} Item is pressable
16037 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
16038 return this.constructor.static.pressable
&& !this.isDisabled() && this.isVisible();
16042 * Check if the option is selected.
16044 * @return {boolean} Item is selected
16046 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
16047 return this.selected
;
16051 * Check if the option is highlighted. A highlight indicates that the
16052 * item may be selected when a user presses enter or clicks.
16054 * @return {boolean} Item is highlighted
16056 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
16057 return this.highlighted
;
16061 * Check if the option is pressed. The pressed state occurs when a user mouses
16062 * down on an item, but has not yet let go of the mouse. The item may appear
16063 * selected, but it will not be selected until the user releases the mouse.
16065 * @return {boolean} Item is pressed
16067 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
16068 return this.pressed
;
16072 * Set the option’s selected state. In general, all modifications to the selection
16073 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
16074 * method instead of this method.
16076 * @param {boolean} [state=false] Select option
16079 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
16080 if ( this.constructor.static.selectable
) {
16081 this.selected
= !!state
;
16083 .toggleClass( 'oo-ui-optionWidget-selected', state
)
16084 .attr( 'aria-selected', state
.toString() );
16085 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
16086 this.scrollElementIntoView();
16088 this.updateThemeClasses();
16094 * Set the option’s highlighted state. In general, all programmatic
16095 * modifications to the highlight should be handled by the
16096 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
16097 * method instead of this method.
16099 * @param {boolean} [state=false] Highlight option
16102 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
16103 if ( this.constructor.static.highlightable
) {
16104 this.highlighted
= !!state
;
16105 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
16106 this.updateThemeClasses();
16112 * Set the option’s pressed state. In general, all
16113 * programmatic modifications to the pressed state should be handled by the
16114 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
16115 * method instead of this method.
16117 * @param {boolean} [state=false] Press option
16120 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
16121 if ( this.constructor.static.pressable
) {
16122 this.pressed
= !!state
;
16123 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
16124 this.updateThemeClasses();
16130 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
16131 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
16132 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
16133 * options. For more information about options and selects, please see the
16134 * [OOjs UI documentation on MediaWiki][1].
16137 * // Decorated options in a select widget
16138 * var select = new OO.ui.SelectWidget( {
16140 * new OO.ui.DecoratedOptionWidget( {
16142 * label: 'Option with icon',
16145 * new OO.ui.DecoratedOptionWidget( {
16147 * label: 'Option with indicator',
16148 * indicator: 'next'
16152 * $( 'body' ).append( select.$element );
16154 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16157 * @extends OO.ui.OptionWidget
16158 * @mixins OO.ui.mixin.IconElement
16159 * @mixins OO.ui.mixin.IndicatorElement
16162 * @param {Object} [config] Configuration options
16164 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
16165 // Parent constructor
16166 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
16168 // Mixin constructors
16169 OO
.ui
.mixin
.IconElement
.call( this, config
);
16170 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
16174 .addClass( 'oo-ui-decoratedOptionWidget' )
16175 .prepend( this.$icon
)
16176 .append( this.$indicator
);
16181 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
16182 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
16183 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
16186 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
16187 * can be selected and configured with data. The class is
16188 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
16189 * [OOjs UI documentation on MediaWiki] [1] for more information.
16191 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
16194 * @extends OO.ui.DecoratedOptionWidget
16195 * @mixins OO.ui.mixin.ButtonElement
16196 * @mixins OO.ui.mixin.TabIndexedElement
16199 * @param {Object} [config] Configuration options
16201 OO
.ui
.ButtonOptionWidget
= function OoUiButtonOptionWidget( config
) {
16202 // Configuration initialization
16203 config
= config
|| {};
16205 // Parent constructor
16206 OO
.ui
.ButtonOptionWidget
.parent
.call( this, config
);
16208 // Mixin constructors
16209 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
16210 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, {
16211 $tabIndexed
: this.$button
,
16216 this.$element
.addClass( 'oo-ui-buttonOptionWidget' );
16217 this.$button
.append( this.$element
.contents() );
16218 this.$element
.append( this.$button
);
16223 OO
.inheritClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
16224 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.ButtonElement
);
16225 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.TabIndexedElement
);
16227 /* Static Properties */
16229 // Allow button mouse down events to pass through so they can be handled by the parent select widget
16230 OO
.ui
.ButtonOptionWidget
.static.cancelButtonMouseDownEvents
= false;
16232 OO
.ui
.ButtonOptionWidget
.static.highlightable
= false;
16239 OO
.ui
.ButtonOptionWidget
.prototype.setSelected = function ( state
) {
16240 OO
.ui
.ButtonOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
16242 if ( this.constructor.static.selectable
) {
16243 this.setActive( state
);
16250 * RadioOptionWidget is an option widget that looks like a radio button.
16251 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
16252 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
16254 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
16257 * @extends OO.ui.OptionWidget
16260 * @param {Object} [config] Configuration options
16262 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
16263 // Configuration initialization
16264 config
= config
|| {};
16266 // Properties (must be done before parent constructor which calls #setDisabled)
16267 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
16269 // Parent constructor
16270 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
16273 this.radio
.$input
.on( 'focus', this.onInputFocus
.bind( this ) );
16276 // Remove implicit role, we're handling it ourselves
16277 this.radio
.$input
.attr( 'role', 'presentation' );
16279 .addClass( 'oo-ui-radioOptionWidget' )
16280 .attr( 'role', 'radio' )
16281 .attr( 'aria-checked', 'false' )
16282 .removeAttr( 'aria-selected' )
16283 .prepend( this.radio
.$element
);
16288 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
16290 /* Static Properties */
16292 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
16294 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
16296 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
16298 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
16303 * @param {jQuery.Event} e Focus event
16306 OO
.ui
.RadioOptionWidget
.prototype.onInputFocus = function () {
16307 this.radio
.$input
.blur();
16308 this.$element
.parent().focus();
16314 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
16315 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
16317 this.radio
.setSelected( state
);
16319 .attr( 'aria-checked', state
.toString() )
16320 .removeAttr( 'aria-selected' );
16328 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
16329 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
16331 this.radio
.setDisabled( this.isDisabled() );
16337 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
16338 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
16339 * the [OOjs UI documentation on MediaWiki] [1] for more information.
16341 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16344 * @extends OO.ui.DecoratedOptionWidget
16347 * @param {Object} [config] Configuration options
16349 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
16350 // Configuration initialization
16351 config
= $.extend( { icon
: 'check' }, config
);
16353 // Parent constructor
16354 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
16358 .attr( 'role', 'menuitem' )
16359 .addClass( 'oo-ui-menuOptionWidget' );
16364 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
16366 /* Static Properties */
16368 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
16371 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
16372 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
16375 * var myDropdown = new OO.ui.DropdownWidget( {
16378 * new OO.ui.MenuSectionOptionWidget( {
16381 * new OO.ui.MenuOptionWidget( {
16383 * label: 'Welsh Corgi'
16385 * new OO.ui.MenuOptionWidget( {
16387 * label: 'Standard Poodle'
16389 * new OO.ui.MenuSectionOptionWidget( {
16392 * new OO.ui.MenuOptionWidget( {
16399 * $( 'body' ).append( myDropdown.$element );
16403 * @extends OO.ui.DecoratedOptionWidget
16406 * @param {Object} [config] Configuration options
16408 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
16409 // Parent constructor
16410 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
16413 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
16418 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
16420 /* Static Properties */
16422 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
16424 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
16427 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
16429 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
16430 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
16434 * @extends OO.ui.DecoratedOptionWidget
16437 * @param {Object} [config] Configuration options
16438 * @cfg {number} [level] Indentation level
16439 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
16441 OO
.ui
.OutlineOptionWidget
= function OoUiOutlineOptionWidget( config
) {
16442 // Configuration initialization
16443 config
= config
|| {};
16445 // Parent constructor
16446 OO
.ui
.OutlineOptionWidget
.parent
.call( this, config
);
16450 this.movable
= !!config
.movable
;
16451 this.removable
= !!config
.removable
;
16454 this.$element
.addClass( 'oo-ui-outlineOptionWidget' );
16455 this.setLevel( config
.level
);
16460 OO
.inheritClass( OO
.ui
.OutlineOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
16462 /* Static Properties */
16464 OO
.ui
.OutlineOptionWidget
.static.highlightable
= false;
16466 OO
.ui
.OutlineOptionWidget
.static.scrollIntoViewOnSelect
= true;
16468 OO
.ui
.OutlineOptionWidget
.static.levelClass
= 'oo-ui-outlineOptionWidget-level-';
16470 OO
.ui
.OutlineOptionWidget
.static.levels
= 3;
16475 * Check if item is movable.
16477 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16479 * @return {boolean} Item is movable
16481 OO
.ui
.OutlineOptionWidget
.prototype.isMovable = function () {
16482 return this.movable
;
16486 * Check if item is removable.
16488 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16490 * @return {boolean} Item is removable
16492 OO
.ui
.OutlineOptionWidget
.prototype.isRemovable = function () {
16493 return this.removable
;
16497 * Get indentation level.
16499 * @return {number} Indentation level
16501 OO
.ui
.OutlineOptionWidget
.prototype.getLevel = function () {
16508 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16510 * @param {boolean} movable Item is movable
16513 OO
.ui
.OutlineOptionWidget
.prototype.setMovable = function ( movable
) {
16514 this.movable
= !!movable
;
16515 this.updateThemeClasses();
16520 * Set removability.
16522 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16524 * @param {boolean} movable Item is removable
16527 OO
.ui
.OutlineOptionWidget
.prototype.setRemovable = function ( removable
) {
16528 this.removable
= !!removable
;
16529 this.updateThemeClasses();
16534 * Set indentation level.
16536 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
16539 OO
.ui
.OutlineOptionWidget
.prototype.setLevel = function ( level
) {
16540 var levels
= this.constructor.static.levels
,
16541 levelClass
= this.constructor.static.levelClass
,
16544 this.level
= level
? Math
.max( 0, Math
.min( levels
- 1, level
) ) : 0;
16546 if ( this.level
=== i
) {
16547 this.$element
.addClass( levelClass
+ i
);
16549 this.$element
.removeClass( levelClass
+ i
);
16552 this.updateThemeClasses();
16558 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
16560 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
16561 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
16565 * @extends OO.ui.OptionWidget
16568 * @param {Object} [config] Configuration options
16570 OO
.ui
.TabOptionWidget
= function OoUiTabOptionWidget( config
) {
16571 // Configuration initialization
16572 config
= config
|| {};
16574 // Parent constructor
16575 OO
.ui
.TabOptionWidget
.parent
.call( this, config
);
16578 this.$element
.addClass( 'oo-ui-tabOptionWidget' );
16583 OO
.inheritClass( OO
.ui
.TabOptionWidget
, OO
.ui
.OptionWidget
);
16585 /* Static Properties */
16587 OO
.ui
.TabOptionWidget
.static.highlightable
= false;
16590 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
16591 * By default, each popup has an anchor that points toward its origin.
16592 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
16595 * // A popup widget.
16596 * var popup = new OO.ui.PopupWidget( {
16597 * $content: $( '<p>Hi there!</p>' ),
16602 * $( 'body' ).append( popup.$element );
16603 * // To display the popup, toggle the visibility to 'true'.
16604 * popup.toggle( true );
16606 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
16609 * @extends OO.ui.Widget
16610 * @mixins OO.ui.mixin.LabelElement
16613 * @param {Object} [config] Configuration options
16614 * @cfg {number} [width=320] Width of popup in pixels
16615 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
16616 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
16617 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
16618 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
16619 * popup is leaning towards the right of the screen.
16620 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
16621 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
16622 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
16623 * sentence in the given language.
16624 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
16625 * See the [OOjs UI docs on MediaWiki][3] for an example.
16626 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
16627 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
16628 * @cfg {jQuery} [$content] Content to append to the popup's body
16629 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
16630 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
16631 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
16633 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
16634 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
16636 * @cfg {boolean} [padded] Add padding to the popup's body
16638 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
16639 // Configuration initialization
16640 config
= config
|| {};
16642 // Parent constructor
16643 OO
.ui
.PopupWidget
.parent
.call( this, config
);
16645 // Properties (must be set before ClippableElement constructor call)
16646 this.$body
= $( '<div>' );
16648 // Mixin constructors
16649 OO
.ui
.mixin
.LabelElement
.call( this, config
);
16650 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$body
} ) );
16653 this.$popup
= $( '<div>' );
16654 this.$head
= $( '<div>' );
16655 this.$anchor
= $( '<div>' );
16656 // If undefined, will be computed lazily in updateDimensions()
16657 this.$container
= config
.$container
;
16658 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
16659 this.autoClose
= !!config
.autoClose
;
16660 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
16661 this.transitionTimeout
= null;
16662 this.anchor
= null;
16663 this.width
= config
.width
!== undefined ? config
.width
: 320;
16664 this.height
= config
.height
!== undefined ? config
.height
: null;
16665 this.setAlignment( config
.align
);
16666 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
16667 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
16668 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
16671 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
16674 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
16675 this.$body
.addClass( 'oo-ui-popupWidget-body' );
16676 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
16678 .addClass( 'oo-ui-popupWidget-head' )
16679 .append( this.$label
, this.closeButton
.$element
);
16680 if ( !config
.head
) {
16681 this.$head
.addClass( 'oo-ui-element-hidden' );
16684 .addClass( 'oo-ui-popupWidget-popup' )
16685 .append( this.$head
, this.$body
);
16687 .addClass( 'oo-ui-popupWidget' )
16688 .append( this.$popup
, this.$anchor
);
16689 // Move content, which was added to #$element by OO.ui.Widget, to the body
16690 if ( config
.$content
instanceof jQuery
) {
16691 this.$body
.append( config
.$content
);
16693 if ( config
.padded
) {
16694 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
16697 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
16698 // that reference properties not initialized at that time of parent class construction
16699 // TODO: Find a better way to handle post-constructor setup
16700 this.visible
= false;
16701 this.$element
.addClass( 'oo-ui-element-hidden' );
16706 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
16707 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
16708 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
16713 * Handles mouse down events.
16716 * @param {MouseEvent} e Mouse down event
16718 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
16720 this.isVisible() &&
16721 !$.contains( this.$element
[ 0 ], e
.target
) &&
16722 ( !this.$autoCloseIgnore
|| !this.$autoCloseIgnore
.has( e
.target
).length
)
16724 this.toggle( false );
16729 * Bind mouse down listener.
16733 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
16734 // Capture clicks outside popup
16735 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler
);
16739 * Handles close button click events.
16743 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
16744 if ( this.isVisible() ) {
16745 this.toggle( false );
16750 * Unbind mouse down listener.
16754 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
16755 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler
);
16759 * Handles key down events.
16762 * @param {KeyboardEvent} e Key down event
16764 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
16766 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
16769 this.toggle( false );
16770 e
.preventDefault();
16771 e
.stopPropagation();
16776 * Bind key down listener.
16780 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
16781 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler
);
16785 * Unbind key down listener.
16789 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
16790 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler
);
16794 * Show, hide, or toggle the visibility of the anchor.
16796 * @param {boolean} [show] Show anchor, omit to toggle
16798 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
16799 show
= show
=== undefined ? !this.anchored
: !!show
;
16801 if ( this.anchored
!== show
) {
16803 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
16805 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
16807 this.anchored
= show
;
16812 * Check if the anchor is visible.
16814 * @return {boolean} Anchor is visible
16816 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
16817 return this.anchor
;
16823 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
16824 show
= show
=== undefined ? !this.isVisible() : !!show
;
16826 var change
= show
!== this.isVisible();
16829 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
16833 if ( this.autoClose
) {
16834 this.bindMouseDownListener();
16835 this.bindKeyDownListener();
16837 this.updateDimensions();
16838 this.toggleClipping( true );
16840 this.toggleClipping( false );
16841 if ( this.autoClose
) {
16842 this.unbindMouseDownListener();
16843 this.unbindKeyDownListener();
16852 * Set the size of the popup.
16854 * Changing the size may also change the popup's position depending on the alignment.
16856 * @param {number} width Width in pixels
16857 * @param {number} height Height in pixels
16858 * @param {boolean} [transition=false] Use a smooth transition
16861 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
16862 this.width
= width
;
16863 this.height
= height
!== undefined ? height
: null;
16864 if ( this.isVisible() ) {
16865 this.updateDimensions( transition
);
16870 * Update the size and position.
16872 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
16873 * be called automatically.
16875 * @param {boolean} [transition=false] Use a smooth transition
16878 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
16879 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
16880 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
16881 align
= this.align
,
16884 if ( !this.$container
) {
16885 // Lazy-initialize $container if not specified in constructor
16886 this.$container
= $( this.getClosestScrollableElementContainer() );
16889 // Set height and width before measuring things, since it might cause our measurements
16890 // to change (e.g. due to scrollbars appearing or disappearing)
16893 height
: this.height
!== null ? this.height
: 'auto'
16896 // If we are in RTL, we need to flip the alignment, unless it is center
16897 if ( align
=== 'forwards' || align
=== 'backwards' ) {
16898 if ( this.$container
.css( 'direction' ) === 'rtl' ) {
16899 align
= ( { forwards
: 'force-left', backwards
: 'force-right' } )[ this.align
];
16901 align
= ( { forwards
: 'force-right', backwards
: 'force-left' } )[ this.align
];
16906 // Compute initial popupOffset based on alignment
16907 popupOffset
= this.width
* ( { 'force-left': -1, center
: -0.5, 'force-right': 0 } )[ align
];
16909 // Figure out if this will cause the popup to go beyond the edge of the container
16910 originOffset
= this.$element
.offset().left
;
16911 containerLeft
= this.$container
.offset().left
;
16912 containerWidth
= this.$container
.innerWidth();
16913 containerRight
= containerLeft
+ containerWidth
;
16914 popupLeft
= popupOffset
- this.containerPadding
;
16915 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
16916 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
16917 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
16919 // Adjust offset to make the popup not go beyond the edge, if needed
16920 if ( overlapRight
< 0 ) {
16921 popupOffset
+= overlapRight
;
16922 } else if ( overlapLeft
< 0 ) {
16923 popupOffset
-= overlapLeft
;
16926 // Adjust offset to avoid anchor being rendered too close to the edge
16927 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
16928 // TODO: Find a measurement that works for CSS anchors and image anchors
16929 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
16930 if ( popupOffset
+ this.width
< anchorWidth
) {
16931 popupOffset
= anchorWidth
- this.width
;
16932 } else if ( -popupOffset
< anchorWidth
) {
16933 popupOffset
= -anchorWidth
;
16936 // Prevent transition from being interrupted
16937 clearTimeout( this.transitionTimeout
);
16938 if ( transition
) {
16939 // Enable transition
16940 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
16943 // Position body relative to anchor
16944 this.$popup
.css( 'margin-left', popupOffset
);
16946 if ( transition
) {
16947 // Prevent transitioning after transition is complete
16948 this.transitionTimeout
= setTimeout( function () {
16949 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
16952 // Prevent transitioning immediately
16953 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
16956 // Reevaluate clipping state since we've relocated and resized the popup
16963 * Set popup alignment
16964 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
16965 * `backwards` or `forwards`.
16967 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
16968 // Validate alignment and transform deprecated values
16969 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
16970 this.align
= { left
: 'force-right', right
: 'force-left' }[ align
] || align
;
16972 this.align
= 'center';
16977 * Get popup alignment
16978 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
16979 * `backwards` or `forwards`.
16981 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
16986 * Progress bars visually display the status of an operation, such as a download,
16987 * and can be either determinate or indeterminate:
16989 * - **determinate** process bars show the percent of an operation that is complete.
16991 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
16992 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
16993 * not use percentages.
16995 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
16998 * // Examples of determinate and indeterminate progress bars.
16999 * var progressBar1 = new OO.ui.ProgressBarWidget( {
17002 * var progressBar2 = new OO.ui.ProgressBarWidget();
17004 * // Create a FieldsetLayout to layout progress bars
17005 * var fieldset = new OO.ui.FieldsetLayout;
17006 * fieldset.addItems( [
17007 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
17008 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
17010 * $( 'body' ).append( fieldset.$element );
17013 * @extends OO.ui.Widget
17016 * @param {Object} [config] Configuration options
17017 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
17018 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
17019 * By default, the progress bar is indeterminate.
17021 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
17022 // Configuration initialization
17023 config
= config
|| {};
17025 // Parent constructor
17026 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
17029 this.$bar
= $( '<div>' );
17030 this.progress
= null;
17033 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
17034 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
17037 role
: 'progressbar',
17038 'aria-valuemin': 0,
17039 'aria-valuemax': 100
17041 .addClass( 'oo-ui-progressBarWidget' )
17042 .append( this.$bar
);
17047 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
17049 /* Static Properties */
17051 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
17056 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
17058 * @return {number|boolean} Progress percent
17060 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
17061 return this.progress
;
17065 * Set the percent of the process completed or `false` for an indeterminate process.
17067 * @param {number|boolean} progress Progress percent or `false` for indeterminate
17069 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
17070 this.progress
= progress
;
17072 if ( progress
!== false ) {
17073 this.$bar
.css( 'width', this.progress
+ '%' );
17074 this.$element
.attr( 'aria-valuenow', this.progress
);
17076 this.$bar
.css( 'width', '' );
17077 this.$element
.removeAttr( 'aria-valuenow' );
17079 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress
);
17083 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
17084 * and a menu of search results, which is displayed beneath the query
17085 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
17086 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
17087 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
17089 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
17090 * the [OOjs UI demos][1] for an example.
17092 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
17095 * @extends OO.ui.Widget
17098 * @param {Object} [config] Configuration options
17099 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
17100 * @cfg {string} [value] Initial query value
17102 OO
.ui
.SearchWidget
= function OoUiSearchWidget( config
) {
17103 // Configuration initialization
17104 config
= config
|| {};
17106 // Parent constructor
17107 OO
.ui
.SearchWidget
.parent
.call( this, config
);
17110 this.query
= new OO
.ui
.TextInputWidget( {
17112 placeholder
: config
.placeholder
,
17113 value
: config
.value
17115 this.results
= new OO
.ui
.SelectWidget();
17116 this.$query
= $( '<div>' );
17117 this.$results
= $( '<div>' );
17120 this.query
.connect( this, {
17121 change
: 'onQueryChange',
17122 enter
: 'onQueryEnter'
17124 this.query
.$input
.on( 'keydown', this.onQueryKeydown
.bind( this ) );
17128 .addClass( 'oo-ui-searchWidget-query' )
17129 .append( this.query
.$element
);
17131 .addClass( 'oo-ui-searchWidget-results' )
17132 .append( this.results
.$element
);
17134 .addClass( 'oo-ui-searchWidget' )
17135 .append( this.$results
, this.$query
);
17140 OO
.inheritClass( OO
.ui
.SearchWidget
, OO
.ui
.Widget
);
17145 * Handle query key down events.
17148 * @param {jQuery.Event} e Key down event
17150 OO
.ui
.SearchWidget
.prototype.onQueryKeydown = function ( e
) {
17151 var highlightedItem
, nextItem
,
17152 dir
= e
.which
=== OO
.ui
.Keys
.DOWN
? 1 : ( e
.which
=== OO
.ui
.Keys
.UP
? -1 : 0 );
17155 highlightedItem
= this.results
.getHighlightedItem();
17156 if ( !highlightedItem
) {
17157 highlightedItem
= this.results
.getSelectedItem();
17159 nextItem
= this.results
.getRelativeSelectableItem( highlightedItem
, dir
);
17160 this.results
.highlightItem( nextItem
);
17161 nextItem
.scrollElementIntoView();
17166 * Handle select widget select events.
17168 * Clears existing results. Subclasses should repopulate items according to new query.
17171 * @param {string} value New value
17173 OO
.ui
.SearchWidget
.prototype.onQueryChange = function () {
17175 this.results
.clearItems();
17179 * Handle select widget enter key events.
17181 * Chooses highlighted item.
17184 * @param {string} value New value
17186 OO
.ui
.SearchWidget
.prototype.onQueryEnter = function () {
17188 this.results
.chooseItem( this.results
.getHighlightedItem() );
17192 * Get the query input.
17194 * @return {OO.ui.TextInputWidget} Query input
17196 OO
.ui
.SearchWidget
.prototype.getQuery = function () {
17201 * Get the search results menu.
17203 * @return {OO.ui.SelectWidget} Menu of search results
17205 OO
.ui
.SearchWidget
.prototype.getResults = function () {
17206 return this.results
;
17210 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
17211 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
17212 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
17215 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
17216 * information, please see the [OOjs UI documentation on MediaWiki][1].
17219 * // Example of a select widget with three options
17220 * var select = new OO.ui.SelectWidget( {
17222 * new OO.ui.OptionWidget( {
17224 * label: 'Option One',
17226 * new OO.ui.OptionWidget( {
17228 * label: 'Option Two',
17230 * new OO.ui.OptionWidget( {
17232 * label: 'Option Three',
17236 * $( 'body' ).append( select.$element );
17238 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17242 * @extends OO.ui.Widget
17243 * @mixins OO.ui.mixin.GroupWidget
17246 * @param {Object} [config] Configuration options
17247 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
17248 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
17249 * the [OOjs UI documentation on MediaWiki] [2] for examples.
17250 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17252 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
17253 // Configuration initialization
17254 config
= config
|| {};
17256 // Parent constructor
17257 OO
.ui
.SelectWidget
.parent
.call( this, config
);
17259 // Mixin constructors
17260 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
17263 this.pressed
= false;
17264 this.selecting
= null;
17265 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
17266 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
17267 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
17268 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
17269 this.keyPressBuffer
= '';
17270 this.keyPressBufferTimer
= null;
17273 this.connect( this, {
17276 this.$element
.on( {
17277 mousedown
: this.onMouseDown
.bind( this ),
17278 mouseover
: this.onMouseOver
.bind( this ),
17279 mouseleave
: this.onMouseLeave
.bind( this )
17284 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
17285 .attr( 'role', 'listbox' );
17286 if ( Array
.isArray( config
.items
) ) {
17287 this.addItems( config
.items
);
17293 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
17295 // Need to mixin base class as well
17296 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupElement
);
17297 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
17300 OO
.ui
.SelectWidget
.static.passAllFilter = function () {
17309 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
17311 * @param {OO.ui.OptionWidget|null} item Highlighted item
17317 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
17318 * pressed state of an option.
17320 * @param {OO.ui.OptionWidget|null} item Pressed item
17326 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
17328 * @param {OO.ui.OptionWidget|null} item Selected item
17333 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
17334 * @param {OO.ui.OptionWidget} item Chosen item
17340 * An `add` event is emitted when options are added to the select with the #addItems method.
17342 * @param {OO.ui.OptionWidget[]} items Added items
17343 * @param {number} index Index of insertion point
17349 * A `remove` event is emitted when options are removed from the select with the #clearItems
17350 * or #removeItems methods.
17352 * @param {OO.ui.OptionWidget[]} items Removed items
17358 * Handle mouse down events.
17361 * @param {jQuery.Event} e Mouse down event
17363 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
17366 if ( !this.isDisabled() && e
.which
=== 1 ) {
17367 this.togglePressed( true );
17368 item
= this.getTargetItem( e
);
17369 if ( item
&& item
.isSelectable() ) {
17370 this.pressItem( item
);
17371 this.selecting
= item
;
17372 OO
.ui
.addCaptureEventListener(
17373 this.getElementDocument(),
17375 this.onMouseUpHandler
17377 OO
.ui
.addCaptureEventListener(
17378 this.getElementDocument(),
17380 this.onMouseMoveHandler
17388 * Handle mouse up events.
17391 * @param {jQuery.Event} e Mouse up event
17393 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
17396 this.togglePressed( false );
17397 if ( !this.selecting
) {
17398 item
= this.getTargetItem( e
);
17399 if ( item
&& item
.isSelectable() ) {
17400 this.selecting
= item
;
17403 if ( !this.isDisabled() && e
.which
=== 1 && this.selecting
) {
17404 this.pressItem( null );
17405 this.chooseItem( this.selecting
);
17406 this.selecting
= null;
17409 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup',
17410 this.onMouseUpHandler
);
17411 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mousemove',
17412 this.onMouseMoveHandler
);
17418 * Handle mouse move events.
17421 * @param {jQuery.Event} e Mouse move event
17423 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
17426 if ( !this.isDisabled() && this.pressed
) {
17427 item
= this.getTargetItem( e
);
17428 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
17429 this.pressItem( item
);
17430 this.selecting
= item
;
17437 * Handle mouse over events.
17440 * @param {jQuery.Event} e Mouse over event
17442 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
17445 if ( !this.isDisabled() ) {
17446 item
= this.getTargetItem( e
);
17447 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
17453 * Handle mouse leave events.
17456 * @param {jQuery.Event} e Mouse over event
17458 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
17459 if ( !this.isDisabled() ) {
17460 this.highlightItem( null );
17466 * Handle key down events.
17469 * @param {jQuery.Event} e Key down event
17471 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
17474 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
17476 if ( !this.isDisabled() && this.isVisible() ) {
17477 switch ( e
.keyCode
) {
17478 case OO
.ui
.Keys
.ENTER
:
17479 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
17480 // Was only highlighted, now let's select it. No-op if already selected.
17481 this.chooseItem( currentItem
);
17485 case OO
.ui
.Keys
.UP
:
17486 case OO
.ui
.Keys
.LEFT
:
17487 this.clearKeyPressBuffer();
17488 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
17491 case OO
.ui
.Keys
.DOWN
:
17492 case OO
.ui
.Keys
.RIGHT
:
17493 this.clearKeyPressBuffer();
17494 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
17497 case OO
.ui
.Keys
.ESCAPE
:
17498 case OO
.ui
.Keys
.TAB
:
17499 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
17500 currentItem
.setHighlighted( false );
17502 this.unbindKeyDownListener();
17503 this.unbindKeyPressListener();
17504 // Don't prevent tabbing away / defocusing
17510 if ( nextItem
.constructor.static.highlightable
) {
17511 this.highlightItem( nextItem
);
17513 this.chooseItem( nextItem
);
17515 nextItem
.scrollElementIntoView();
17519 // Can't just return false, because e is not always a jQuery event
17520 e
.preventDefault();
17521 e
.stopPropagation();
17527 * Bind key down listener.
17531 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
17532 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler
);
17536 * Unbind key down listener.
17540 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
17541 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler
);
17545 * Clear the key-press buffer
17549 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
17550 if ( this.keyPressBufferTimer
) {
17551 clearTimeout( this.keyPressBufferTimer
);
17552 this.keyPressBufferTimer
= null;
17554 this.keyPressBuffer
= '';
17558 * Handle key press events.
17561 * @param {jQuery.Event} e Key press event
17563 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
17564 var c
, filter
, item
;
17566 if ( !e
.charCode
) {
17567 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
17568 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
17573 if ( String
.fromCodePoint
) {
17574 c
= String
.fromCodePoint( e
.charCode
);
17576 c
= String
.fromCharCode( e
.charCode
);
17579 if ( this.keyPressBufferTimer
) {
17580 clearTimeout( this.keyPressBufferTimer
);
17582 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
17584 item
= this.getHighlightedItem() || this.getSelectedItem();
17586 if ( this.keyPressBuffer
=== c
) {
17587 // Common (if weird) special case: typing "xxxx" will cycle through all
17588 // the items beginning with "x".
17590 item
= this.getRelativeSelectableItem( item
, 1 );
17593 this.keyPressBuffer
+= c
;
17596 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
17597 if ( !item
|| !filter( item
) ) {
17598 item
= this.getRelativeSelectableItem( item
, 1, filter
);
17601 if ( item
.constructor.static.highlightable
) {
17602 this.highlightItem( item
);
17604 this.chooseItem( item
);
17606 item
.scrollElementIntoView();
17613 * Get a matcher for the specific string
17616 * @param {string} s String to match against items
17617 * @param {boolean} [exact=false] Only accept exact matches
17618 * @return {Function} function ( OO.ui.OptionItem ) => boolean
17620 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
17623 if ( s
.normalize
) {
17626 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
17627 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
17631 re
= new RegExp( re
, 'i' );
17632 return function ( item
) {
17633 var l
= item
.getLabel();
17634 if ( typeof l
!== 'string' ) {
17635 l
= item
.$label
.text();
17637 if ( l
.normalize
) {
17640 return re
.test( l
);
17645 * Bind key press listener.
17649 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
17650 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler
);
17654 * Unbind key down listener.
17656 * If you override this, be sure to call this.clearKeyPressBuffer() from your
17661 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
17662 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler
);
17663 this.clearKeyPressBuffer();
17667 * Visibility change handler
17670 * @param {boolean} visible
17672 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
17674 this.clearKeyPressBuffer();
17679 * Get the closest item to a jQuery.Event.
17682 * @param {jQuery.Event} e
17683 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
17685 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
17686 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
17690 * Get selected item.
17692 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
17694 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
17697 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
17698 if ( this.items
[ i
].isSelected() ) {
17699 return this.items
[ i
];
17706 * Get highlighted item.
17708 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
17710 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
17713 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
17714 if ( this.items
[ i
].isHighlighted() ) {
17715 return this.items
[ i
];
17722 * Toggle pressed state.
17724 * Press is a state that occurs when a user mouses down on an item, but
17725 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
17726 * until the user releases the mouse.
17728 * @param {boolean} pressed An option is being pressed
17730 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
17731 if ( pressed
=== undefined ) {
17732 pressed
= !this.pressed
;
17734 if ( pressed
!== this.pressed
) {
17736 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
17737 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
17738 this.pressed
= pressed
;
17743 * Highlight an option. If the `item` param is omitted, no options will be highlighted
17744 * and any existing highlight will be removed. The highlight is mutually exclusive.
17746 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
17750 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
17751 var i
, len
, highlighted
,
17754 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
17755 highlighted
= this.items
[ i
] === item
;
17756 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
17757 this.items
[ i
].setHighlighted( highlighted
);
17762 this.emit( 'highlight', item
);
17769 * Fetch an item by its label.
17771 * @param {string} label Label of the item to select.
17772 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
17773 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
17775 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
17776 var i
, item
, found
,
17777 len
= this.items
.length
,
17778 filter
= this.getItemMatcher( label
, true );
17780 for ( i
= 0; i
< len
; i
++ ) {
17781 item
= this.items
[i
];
17782 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
17789 filter
= this.getItemMatcher( label
, false );
17790 for ( i
= 0; i
< len
; i
++ ) {
17791 item
= this.items
[i
];
17792 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
17808 * Programmatically select an option by its label. If the item does not exist,
17809 * all options will be deselected.
17811 * @param {string} [label] Label of the item to select.
17812 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
17816 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
17817 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
17818 if ( label
=== undefined || !itemFromLabel
) {
17819 return this.selectItem();
17821 return this.selectItem( itemFromLabel
);
17825 * Programmatically select an option by its data. If the `data` parameter is omitted,
17826 * or if the item does not exist, all options will be deselected.
17828 * @param {Object|string} [data] Value of the item to select, omit to deselect all
17832 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
17833 var itemFromData
= this.getItemFromData( data
);
17834 if ( data
=== undefined || !itemFromData
) {
17835 return this.selectItem();
17837 return this.selectItem( itemFromData
);
17841 * Programmatically select an option by its reference. If the `item` parameter is omitted,
17842 * all options will be deselected.
17844 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
17848 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
17849 var i
, len
, selected
,
17852 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
17853 selected
= this.items
[ i
] === item
;
17854 if ( this.items
[ i
].isSelected() !== selected
) {
17855 this.items
[ i
].setSelected( selected
);
17860 this.emit( 'select', item
);
17869 * Press is a state that occurs when a user mouses down on an item, but has not
17870 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
17871 * releases the mouse.
17873 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
17877 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
17878 var i
, len
, pressed
,
17881 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
17882 pressed
= this.items
[ i
] === item
;
17883 if ( this.items
[ i
].isPressed() !== pressed
) {
17884 this.items
[ i
].setPressed( pressed
);
17889 this.emit( 'press', item
);
17898 * Note that ‘choose’ should never be modified programmatically. A user can choose
17899 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
17900 * use the #selectItem method.
17902 * This method is identical to #selectItem, but may vary in subclasses that take additional action
17903 * when users choose an item with the keyboard or mouse.
17905 * @param {OO.ui.OptionWidget} item Item to choose
17909 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
17910 this.selectItem( item
);
17911 this.emit( 'choose', item
);
17917 * Get an option by its position relative to the specified item (or to the start of the option array,
17918 * if item is `null`). The direction in which to search through the option array is specified with a
17919 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
17920 * `null` if there are no options in the array.
17922 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
17923 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
17924 * @param {Function} filter Only consider items for which this function returns
17925 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
17926 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
17928 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
17929 var currentIndex
, nextIndex
, i
,
17930 increase
= direction
> 0 ? 1 : -1,
17931 len
= this.items
.length
;
17933 if ( !$.isFunction( filter
) ) {
17934 filter
= OO
.ui
.SelectWidget
.static.passAllFilter
;
17937 if ( item
instanceof OO
.ui
.OptionWidget
) {
17938 currentIndex
= $.inArray( item
, this.items
);
17939 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
17941 // If no item is selected and moving forward, start at the beginning.
17942 // If moving backward, start at the end.
17943 nextIndex
= direction
> 0 ? 0 : len
- 1;
17946 for ( i
= 0; i
< len
; i
++ ) {
17947 item
= this.items
[ nextIndex
];
17948 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
17951 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
17957 * Get the next selectable item or `null` if there are no selectable items.
17958 * Disabled options and menu-section markers and breaks are not selectable.
17960 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
17962 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
17965 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
17966 item
= this.items
[ i
];
17967 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
17976 * Add an array of options to the select. Optionally, an index number can be used to
17977 * specify an insertion point.
17979 * @param {OO.ui.OptionWidget[]} items Items to add
17980 * @param {number} [index] Index to insert items after
17984 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
17986 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
17988 // Always provide an index, even if it was omitted
17989 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
17995 * Remove the specified array of options from the select. Options will be detached
17996 * from the DOM, not removed, so they can be reused later. To remove all options from
17997 * the select, you may wish to use the #clearItems method instead.
17999 * @param {OO.ui.OptionWidget[]} items Items to remove
18003 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
18006 // Deselect items being removed
18007 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
18009 if ( item
.isSelected() ) {
18010 this.selectItem( null );
18015 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
18017 this.emit( 'remove', items
);
18023 * Clear all options from the select. Options will be detached from the DOM, not removed,
18024 * so that they can be reused later. To remove a subset of options from the select, use
18025 * the #removeItems method.
18030 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
18031 var items
= this.items
.slice();
18034 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
18037 this.selectItem( null );
18039 this.emit( 'remove', items
);
18045 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
18046 * button options and is used together with
18047 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
18048 * highlighting, choosing, and selecting mutually exclusive options. Please see
18049 * the [OOjs UI documentation on MediaWiki] [1] for more information.
18052 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
18053 * var option1 = new OO.ui.ButtonOptionWidget( {
18055 * label: 'Option 1',
18056 * title: 'Button option 1'
18059 * var option2 = new OO.ui.ButtonOptionWidget( {
18061 * label: 'Option 2',
18062 * title: 'Button option 2'
18065 * var option3 = new OO.ui.ButtonOptionWidget( {
18067 * label: 'Option 3',
18068 * title: 'Button option 3'
18071 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
18072 * items: [ option1, option2, option3 ]
18074 * $( 'body' ).append( buttonSelect.$element );
18076 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18079 * @extends OO.ui.SelectWidget
18080 * @mixins OO.ui.mixin.TabIndexedElement
18083 * @param {Object} [config] Configuration options
18085 OO
.ui
.ButtonSelectWidget
= function OoUiButtonSelectWidget( config
) {
18086 // Parent constructor
18087 OO
.ui
.ButtonSelectWidget
.parent
.call( this, config
);
18089 // Mixin constructors
18090 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
18093 this.$element
.on( {
18094 focus
: this.bindKeyDownListener
.bind( this ),
18095 blur
: this.unbindKeyDownListener
.bind( this )
18099 this.$element
.addClass( 'oo-ui-buttonSelectWidget' );
18104 OO
.inheritClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.SelectWidget
);
18105 OO
.mixinClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
18108 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
18109 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
18110 * an interface for adding, removing and selecting options.
18111 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18113 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
18114 * OO.ui.RadioSelectInputWidget instead.
18117 * // A RadioSelectWidget with RadioOptions.
18118 * var option1 = new OO.ui.RadioOptionWidget( {
18120 * label: 'Selected radio option'
18123 * var option2 = new OO.ui.RadioOptionWidget( {
18125 * label: 'Unselected radio option'
18128 * var radioSelect=new OO.ui.RadioSelectWidget( {
18129 * items: [ option1, option2 ]
18132 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
18133 * radioSelect.selectItem( option1 );
18135 * $( 'body' ).append( radioSelect.$element );
18137 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18141 * @extends OO.ui.SelectWidget
18142 * @mixins OO.ui.mixin.TabIndexedElement
18145 * @param {Object} [config] Configuration options
18147 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
18148 // Parent constructor
18149 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
18151 // Mixin constructors
18152 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
18155 this.$element
.on( {
18156 focus
: this.bindKeyDownListener
.bind( this ),
18157 blur
: this.unbindKeyDownListener
.bind( this )
18162 .addClass( 'oo-ui-radioSelectWidget' )
18163 .attr( 'role', 'radiogroup' );
18168 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
18169 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
18172 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
18173 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
18174 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
18175 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
18176 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
18177 * and customized to be opened, closed, and displayed as needed.
18179 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
18180 * mouse outside the menu.
18182 * Menus also have support for keyboard interaction:
18184 * - Enter/Return key: choose and select a menu option
18185 * - Up-arrow key: highlight the previous menu option
18186 * - Down-arrow key: highlight the next menu option
18187 * - Esc key: hide the menu
18189 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18190 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18193 * @extends OO.ui.SelectWidget
18194 * @mixins OO.ui.mixin.ClippableElement
18197 * @param {Object} [config] Configuration options
18198 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
18199 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
18200 * and {@link OO.ui.mixin.LookupElement LookupElement}
18201 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
18202 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
18203 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
18204 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
18205 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
18206 * that button, unless the button (or its parent widget) is passed in here.
18207 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
18208 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
18210 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
18211 // Configuration initialization
18212 config
= config
|| {};
18214 // Parent constructor
18215 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
18217 // Mixin constructors
18218 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
18221 this.newItems
= null;
18222 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
18223 this.filterFromInput
= !!config
.filterFromInput
;
18224 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
18225 this.$widget
= config
.widget
? config
.widget
.$element
: null;
18226 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
18227 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
18231 .addClass( 'oo-ui-menuSelectWidget' )
18232 .attr( 'role', 'menu' );
18234 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
18235 // that reference properties not initialized at that time of parent class construction
18236 // TODO: Find a better way to handle post-constructor setup
18237 this.visible
= false;
18238 this.$element
.addClass( 'oo-ui-element-hidden' );
18243 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
18244 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
18249 * Handles document mouse down events.
18252 * @param {jQuery.Event} e Key down event
18254 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
18256 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
18257 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
18259 this.toggle( false );
18266 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
18267 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
18269 if ( !this.isDisabled() && this.isVisible() ) {
18270 switch ( e
.keyCode
) {
18271 case OO
.ui
.Keys
.LEFT
:
18272 case OO
.ui
.Keys
.RIGHT
:
18273 // Do nothing if a text field is associated, arrow keys will be handled natively
18274 if ( !this.$input
) {
18275 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
18278 case OO
.ui
.Keys
.ESCAPE
:
18279 case OO
.ui
.Keys
.TAB
:
18280 if ( currentItem
) {
18281 currentItem
.setHighlighted( false );
18283 this.toggle( false );
18284 // Don't prevent tabbing away, prevent defocusing
18285 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
18286 e
.preventDefault();
18287 e
.stopPropagation();
18291 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
18298 * Update menu item visibility after input changes.
18301 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
18303 len
= this.items
.length
,
18304 showAll
= !this.isVisible(),
18305 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
18307 for ( i
= 0; i
< len
; i
++ ) {
18308 item
= this.items
[i
];
18309 if ( item
instanceof OO
.ui
.OptionWidget
) {
18310 item
.toggle( showAll
|| filter( item
) );
18314 // Reevaluate clipping
18321 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
18322 if ( this.$input
) {
18323 this.$input
.on( 'keydown', this.onKeyDownHandler
);
18325 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
18332 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
18333 if ( this.$input
) {
18334 this.$input
.off( 'keydown', this.onKeyDownHandler
);
18336 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
18343 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
18344 if ( this.$input
) {
18345 if ( this.filterFromInput
) {
18346 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
18349 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
18356 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
18357 if ( this.$input
) {
18358 if ( this.filterFromInput
) {
18359 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
18360 this.updateItemVisibility();
18363 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
18370 * When a user chooses an item, the menu is closed.
18372 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
18373 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
18374 * @param {OO.ui.OptionWidget} item Item to choose
18377 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
18378 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
18379 this.toggle( false );
18386 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
18390 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
18393 if ( !this.newItems
) {
18394 this.newItems
= [];
18397 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
18399 if ( this.isVisible() ) {
18400 // Defer fitting label until item has been attached
18403 this.newItems
.push( item
);
18407 // Reevaluate clipping
18416 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
18418 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
18420 // Reevaluate clipping
18429 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
18431 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
18433 // Reevaluate clipping
18442 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
18443 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
18446 change
= visible
!== this.isVisible();
18449 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
18453 this.bindKeyDownListener();
18454 this.bindKeyPressListener();
18456 if ( this.newItems
&& this.newItems
.length
) {
18457 for ( i
= 0, len
= this.newItems
.length
; i
< len
; i
++ ) {
18458 this.newItems
[ i
].fitLabel();
18460 this.newItems
= null;
18462 this.toggleClipping( true );
18465 if ( this.autoHide
) {
18466 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler
);
18469 this.unbindKeyDownListener();
18470 this.unbindKeyPressListener();
18471 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler
);
18472 this.toggleClipping( false );
18480 * FloatingMenuSelectWidget is a menu that will stick under a specified
18481 * container, even when it is inserted elsewhere in the document (for example,
18482 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
18483 * menu from being clipped too aggresively.
18485 * The menu's position is automatically calculated and maintained when the menu
18486 * is toggled or the window is resized.
18488 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
18491 * @extends OO.ui.MenuSelectWidget
18494 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
18495 * Deprecated, omit this parameter and specify `$container` instead.
18496 * @param {Object} [config] Configuration options
18497 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
18499 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
18500 // Allow 'inputWidget' parameter and config for backwards compatibility
18501 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
18502 config
= inputWidget
;
18503 inputWidget
= config
.inputWidget
;
18506 // Configuration initialization
18507 config
= config
|| {};
18509 // Parent constructor
18510 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, config
);
18513 this.inputWidget
= inputWidget
; // For backwards compatibility
18514 this.$container
= config
.$container
|| this.inputWidget
.$element
;
18515 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
18518 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
18519 // For backwards compatibility
18520 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
18525 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
18527 // For backwards compatibility
18528 OO
.ui
.TextInputMenuSelectWidget
= OO
.ui
.FloatingMenuSelectWidget
;
18533 * Handle window resize event.
18536 * @param {jQuery.Event} e Window resize event
18538 OO
.ui
.FloatingMenuSelectWidget
.prototype.onWindowResize = function () {
18545 OO
.ui
.FloatingMenuSelectWidget
.prototype.toggle = function ( visible
) {
18546 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
18548 var change
= visible
!== this.isVisible();
18550 if ( change
&& visible
) {
18551 // Make sure the width is set before the parent method runs.
18552 // After this we have to call this.position(); again to actually
18553 // position ourselves correctly.
18558 OO
.ui
.FloatingMenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
18561 if ( this.isVisible() ) {
18563 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
18565 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
18573 * Position the menu.
18578 OO
.ui
.FloatingMenuSelectWidget
.prototype.position = function () {
18579 var $container
= this.$container
,
18580 pos
= OO
.ui
.Element
.static.getRelativePosition( $container
, this.$element
.offsetParent() );
18582 // Position under input
18583 pos
.top
+= $container
.height();
18584 this.$element
.css( pos
);
18587 this.setIdealSize( $container
.width() );
18588 // We updated the position, so re-evaluate the clipping state
18595 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
18596 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
18598 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
18601 * @extends OO.ui.SelectWidget
18602 * @mixins OO.ui.mixin.TabIndexedElement
18605 * @param {Object} [config] Configuration options
18607 OO
.ui
.OutlineSelectWidget
= function OoUiOutlineSelectWidget( config
) {
18608 // Parent constructor
18609 OO
.ui
.OutlineSelectWidget
.parent
.call( this, config
);
18611 // Mixin constructors
18612 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
18615 this.$element
.on( {
18616 focus
: this.bindKeyDownListener
.bind( this ),
18617 blur
: this.unbindKeyDownListener
.bind( this )
18621 this.$element
.addClass( 'oo-ui-outlineSelectWidget' );
18626 OO
.inheritClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.SelectWidget
);
18627 OO
.mixinClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
18630 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
18632 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
18635 * @extends OO.ui.SelectWidget
18636 * @mixins OO.ui.mixin.TabIndexedElement
18639 * @param {Object} [config] Configuration options
18641 OO
.ui
.TabSelectWidget
= function OoUiTabSelectWidget( config
) {
18642 // Parent constructor
18643 OO
.ui
.TabSelectWidget
.parent
.call( this, config
);
18645 // Mixin constructors
18646 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
18649 this.$element
.on( {
18650 focus
: this.bindKeyDownListener
.bind( this ),
18651 blur
: this.unbindKeyDownListener
.bind( this )
18655 this.$element
.addClass( 'oo-ui-tabSelectWidget' );
18660 OO
.inheritClass( OO
.ui
.TabSelectWidget
, OO
.ui
.SelectWidget
);
18661 OO
.mixinClass( OO
.ui
.TabSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
18664 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
18665 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
18666 * (to adjust the value in increments) to allow the user to enter a number.
18669 * // Example: A NumberInputWidget.
18670 * var numberInput = new OO.ui.NumberInputWidget( {
18671 * label: 'NumberInputWidget',
18672 * input: { value: 5, min: 1, max: 10 }
18674 * $( 'body' ).append( numberInput.$element );
18677 * @extends OO.ui.Widget
18680 * @param {Object} [config] Configuration options
18681 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
18682 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
18683 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
18684 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
18685 * @cfg {number} [min=-Infinity] Minimum allowed value
18686 * @cfg {number} [max=Infinity] Maximum allowed value
18687 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
18688 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
18690 OO
.ui
.NumberInputWidget
= function OoUiNumberInputWidget( config
) {
18691 // Configuration initialization
18692 config
= $.extend( {
18700 // Parent constructor
18701 OO
.ui
.NumberInputWidget
.parent
.call( this, config
);
18704 this.input
= new OO
.ui
.TextInputWidget( $.extend(
18706 disabled
: this.isDisabled()
18710 this.minusButton
= new OO
.ui
.ButtonWidget( $.extend(
18712 disabled
: this.isDisabled(),
18715 config
.minusButton
,
18717 classes
: [ 'oo-ui-numberInputWidget-minusButton' ],
18721 this.plusButton
= new OO
.ui
.ButtonWidget( $.extend(
18723 disabled
: this.isDisabled(),
18728 classes
: [ 'oo-ui-numberInputWidget-plusButton' ],
18734 this.input
.connect( this, {
18735 change
: this.emit
.bind( this, 'change' ),
18736 enter
: this.emit
.bind( this, 'enter' )
18738 this.input
.$input
.on( {
18739 keydown
: this.onKeyDown
.bind( this ),
18740 'wheel mousewheel DOMMouseScroll': this.onWheel
.bind( this )
18742 this.plusButton
.connect( this, {
18743 click
: [ 'onButtonClick', +1 ]
18745 this.minusButton
.connect( this, {
18746 click
: [ 'onButtonClick', -1 ]
18750 this.setIsInteger( !!config
.isInteger
);
18751 this.setRange( config
.min
, config
.max
);
18752 this.setStep( config
.step
, config
.pageStep
);
18754 this.$field
= $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
18756 this.minusButton
.$element
,
18757 this.input
.$element
,
18758 this.plusButton
.$element
18760 this.$element
.addClass( 'oo-ui-numberInputWidget' ).append( this.$field
);
18761 this.input
.setValidation( this.validateNumber
.bind( this ) );
18766 OO
.inheritClass( OO
.ui
.NumberInputWidget
, OO
.ui
.Widget
);
18771 * A `change` event is emitted when the value of the input changes.
18777 * An `enter` event is emitted when the user presses 'enter' inside the text box.
18785 * Set whether only integers are allowed
18786 * @param {boolean} flag
18788 OO
.ui
.NumberInputWidget
.prototype.setIsInteger = function ( flag
) {
18789 this.isInteger
= !!flag
;
18790 this.input
.setValidityFlag();
18794 * Get whether only integers are allowed
18795 * @return {boolean} Flag value
18797 OO
.ui
.NumberInputWidget
.prototype.getIsInteger = function () {
18798 return this.isInteger
;
18802 * Set the range of allowed values
18803 * @param {number} min Minimum allowed value
18804 * @param {number} max Maximum allowed value
18806 OO
.ui
.NumberInputWidget
.prototype.setRange = function ( min
, max
) {
18808 throw new Error( 'Minimum (' + min
+ ') must not be greater than maximum (' + max
+ ')' );
18812 this.input
.setValidityFlag();
18816 * Get the current range
18817 * @return {number[]} Minimum and maximum values
18819 OO
.ui
.NumberInputWidget
.prototype.getRange = function () {
18820 return [ this.min
, this.max
];
18824 * Set the stepping deltas
18825 * @param {number} step Normal step
18826 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
18828 OO
.ui
.NumberInputWidget
.prototype.setStep = function ( step
, pageStep
) {
18830 throw new Error( 'Step value must be positive' );
18832 if ( pageStep
=== null ) {
18833 pageStep
= step
* 10;
18834 } else if ( pageStep
<= 0 ) {
18835 throw new Error( 'Page step value must be positive' );
18838 this.pageStep
= pageStep
;
18842 * Get the current stepping values
18843 * @return {number[]} Step and page step
18845 OO
.ui
.NumberInputWidget
.prototype.getStep = function () {
18846 return [ this.step
, this.pageStep
];
18850 * Get the current value of the widget
18853 OO
.ui
.NumberInputWidget
.prototype.getValue = function () {
18854 return this.input
.getValue();
18858 * Get the current value of the widget as a number
18859 * @return {number} May be NaN, or an invalid number
18861 OO
.ui
.NumberInputWidget
.prototype.getNumericValue = function () {
18862 return +this.input
.getValue();
18866 * Set the value of the widget
18867 * @param {string} value Invalid values are allowed
18869 OO
.ui
.NumberInputWidget
.prototype.setValue = function ( value
) {
18870 this.input
.setValue( value
);
18874 * Adjust the value of the widget
18875 * @param {number} delta Adjustment amount
18877 OO
.ui
.NumberInputWidget
.prototype.adjustValue = function ( delta
) {
18878 var n
, v
= this.getNumericValue();
18881 if ( isNaN( delta
) || !isFinite( delta
) ) {
18882 throw new Error( 'Delta must be a finite number' );
18885 if ( isNaN( v
) ) {
18889 n
= Math
.max( Math
.min( n
, this.max
), this.min
);
18890 if ( this.isInteger
) {
18891 n
= Math
.round( n
);
18896 this.setValue( n
);
18903 * @param {string} value Field value
18904 * @return {boolean}
18906 OO
.ui
.NumberInputWidget
.prototype.validateNumber = function ( value
) {
18908 if ( isNaN( n
) || !isFinite( n
) ) {
18912 /*jshint bitwise: false */
18913 if ( this.isInteger
&& ( n
| 0 ) !== n
) {
18916 /*jshint bitwise: true */
18918 if ( n
< this.min
|| n
> this.max
) {
18926 * Handle mouse click events.
18929 * @param {number} dir +1 or -1
18931 OO
.ui
.NumberInputWidget
.prototype.onButtonClick = function ( dir
) {
18932 this.adjustValue( dir
* this.step
);
18936 * Handle mouse wheel events.
18939 * @param {jQuery.Event} event
18941 OO
.ui
.NumberInputWidget
.prototype.onWheel = function ( event
) {
18944 // Standard 'wheel' event
18945 if ( event
.originalEvent
.deltaMode
!== undefined ) {
18946 this.sawWheelEvent
= true;
18948 if ( event
.originalEvent
.deltaY
) {
18949 delta
= -event
.originalEvent
.deltaY
;
18950 } else if ( event
.originalEvent
.deltaX
) {
18951 delta
= event
.originalEvent
.deltaX
;
18954 // Non-standard events
18955 if ( !this.sawWheelEvent
) {
18956 if ( event
.originalEvent
.wheelDeltaX
) {
18957 delta
= -event
.originalEvent
.wheelDeltaX
;
18958 } else if ( event
.originalEvent
.wheelDeltaY
) {
18959 delta
= event
.originalEvent
.wheelDeltaY
;
18960 } else if ( event
.originalEvent
.wheelDelta
) {
18961 delta
= event
.originalEvent
.wheelDelta
;
18962 } else if ( event
.originalEvent
.detail
) {
18963 delta
= -event
.originalEvent
.detail
;
18968 delta
= delta
< 0 ? -1 : 1;
18969 this.adjustValue( delta
* this.step
);
18976 * Handle key down events.
18980 * @param {jQuery.Event} e Key down event
18982 OO
.ui
.NumberInputWidget
.prototype.onKeyDown = function ( e
) {
18983 if ( !this.isDisabled() ) {
18984 switch ( e
.which
) {
18985 case OO
.ui
.Keys
.UP
:
18986 this.adjustValue( this.step
);
18988 case OO
.ui
.Keys
.DOWN
:
18989 this.adjustValue( -this.step
);
18991 case OO
.ui
.Keys
.PAGEUP
:
18992 this.adjustValue( this.pageStep
);
18994 case OO
.ui
.Keys
.PAGEDOWN
:
18995 this.adjustValue( -this.pageStep
);
19004 OO
.ui
.NumberInputWidget
.prototype.setDisabled = function ( disabled
) {
19006 OO
.ui
.NumberInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
19008 if ( this.input
) {
19009 this.input
.setDisabled( this.isDisabled() );
19011 if ( this.minusButton
) {
19012 this.minusButton
.setDisabled( this.isDisabled() );
19014 if ( this.plusButton
) {
19015 this.plusButton
.setDisabled( this.isDisabled() );
19022 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
19023 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
19024 * visually by a slider in the leftmost position.
19027 * // Toggle switches in the 'off' and 'on' position.
19028 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
19029 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
19033 * // Create a FieldsetLayout to layout and label switches
19034 * var fieldset = new OO.ui.FieldsetLayout( {
19035 * label: 'Toggle switches'
19037 * fieldset.addItems( [
19038 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
19039 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
19041 * $( 'body' ).append( fieldset.$element );
19044 * @extends OO.ui.ToggleWidget
19045 * @mixins OO.ui.mixin.TabIndexedElement
19048 * @param {Object} [config] Configuration options
19049 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
19050 * By default, the toggle switch is in the 'off' position.
19052 OO
.ui
.ToggleSwitchWidget
= function OoUiToggleSwitchWidget( config
) {
19053 // Parent constructor
19054 OO
.ui
.ToggleSwitchWidget
.parent
.call( this, config
);
19056 // Mixin constructors
19057 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19060 this.dragging
= false;
19061 this.dragStart
= null;
19062 this.sliding
= false;
19063 this.$glow
= $( '<span>' );
19064 this.$grip
= $( '<span>' );
19067 this.$element
.on( {
19068 click
: this.onClick
.bind( this ),
19069 keypress
: this.onKeyPress
.bind( this )
19073 this.$glow
.addClass( 'oo-ui-toggleSwitchWidget-glow' );
19074 this.$grip
.addClass( 'oo-ui-toggleSwitchWidget-grip' );
19076 .addClass( 'oo-ui-toggleSwitchWidget' )
19077 .attr( 'role', 'checkbox' )
19078 .append( this.$glow
, this.$grip
);
19083 OO
.inheritClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.ToggleWidget
);
19084 OO
.mixinClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19089 * Handle mouse click events.
19092 * @param {jQuery.Event} e Mouse click event
19094 OO
.ui
.ToggleSwitchWidget
.prototype.onClick = function ( e
) {
19095 if ( !this.isDisabled() && e
.which
=== 1 ) {
19096 this.setValue( !this.value
);
19102 * Handle key press events.
19105 * @param {jQuery.Event} e Key press event
19107 OO
.ui
.ToggleSwitchWidget
.prototype.onKeyPress = function ( e
) {
19108 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
19109 this.setValue( !this.value
);
19115 * Deprecated aliases for classes in the `OO.ui.mixin` namespace.
19119 * @inheritdoc OO.ui.mixin.ButtonElement
19120 * @deprecated Use {@link OO.ui.mixin.ButtonElement} instead.
19122 OO
.ui
.ButtonElement
= OO
.ui
.mixin
.ButtonElement
;
19125 * @inheritdoc OO.ui.mixin.ClippableElement
19126 * @deprecated Use {@link OO.ui.mixin.ClippableElement} instead.
19128 OO
.ui
.ClippableElement
= OO
.ui
.mixin
.ClippableElement
;
19131 * @inheritdoc OO.ui.mixin.DraggableElement
19132 * @deprecated Use {@link OO.ui.mixin.DraggableElement} instead.
19134 OO
.ui
.DraggableElement
= OO
.ui
.mixin
.DraggableElement
;
19137 * @inheritdoc OO.ui.mixin.DraggableGroupElement
19138 * @deprecated Use {@link OO.ui.mixin.DraggableGroupElement} instead.
19140 OO
.ui
.DraggableGroupElement
= OO
.ui
.mixin
.DraggableGroupElement
;
19143 * @inheritdoc OO.ui.mixin.FlaggedElement
19144 * @deprecated Use {@link OO.ui.mixin.FlaggedElement} instead.
19146 OO
.ui
.FlaggedElement
= OO
.ui
.mixin
.FlaggedElement
;
19149 * @inheritdoc OO.ui.mixin.GroupElement
19150 * @deprecated Use {@link OO.ui.mixin.GroupElement} instead.
19152 OO
.ui
.GroupElement
= OO
.ui
.mixin
.GroupElement
;
19155 * @inheritdoc OO.ui.mixin.GroupWidget
19156 * @deprecated Use {@link OO.ui.mixin.GroupWidget} instead.
19158 OO
.ui
.GroupWidget
= OO
.ui
.mixin
.GroupWidget
;
19161 * @inheritdoc OO.ui.mixin.IconElement
19162 * @deprecated Use {@link OO.ui.mixin.IconElement} instead.
19164 OO
.ui
.IconElement
= OO
.ui
.mixin
.IconElement
;
19167 * @inheritdoc OO.ui.mixin.IndicatorElement
19168 * @deprecated Use {@link OO.ui.mixin.IndicatorElement} instead.
19170 OO
.ui
.IndicatorElement
= OO
.ui
.mixin
.IndicatorElement
;
19173 * @inheritdoc OO.ui.mixin.ItemWidget
19174 * @deprecated Use {@link OO.ui.mixin.ItemWidget} instead.
19176 OO
.ui
.ItemWidget
= OO
.ui
.mixin
.ItemWidget
;
19179 * @inheritdoc OO.ui.mixin.LabelElement
19180 * @deprecated Use {@link OO.ui.mixin.LabelElement} instead.
19182 OO
.ui
.LabelElement
= OO
.ui
.mixin
.LabelElement
;
19185 * @inheritdoc OO.ui.mixin.LookupElement
19186 * @deprecated Use {@link OO.ui.mixin.LookupElement} instead.
19188 OO
.ui
.LookupElement
= OO
.ui
.mixin
.LookupElement
;
19191 * @inheritdoc OO.ui.mixin.PendingElement
19192 * @deprecated Use {@link OO.ui.mixin.PendingElement} instead.
19194 OO
.ui
.PendingElement
= OO
.ui
.mixin
.PendingElement
;
19197 * @inheritdoc OO.ui.mixin.PopupElement
19198 * @deprecated Use {@link OO.ui.mixin.PopupElement} instead.
19200 OO
.ui
.PopupElement
= OO
.ui
.mixin
.PopupElement
;
19203 * @inheritdoc OO.ui.mixin.TabIndexedElement
19204 * @deprecated Use {@link OO.ui.mixin.TabIndexedElement} instead.
19206 OO
.ui
.TabIndexedElement
= OO
.ui
.mixin
.TabIndexedElement
;
19209 * @inheritdoc OO.ui.mixin.TitledElement
19210 * @deprecated Use {@link OO.ui.mixin.TitledElement} instead.
19212 OO
.ui
.TitledElement
= OO
.ui
.mixin
.TitledElement
;