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-26T00:14:36Z
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
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 // Default placeholder for file selection widgets when using drag drop UI
287 'ooui-selectfile-dragdrop-placeholder': 'Drop file here (or click to browse)',
288 // Semicolon separator
289 'ooui-semicolon-separator': '; '
293 * Get a localized message.
295 * In environments that provide a localization system, this function should be overridden to
296 * return the message translated in the user's language. The default implementation always returns
299 * After the message key, message parameters may optionally be passed. In the default implementation,
300 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
301 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
302 * they support unnamed, ordered message parameters.
305 * @param {string} key Message key
306 * @param {Mixed...} [params] Message parameters
307 * @return {string} Translated message with parameters substituted
309 OO
.ui
.msg = function ( key
) {
310 var message
= messages
[ key
],
311 params
= Array
.prototype.slice
.call( arguments
, 1 );
312 if ( typeof message
=== 'string' ) {
313 // Perform $1 substitution
314 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
315 var i
= parseInt( n
, 10 );
316 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
319 // Return placeholder if message not found
320 message
= '[' + key
+ ']';
326 * Package a message and arguments for deferred resolution.
328 * Use this when you are statically specifying a message and the message may not yet be present.
330 * @param {string} key Message key
331 * @param {Mixed...} [params] Message parameters
332 * @return {Function} Function that returns the resolved message when executed
334 OO
.ui
.deferMsg = function () {
335 var args
= arguments
;
337 return OO
.ui
.msg
.apply( OO
.ui
, args
);
344 * If the message is a function it will be executed, otherwise it will pass through directly.
346 * @param {Function|string} msg Deferred message, or message text
347 * @return {string} Resolved message
349 OO
.ui
.resolveMsg = function ( msg
) {
350 if ( $.isFunction( msg
) ) {
357 * @param {string} url
360 OO
.ui
.isSafeUrl = function ( url
) {
362 // Keep in sync with php/Tag.php
364 'bitcoin:', 'ftp:', 'ftps:', 'geo:', 'git:', 'gopher:', 'http:', 'https:', 'irc:', 'ircs:',
365 'magnet:', 'mailto:', 'mms:', 'news:', 'nntp:', 'redis:', 'sftp:', 'sip:', 'sips:', 'sms:', 'ssh:',
366 'svn:', 'tel:', 'telnet:', 'urn:', 'worldwind:', 'xmpp:'
369 if ( url
.indexOf( ':' ) === -1 ) {
374 protocol
= url
.split( ':', 1 )[ 0 ] + ':';
375 if ( !protocol
.match( /^([A-za-z0-9\+\.\-])+:/ ) ) {
376 // Not a valid protocol, safe
380 // Safe if in the whitelist
381 return whitelist
.indexOf( protocol
) !== -1;
391 * Namespace for OOjs UI mixins.
393 * Mixins are named according to the type of object they are intended to
394 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
395 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
396 * is intended to be mixed in to an instance of OO.ui.Widget.
404 * PendingElement is a mixin that is used to create elements that notify users that something is happening
405 * and that they should wait before proceeding. The pending state is visually represented with a pending
406 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
407 * field of a {@link OO.ui.TextInputWidget text input widget}.
409 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
410 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
411 * in process dialogs.
414 * function MessageDialog( config ) {
415 * MessageDialog.parent.call( this, config );
417 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
419 * MessageDialog.static.actions = [
420 * { action: 'save', label: 'Done', flags: 'primary' },
421 * { label: 'Cancel', flags: 'safe' }
424 * MessageDialog.prototype.initialize = function () {
425 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
426 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
427 * 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>' );
428 * this.$body.append( this.content.$element );
430 * MessageDialog.prototype.getBodyHeight = function () {
433 * MessageDialog.prototype.getActionProcess = function ( action ) {
435 * if ( action === 'save' ) {
436 * dialog.getActions().get({actions: 'save'})[0].pushPending();
437 * return new OO.ui.Process()
439 * .next( function () {
440 * dialog.getActions().get({actions: 'save'})[0].popPending();
443 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
446 * var windowManager = new OO.ui.WindowManager();
447 * $( 'body' ).append( windowManager.$element );
449 * var dialog = new MessageDialog();
450 * windowManager.addWindows( [ dialog ] );
451 * windowManager.openWindow( dialog );
457 * @param {Object} [config] Configuration options
458 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
460 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
461 // Configuration initialization
462 config
= config
|| {};
466 this.$pending
= null;
469 this.setPendingElement( config
.$pending
|| this.$element
);
474 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
479 * Set the pending element (and clean up any existing one).
481 * @param {jQuery} $pending The element to set to pending.
483 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
484 if ( this.$pending
) {
485 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
488 this.$pending
= $pending
;
489 if ( this.pending
> 0 ) {
490 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
495 * Check if an element is pending.
497 * @return {boolean} Element is pending
499 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
500 return !!this.pending
;
504 * Increase the pending counter. The pending state will remain active until the counter is zero
505 * (i.e., the number of calls to #pushPending and #popPending is the same).
509 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
510 if ( this.pending
=== 0 ) {
511 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
512 this.updateThemeClasses();
520 * Decrease the pending counter. The pending state will remain active until the counter is zero
521 * (i.e., the number of calls to #pushPending and #popPending is the same).
525 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
526 if ( this.pending
=== 1 ) {
527 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
528 this.updateThemeClasses();
530 this.pending
= Math
.max( 0, this.pending
- 1 );
536 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
537 * Actions can be made available for specific contexts (modes) and circumstances
538 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
540 * ActionSets contain two types of actions:
542 * - 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.
543 * - Other: Other actions include all non-special visible actions.
545 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
548 * // Example: An action set used in a process dialog
549 * function MyProcessDialog( config ) {
550 * MyProcessDialog.parent.call( this, config );
552 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
553 * MyProcessDialog.static.title = 'An action set in a process dialog';
554 * // An action set that uses modes ('edit' and 'help' mode, in this example).
555 * MyProcessDialog.static.actions = [
556 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
557 * { action: 'help', modes: 'edit', label: 'Help' },
558 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
559 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
562 * MyProcessDialog.prototype.initialize = function () {
563 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
564 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
565 * 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>' );
566 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
567 * 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>' );
568 * this.stackLayout = new OO.ui.StackLayout( {
569 * items: [ this.panel1, this.panel2 ]
571 * this.$body.append( this.stackLayout.$element );
573 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
574 * return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
575 * .next( function () {
576 * this.actions.setMode( 'edit' );
579 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
580 * if ( action === 'help' ) {
581 * this.actions.setMode( 'help' );
582 * this.stackLayout.setItem( this.panel2 );
583 * } else if ( action === 'back' ) {
584 * this.actions.setMode( 'edit' );
585 * this.stackLayout.setItem( this.panel1 );
586 * } else if ( action === 'continue' ) {
588 * return new OO.ui.Process( function () {
592 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
594 * MyProcessDialog.prototype.getBodyHeight = function () {
595 * return this.panel1.$element.outerHeight( true );
597 * var windowManager = new OO.ui.WindowManager();
598 * $( 'body' ).append( windowManager.$element );
599 * var dialog = new MyProcessDialog( {
602 * windowManager.addWindows( [ dialog ] );
603 * windowManager.openWindow( dialog );
605 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
609 * @mixins OO.EventEmitter
612 * @param {Object} [config] Configuration options
614 OO
.ui
.ActionSet
= function OoUiActionSet( config
) {
615 // Configuration initialization
616 config
= config
|| {};
618 // Mixin constructors
619 OO
.EventEmitter
.call( this );
624 actions
: 'getAction',
628 this.categorized
= {};
631 this.organized
= false;
632 this.changing
= false;
633 this.changed
= false;
638 OO
.mixinClass( OO
.ui
.ActionSet
, OO
.EventEmitter
);
640 /* Static Properties */
643 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
644 * header of a {@link OO.ui.ProcessDialog process dialog}.
645 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
647 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
654 OO
.ui
.ActionSet
.static.specialFlags
= [ 'safe', 'primary' ];
661 * A 'click' event is emitted when an action is clicked.
663 * @param {OO.ui.ActionWidget} action Action that was clicked
669 * A 'resize' event is emitted when an action widget is resized.
671 * @param {OO.ui.ActionWidget} action Action that was resized
677 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
679 * @param {OO.ui.ActionWidget[]} added Actions added
685 * A 'remove' event is emitted when actions are {@link #method-remove removed}
686 * or {@link #clear cleared}.
688 * @param {OO.ui.ActionWidget[]} added Actions removed
694 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
695 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
702 * Handle action change events.
707 OO
.ui
.ActionSet
.prototype.onActionChange = function () {
708 this.organized
= false;
709 if ( this.changing
) {
712 this.emit( 'change' );
717 * Check if an action is one of the special actions.
719 * @param {OO.ui.ActionWidget} action Action to check
720 * @return {boolean} Action is special
722 OO
.ui
.ActionSet
.prototype.isSpecial = function ( action
) {
725 for ( flag
in this.special
) {
726 if ( action
=== this.special
[ flag
] ) {
735 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
738 * @param {Object} [filters] Filters to use, omit to get all actions
739 * @param {string|string[]} [filters.actions] Actions that action widgets must have
740 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
741 * @param {string|string[]} [filters.modes] Modes that action widgets must have
742 * @param {boolean} [filters.visible] Action widgets must be visible
743 * @param {boolean} [filters.disabled] Action widgets must be disabled
744 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
746 OO
.ui
.ActionSet
.prototype.get = function ( filters
) {
747 var i
, len
, list
, category
, actions
, index
, match
, matches
;
752 // Collect category candidates
754 for ( category
in this.categorized
) {
755 list
= filters
[ category
];
757 if ( !Array
.isArray( list
) ) {
760 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
761 actions
= this.categorized
[ category
][ list
[ i
] ];
762 if ( Array
.isArray( actions
) ) {
763 matches
.push
.apply( matches
, actions
);
768 // Remove by boolean filters
769 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
770 match
= matches
[ i
];
772 ( filters
.visible
!== undefined && match
.isVisible() !== filters
.visible
) ||
773 ( filters
.disabled
!== undefined && match
.isDisabled() !== filters
.disabled
)
775 matches
.splice( i
, 1 );
781 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
782 match
= matches
[ i
];
783 index
= matches
.lastIndexOf( match
);
784 while ( index
!== i
) {
785 matches
.splice( index
, 1 );
787 index
= matches
.lastIndexOf( match
);
792 return this.list
.slice();
796 * Get 'special' actions.
798 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
799 * Special flags can be configured in subclasses by changing the static #specialFlags property.
801 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
803 OO
.ui
.ActionSet
.prototype.getSpecial = function () {
805 return $.extend( {}, this.special
);
809 * Get 'other' actions.
811 * Other actions include all non-special visible action widgets.
813 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
815 OO
.ui
.ActionSet
.prototype.getOthers = function () {
817 return this.others
.slice();
821 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
822 * to be available in the specified mode will be made visible. All other actions will be hidden.
824 * @param {string} mode The mode. Only actions configured to be available in the specified
825 * mode will be made visible.
830 OO
.ui
.ActionSet
.prototype.setMode = function ( mode
) {
833 this.changing
= true;
834 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
835 action
= this.list
[ i
];
836 action
.toggle( action
.hasMode( mode
) );
839 this.organized
= false;
840 this.changing
= false;
841 this.emit( 'change' );
847 * Set the abilities of the specified actions.
849 * Action widgets that are configured with the specified actions will be enabled
850 * or disabled based on the boolean values specified in the `actions`
853 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
854 * values that indicate whether or not the action should be enabled.
857 OO
.ui
.ActionSet
.prototype.setAbilities = function ( actions
) {
858 var i
, len
, action
, item
;
860 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
861 item
= this.list
[ i
];
862 action
= item
.getAction();
863 if ( actions
[ action
] !== undefined ) {
864 item
.setDisabled( !actions
[ action
] );
872 * Executes a function once per action.
874 * When making changes to multiple actions, use this method instead of iterating over the actions
875 * manually to defer emitting a #change event until after all actions have been changed.
877 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
878 * @param {Function} callback Callback to run for each action; callback is invoked with three
879 * arguments: the action, the action's index, the list of actions being iterated over
882 OO
.ui
.ActionSet
.prototype.forEach = function ( filter
, callback
) {
883 this.changed
= false;
884 this.changing
= true;
885 this.get( filter
).forEach( callback
);
886 this.changing
= false;
887 if ( this.changed
) {
888 this.emit( 'change' );
895 * Add action widgets to the action set.
897 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
902 OO
.ui
.ActionSet
.prototype.add = function ( actions
) {
905 this.changing
= true;
906 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
907 action
= actions
[ i
];
908 action
.connect( this, {
909 click
: [ 'emit', 'click', action
],
910 resize
: [ 'emit', 'resize', action
],
911 toggle
: [ 'onActionChange' ]
913 this.list
.push( action
);
915 this.organized
= false;
916 this.emit( 'add', actions
);
917 this.changing
= false;
918 this.emit( 'change' );
924 * Remove action widgets from the set.
926 * To remove all actions, you may wish to use the #clear method instead.
928 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
933 OO
.ui
.ActionSet
.prototype.remove = function ( actions
) {
934 var i
, len
, index
, action
;
936 this.changing
= true;
937 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
938 action
= actions
[ i
];
939 index
= this.list
.indexOf( action
);
940 if ( index
!== -1 ) {
941 action
.disconnect( this );
942 this.list
.splice( index
, 1 );
945 this.organized
= false;
946 this.emit( 'remove', actions
);
947 this.changing
= false;
948 this.emit( 'change' );
954 * Remove all action widets from the set.
956 * To remove only specified actions, use the {@link #method-remove remove} method instead.
962 OO
.ui
.ActionSet
.prototype.clear = function () {
964 removed
= this.list
.slice();
966 this.changing
= true;
967 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
968 action
= this.list
[ i
];
969 action
.disconnect( this );
974 this.organized
= false;
975 this.emit( 'remove', removed
);
976 this.changing
= false;
977 this.emit( 'change' );
985 * This is called whenever organized information is requested. It will only reorganize the actions
986 * if something has changed since the last time it ran.
991 OO
.ui
.ActionSet
.prototype.organize = function () {
992 var i
, iLen
, j
, jLen
, flag
, action
, category
, list
, item
, special
,
993 specialFlags
= this.constructor.static.specialFlags
;
995 if ( !this.organized
) {
996 this.categorized
= {};
999 for ( i
= 0, iLen
= this.list
.length
; i
< iLen
; i
++ ) {
1000 action
= this.list
[ i
];
1001 if ( action
.isVisible() ) {
1002 // Populate categories
1003 for ( category
in this.categories
) {
1004 if ( !this.categorized
[ category
] ) {
1005 this.categorized
[ category
] = {};
1007 list
= action
[ this.categories
[ category
] ]();
1008 if ( !Array
.isArray( list
) ) {
1011 for ( j
= 0, jLen
= list
.length
; j
< jLen
; j
++ ) {
1013 if ( !this.categorized
[ category
][ item
] ) {
1014 this.categorized
[ category
][ item
] = [];
1016 this.categorized
[ category
][ item
].push( action
);
1019 // Populate special/others
1021 for ( j
= 0, jLen
= specialFlags
.length
; j
< jLen
; j
++ ) {
1022 flag
= specialFlags
[ j
];
1023 if ( !this.special
[ flag
] && action
.hasFlag( flag
) ) {
1024 this.special
[ flag
] = action
;
1030 this.others
.push( action
);
1034 this.organized
= true;
1041 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
1042 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
1043 * connected to them and can't be interacted with.
1049 * @param {Object} [config] Configuration options
1050 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
1051 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
1053 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
1054 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
1055 * @cfg {string} [text] Text to insert
1056 * @cfg {Array} [content] An array of content elements to append (after #text).
1057 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
1058 * Instances of OO.ui.Element will have their $element appended.
1059 * @cfg {jQuery} [$content] Content elements to append (after #text)
1060 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
1061 * Data can also be specified with the #setData method.
1063 OO
.ui
.Element
= function OoUiElement( config
) {
1064 // Configuration initialization
1065 config
= config
|| {};
1069 this.visible
= true;
1070 this.data
= config
.data
;
1071 this.$element
= config
.$element
||
1072 $( document
.createElement( this.getTagName() ) );
1073 this.elementGroup
= null;
1074 this.debouncedUpdateThemeClassesHandler
= OO
.ui
.debounce( this.debouncedUpdateThemeClasses
);
1077 if ( Array
.isArray( config
.classes
) ) {
1078 this.$element
.addClass( config
.classes
.join( ' ' ) );
1081 this.$element
.attr( 'id', config
.id
);
1083 if ( config
.text
) {
1084 this.$element
.text( config
.text
);
1086 if ( config
.content
) {
1087 // The `content` property treats plain strings as text; use an
1088 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
1089 // appropriate $element appended.
1090 this.$element
.append( config
.content
.map( function ( v
) {
1091 if ( typeof v
=== 'string' ) {
1092 // Escape string so it is properly represented in HTML.
1093 return document
.createTextNode( v
);
1094 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
1096 return v
.toString();
1097 } else if ( v
instanceof OO
.ui
.Element
) {
1103 if ( config
.$content
) {
1104 // The `$content` property treats plain strings as HTML.
1105 this.$element
.append( config
.$content
);
1111 OO
.initClass( OO
.ui
.Element
);
1113 /* Static Properties */
1116 * The name of the HTML tag used by the element.
1118 * The static value may be ignored if the #getTagName method is overridden.
1122 * @property {string}
1124 OO
.ui
.Element
.static.tagName
= 'div';
1126 /* Static Methods */
1129 * Reconstitute a JavaScript object corresponding to a widget created
1130 * by the PHP implementation.
1132 * @param {string|HTMLElement|jQuery} idOrNode
1133 * A DOM id (if a string) or node for the widget to infuse.
1134 * @return {OO.ui.Element}
1135 * The `OO.ui.Element` corresponding to this (infusable) document node.
1136 * For `Tag` objects emitted on the HTML side (used occasionally for content)
1137 * the value returned is a newly-created Element wrapping around the existing
1140 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
1141 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, false );
1142 // Verify that the type matches up.
1143 // FIXME: uncomment after T89721 is fixed (see T90929)
1145 if ( !( obj instanceof this['class'] ) ) {
1146 throw new Error( 'Infusion type mismatch!' );
1153 * Implementation helper for `infuse`; skips the type check and has an
1154 * extra property so that only the top-level invocation touches the DOM.
1156 * @param {string|HTMLElement|jQuery} idOrNode
1157 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
1158 * when the top-level widget of this infusion is inserted into DOM,
1159 * replacing the original node; or false for top-level invocation.
1160 * @return {OO.ui.Element}
1162 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, domPromise
) {
1163 // look for a cached result of a previous infusion.
1164 var id
, $elem
, data
, cls
, parts
, parent
, obj
, top
, state
;
1165 if ( typeof idOrNode
=== 'string' ) {
1167 $elem
= $( document
.getElementById( id
) );
1169 $elem
= $( idOrNode
);
1170 id
= $elem
.attr( 'id' );
1172 if ( !$elem
.length
) {
1173 throw new Error( 'Widget not found: ' + id
);
1175 data
= $elem
.data( 'ooui-infused' ) || $elem
[ 0 ].oouiInfused
;
1178 if ( data
=== true ) {
1179 throw new Error( 'Circular dependency! ' + id
);
1183 data
= $elem
.attr( 'data-ooui' );
1185 throw new Error( 'No infusion data found: ' + id
);
1188 data
= $.parseJSON( data
);
1192 if ( !( data
&& data
._
) ) {
1193 throw new Error( 'No valid infusion data found: ' + id
);
1195 if ( data
._
=== 'Tag' ) {
1196 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1197 return new OO
.ui
.Element( { $element
: $elem
} );
1199 parts
= data
._
.split( '.' );
1200 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
1201 if ( cls
=== undefined ) {
1202 // The PHP output might be old and not including the "OO.ui" prefix
1203 // TODO: Remove this back-compat after next major release
1204 cls
= OO
.getProp
.apply( OO
, [ OO
.ui
].concat( parts
) );
1205 if ( cls
=== undefined ) {
1206 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
1210 // Verify that we're creating an OO.ui.Element instance
1211 parent
= cls
.parent
;
1213 while ( parent
!== undefined ) {
1214 if ( parent
=== OO
.ui
.Element
) {
1219 parent
= parent
.parent
;
1222 if ( parent
!== OO
.ui
.Element
) {
1223 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
1226 if ( domPromise
=== false ) {
1228 domPromise
= top
.promise();
1230 $elem
.data( 'ooui-infused', true ); // prevent loops
1231 data
.id
= id
; // implicit
1232 data
= OO
.copy( data
, null, function deserialize( value
) {
1233 if ( OO
.isPlainObject( value
) ) {
1235 return OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, domPromise
);
1238 return new OO
.ui
.HtmlSnippet( value
.html
);
1242 // jscs:disable requireCapitalizedConstructors
1243 obj
= new cls( data
); // rebuild widget
1244 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
1245 state
= obj
.gatherPreInfuseState( $elem
);
1246 // now replace old DOM with this new DOM.
1248 $elem
.replaceWith( obj
.$element
);
1249 // This element is now gone from the DOM, but if anyone is holding a reference to it,
1250 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
1251 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
1252 $elem
[ 0 ].oouiInfused
= obj
;
1255 obj
.$element
.data( 'ooui-infused', obj
);
1256 // set the 'data-ooui' attribute so we can identify infused widgets
1257 obj
.$element
.attr( 'data-ooui', '' );
1258 // restore dynamic state after the new element is inserted into DOM
1259 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
1264 * Get a jQuery function within a specific document.
1267 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1268 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1270 * @return {Function} Bound jQuery function
1272 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
1273 function wrapper( selector
) {
1274 return $( selector
, wrapper
.context
);
1277 wrapper
.context
= this.getDocument( context
);
1280 wrapper
.$iframe
= $iframe
;
1287 * Get the document of an element.
1290 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1291 * @return {HTMLDocument|null} Document object
1293 OO
.ui
.Element
.static.getDocument = function ( obj
) {
1294 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1295 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
1296 // Empty jQuery selections might have a context
1299 obj
.ownerDocument
||
1303 ( obj
.nodeType
=== 9 && obj
) ||
1308 * Get the window of an element or document.
1311 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1312 * @return {Window} Window object
1314 OO
.ui
.Element
.static.getWindow = function ( obj
) {
1315 var doc
= this.getDocument( obj
);
1317 // Standard Document.defaultView is IE9+
1318 return doc
.parentWindow
|| doc
.defaultView
;
1322 * Get the direction of an element or document.
1325 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1326 * @return {string} Text direction, either 'ltr' or 'rtl'
1328 OO
.ui
.Element
.static.getDir = function ( obj
) {
1331 if ( obj
instanceof jQuery
) {
1334 isDoc
= obj
.nodeType
=== 9;
1335 isWin
= obj
.document
!== undefined;
1336 if ( isDoc
|| isWin
) {
1342 return $( obj
).css( 'direction' );
1346 * Get the offset between two frames.
1348 * TODO: Make this function not use recursion.
1351 * @param {Window} from Window of the child frame
1352 * @param {Window} [to=window] Window of the parent frame
1353 * @param {Object} [offset] Offset to start with, used internally
1354 * @return {Object} Offset object, containing left and top properties
1356 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
1357 var i
, len
, frames
, frame
, rect
;
1363 offset
= { top
: 0, left
: 0 };
1365 if ( from.parent
=== from ) {
1369 // Get iframe element
1370 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
1371 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
1372 if ( frames
[ i
].contentWindow
=== from ) {
1373 frame
= frames
[ i
];
1378 // Recursively accumulate offset values
1380 rect
= frame
.getBoundingClientRect();
1381 offset
.left
+= rect
.left
;
1382 offset
.top
+= rect
.top
;
1383 if ( from !== to
) {
1384 this.getFrameOffset( from.parent
, offset
);
1391 * Get the offset between two elements.
1393 * The two elements may be in a different frame, but in that case the frame $element is in must
1394 * be contained in the frame $anchor is in.
1397 * @param {jQuery} $element Element whose position to get
1398 * @param {jQuery} $anchor Element to get $element's position relative to
1399 * @return {Object} Translated position coordinates, containing top and left properties
1401 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
1402 var iframe
, iframePos
,
1403 pos
= $element
.offset(),
1404 anchorPos
= $anchor
.offset(),
1405 elementDocument
= this.getDocument( $element
),
1406 anchorDocument
= this.getDocument( $anchor
);
1408 // If $element isn't in the same document as $anchor, traverse up
1409 while ( elementDocument
!== anchorDocument
) {
1410 iframe
= elementDocument
.defaultView
.frameElement
;
1412 throw new Error( '$element frame is not contained in $anchor frame' );
1414 iframePos
= $( iframe
).offset();
1415 pos
.left
+= iframePos
.left
;
1416 pos
.top
+= iframePos
.top
;
1417 elementDocument
= iframe
.ownerDocument
;
1419 pos
.left
-= anchorPos
.left
;
1420 pos
.top
-= anchorPos
.top
;
1425 * Get element border sizes.
1428 * @param {HTMLElement} el Element to measure
1429 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1431 OO
.ui
.Element
.static.getBorders = function ( el
) {
1432 var doc
= el
.ownerDocument
,
1434 // Standard Document.defaultView is IE9+
1435 win
= doc
.parentWindow
|| doc
.defaultView
,
1436 style
= win
&& win
.getComputedStyle
?
1437 win
.getComputedStyle( el
, null ) :
1439 // Standard getComputedStyle() is IE9+
1442 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1443 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1444 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1445 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1456 * Get dimensions of an element or window.
1459 * @param {HTMLElement|Window} el Element to measure
1460 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1462 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1464 doc
= el
.ownerDocument
|| el
.document
,
1466 // Standard Document.defaultView is IE9+
1467 win
= doc
.parentWindow
|| doc
.defaultView
;
1469 if ( win
=== el
|| el
=== doc
.documentElement
) {
1472 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1474 top
: $win
.scrollTop(),
1475 left
: $win
.scrollLeft()
1477 scrollbar
: { right
: 0, bottom
: 0 },
1481 bottom
: $win
.innerHeight(),
1482 right
: $win
.innerWidth()
1488 borders
: this.getBorders( el
),
1490 top
: $el
.scrollTop(),
1491 left
: $el
.scrollLeft()
1494 right
: $el
.innerWidth() - el
.clientWidth
,
1495 bottom
: $el
.innerHeight() - el
.clientHeight
1497 rect
: el
.getBoundingClientRect()
1503 * Get scrollable object parent
1505 * documentElement can't be used to get or set the scrollTop
1506 * property on Blink. Changing and testing its value lets us
1507 * use 'body' or 'documentElement' based on what is working.
1509 * https://code.google.com/p/chromium/issues/detail?id=303131
1512 * @param {HTMLElement} el Element to find scrollable parent for
1513 * @return {HTMLElement} Scrollable parent
1515 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1516 var scrollTop
, body
;
1518 if ( OO
.ui
.scrollableElement
=== undefined ) {
1519 body
= el
.ownerDocument
.body
;
1520 scrollTop
= body
.scrollTop
;
1523 if ( body
.scrollTop
=== 1 ) {
1524 body
.scrollTop
= scrollTop
;
1525 OO
.ui
.scrollableElement
= 'body';
1527 OO
.ui
.scrollableElement
= 'documentElement';
1531 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1535 * Get closest scrollable container.
1537 * Traverses up until either a scrollable element or the root is reached, in which case the window
1541 * @param {HTMLElement} el Element to find scrollable container for
1542 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1543 * @return {HTMLElement} Closest scrollable container
1545 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1547 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1548 props
= [ 'overflow-x', 'overflow-y' ],
1549 $parent
= $( el
).parent();
1551 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1552 props
= [ 'overflow-' + dimension
];
1555 while ( $parent
.length
) {
1556 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1557 return $parent
[ 0 ];
1561 val
= $parent
.css( props
[ i
] );
1562 if ( val
=== 'auto' || val
=== 'scroll' ) {
1563 return $parent
[ 0 ];
1566 $parent
= $parent
.parent();
1568 return this.getDocument( el
).body
;
1572 * Scroll element into view.
1575 * @param {HTMLElement} el Element to scroll into view
1576 * @param {Object} [config] Configuration options
1577 * @param {string} [config.duration] jQuery animation duration value
1578 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1579 * to scroll in both directions
1580 * @param {Function} [config.complete] Function to call when scrolling completes
1582 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1583 var rel
, anim
, callback
, sc
, $sc
, eld
, scd
, $win
;
1585 // Configuration initialization
1586 config
= config
|| {};
1589 callback
= typeof config
.complete
=== 'function' && config
.complete
;
1590 sc
= this.getClosestScrollableContainer( el
, config
.direction
);
1592 eld
= this.getDimensions( el
);
1593 scd
= this.getDimensions( sc
);
1594 $win
= $( this.getWindow( el
) );
1596 // Compute the distances between the edges of el and the edges of the scroll viewport
1597 if ( $sc
.is( 'html, body' ) ) {
1598 // If the scrollable container is the root, this is easy
1601 bottom
: $win
.innerHeight() - eld
.rect
.bottom
,
1602 left
: eld
.rect
.left
,
1603 right
: $win
.innerWidth() - eld
.rect
.right
1606 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1608 top
: eld
.rect
.top
- ( scd
.rect
.top
+ scd
.borders
.top
),
1609 bottom
: scd
.rect
.bottom
- scd
.borders
.bottom
- scd
.scrollbar
.bottom
- eld
.rect
.bottom
,
1610 left
: eld
.rect
.left
- ( scd
.rect
.left
+ scd
.borders
.left
),
1611 right
: scd
.rect
.right
- scd
.borders
.right
- scd
.scrollbar
.right
- eld
.rect
.right
1615 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1616 if ( rel
.top
< 0 ) {
1617 anim
.scrollTop
= scd
.scroll
.top
+ rel
.top
;
1618 } else if ( rel
.top
> 0 && rel
.bottom
< 0 ) {
1619 anim
.scrollTop
= scd
.scroll
.top
+ Math
.min( rel
.top
, -rel
.bottom
);
1622 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1623 if ( rel
.left
< 0 ) {
1624 anim
.scrollLeft
= scd
.scroll
.left
+ rel
.left
;
1625 } else if ( rel
.left
> 0 && rel
.right
< 0 ) {
1626 anim
.scrollLeft
= scd
.scroll
.left
+ Math
.min( rel
.left
, -rel
.right
);
1629 if ( !$.isEmptyObject( anim
) ) {
1630 $sc
.stop( true ).animate( anim
, config
.duration
|| 'fast' );
1632 $sc
.queue( function ( next
) {
1645 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1646 * and reserve space for them, because it probably doesn't.
1648 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1649 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1650 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1651 * and then reattach (or show) them back.
1654 * @param {HTMLElement} el Element to reconsider the scrollbars on
1656 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1657 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1658 // Save scroll position
1659 scrollLeft
= el
.scrollLeft
;
1660 scrollTop
= el
.scrollTop
;
1661 // Detach all children
1662 while ( el
.firstChild
) {
1663 nodes
.push( el
.firstChild
);
1664 el
.removeChild( el
.firstChild
);
1667 void el
.offsetHeight
;
1668 // Reattach all children
1669 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1670 el
.appendChild( nodes
[ i
] );
1672 // Restore scroll position (no-op if scrollbars disappeared)
1673 el
.scrollLeft
= scrollLeft
;
1674 el
.scrollTop
= scrollTop
;
1680 * Toggle visibility of an element.
1682 * @param {boolean} [show] Make element visible, omit to toggle visibility
1686 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1687 show
= show
=== undefined ? !this.visible
: !!show
;
1689 if ( show
!== this.isVisible() ) {
1690 this.visible
= show
;
1691 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1692 this.emit( 'toggle', show
);
1699 * Check if element is visible.
1701 * @return {boolean} element is visible
1703 OO
.ui
.Element
.prototype.isVisible = function () {
1704 return this.visible
;
1710 * @return {Mixed} Element data
1712 OO
.ui
.Element
.prototype.getData = function () {
1719 * @param {Mixed} Element data
1722 OO
.ui
.Element
.prototype.setData = function ( data
) {
1728 * Check if element supports one or more methods.
1730 * @param {string|string[]} methods Method or list of methods to check
1731 * @return {boolean} All methods are supported
1733 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1737 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1738 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1739 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1744 return methods
.length
=== support
;
1748 * Update the theme-provided classes.
1750 * @localdoc This is called in element mixins and widget classes any time state changes.
1751 * Updating is debounced, minimizing overhead of changing multiple attributes and
1752 * guaranteeing that theme updates do not occur within an element's constructor
1754 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1755 this.debouncedUpdateThemeClassesHandler();
1760 * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to
1761 * make them synchronous.
1763 OO
.ui
.Element
.prototype.debouncedUpdateThemeClasses = function () {
1764 OO
.ui
.theme
.updateElementClasses( this );
1768 * Get the HTML tag name.
1770 * Override this method to base the result on instance information.
1772 * @return {string} HTML tag name
1774 OO
.ui
.Element
.prototype.getTagName = function () {
1775 return this.constructor.static.tagName
;
1779 * Check if the element is attached to the DOM
1780 * @return {boolean} The element is attached to the DOM
1782 OO
.ui
.Element
.prototype.isElementAttached = function () {
1783 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1787 * Get the DOM document.
1789 * @return {HTMLDocument} Document object
1791 OO
.ui
.Element
.prototype.getElementDocument = function () {
1792 // Don't cache this in other ways either because subclasses could can change this.$element
1793 return OO
.ui
.Element
.static.getDocument( this.$element
);
1797 * Get the DOM window.
1799 * @return {Window} Window object
1801 OO
.ui
.Element
.prototype.getElementWindow = function () {
1802 return OO
.ui
.Element
.static.getWindow( this.$element
);
1806 * Get closest scrollable container.
1808 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1809 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1813 * Get group element is in.
1815 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1817 OO
.ui
.Element
.prototype.getElementGroup = function () {
1818 return this.elementGroup
;
1822 * Set group element is in.
1824 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1827 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1828 this.elementGroup
= group
;
1833 * Scroll element into view.
1835 * @param {Object} [config] Configuration options
1837 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1838 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1842 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
1843 * (and its children) that represent an Element of the same type and configuration as the current
1844 * one, generated by the PHP implementation.
1846 * This method is called just before `node` is detached from the DOM. The return value of this
1847 * function will be passed to #restorePreInfuseState after this widget's #$element is inserted into
1848 * DOM to replace `node`.
1851 * @param {HTMLElement} node
1854 OO
.ui
.Element
.prototype.gatherPreInfuseState = function () {
1859 * Restore the pre-infusion dynamic state for this widget.
1861 * This method is called after #$element has been inserted into DOM. The parameter is the return
1862 * value of #gatherPreInfuseState.
1865 * @param {Object} state
1867 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1871 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1872 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1873 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1874 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1875 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1879 * @extends OO.ui.Element
1880 * @mixins OO.EventEmitter
1883 * @param {Object} [config] Configuration options
1885 OO
.ui
.Layout
= function OoUiLayout( config
) {
1886 // Configuration initialization
1887 config
= config
|| {};
1889 // Parent constructor
1890 OO
.ui
.Layout
.parent
.call( this, config
);
1892 // Mixin constructors
1893 OO
.EventEmitter
.call( this );
1896 this.$element
.addClass( 'oo-ui-layout' );
1901 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1902 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1905 * Widgets are compositions of one or more OOjs UI elements that users can both view
1906 * and interact with. All widgets can be configured and modified via a standard API,
1907 * and their state can change dynamically according to a model.
1911 * @extends OO.ui.Element
1912 * @mixins OO.EventEmitter
1915 * @param {Object} [config] Configuration options
1916 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1917 * appearance reflects this state.
1919 OO
.ui
.Widget
= function OoUiWidget( config
) {
1920 // Initialize config
1921 config
= $.extend( { disabled
: false }, config
);
1923 // Parent constructor
1924 OO
.ui
.Widget
.parent
.call( this, config
);
1926 // Mixin constructors
1927 OO
.EventEmitter
.call( this );
1930 this.disabled
= null;
1931 this.wasDisabled
= null;
1934 this.$element
.addClass( 'oo-ui-widget' );
1935 this.setDisabled( !!config
.disabled
);
1940 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1941 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1943 /* Static Properties */
1946 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
1947 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
1952 * @property {boolean}
1954 OO
.ui
.Widget
.static.supportsSimpleLabel
= false;
1961 * A 'disable' event is emitted when a widget is disabled.
1963 * @param {boolean} disabled Widget is disabled
1969 * A 'toggle' event is emitted when the visibility of the widget changes.
1971 * @param {boolean} visible Widget is visible
1977 * Check if the widget is disabled.
1979 * @return {boolean} Widget is disabled
1981 OO
.ui
.Widget
.prototype.isDisabled = function () {
1982 return this.disabled
;
1986 * Set the 'disabled' state of the widget.
1988 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1990 * @param {boolean} disabled Disable widget
1993 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1996 this.disabled
= !!disabled
;
1997 isDisabled
= this.isDisabled();
1998 if ( isDisabled
!== this.wasDisabled
) {
1999 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
2000 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
2001 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
2002 this.emit( 'disable', isDisabled
);
2003 this.updateThemeClasses();
2005 this.wasDisabled
= isDisabled
;
2011 * Update the disabled state, in case of changes in parent widget.
2015 OO
.ui
.Widget
.prototype.updateDisabled = function () {
2016 this.setDisabled( this.disabled
);
2021 * A window is a container for elements that are in a child frame. They are used with
2022 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
2023 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
2024 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
2025 * the window manager will choose a sensible fallback.
2027 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
2028 * different processes are executed:
2030 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
2031 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
2034 * - {@link #getSetupProcess} method is called and its result executed
2035 * - {@link #getReadyProcess} method is called and its result executed
2037 * **opened**: The window is now open
2039 * **closing**: The closing stage begins when the window manager's
2040 * {@link OO.ui.WindowManager#closeWindow closeWindow}
2041 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
2043 * - {@link #getHoldProcess} method is called and its result executed
2044 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
2046 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
2047 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
2048 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
2049 * processing can complete. Always assume window processes are executed asynchronously.
2051 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2053 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
2057 * @extends OO.ui.Element
2058 * @mixins OO.EventEmitter
2061 * @param {Object} [config] Configuration options
2062 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
2063 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
2065 OO
.ui
.Window
= function OoUiWindow( config
) {
2066 // Configuration initialization
2067 config
= config
|| {};
2069 // Parent constructor
2070 OO
.ui
.Window
.parent
.call( this, config
);
2072 // Mixin constructors
2073 OO
.EventEmitter
.call( this );
2076 this.manager
= null;
2077 this.size
= config
.size
|| this.constructor.static.size
;
2078 this.$frame
= $( '<div>' );
2079 this.$overlay
= $( '<div>' );
2080 this.$content
= $( '<div>' );
2083 this.$overlay
.addClass( 'oo-ui-window-overlay' );
2085 .addClass( 'oo-ui-window-content' )
2086 .attr( 'tabindex', 0 );
2088 .addClass( 'oo-ui-window-frame' )
2089 .append( this.$content
);
2092 .addClass( 'oo-ui-window' )
2093 .append( this.$frame
, this.$overlay
);
2095 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
2096 // that reference properties not initialized at that time of parent class construction
2097 // TODO: Find a better way to handle post-constructor setup
2098 this.visible
= false;
2099 this.$element
.addClass( 'oo-ui-element-hidden' );
2104 OO
.inheritClass( OO
.ui
.Window
, OO
.ui
.Element
);
2105 OO
.mixinClass( OO
.ui
.Window
, OO
.EventEmitter
);
2107 /* Static Properties */
2110 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
2112 * The static size is used if no #size is configured during construction.
2116 * @property {string}
2118 OO
.ui
.Window
.static.size
= 'medium';
2123 * Handle mouse down events.
2126 * @param {jQuery.Event} e Mouse down event
2128 OO
.ui
.Window
.prototype.onMouseDown = function ( e
) {
2129 // Prevent clicking on the click-block from stealing focus
2130 if ( e
.target
=== this.$element
[ 0 ] ) {
2136 * Check if the window has been initialized.
2138 * Initialization occurs when a window is added to a manager.
2140 * @return {boolean} Window has been initialized
2142 OO
.ui
.Window
.prototype.isInitialized = function () {
2143 return !!this.manager
;
2147 * Check if the window is visible.
2149 * @return {boolean} Window is visible
2151 OO
.ui
.Window
.prototype.isVisible = function () {
2152 return this.visible
;
2156 * Check if the window is opening.
2158 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2161 * @return {boolean} Window is opening
2163 OO
.ui
.Window
.prototype.isOpening = function () {
2164 return this.manager
.isOpening( this );
2168 * Check if the window is closing.
2170 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2172 * @return {boolean} Window is closing
2174 OO
.ui
.Window
.prototype.isClosing = function () {
2175 return this.manager
.isClosing( this );
2179 * Check if the window is opened.
2181 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2183 * @return {boolean} Window is opened
2185 OO
.ui
.Window
.prototype.isOpened = function () {
2186 return this.manager
.isOpened( this );
2190 * Get the window manager.
2192 * All windows must be attached to a window manager, which is used to open
2193 * and close the window and control its presentation.
2195 * @return {OO.ui.WindowManager} Manager of window
2197 OO
.ui
.Window
.prototype.getManager = function () {
2198 return this.manager
;
2202 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2204 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2206 OO
.ui
.Window
.prototype.getSize = function () {
2207 var viewport
= OO
.ui
.Element
.static.getDimensions( this.getElementWindow() ),
2208 sizes
= this.manager
.constructor.static.sizes
,
2211 if ( !sizes
[ size
] ) {
2212 size
= this.manager
.constructor.static.defaultSize
;
2214 if ( size
!== 'full' && viewport
.rect
.right
- viewport
.rect
.left
< sizes
[ size
].width
) {
2222 * Get the size properties associated with the current window size
2224 * @return {Object} Size properties
2226 OO
.ui
.Window
.prototype.getSizeProperties = function () {
2227 return this.manager
.constructor.static.sizes
[ this.getSize() ];
2231 * Disable transitions on window's frame for the duration of the callback function, then enable them
2235 * @param {Function} callback Function to call while transitions are disabled
2237 OO
.ui
.Window
.prototype.withoutSizeTransitions = function ( callback
) {
2238 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2239 // Disable transitions first, otherwise we'll get values from when the window was animating.
2241 styleObj
= this.$frame
[ 0 ].style
;
2242 oldTransition
= styleObj
.transition
|| styleObj
.OTransition
|| styleObj
.MsTransition
||
2243 styleObj
.MozTransition
|| styleObj
.WebkitTransition
;
2244 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
2245 styleObj
.MozTransition
= styleObj
.WebkitTransition
= 'none';
2247 // Force reflow to make sure the style changes done inside callback really are not transitioned
2248 this.$frame
.height();
2249 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
2250 styleObj
.MozTransition
= styleObj
.WebkitTransition
= oldTransition
;
2254 * Get the height of the full window contents (i.e., the window head, body and foot together).
2256 * What consistitutes the head, body, and foot varies depending on the window type.
2257 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2258 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2259 * and special actions in the head, and dialog content in the body.
2261 * To get just the height of the dialog body, use the #getBodyHeight method.
2263 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2265 OO
.ui
.Window
.prototype.getContentHeight = function () {
2268 bodyStyleObj
= this.$body
[ 0 ].style
,
2269 frameStyleObj
= this.$frame
[ 0 ].style
;
2271 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2272 // Disable transitions first, otherwise we'll get values from when the window was animating.
2273 this.withoutSizeTransitions( function () {
2274 var oldHeight
= frameStyleObj
.height
,
2275 oldPosition
= bodyStyleObj
.position
;
2276 frameStyleObj
.height
= '1px';
2277 // Force body to resize to new width
2278 bodyStyleObj
.position
= 'relative';
2279 bodyHeight
= win
.getBodyHeight();
2280 frameStyleObj
.height
= oldHeight
;
2281 bodyStyleObj
.position
= oldPosition
;
2285 // Add buffer for border
2286 ( this.$frame
.outerHeight() - this.$frame
.innerHeight() ) +
2287 // Use combined heights of children
2288 ( this.$head
.outerHeight( true ) + bodyHeight
+ this.$foot
.outerHeight( true ) )
2293 * Get the height of the window body.
2295 * To get the height of the full window contents (the window body, head, and foot together),
2296 * use #getContentHeight.
2298 * When this function is called, the window will temporarily have been resized
2299 * to height=1px, so .scrollHeight measurements can be taken accurately.
2301 * @return {number} Height of the window body in pixels
2303 OO
.ui
.Window
.prototype.getBodyHeight = function () {
2304 return this.$body
[ 0 ].scrollHeight
;
2308 * Get the directionality of the frame (right-to-left or left-to-right).
2310 * @return {string} Directionality: `'ltr'` or `'rtl'`
2312 OO
.ui
.Window
.prototype.getDir = function () {
2313 return OO
.ui
.Element
.static.getDir( this.$content
) || 'ltr';
2317 * Get the 'setup' process.
2319 * The setup process is used to set up a window for use in a particular context,
2320 * based on the `data` argument. This method is called during the opening phase of the window’s
2323 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2324 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2327 * To add window content that persists between openings, you may wish to use the #initialize method
2331 * @param {Object} [data] Window opening data
2332 * @return {OO.ui.Process} Setup process
2334 OO
.ui
.Window
.prototype.getSetupProcess = function () {
2335 return new OO
.ui
.Process();
2339 * Get the ‘ready’ process.
2341 * The ready process is used to ready a window for use in a particular
2342 * context, based on the `data` argument. This method is called during the opening phase of
2343 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2345 * Override this method to add additional steps to the ‘ready’ process the parent method
2346 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2347 * methods of OO.ui.Process.
2350 * @param {Object} [data] Window opening data
2351 * @return {OO.ui.Process} Ready process
2353 OO
.ui
.Window
.prototype.getReadyProcess = function () {
2354 return new OO
.ui
.Process();
2358 * Get the 'hold' process.
2360 * The hold proccess is used to keep a window from being used in a particular context,
2361 * based on the `data` argument. This method is called during the closing phase of the window’s
2364 * Override this method to add additional steps to the 'hold' process the parent method provides
2365 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2369 * @param {Object} [data] Window closing data
2370 * @return {OO.ui.Process} Hold process
2372 OO
.ui
.Window
.prototype.getHoldProcess = function () {
2373 return new OO
.ui
.Process();
2377 * Get the ‘teardown’ process.
2379 * The teardown process is used to teardown a window after use. During teardown,
2380 * user interactions within the window are conveyed and the window is closed, based on the `data`
2381 * argument. This method is called during the closing phase of the window’s lifecycle.
2383 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2384 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2388 * @param {Object} [data] Window closing data
2389 * @return {OO.ui.Process} Teardown process
2391 OO
.ui
.Window
.prototype.getTeardownProcess = function () {
2392 return new OO
.ui
.Process();
2396 * Set the window manager.
2398 * This will cause the window to initialize. Calling it more than once will cause an error.
2400 * @param {OO.ui.WindowManager} manager Manager for this window
2401 * @throws {Error} An error is thrown if the method is called more than once
2404 OO
.ui
.Window
.prototype.setManager = function ( manager
) {
2405 if ( this.manager
) {
2406 throw new Error( 'Cannot set window manager, window already has a manager' );
2409 this.manager
= manager
;
2416 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2418 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2422 OO
.ui
.Window
.prototype.setSize = function ( size
) {
2429 * Update the window size.
2431 * @throws {Error} An error is thrown if the window is not attached to a window manager
2434 OO
.ui
.Window
.prototype.updateSize = function () {
2435 if ( !this.manager
) {
2436 throw new Error( 'Cannot update window size, must be attached to a manager' );
2439 this.manager
.updateWindowSize( this );
2445 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2446 * when the window is opening. In general, setDimensions should not be called directly.
2448 * To set the size of the window, use the #setSize method.
2450 * @param {Object} dim CSS dimension properties
2451 * @param {string|number} [dim.width] Width
2452 * @param {string|number} [dim.minWidth] Minimum width
2453 * @param {string|number} [dim.maxWidth] Maximum width
2454 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2455 * @param {string|number} [dim.minWidth] Minimum height
2456 * @param {string|number} [dim.maxWidth] Maximum height
2459 OO
.ui
.Window
.prototype.setDimensions = function ( dim
) {
2462 styleObj
= this.$frame
[ 0 ].style
;
2464 // Calculate the height we need to set using the correct width
2465 if ( dim
.height
=== undefined ) {
2466 this.withoutSizeTransitions( function () {
2467 var oldWidth
= styleObj
.width
;
2468 win
.$frame
.css( 'width', dim
.width
|| '' );
2469 height
= win
.getContentHeight();
2470 styleObj
.width
= oldWidth
;
2473 height
= dim
.height
;
2477 width
: dim
.width
|| '',
2478 minWidth
: dim
.minWidth
|| '',
2479 maxWidth
: dim
.maxWidth
|| '',
2480 height
: height
|| '',
2481 minHeight
: dim
.minHeight
|| '',
2482 maxHeight
: dim
.maxHeight
|| ''
2489 * Initialize window contents.
2491 * Before the window is opened for the first time, #initialize is called so that content that
2492 * persists between openings can be added to the window.
2494 * To set up a window with new content each time the window opens, use #getSetupProcess.
2496 * @throws {Error} An error is thrown if the window is not attached to a window manager
2499 OO
.ui
.Window
.prototype.initialize = function () {
2500 if ( !this.manager
) {
2501 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2505 this.$head
= $( '<div>' );
2506 this.$body
= $( '<div>' );
2507 this.$foot
= $( '<div>' );
2508 this.$document
= $( this.getElementDocument() );
2511 this.$element
.on( 'mousedown', this.onMouseDown
.bind( this ) );
2514 this.$head
.addClass( 'oo-ui-window-head' );
2515 this.$body
.addClass( 'oo-ui-window-body' );
2516 this.$foot
.addClass( 'oo-ui-window-foot' );
2517 this.$content
.append( this.$head
, this.$body
, this.$foot
);
2525 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2526 * method, which returns a promise resolved when the window is done opening.
2528 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2530 * @param {Object} [data] Window opening data
2531 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2532 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2533 * value is a new promise, which is resolved when the window begins closing.
2534 * @throws {Error} An error is thrown if the window is not attached to a window manager
2536 OO
.ui
.Window
.prototype.open = function ( data
) {
2537 if ( !this.manager
) {
2538 throw new Error( 'Cannot open window, must be attached to a manager' );
2541 return this.manager
.openWindow( this, data
);
2547 * This method is a wrapper around a call to the window
2548 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2549 * which returns a closing promise resolved when the window is done closing.
2551 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2552 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2553 * the window closes.
2555 * @param {Object} [data] Window closing data
2556 * @return {jQuery.Promise} Promise resolved when window is closed
2557 * @throws {Error} An error is thrown if the window is not attached to a window manager
2559 OO
.ui
.Window
.prototype.close = function ( data
) {
2560 if ( !this.manager
) {
2561 throw new Error( 'Cannot close window, must be attached to a manager' );
2564 return this.manager
.closeWindow( this, data
);
2570 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2573 * @param {Object} [data] Window opening data
2574 * @return {jQuery.Promise} Promise resolved when window is setup
2576 OO
.ui
.Window
.prototype.setup = function ( data
) {
2578 deferred
= $.Deferred();
2580 this.toggle( true );
2582 this.getSetupProcess( data
).execute().done( function () {
2583 // Force redraw by asking the browser to measure the elements' widths
2584 win
.$element
.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2585 win
.$content
.addClass( 'oo-ui-window-content-setup' ).width();
2589 return deferred
.promise();
2595 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2598 * @param {Object} [data] Window opening data
2599 * @return {jQuery.Promise} Promise resolved when window is ready
2601 OO
.ui
.Window
.prototype.ready = function ( data
) {
2603 deferred
= $.Deferred();
2605 this.$content
.focus();
2606 this.getReadyProcess( data
).execute().done( function () {
2607 // Force redraw by asking the browser to measure the elements' widths
2608 win
.$element
.addClass( 'oo-ui-window-ready' ).width();
2609 win
.$content
.addClass( 'oo-ui-window-content-ready' ).width();
2613 return deferred
.promise();
2619 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2622 * @param {Object} [data] Window closing data
2623 * @return {jQuery.Promise} Promise resolved when window is held
2625 OO
.ui
.Window
.prototype.hold = function ( data
) {
2627 deferred
= $.Deferred();
2629 this.getHoldProcess( data
).execute().done( function () {
2630 // Get the focused element within the window's content
2631 var $focus
= win
.$content
.find( OO
.ui
.Element
.static.getDocument( win
.$content
).activeElement
);
2633 // Blur the focused element
2634 if ( $focus
.length
) {
2638 // Force redraw by asking the browser to measure the elements' widths
2639 win
.$element
.removeClass( 'oo-ui-window-ready' ).width();
2640 win
.$content
.removeClass( 'oo-ui-window-content-ready' ).width();
2644 return deferred
.promise();
2650 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2653 * @param {Object} [data] Window closing data
2654 * @return {jQuery.Promise} Promise resolved when window is torn down
2656 OO
.ui
.Window
.prototype.teardown = function ( data
) {
2659 return this.getTeardownProcess( data
).execute()
2660 .done( function () {
2661 // Force redraw by asking the browser to measure the elements' widths
2662 win
.$element
.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2663 win
.$content
.removeClass( 'oo-ui-window-content-setup' ).width();
2664 win
.toggle( false );
2669 * The Dialog class serves as the base class for the other types of dialogs.
2670 * Unless extended to include controls, the rendered dialog box is a simple window
2671 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2672 * which opens, closes, and controls the presentation of the window. See the
2673 * [OOjs UI documentation on MediaWiki] [1] for more information.
2676 * // A simple dialog window.
2677 * function MyDialog( config ) {
2678 * MyDialog.parent.call( this, config );
2680 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2681 * MyDialog.prototype.initialize = function () {
2682 * MyDialog.parent.prototype.initialize.call( this );
2683 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2684 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2685 * this.$body.append( this.content.$element );
2687 * MyDialog.prototype.getBodyHeight = function () {
2688 * return this.content.$element.outerHeight( true );
2690 * var myDialog = new MyDialog( {
2693 * // Create and append a window manager, which opens and closes the window.
2694 * var windowManager = new OO.ui.WindowManager();
2695 * $( 'body' ).append( windowManager.$element );
2696 * windowManager.addWindows( [ myDialog ] );
2697 * // Open the window!
2698 * windowManager.openWindow( myDialog );
2700 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2704 * @extends OO.ui.Window
2705 * @mixins OO.ui.mixin.PendingElement
2708 * @param {Object} [config] Configuration options
2710 OO
.ui
.Dialog
= function OoUiDialog( config
) {
2711 // Parent constructor
2712 OO
.ui
.Dialog
.parent
.call( this, config
);
2714 // Mixin constructors
2715 OO
.ui
.mixin
.PendingElement
.call( this );
2718 this.actions
= new OO
.ui
.ActionSet();
2719 this.attachedActions
= [];
2720 this.currentAction
= null;
2721 this.onDialogKeyDownHandler
= this.onDialogKeyDown
.bind( this );
2724 this.actions
.connect( this, {
2725 click
: 'onActionClick',
2726 resize
: 'onActionResize',
2727 change
: 'onActionsChange'
2732 .addClass( 'oo-ui-dialog' )
2733 .attr( 'role', 'dialog' );
2738 OO
.inheritClass( OO
.ui
.Dialog
, OO
.ui
.Window
);
2739 OO
.mixinClass( OO
.ui
.Dialog
, OO
.ui
.mixin
.PendingElement
);
2741 /* Static Properties */
2744 * Symbolic name of dialog.
2746 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2747 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2749 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2754 * @property {string}
2756 OO
.ui
.Dialog
.static.name
= '';
2761 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2762 * that will produce a Label node or string. The title can also be specified with data passed to the
2763 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2768 * @property {jQuery|string|Function}
2770 OO
.ui
.Dialog
.static.title
= '';
2773 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2775 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2776 * value will be overriden.
2778 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2782 * @property {Object[]}
2784 OO
.ui
.Dialog
.static.actions
= [];
2787 * Close the dialog when the 'Esc' key is pressed.
2792 * @property {boolean}
2794 OO
.ui
.Dialog
.static.escapable
= true;
2799 * Handle frame document key down events.
2802 * @param {jQuery.Event} e Key down event
2804 OO
.ui
.Dialog
.prototype.onDialogKeyDown = function ( e
) {
2805 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
2808 e
.stopPropagation();
2813 * Handle action resized events.
2816 * @param {OO.ui.ActionWidget} action Action that was resized
2818 OO
.ui
.Dialog
.prototype.onActionResize = function () {
2819 // Override in subclass
2823 * Handle action click events.
2826 * @param {OO.ui.ActionWidget} action Action that was clicked
2828 OO
.ui
.Dialog
.prototype.onActionClick = function ( action
) {
2829 if ( !this.isPending() ) {
2830 this.executeAction( action
.getAction() );
2835 * Handle actions change event.
2839 OO
.ui
.Dialog
.prototype.onActionsChange = function () {
2840 this.detachActions();
2841 if ( !this.isClosing() ) {
2842 this.attachActions();
2847 * Get the set of actions used by the dialog.
2849 * @return {OO.ui.ActionSet}
2851 OO
.ui
.Dialog
.prototype.getActions = function () {
2852 return this.actions
;
2856 * Get a process for taking action.
2858 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2859 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2860 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2863 * @param {string} [action] Symbolic name of action
2864 * @return {OO.ui.Process} Action process
2866 OO
.ui
.Dialog
.prototype.getActionProcess = function ( action
) {
2867 return new OO
.ui
.Process()
2868 .next( function () {
2870 // An empty action always closes the dialog without data, which should always be
2871 // safe and make no changes
2880 * @param {Object} [data] Dialog opening data
2881 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2882 * the {@link #static-title static title}
2883 * @param {Object[]} [data.actions] List of configuration options for each
2884 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2886 OO
.ui
.Dialog
.prototype.getSetupProcess = function ( data
) {
2890 return OO
.ui
.Dialog
.parent
.prototype.getSetupProcess
.call( this, data
)
2891 .next( function () {
2892 var config
= this.constructor.static,
2893 actions
= data
.actions
!== undefined ? data
.actions
: config
.actions
;
2895 this.title
.setLabel(
2896 data
.title
!== undefined ? data
.title
: this.constructor.static.title
2898 this.actions
.add( this.getActionWidgets( actions
) );
2900 if ( this.constructor.static.escapable
) {
2901 this.$element
.on( 'keydown', this.onDialogKeyDownHandler
);
2909 OO
.ui
.Dialog
.prototype.getTeardownProcess = function ( data
) {
2911 return OO
.ui
.Dialog
.parent
.prototype.getTeardownProcess
.call( this, data
)
2912 .first( function () {
2913 if ( this.constructor.static.escapable
) {
2914 this.$element
.off( 'keydown', this.onDialogKeyDownHandler
);
2917 this.actions
.clear();
2918 this.currentAction
= null;
2925 OO
.ui
.Dialog
.prototype.initialize = function () {
2929 OO
.ui
.Dialog
.parent
.prototype.initialize
.call( this );
2931 titleId
= OO
.ui
.generateElementId();
2934 this.title
= new OO
.ui
.LabelWidget( {
2939 this.$content
.addClass( 'oo-ui-dialog-content' );
2940 this.$element
.attr( 'aria-labelledby', titleId
);
2941 this.setPendingElement( this.$head
);
2945 * Get action widgets from a list of configs
2947 * @param {Object[]} actions Action widget configs
2948 * @return {OO.ui.ActionWidget[]} Action widgets
2950 OO
.ui
.Dialog
.prototype.getActionWidgets = function ( actions
) {
2951 var i
, len
, widgets
= [];
2952 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
2954 new OO
.ui
.ActionWidget( actions
[ i
] )
2961 * Attach action actions.
2965 OO
.ui
.Dialog
.prototype.attachActions = function () {
2966 // Remember the list of potentially attached actions
2967 this.attachedActions
= this.actions
.get();
2971 * Detach action actions.
2976 OO
.ui
.Dialog
.prototype.detachActions = function () {
2979 // Detach all actions that may have been previously attached
2980 for ( i
= 0, len
= this.attachedActions
.length
; i
< len
; i
++ ) {
2981 this.attachedActions
[ i
].$element
.detach();
2983 this.attachedActions
= [];
2987 * Execute an action.
2989 * @param {string} action Symbolic name of action to execute
2990 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2992 OO
.ui
.Dialog
.prototype.executeAction = function ( action
) {
2994 this.currentAction
= action
;
2995 return this.getActionProcess( action
).execute()
2996 .always( this.popPending
.bind( this ) );
3000 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
3001 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
3002 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
3003 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
3004 * pertinent data and reused.
3006 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
3007 * `opened`, and `closing`, which represent the primary stages of the cycle:
3009 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
3010 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
3012 * - an `opening` event is emitted with an `opening` promise
3013 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
3014 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
3015 * window and its result executed
3016 * - a `setup` progress notification is emitted from the `opening` promise
3017 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
3018 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
3019 * window and its result executed
3020 * - a `ready` progress notification is emitted from the `opening` promise
3021 * - the `opening` promise is resolved with an `opened` promise
3023 * **Opened**: the window is now open.
3025 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
3026 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
3027 * to close the window.
3029 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
3030 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
3031 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
3032 * window and its result executed
3033 * - a `hold` progress notification is emitted from the `closing` promise
3034 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
3035 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
3036 * window and its result executed
3037 * - a `teardown` progress notification is emitted from the `closing` promise
3038 * - the `closing` promise is resolved. The window is now closed
3040 * See the [OOjs UI documentation on MediaWiki][1] for more information.
3042 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3045 * @extends OO.ui.Element
3046 * @mixins OO.EventEmitter
3049 * @param {Object} [config] Configuration options
3050 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
3051 * Note that window classes that are instantiated with a factory must have
3052 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
3053 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
3055 OO
.ui
.WindowManager
= function OoUiWindowManager( config
) {
3056 // Configuration initialization
3057 config
= config
|| {};
3059 // Parent constructor
3060 OO
.ui
.WindowManager
.parent
.call( this, config
);
3062 // Mixin constructors
3063 OO
.EventEmitter
.call( this );
3066 this.factory
= config
.factory
;
3067 this.modal
= config
.modal
=== undefined || !!config
.modal
;
3069 this.opening
= null;
3071 this.closing
= null;
3072 this.preparingToOpen
= null;
3073 this.preparingToClose
= null;
3074 this.currentWindow
= null;
3075 this.globalEvents
= false;
3076 this.$ariaHidden
= null;
3077 this.onWindowResizeTimeout
= null;
3078 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
3079 this.afterWindowResizeHandler
= this.afterWindowResize
.bind( this );
3083 .addClass( 'oo-ui-windowManager' )
3084 .toggleClass( 'oo-ui-windowManager-modal', this.modal
);
3089 OO
.inheritClass( OO
.ui
.WindowManager
, OO
.ui
.Element
);
3090 OO
.mixinClass( OO
.ui
.WindowManager
, OO
.EventEmitter
);
3095 * An 'opening' event is emitted when the window begins to be opened.
3098 * @param {OO.ui.Window} win Window that's being opened
3099 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
3100 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
3101 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
3102 * @param {Object} data Window opening data
3106 * A 'closing' event is emitted when the window begins to be closed.
3109 * @param {OO.ui.Window} win Window that's being closed
3110 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
3111 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
3112 * processes are complete. When the `closing` promise is resolved, the first argument of its value
3113 * is the closing data.
3114 * @param {Object} data Window closing data
3118 * A 'resize' event is emitted when a window is resized.
3121 * @param {OO.ui.Window} win Window that was resized
3124 /* Static Properties */
3127 * Map of the symbolic name of each window size and its CSS properties.
3131 * @property {Object}
3133 OO
.ui
.WindowManager
.static.sizes
= {
3147 // These can be non-numeric because they are never used in calculations
3154 * Symbolic name of the default window size.
3156 * The default size is used if the window's requested size is not recognized.
3160 * @property {string}
3162 OO
.ui
.WindowManager
.static.defaultSize
= 'medium';
3167 * Handle window resize events.
3170 * @param {jQuery.Event} e Window resize event
3172 OO
.ui
.WindowManager
.prototype.onWindowResize = function () {
3173 clearTimeout( this.onWindowResizeTimeout
);
3174 this.onWindowResizeTimeout
= setTimeout( this.afterWindowResizeHandler
, 200 );
3178 * Handle window resize events.
3181 * @param {jQuery.Event} e Window resize event
3183 OO
.ui
.WindowManager
.prototype.afterWindowResize = function () {
3184 if ( this.currentWindow
) {
3185 this.updateWindowSize( this.currentWindow
);
3190 * Check if window is opening.
3192 * @return {boolean} Window is opening
3194 OO
.ui
.WindowManager
.prototype.isOpening = function ( win
) {
3195 return win
=== this.currentWindow
&& !!this.opening
&& this.opening
.state() === 'pending';
3199 * Check if window is closing.
3201 * @return {boolean} Window is closing
3203 OO
.ui
.WindowManager
.prototype.isClosing = function ( win
) {
3204 return win
=== this.currentWindow
&& !!this.closing
&& this.closing
.state() === 'pending';
3208 * Check if window is opened.
3210 * @return {boolean} Window is opened
3212 OO
.ui
.WindowManager
.prototype.isOpened = function ( win
) {
3213 return win
=== this.currentWindow
&& !!this.opened
&& this.opened
.state() === 'pending';
3217 * Check if a window is being managed.
3219 * @param {OO.ui.Window} win Window to check
3220 * @return {boolean} Window is being managed
3222 OO
.ui
.WindowManager
.prototype.hasWindow = function ( win
) {
3225 for ( name
in this.windows
) {
3226 if ( this.windows
[ name
] === win
) {
3235 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ 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.getSetupDelay = function () {
3246 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3248 * @param {OO.ui.Window} win Window being opened
3249 * @param {Object} [data] Window opening data
3250 * @return {number} Milliseconds to wait
3252 OO
.ui
.WindowManager
.prototype.getReadyDelay = function () {
3257 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3259 * @param {OO.ui.Window} win Window being closed
3260 * @param {Object} [data] Window closing data
3261 * @return {number} Milliseconds to wait
3263 OO
.ui
.WindowManager
.prototype.getHoldDelay = function () {
3268 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3269 * executing the ‘teardown’ process.
3271 * @param {OO.ui.Window} win Window being closed
3272 * @param {Object} [data] Window closing data
3273 * @return {number} Milliseconds to wait
3275 OO
.ui
.WindowManager
.prototype.getTeardownDelay = function () {
3276 return this.modal
? 250 : 0;
3280 * Get a window by its symbolic name.
3282 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3283 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3284 * for more information about using factories.
3285 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3287 * @param {string} name Symbolic name of the window
3288 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3289 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3290 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3292 OO
.ui
.WindowManager
.prototype.getWindow = function ( name
) {
3293 var deferred
= $.Deferred(),
3294 win
= this.windows
[ name
];
3296 if ( !( win
instanceof OO
.ui
.Window
) ) {
3297 if ( this.factory
) {
3298 if ( !this.factory
.lookup( name
) ) {
3299 deferred
.reject( new OO
.ui
.Error(
3300 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3303 win
= this.factory
.create( name
);
3304 this.addWindows( [ win
] );
3305 deferred
.resolve( win
);
3308 deferred
.reject( new OO
.ui
.Error(
3309 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3313 deferred
.resolve( win
);
3316 return deferred
.promise();
3320 * Get current window.
3322 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3324 OO
.ui
.WindowManager
.prototype.getCurrentWindow = function () {
3325 return this.currentWindow
;
3331 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3332 * @param {Object} [data] Window opening data
3333 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3334 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3337 OO
.ui
.WindowManager
.prototype.openWindow = function ( win
, data
) {
3339 opening
= $.Deferred();
3341 // Argument handling
3342 if ( typeof win
=== 'string' ) {
3343 return this.getWindow( win
).then( function ( win
) {
3344 return manager
.openWindow( win
, data
);
3349 if ( !this.hasWindow( win
) ) {
3350 opening
.reject( new OO
.ui
.Error(
3351 'Cannot open window: window is not attached to manager'
3353 } else if ( this.preparingToOpen
|| this.opening
|| this.opened
) {
3354 opening
.reject( new OO
.ui
.Error(
3355 'Cannot open window: another window is opening or open'
3360 if ( opening
.state() !== 'rejected' ) {
3361 // If a window is currently closing, wait for it to complete
3362 this.preparingToOpen
= $.when( this.closing
);
3363 // Ensure handlers get called after preparingToOpen is set
3364 this.preparingToOpen
.done( function () {
3365 if ( manager
.modal
) {
3366 manager
.toggleGlobalEvents( true );
3367 manager
.toggleAriaIsolation( true );
3369 manager
.currentWindow
= win
;
3370 manager
.opening
= opening
;
3371 manager
.preparingToOpen
= null;
3372 manager
.emit( 'opening', win
, opening
, data
);
3373 setTimeout( function () {
3374 win
.setup( data
).then( function () {
3375 manager
.updateWindowSize( win
);
3376 manager
.opening
.notify( { state
: 'setup' } );
3377 setTimeout( function () {
3378 win
.ready( data
).then( function () {
3379 manager
.opening
.notify( { state
: 'ready' } );
3380 manager
.opening
= null;
3381 manager
.opened
= $.Deferred();
3382 opening
.resolve( manager
.opened
.promise(), data
);
3384 }, manager
.getReadyDelay() );
3386 }, manager
.getSetupDelay() );
3390 return opening
.promise();
3396 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3397 * @param {Object} [data] Window closing data
3398 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3399 * See {@link #event-closing 'closing' event} for more information about closing promises.
3400 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3403 OO
.ui
.WindowManager
.prototype.closeWindow = function ( win
, data
) {
3405 closing
= $.Deferred(),
3408 // Argument handling
3409 if ( typeof win
=== 'string' ) {
3410 win
= this.windows
[ win
];
3411 } else if ( !this.hasWindow( win
) ) {
3417 closing
.reject( new OO
.ui
.Error(
3418 'Cannot close window: window is not attached to manager'
3420 } else if ( win
!== this.currentWindow
) {
3421 closing
.reject( new OO
.ui
.Error(
3422 'Cannot close window: window already closed with different data'
3424 } else if ( this.preparingToClose
|| this.closing
) {
3425 closing
.reject( new OO
.ui
.Error(
3426 'Cannot close window: window already closing with different data'
3431 if ( closing
.state() !== 'rejected' ) {
3432 // If the window is currently opening, close it when it's done
3433 this.preparingToClose
= $.when( this.opening
);
3434 // Ensure handlers get called after preparingToClose is set
3435 this.preparingToClose
.done( function () {
3436 manager
.closing
= closing
;
3437 manager
.preparingToClose
= null;
3438 manager
.emit( 'closing', win
, closing
, data
);
3439 opened
= manager
.opened
;
3440 manager
.opened
= null;
3441 opened
.resolve( closing
.promise(), data
);
3442 setTimeout( function () {
3443 win
.hold( data
).then( function () {
3444 closing
.notify( { state
: 'hold' } );
3445 setTimeout( function () {
3446 win
.teardown( data
).then( function () {
3447 closing
.notify( { state
: 'teardown' } );
3448 if ( manager
.modal
) {
3449 manager
.toggleGlobalEvents( false );
3450 manager
.toggleAriaIsolation( false );
3452 manager
.closing
= null;
3453 manager
.currentWindow
= null;
3454 closing
.resolve( data
);
3456 }, manager
.getTeardownDelay() );
3458 }, manager
.getHoldDelay() );
3462 return closing
.promise();
3466 * Add windows to the window manager.
3468 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3469 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3470 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3472 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3473 * by reference, symbolic name, or explicitly defined symbolic names.
3474 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3475 * explicit nor a statically configured symbolic name.
3477 OO
.ui
.WindowManager
.prototype.addWindows = function ( windows
) {
3478 var i
, len
, win
, name
, list
;
3480 if ( Array
.isArray( windows
) ) {
3481 // Convert to map of windows by looking up symbolic names from static configuration
3483 for ( i
= 0, len
= windows
.length
; i
< len
; i
++ ) {
3484 name
= windows
[ i
].constructor.static.name
;
3485 if ( typeof name
!== 'string' ) {
3486 throw new Error( 'Cannot add window' );
3488 list
[ name
] = windows
[ i
];
3490 } else if ( OO
.isPlainObject( windows
) ) {
3495 for ( name
in list
) {
3497 this.windows
[ name
] = win
.toggle( false );
3498 this.$element
.append( win
.$element
);
3499 win
.setManager( this );
3504 * Remove the specified windows from the windows manager.
3506 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3507 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3508 * longer listens to events, use the #destroy method.
3510 * @param {string[]} names Symbolic names of windows to remove
3511 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3512 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3514 OO
.ui
.WindowManager
.prototype.removeWindows = function ( names
) {
3515 var i
, len
, win
, name
, cleanupWindow
,
3518 cleanup = function ( name
, win
) {
3519 delete manager
.windows
[ name
];
3520 win
.$element
.detach();
3523 for ( i
= 0, len
= names
.length
; i
< len
; i
++ ) {
3525 win
= this.windows
[ name
];
3527 throw new Error( 'Cannot remove window' );
3529 cleanupWindow
= cleanup
.bind( null, name
, win
);
3530 promises
.push( this.closeWindow( name
).then( cleanupWindow
, cleanupWindow
) );
3533 return $.when
.apply( $, promises
);
3537 * Remove all windows from the window manager.
3539 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3540 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3541 * To remove just a subset of windows, use the #removeWindows method.
3543 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3545 OO
.ui
.WindowManager
.prototype.clearWindows = function () {
3546 return this.removeWindows( Object
.keys( this.windows
) );
3550 * Set dialog size. In general, this method should not be called directly.
3552 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3556 OO
.ui
.WindowManager
.prototype.updateWindowSize = function ( win
) {
3559 // Bypass for non-current, and thus invisible, windows
3560 if ( win
!== this.currentWindow
) {
3564 isFullscreen
= win
.getSize() === 'full';
3566 this.$element
.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen
);
3567 this.$element
.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen
);
3568 win
.setDimensions( win
.getSizeProperties() );
3570 this.emit( 'resize', win
);
3576 * Bind or unbind global events for scrolling.
3579 * @param {boolean} [on] Bind global events
3582 OO
.ui
.WindowManager
.prototype.toggleGlobalEvents = function ( on
) {
3583 var scrollWidth
, bodyMargin
,
3584 $body
= $( this.getElementDocument().body
),
3585 // We could have multiple window managers open so only modify
3586 // the body css at the bottom of the stack
3587 stackDepth
= $body
.data( 'windowManagerGlobalEvents' ) || 0 ;
3589 on
= on
=== undefined ? !!this.globalEvents
: !!on
;
3592 if ( !this.globalEvents
) {
3593 $( this.getElementWindow() ).on( {
3594 // Start listening for top-level window dimension changes
3595 'orientationchange resize': this.onWindowResizeHandler
3597 if ( stackDepth
=== 0 ) {
3598 scrollWidth
= window
.innerWidth
- document
.documentElement
.clientWidth
;
3599 bodyMargin
= parseFloat( $body
.css( 'margin-right' ) ) || 0;
3602 'margin-right': bodyMargin
+ scrollWidth
3606 this.globalEvents
= true;
3608 } else if ( this.globalEvents
) {
3609 $( this.getElementWindow() ).off( {
3610 // Stop listening for top-level window dimension changes
3611 'orientationchange resize': this.onWindowResizeHandler
3614 if ( stackDepth
=== 0 ) {
3620 this.globalEvents
= false;
3622 $body
.data( 'windowManagerGlobalEvents', stackDepth
);
3628 * Toggle screen reader visibility of content other than the window manager.
3631 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3634 OO
.ui
.WindowManager
.prototype.toggleAriaIsolation = function ( isolate
) {
3635 isolate
= isolate
=== undefined ? !this.$ariaHidden
: !!isolate
;
3638 if ( !this.$ariaHidden
) {
3639 // Hide everything other than the window manager from screen readers
3640 this.$ariaHidden
= $( 'body' )
3642 .not( this.$element
.parentsUntil( 'body' ).last() )
3643 .attr( 'aria-hidden', '' );
3645 } else if ( this.$ariaHidden
) {
3646 // Restore screen reader visibility
3647 this.$ariaHidden
.removeAttr( 'aria-hidden' );
3648 this.$ariaHidden
= null;
3655 * Destroy the window manager.
3657 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3658 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3661 OO
.ui
.WindowManager
.prototype.destroy = function () {
3662 this.toggleGlobalEvents( false );
3663 this.toggleAriaIsolation( false );
3664 this.clearWindows();
3665 this.$element
.remove();
3669 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3670 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3671 * appearance and functionality of the error interface.
3673 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3674 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3675 * that initiated the failed process will be disabled.
3677 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3680 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3682 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3687 * @param {string|jQuery} message Description of error
3688 * @param {Object} [config] Configuration options
3689 * @cfg {boolean} [recoverable=true] Error is recoverable.
3690 * By default, errors are recoverable, and users can try the process again.
3691 * @cfg {boolean} [warning=false] Error is a warning.
3692 * If the error is a warning, the error interface will include a
3693 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3694 * is not triggered a second time if the user chooses to continue.
3696 OO
.ui
.Error
= function OoUiError( message
, config
) {
3697 // Allow passing positional parameters inside the config object
3698 if ( OO
.isPlainObject( message
) && config
=== undefined ) {
3700 message
= config
.message
;
3703 // Configuration initialization
3704 config
= config
|| {};
3707 this.message
= message
instanceof jQuery
? message
: String( message
);
3708 this.recoverable
= config
.recoverable
=== undefined || !!config
.recoverable
;
3709 this.warning
= !!config
.warning
;
3714 OO
.initClass( OO
.ui
.Error
);
3719 * Check if the error is recoverable.
3721 * If the error is recoverable, users are able to try the process again.
3723 * @return {boolean} Error is recoverable
3725 OO
.ui
.Error
.prototype.isRecoverable = function () {
3726 return this.recoverable
;
3730 * Check if the error is a warning.
3732 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3734 * @return {boolean} Error is warning
3736 OO
.ui
.Error
.prototype.isWarning = function () {
3737 return this.warning
;
3741 * Get error message as DOM nodes.
3743 * @return {jQuery} Error message in DOM nodes
3745 OO
.ui
.Error
.prototype.getMessage = function () {
3746 return this.message
instanceof jQuery
?
3747 this.message
.clone() :
3748 $( '<div>' ).text( this.message
).contents();
3752 * Get the error message text.
3754 * @return {string} Error message
3756 OO
.ui
.Error
.prototype.getMessageText = function () {
3757 return this.message
instanceof jQuery
? this.message
.text() : this.message
;
3761 * Wraps an HTML snippet for use with configuration values which default
3762 * to strings. This bypasses the default html-escaping done to string
3768 * @param {string} [content] HTML content
3770 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
3772 this.content
= content
;
3777 OO
.initClass( OO
.ui
.HtmlSnippet
);
3784 * @return {string} Unchanged HTML snippet.
3786 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
3787 return this.content
;
3791 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3794 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3795 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3796 * or stop if the promise is rejected.
3797 * - **function**: the process will execute the function. The process will stop if the function returns
3798 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3799 * will wait for that number of milliseconds before proceeding.
3801 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3802 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3803 * its remaining steps will not be performed.
3808 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3809 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3810 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3811 * a number or promise.
3812 * @return {Object} Step object, with `callback` and `context` properties
3814 OO
.ui
.Process = function ( step
, context
) {
3819 if ( step
!== undefined ) {
3820 this.next( step
, context
);
3826 OO
.initClass( OO
.ui
.Process
);
3831 * Start the process.
3833 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3834 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3835 * and any remaining steps are not performed.
3837 OO
.ui
.Process
.prototype.execute = function () {
3838 var i
, len
, promise
;
3841 * Continue execution.
3844 * @param {Array} step A function and the context it should be called in
3845 * @return {Function} Function that continues the process
3847 function proceed( step
) {
3848 return function () {
3849 // Execute step in the correct context
3851 result
= step
.callback
.call( step
.context
);
3853 if ( result
=== false ) {
3854 // Use rejected promise for boolean false results
3855 return $.Deferred().reject( [] ).promise();
3857 if ( typeof result
=== 'number' ) {
3859 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3861 // Use a delayed promise for numbers, expecting them to be in milliseconds
3862 deferred
= $.Deferred();
3863 setTimeout( deferred
.resolve
, result
);
3864 return deferred
.promise();
3866 if ( result
instanceof OO
.ui
.Error
) {
3867 // Use rejected promise for error
3868 return $.Deferred().reject( [ result
] ).promise();
3870 if ( Array
.isArray( result
) && result
.length
&& result
[ 0 ] instanceof OO
.ui
.Error
) {
3871 // Use rejected promise for list of errors
3872 return $.Deferred().reject( result
).promise();
3874 // Duck-type the object to see if it can produce a promise
3875 if ( result
&& $.isFunction( result
.promise
) ) {
3876 // Use a promise generated from the result
3877 return result
.promise();
3879 // Use resolved promise for other results
3880 return $.Deferred().resolve().promise();
3884 if ( this.steps
.length
) {
3885 // Generate a chain reaction of promises
3886 promise
= proceed( this.steps
[ 0 ] )();
3887 for ( i
= 1, len
= this.steps
.length
; i
< len
; i
++ ) {
3888 promise
= promise
.then( proceed( this.steps
[ i
] ) );
3891 promise
= $.Deferred().resolve().promise();
3898 * Create a process step.
3901 * @param {number|jQuery.Promise|Function} step
3903 * - Number of milliseconds to wait before proceeding
3904 * - Promise that must be resolved before proceeding
3905 * - Function to execute
3906 * - If the function returns a boolean false the process will stop
3907 * - If the function returns a promise, the process will continue to the next
3908 * step when the promise is resolved or stop if the promise is rejected
3909 * - If the function returns a number, the process will wait for that number of
3910 * milliseconds before proceeding
3911 * @param {Object} [context=null] Execution context of the function. The context is
3912 * ignored if the step is a number or promise.
3913 * @return {Object} Step object, with `callback` and `context` properties
3915 OO
.ui
.Process
.prototype.createStep = function ( step
, context
) {
3916 if ( typeof step
=== 'number' || $.isFunction( step
.promise
) ) {
3918 callback: function () {
3924 if ( $.isFunction( step
) ) {
3930 throw new Error( 'Cannot create process step: number, promise or function expected' );
3934 * Add step to the beginning of the process.
3936 * @inheritdoc #createStep
3937 * @return {OO.ui.Process} this
3940 OO
.ui
.Process
.prototype.first = function ( step
, context
) {
3941 this.steps
.unshift( this.createStep( step
, context
) );
3946 * Add step to the end of the process.
3948 * @inheritdoc #createStep
3949 * @return {OO.ui.Process} this
3952 OO
.ui
.Process
.prototype.next = function ( step
, context
) {
3953 this.steps
.push( this.createStep( step
, context
) );
3958 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
3959 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
3960 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
3962 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
3964 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
3967 * @extends OO.Factory
3970 OO
.ui
.ToolFactory
= function OoUiToolFactory() {
3971 // Parent constructor
3972 OO
.ui
.ToolFactory
.parent
.call( this );
3977 OO
.inheritClass( OO
.ui
.ToolFactory
, OO
.Factory
);
3982 * Get tools from the factory
3984 * @param {Array} include Included tools
3985 * @param {Array} exclude Excluded tools
3986 * @param {Array} promote Promoted tools
3987 * @param {Array} demote Demoted tools
3988 * @return {string[]} List of tools
3990 OO
.ui
.ToolFactory
.prototype.getTools = function ( include
, exclude
, promote
, demote
) {
3991 var i
, len
, included
, promoted
, demoted
,
3995 // Collect included and not excluded tools
3996 included
= OO
.simpleArrayDifference( this.extract( include
), this.extract( exclude
) );
3999 promoted
= this.extract( promote
, used
);
4000 demoted
= this.extract( demote
, used
);
4003 for ( i
= 0, len
= included
.length
; i
< len
; i
++ ) {
4004 if ( !used
[ included
[ i
] ] ) {
4005 auto
.push( included
[ i
] );
4009 return promoted
.concat( auto
).concat( demoted
);
4013 * Get a flat list of names from a list of names or groups.
4015 * Tools can be specified in the following ways:
4017 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
4018 * - All tools in a group: `{ group: 'group-name' }`
4019 * - All tools: `'*'`
4022 * @param {Array|string} collection List of tools
4023 * @param {Object} [used] Object with names that should be skipped as properties; extracted
4024 * names will be added as properties
4025 * @return {string[]} List of extracted names
4027 OO
.ui
.ToolFactory
.prototype.extract = function ( collection
, used
) {
4028 var i
, len
, item
, name
, tool
,
4031 if ( collection
=== '*' ) {
4032 for ( name
in this.registry
) {
4033 tool
= this.registry
[ name
];
4035 // Only add tools by group name when auto-add is enabled
4036 tool
.static.autoAddToCatchall
&&
4037 // Exclude already used tools
4038 ( !used
|| !used
[ name
] )
4042 used
[ name
] = true;
4046 } else if ( Array
.isArray( collection
) ) {
4047 for ( i
= 0, len
= collection
.length
; i
< len
; i
++ ) {
4048 item
= collection
[ i
];
4049 // Allow plain strings as shorthand for named tools
4050 if ( typeof item
=== 'string' ) {
4051 item
= { name
: item
};
4053 if ( OO
.isPlainObject( item
) ) {
4055 for ( name
in this.registry
) {
4056 tool
= this.registry
[ name
];
4058 // Include tools with matching group
4059 tool
.static.group
=== item
.group
&&
4060 // Only add tools by group name when auto-add is enabled
4061 tool
.static.autoAddToGroup
&&
4062 // Exclude already used tools
4063 ( !used
|| !used
[ name
] )
4067 used
[ name
] = true;
4071 // Include tools with matching name and exclude already used tools
4072 } else if ( item
.name
&& ( !used
|| !used
[ item
.name
] ) ) {
4073 names
.push( item
.name
);
4075 used
[ item
.name
] = true;
4085 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
4086 * specify a symbolic name and be registered with the factory. The following classes are registered by
4089 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
4090 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
4091 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
4093 * See {@link OO.ui.Toolbar toolbars} for an example.
4095 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4097 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4099 * @extends OO.Factory
4102 OO
.ui
.ToolGroupFactory
= function OoUiToolGroupFactory() {
4103 var i
, l
, defaultClasses
;
4104 // Parent constructor
4105 OO
.Factory
.call( this );
4107 defaultClasses
= this.constructor.static.getDefaultClasses();
4109 // Register default toolgroups
4110 for ( i
= 0, l
= defaultClasses
.length
; i
< l
; i
++ ) {
4111 this.register( defaultClasses
[ i
] );
4117 OO
.inheritClass( OO
.ui
.ToolGroupFactory
, OO
.Factory
);
4119 /* Static Methods */
4122 * Get a default set of classes to be registered on construction.
4124 * @return {Function[]} Default classes
4126 OO
.ui
.ToolGroupFactory
.static.getDefaultClasses = function () {
4129 OO
.ui
.ListToolGroup
,
4141 * @param {Object} [config] Configuration options
4143 OO
.ui
.Theme
= function OoUiTheme( config
) {
4144 // Configuration initialization
4145 config
= config
|| {};
4150 OO
.initClass( OO
.ui
.Theme
);
4155 * Get a list of classes to be applied to a widget.
4157 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4158 * otherwise state transitions will not work properly.
4160 * @param {OO.ui.Element} element Element for which to get classes
4161 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4163 OO
.ui
.Theme
.prototype.getElementClasses = function ( /* element */ ) {
4164 return { on
: [], off
: [] };
4168 * Update CSS classes provided by the theme.
4170 * For elements with theme logic hooks, this should be called any time there's a state change.
4172 * @param {OO.ui.Element} element Element for which to update classes
4173 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4175 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
4176 var $elements
= $( [] ),
4177 classes
= this.getElementClasses( element
);
4179 if ( element
.$icon
) {
4180 $elements
= $elements
.add( element
.$icon
);
4182 if ( element
.$indicator
) {
4183 $elements
= $elements
.add( element
.$indicator
);
4187 .removeClass( classes
.off
.join( ' ' ) )
4188 .addClass( classes
.on
.join( ' ' ) );
4192 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4193 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4194 * order in which users will navigate through the focusable elements via the "tab" key.
4197 * // TabIndexedElement is mixed into the ButtonWidget class
4198 * // to provide a tabIndex property.
4199 * var button1 = new OO.ui.ButtonWidget( {
4203 * var button2 = new OO.ui.ButtonWidget( {
4207 * var button3 = new OO.ui.ButtonWidget( {
4211 * var button4 = new OO.ui.ButtonWidget( {
4215 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4221 * @param {Object} [config] Configuration options
4222 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4223 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4224 * functionality will be applied to it instead.
4225 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4226 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4227 * to remove the element from the tab-navigation flow.
4229 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
4230 // Configuration initialization
4231 config
= $.extend( { tabIndex
: 0 }, config
);
4234 this.$tabIndexed
= null;
4235 this.tabIndex
= null;
4238 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
4241 this.setTabIndex( config
.tabIndex
);
4242 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
4247 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
4252 * Set the element that should use the tabindex functionality.
4254 * This method is used to retarget a tabindex mixin so that its functionality applies
4255 * to the specified element. If an element is currently using the functionality, the mixin’s
4256 * effect on that element is removed before the new element is set up.
4258 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4261 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
4262 var tabIndex
= this.tabIndex
;
4263 // Remove attributes from old $tabIndexed
4264 this.setTabIndex( null );
4265 // Force update of new $tabIndexed
4266 this.$tabIndexed
= $tabIndexed
;
4267 this.tabIndex
= tabIndex
;
4268 return this.updateTabIndex();
4272 * Set the value of the tabindex.
4274 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4277 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
4278 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
4280 if ( this.tabIndex
!== tabIndex
) {
4281 this.tabIndex
= tabIndex
;
4282 this.updateTabIndex();
4289 * Update the `tabindex` attribute, in case of changes to tab index or
4295 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
4296 if ( this.$tabIndexed
) {
4297 if ( this.tabIndex
!== null ) {
4298 // Do not index over disabled elements
4299 this.$tabIndexed
.attr( {
4300 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
4301 // Support: ChromeVox and NVDA
4302 // These do not seem to inherit aria-disabled from parent elements
4303 'aria-disabled': this.isDisabled().toString()
4306 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
4313 * Handle disable events.
4316 * @param {boolean} disabled Element is disabled
4318 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
4319 this.updateTabIndex();
4323 * Get the value of the tabindex.
4325 * @return {number|null} Tabindex value
4327 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
4328 return this.tabIndex
;
4332 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4333 * interface element that can be configured with access keys for accessibility.
4334 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4336 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4341 * @param {Object} [config] Configuration options
4342 * @cfg {jQuery} [$button] The button element created by the class.
4343 * If this configuration is omitted, the button element will use a generated `<a>`.
4344 * @cfg {boolean} [framed=true] Render the button with a frame
4346 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
4347 // Configuration initialization
4348 config
= config
|| {};
4351 this.$button
= null;
4353 this.active
= false;
4354 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
4355 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4356 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
4357 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
4358 this.onClickHandler
= this.onClick
.bind( this );
4359 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
4362 this.$element
.addClass( 'oo-ui-buttonElement' );
4363 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
4364 this.setButtonElement( config
.$button
|| $( '<a>' ) );
4369 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
4371 /* Static Properties */
4374 * Cancel mouse down events.
4376 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4377 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4378 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4383 * @property {boolean}
4385 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
4390 * A 'click' event is emitted when the button element is clicked.
4398 * Set the button element.
4400 * This method is used to retarget a button mixin so that its functionality applies to
4401 * the specified button element instead of the one created by the class. If a button element
4402 * is already set, the method will remove the mixin’s effect on that element.
4404 * @param {jQuery} $button Element to use as button
4406 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
4407 if ( this.$button
) {
4409 .removeClass( 'oo-ui-buttonElement-button' )
4410 .removeAttr( 'role accesskey' )
4412 mousedown
: this.onMouseDownHandler
,
4413 keydown
: this.onKeyDownHandler
,
4414 click
: this.onClickHandler
,
4415 keypress
: this.onKeyPressHandler
4419 this.$button
= $button
4420 .addClass( 'oo-ui-buttonElement-button' )
4421 .attr( { role
: 'button' } )
4423 mousedown
: this.onMouseDownHandler
,
4424 keydown
: this.onKeyDownHandler
,
4425 click
: this.onClickHandler
,
4426 keypress
: this.onKeyPressHandler
4431 * Handles mouse down events.
4434 * @param {jQuery.Event} e Mouse down event
4436 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
4437 if ( this.isDisabled() || e
.which
!== 1 ) {
4440 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4441 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4442 // reliably remove the pressed class
4443 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler
);
4444 // Prevent change of focus unless specifically configured otherwise
4445 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
4451 * Handles mouse up events.
4454 * @param {jQuery.Event} e Mouse up event
4456 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
4457 if ( this.isDisabled() || e
.which
!== 1 ) {
4460 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4461 // Stop listening for mouseup, since we only needed this once
4462 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler
);
4466 * Handles mouse click events.
4469 * @param {jQuery.Event} e Mouse click event
4472 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
4473 if ( !this.isDisabled() && e
.which
=== 1 ) {
4474 if ( this.emit( 'click' ) ) {
4481 * Handles key down events.
4484 * @param {jQuery.Event} e Key down event
4486 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
4487 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4490 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4491 // Run the keyup handler no matter where the key is when the button is let go, so we can
4492 // reliably remove the pressed class
4493 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler
);
4497 * Handles key up events.
4500 * @param {jQuery.Event} e Key up event
4502 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
4503 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4506 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4507 // Stop listening for keyup, since we only needed this once
4508 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler
);
4512 * Handles key press events.
4515 * @param {jQuery.Event} e Key press event
4518 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
4519 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
4520 if ( this.emit( 'click' ) ) {
4527 * Check if button has a frame.
4529 * @return {boolean} Button is framed
4531 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
4536 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4538 * @param {boolean} [framed] Make button framed, omit to toggle
4541 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
4542 framed
= framed
=== undefined ? !this.framed
: !!framed
;
4543 if ( framed
!== this.framed
) {
4544 this.framed
= framed
;
4546 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
4547 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
4548 this.updateThemeClasses();
4555 * Set the button to its 'active' state.
4557 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4558 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4559 * for other button types.
4561 * @param {boolean} [value] Make button active
4564 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
4565 this.$element
.toggleClass( 'oo-ui-buttonElement-active', !!value
);
4570 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4571 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4572 * items from the group is done through the interface the class provides.
4573 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4575 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4581 * @param {Object} [config] Configuration options
4582 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4583 * is omitted, the group element will use a generated `<div>`.
4585 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
4586 // Configuration initialization
4587 config
= config
|| {};
4592 this.aggregateItemEvents
= {};
4595 this.setGroupElement( config
.$group
|| $( '<div>' ) );
4601 * Set the group element.
4603 * If an element is already set, items will be moved to the new element.
4605 * @param {jQuery} $group Element to use as group
4607 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
4610 this.$group
= $group
;
4611 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4612 this.$group
.append( this.items
[ i
].$element
);
4617 * Check if a group contains no items.
4619 * @return {boolean} Group is empty
4621 OO
.ui
.mixin
.GroupElement
.prototype.isEmpty = function () {
4622 return !this.items
.length
;
4626 * Get all items in the group.
4628 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4629 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4632 * @return {OO.ui.Element[]} An array of items.
4634 OO
.ui
.mixin
.GroupElement
.prototype.getItems = function () {
4635 return this.items
.slice( 0 );
4639 * Get an item by its data.
4641 * Only the first item with matching data will be returned. To return all matching items,
4642 * use the #getItemsFromData method.
4644 * @param {Object} data Item data to search for
4645 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4647 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
4649 hash
= OO
.getHash( data
);
4651 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4652 item
= this.items
[ i
];
4653 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4662 * Get items by their data.
4664 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4666 * @param {Object} data Item data to search for
4667 * @return {OO.ui.Element[]} Items with equivalent data
4669 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
4671 hash
= OO
.getHash( data
),
4674 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4675 item
= this.items
[ i
];
4676 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4685 * Aggregate the events emitted by the group.
4687 * When events are aggregated, the group will listen to all contained items for the event,
4688 * and then emit the event under a new name. The new event will contain an additional leading
4689 * parameter containing the item that emitted the original event. Other arguments emitted from
4690 * the original event are passed through.
4692 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4693 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4694 * A `null` value will remove aggregated events.
4696 * @throws {Error} An error is thrown if aggregation already exists.
4698 OO
.ui
.mixin
.GroupElement
.prototype.aggregate = function ( events
) {
4699 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
4701 for ( itemEvent
in events
) {
4702 groupEvent
= events
[ itemEvent
];
4704 // Remove existing aggregated event
4705 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4706 // Don't allow duplicate aggregations
4708 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
4710 // Remove event aggregation from existing items
4711 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4712 item
= this.items
[ i
];
4713 if ( item
.connect
&& item
.disconnect
) {
4715 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4716 item
.disconnect( this, remove
);
4719 // Prevent future items from aggregating event
4720 delete this.aggregateItemEvents
[ itemEvent
];
4723 // Add new aggregate event
4725 // Make future items aggregate event
4726 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
4727 // Add event aggregation to existing items
4728 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4729 item
= this.items
[ i
];
4730 if ( item
.connect
&& item
.disconnect
) {
4732 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
4733 item
.connect( this, add
);
4741 * Add items to the group.
4743 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4744 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4746 * @param {OO.ui.Element[]} items An array of items to add to the group
4747 * @param {number} [index] Index of the insertion point
4750 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
4751 var i
, len
, item
, event
, events
, currentIndex
,
4754 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4757 // Check if item exists then remove it first, effectively "moving" it
4758 currentIndex
= this.items
.indexOf( item
);
4759 if ( currentIndex
>= 0 ) {
4760 this.removeItems( [ item
] );
4761 // Adjust index to compensate for removal
4762 if ( currentIndex
< index
) {
4767 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
4769 for ( event
in this.aggregateItemEvents
) {
4770 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
4772 item
.connect( this, events
);
4774 item
.setElementGroup( this );
4775 itemElements
.push( item
.$element
.get( 0 ) );
4778 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
4779 this.$group
.append( itemElements
);
4780 this.items
.push
.apply( this.items
, items
);
4781 } else if ( index
=== 0 ) {
4782 this.$group
.prepend( itemElements
);
4783 this.items
.unshift
.apply( this.items
, items
);
4785 this.items
[ index
].$element
.before( itemElements
);
4786 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
4793 * Remove the specified items from a group.
4795 * Removed items are detached (not removed) from the DOM so that they may be reused.
4796 * To remove all items from a group, you may wish to use the #clearItems method instead.
4798 * @param {OO.ui.Element[]} items An array of items to remove
4801 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
4802 var i
, len
, item
, index
, remove
, itemEvent
;
4804 // Remove specific items
4805 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4807 index
= this.items
.indexOf( item
);
4808 if ( index
!== -1 ) {
4810 item
.connect
&& item
.disconnect
&&
4811 !$.isEmptyObject( this.aggregateItemEvents
)
4814 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4815 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4817 item
.disconnect( this, remove
);
4819 item
.setElementGroup( null );
4820 this.items
.splice( index
, 1 );
4821 item
.$element
.detach();
4829 * Clear all items from the group.
4831 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4832 * To remove only a subset of items from a group, use the #removeItems method.
4836 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
4837 var i
, len
, item
, remove
, itemEvent
;
4840 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4841 item
= this.items
[ i
];
4843 item
.connect
&& item
.disconnect
&&
4844 !$.isEmptyObject( this.aggregateItemEvents
)
4847 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4848 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4850 item
.disconnect( this, remove
);
4852 item
.setElementGroup( null );
4853 item
.$element
.detach();
4861 * DraggableElement is a mixin class used to create elements that can be clicked
4862 * and dragged by a mouse to a new position within a group. This class must be used
4863 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
4864 * the draggable elements.
4871 OO
.ui
.mixin
.DraggableElement
= function OoUiMixinDraggableElement() {
4875 // Initialize and events
4877 .attr( 'draggable', true )
4878 .addClass( 'oo-ui-draggableElement' )
4880 dragstart
: this.onDragStart
.bind( this ),
4881 dragover
: this.onDragOver
.bind( this ),
4882 dragend
: this.onDragEnd
.bind( this ),
4883 drop
: this.onDrop
.bind( this )
4887 OO
.initClass( OO
.ui
.mixin
.DraggableElement
);
4894 * A dragstart event is emitted when the user clicks and begins dragging an item.
4895 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4900 * A dragend event is emitted when the user drags an item and releases the mouse,
4901 * thus terminating the drag operation.
4906 * A drop event is emitted when the user drags an item and then releases the mouse button
4907 * over a valid target.
4910 /* Static Properties */
4913 * @inheritdoc OO.ui.mixin.ButtonElement
4915 OO
.ui
.mixin
.DraggableElement
.static.cancelButtonMouseDownEvents
= false;
4920 * Respond to dragstart event.
4923 * @param {jQuery.Event} event jQuery event
4926 OO
.ui
.mixin
.DraggableElement
.prototype.onDragStart = function ( e
) {
4927 var dataTransfer
= e
.originalEvent
.dataTransfer
;
4928 // Define drop effect
4929 dataTransfer
.dropEffect
= 'none';
4930 dataTransfer
.effectAllowed
= 'move';
4932 // We must set up a dataTransfer data property or Firefox seems to
4933 // ignore the fact the element is draggable.
4935 dataTransfer
.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4937 // The above is only for Firefox. Move on if it fails.
4939 // Add dragging class
4940 this.$element
.addClass( 'oo-ui-draggableElement-dragging' );
4942 this.emit( 'dragstart', this );
4947 * Respond to dragend event.
4952 OO
.ui
.mixin
.DraggableElement
.prototype.onDragEnd = function () {
4953 this.$element
.removeClass( 'oo-ui-draggableElement-dragging' );
4954 this.emit( 'dragend' );
4958 * Handle drop event.
4961 * @param {jQuery.Event} event jQuery event
4964 OO
.ui
.mixin
.DraggableElement
.prototype.onDrop = function ( e
) {
4966 this.emit( 'drop', e
);
4970 * In order for drag/drop to work, the dragover event must
4971 * return false and stop propogation.
4975 OO
.ui
.mixin
.DraggableElement
.prototype.onDragOver = function ( e
) {
4981 * Store it in the DOM so we can access from the widget drag event
4984 * @param {number} Item index
4986 OO
.ui
.mixin
.DraggableElement
.prototype.setIndex = function ( index
) {
4987 if ( this.index
!== index
) {
4989 this.$element
.data( 'index', index
);
4997 * @return {number} Item index
4999 OO
.ui
.mixin
.DraggableElement
.prototype.getIndex = function () {
5004 * DraggableGroupElement is a mixin class used to create a group element to
5005 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
5006 * The class is used with OO.ui.mixin.DraggableElement.
5010 * @mixins OO.ui.mixin.GroupElement
5013 * @param {Object} [config] Configuration options
5014 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
5015 * should match the layout of the items. Items displayed in a single row
5016 * or in several rows should use horizontal orientation. The vertical orientation should only be
5017 * used when the items are displayed in a single column. Defaults to 'vertical'
5019 OO
.ui
.mixin
.DraggableGroupElement
= function OoUiMixinDraggableGroupElement( config
) {
5020 // Configuration initialization
5021 config
= config
|| {};
5023 // Parent constructor
5024 OO
.ui
.mixin
.GroupElement
.call( this, config
);
5027 this.orientation
= config
.orientation
|| 'vertical';
5028 this.dragItem
= null;
5029 this.itemDragOver
= null;
5031 this.sideInsertion
= '';
5035 dragstart
: 'itemDragStart',
5036 dragend
: 'itemDragEnd',
5039 this.connect( this, {
5040 itemDragStart
: 'onItemDragStart',
5041 itemDrop
: 'onItemDrop',
5042 itemDragEnd
: 'onItemDragEnd'
5045 dragover
: this.onDragOver
.bind( this ),
5046 dragleave
: this.onDragLeave
.bind( this )
5050 if ( Array
.isArray( config
.items
) ) {
5051 this.addItems( config
.items
);
5053 this.$placeholder
= $( '<div>' )
5054 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
5056 .addClass( 'oo-ui-draggableGroupElement' )
5057 .append( this.$status
)
5058 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation
=== 'horizontal' )
5059 .prepend( this.$placeholder
);
5063 OO
.mixinClass( OO
.ui
.mixin
.DraggableGroupElement
, OO
.ui
.mixin
.GroupElement
);
5068 * A 'reorder' event is emitted when the order of items in the group changes.
5071 * @param {OO.ui.mixin.DraggableElement} item Reordered item
5072 * @param {number} [newIndex] New index for the item
5078 * Respond to item drag start event
5081 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5083 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDragStart = function ( item
) {
5086 // Map the index of each object
5087 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5088 this.items
[ i
].setIndex( i
);
5091 if ( this.orientation
=== 'horizontal' ) {
5092 // Set the height of the indicator
5093 this.$placeholder
.css( {
5094 height
: item
.$element
.outerHeight(),
5098 // Set the width of the indicator
5099 this.$placeholder
.css( {
5101 width
: item
.$element
.outerWidth()
5104 this.setDragItem( item
);
5108 * Respond to item drag end event
5112 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDragEnd = function () {
5113 this.unsetDragItem();
5118 * Handle drop event and switch the order of the items accordingly
5121 * @param {OO.ui.mixin.DraggableElement} item Dropped item
5124 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDrop = function ( item
) {
5125 var toIndex
= item
.getIndex();
5126 // Check if the dropped item is from the current group
5127 // TODO: Figure out a way to configure a list of legally droppable
5128 // elements even if they are not yet in the list
5129 if ( this.getDragItem() ) {
5130 // If the insertion point is 'after', the insertion index
5131 // is shifted to the right (or to the left in RTL, hence 'after')
5132 if ( this.sideInsertion
=== 'after' ) {
5135 // Emit change event
5136 this.emit( 'reorder', this.getDragItem(), toIndex
);
5138 this.unsetDragItem();
5139 // Return false to prevent propogation
5144 * Handle dragleave event.
5148 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onDragLeave = function () {
5149 // This means the item was dragged outside the widget
5152 .addClass( 'oo-ui-element-hidden' );
5156 * Respond to dragover event
5159 * @param {jQuery.Event} event Event details
5161 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onDragOver = function ( e
) {
5162 var dragOverObj
, $optionWidget
, itemOffset
, itemMidpoint
, itemBoundingRect
,
5163 itemSize
, cssOutput
, dragPosition
, itemIndex
, itemPosition
,
5164 clientX
= e
.originalEvent
.clientX
,
5165 clientY
= e
.originalEvent
.clientY
;
5167 // Get the OptionWidget item we are dragging over
5168 dragOverObj
= this.getElementDocument().elementFromPoint( clientX
, clientY
);
5169 $optionWidget
= $( dragOverObj
).closest( '.oo-ui-draggableElement' );
5170 if ( $optionWidget
[ 0 ] ) {
5171 itemOffset
= $optionWidget
.offset();
5172 itemBoundingRect
= $optionWidget
[ 0 ].getBoundingClientRect();
5173 itemPosition
= $optionWidget
.position();
5174 itemIndex
= $optionWidget
.data( 'index' );
5179 this.isDragging() &&
5180 itemIndex
!== this.getDragItem().getIndex()
5182 if ( this.orientation
=== 'horizontal' ) {
5183 // Calculate where the mouse is relative to the item width
5184 itemSize
= itemBoundingRect
.width
;
5185 itemMidpoint
= itemBoundingRect
.left
+ itemSize
/ 2;
5186 dragPosition
= clientX
;
5187 // Which side of the item we hover over will dictate
5188 // where the placeholder will appear, on the left or
5191 left
: dragPosition
< itemMidpoint
? itemPosition
.left
: itemPosition
.left
+ itemSize
,
5192 top
: itemPosition
.top
5195 // Calculate where the mouse is relative to the item height
5196 itemSize
= itemBoundingRect
.height
;
5197 itemMidpoint
= itemBoundingRect
.top
+ itemSize
/ 2;
5198 dragPosition
= clientY
;
5199 // Which side of the item we hover over will dictate
5200 // where the placeholder will appear, on the top or
5203 top
: dragPosition
< itemMidpoint
? itemPosition
.top
: itemPosition
.top
+ itemSize
,
5204 left
: itemPosition
.left
5207 // Store whether we are before or after an item to rearrange
5208 // For horizontal layout, we need to account for RTL, as this is flipped
5209 if ( this.orientation
=== 'horizontal' && this.$element
.css( 'direction' ) === 'rtl' ) {
5210 this.sideInsertion
= dragPosition
< itemMidpoint
? 'after' : 'before';
5212 this.sideInsertion
= dragPosition
< itemMidpoint
? 'before' : 'after';
5214 // Add drop indicator between objects
5217 .removeClass( 'oo-ui-element-hidden' );
5219 // This means the item was dragged outside the widget
5222 .addClass( 'oo-ui-element-hidden' );
5229 * Set a dragged item
5231 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5233 OO
.ui
.mixin
.DraggableGroupElement
.prototype.setDragItem = function ( item
) {
5234 this.dragItem
= item
;
5238 * Unset the current dragged item
5240 OO
.ui
.mixin
.DraggableGroupElement
.prototype.unsetDragItem = function () {
5241 this.dragItem
= null;
5242 this.itemDragOver
= null;
5243 this.$placeholder
.addClass( 'oo-ui-element-hidden' );
5244 this.sideInsertion
= '';
5248 * Get the item that is currently being dragged.
5250 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5252 OO
.ui
.mixin
.DraggableGroupElement
.prototype.getDragItem = function () {
5253 return this.dragItem
;
5257 * Check if an item in the group is currently being dragged.
5259 * @return {Boolean} Item is being dragged
5261 OO
.ui
.mixin
.DraggableGroupElement
.prototype.isDragging = function () {
5262 return this.getDragItem() !== null;
5266 * IconElement is often mixed into other classes to generate an icon.
5267 * Icons are graphics, about the size of normal text. They are used to aid the user
5268 * in locating a control or to convey information in a space-efficient way. See the
5269 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5270 * included in the library.
5272 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5278 * @param {Object} [config] Configuration options
5279 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5280 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5281 * the icon element be set to an existing icon instead of the one generated by this class, set a
5282 * value using a jQuery selection. For example:
5284 * // Use a <div> tag instead of a <span>
5286 * // Use an existing icon element instead of the one generated by the class
5287 * $icon: this.$element
5288 * // Use an icon element from a child widget
5289 * $icon: this.childwidget.$element
5290 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5291 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5292 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5293 * by the user's language.
5295 * Example of an i18n map:
5297 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5298 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5299 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5300 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5301 * text. The icon title is displayed when users move the mouse over the icon.
5303 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
5304 // Configuration initialization
5305 config
= config
|| {};
5310 this.iconTitle
= null;
5313 this.setIcon( config
.icon
|| this.constructor.static.icon
);
5314 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
5315 this.setIconElement( config
.$icon
|| $( '<span>' ) );
5320 OO
.initClass( OO
.ui
.mixin
.IconElement
);
5322 /* Static Properties */
5325 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5326 * for i18n purposes and contains a `default` icon name and additional names keyed by
5327 * language code. The `default` name is used when no icon is keyed by the user's language.
5329 * Example of an i18n map:
5331 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5333 * Note: the static property will be overridden if the #icon configuration is used.
5337 * @property {Object|string}
5339 OO
.ui
.mixin
.IconElement
.static.icon
= null;
5342 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5343 * function that returns title text, or `null` for no title.
5345 * The static property will be overridden if the #iconTitle configuration is used.
5349 * @property {string|Function|null}
5351 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
5356 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5357 * applies to the specified icon element instead of the one created by the class. If an icon
5358 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5359 * and mixin methods will no longer affect the element.
5361 * @param {jQuery} $icon Element to use as icon
5363 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
5366 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
5367 .removeAttr( 'title' );
5371 .addClass( 'oo-ui-iconElement-icon' )
5372 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
5373 if ( this.iconTitle
!== null ) {
5374 this.$icon
.attr( 'title', this.iconTitle
);
5377 this.updateThemeClasses();
5381 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5382 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5385 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5386 * by language code, or `null` to remove the icon.
5389 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
5390 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
5391 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
5393 if ( this.icon
!== icon
) {
5395 if ( this.icon
!== null ) {
5396 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
5398 if ( icon
!== null ) {
5399 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
5405 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
5406 this.updateThemeClasses();
5412 * Set the icon title. Use `null` to remove the title.
5414 * @param {string|Function|null} iconTitle A text string used as the icon title,
5415 * a function that returns title text, or `null` for no title.
5418 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
5419 iconTitle
= typeof iconTitle
=== 'function' ||
5420 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
5421 OO
.ui
.resolveMsg( iconTitle
) : null;
5423 if ( this.iconTitle
!== iconTitle
) {
5424 this.iconTitle
= iconTitle
;
5426 if ( this.iconTitle
!== null ) {
5427 this.$icon
.attr( 'title', iconTitle
);
5429 this.$icon
.removeAttr( 'title' );
5438 * Get the symbolic name of the icon.
5440 * @return {string} Icon name
5442 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
5447 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5449 * @return {string} Icon title text
5451 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
5452 return this.iconTitle
;
5456 * IndicatorElement is often mixed into other classes to generate an indicator.
5457 * Indicators are small graphics that are generally used in two ways:
5459 * - To draw attention to the status of an item. For example, an indicator might be
5460 * used to show that an item in a list has errors that need to be resolved.
5461 * - To clarify the function of a control that acts in an exceptional way (a button
5462 * that opens a menu instead of performing an action directly, for example).
5464 * For a list of indicators included in the library, please see the
5465 * [OOjs UI documentation on MediaWiki] [1].
5467 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5473 * @param {Object} [config] Configuration options
5474 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5475 * configuration is omitted, the indicator element will use a generated `<span>`.
5476 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5477 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5479 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5480 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5481 * or a function that returns title text. The indicator title is displayed when users move
5482 * the mouse over the indicator.
5484 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
5485 // Configuration initialization
5486 config
= config
|| {};
5489 this.$indicator
= null;
5490 this.indicator
= null;
5491 this.indicatorTitle
= null;
5494 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
5495 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
5496 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
5501 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
5503 /* Static Properties */
5506 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5507 * The static property will be overridden if the #indicator configuration is used.
5511 * @property {string|null}
5513 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
5516 * A text string used as the indicator title, a function that returns title text, or `null`
5517 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5521 * @property {string|Function|null}
5523 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
5528 * Set the indicator element.
5530 * If an element is already set, it will be cleaned up before setting up the new element.
5532 * @param {jQuery} $indicator Element to use as indicator
5534 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
5535 if ( this.$indicator
) {
5537 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
5538 .removeAttr( 'title' );
5541 this.$indicator
= $indicator
5542 .addClass( 'oo-ui-indicatorElement-indicator' )
5543 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
5544 if ( this.indicatorTitle
!== null ) {
5545 this.$indicator
.attr( 'title', this.indicatorTitle
);
5548 this.updateThemeClasses();
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.
6517 * The dimensions of #$clippableContainer will be compared to the boundaries of the
6518 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
6519 * then #$clippable will be given a fixed reduced height and/or width and will be made
6520 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
6521 * but you can build a static footer by setting #$clippableContainer to an element that contains
6522 * #$clippable and the footer.
6528 * @param {Object} [config] Configuration options
6529 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
6530 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
6531 * omit to use #$clippable
6533 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
6534 // Configuration initialization
6535 config
= config
|| {};
6538 this.$clippable
= null;
6539 this.$clippableContainer
= null;
6540 this.clipping
= false;
6541 this.clippedHorizontally
= false;
6542 this.clippedVertically
= false;
6543 this.$clippableScrollableContainer
= null;
6544 this.$clippableScroller
= null;
6545 this.$clippableWindow
= null;
6546 this.idealWidth
= null;
6547 this.idealHeight
= null;
6548 this.onClippableScrollHandler
= this.clip
.bind( this );
6549 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
6552 if ( config
.$clippableContainer
) {
6553 this.setClippableContainer( config
.$clippableContainer
);
6555 this.setClippableElement( config
.$clippable
|| this.$element
);
6561 * Set clippable element.
6563 * If an element is already set, it will be cleaned up before setting up the new element.
6565 * @param {jQuery} $clippable Element to make clippable
6567 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
6568 if ( this.$clippable
) {
6569 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
6570 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6571 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6574 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
6579 * Set clippable container.
6581 * This is the container that will be measured when deciding whether to clip. When clipping,
6582 * #$clippable will be resized in order to keep the clippable container fully visible.
6584 * If the clippable container is unset, #$clippable will be used.
6586 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
6588 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
6589 this.$clippableContainer
= $clippableContainer
;
6590 if ( this.$clippable
) {
6598 * Do not turn clipping on until after the element is attached to the DOM and visible.
6600 * @param {boolean} [clipping] Enable clipping, omit to toggle
6603 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
6604 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
6606 if ( this.clipping
!== clipping
) {
6607 this.clipping
= clipping
;
6609 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
6610 // If the clippable container is the root, we have to listen to scroll events and check
6611 // jQuery.scrollTop on the window because of browser inconsistencies
6612 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
6613 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
6614 this.$clippableScrollableContainer
;
6615 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
6616 this.$clippableWindow
= $( this.getElementWindow() )
6617 .on( 'resize', this.onClippableWindowResizeHandler
);
6618 // Initial clip after visible
6621 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6622 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6624 this.$clippableScrollableContainer
= null;
6625 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
6626 this.$clippableScroller
= null;
6627 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
6628 this.$clippableWindow
= null;
6636 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6638 * @return {boolean} Element will be clipped to the visible area
6640 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
6641 return this.clipping
;
6645 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6647 * @return {boolean} Part of the element is being clipped
6649 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
6650 return this.clippedHorizontally
|| this.clippedVertically
;
6654 * Check if the right of the element is being clipped by the nearest scrollable container.
6656 * @return {boolean} Part of the element is being clipped
6658 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
6659 return this.clippedHorizontally
;
6663 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6665 * @return {boolean} Part of the element is being clipped
6667 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
6668 return this.clippedVertically
;
6672 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6674 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6675 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6677 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
6678 this.idealWidth
= width
;
6679 this.idealHeight
= height
;
6681 if ( !this.clipping
) {
6682 // Update dimensions
6683 this.$clippable
.css( { width
: width
, height
: height
} );
6685 // While clipping, idealWidth and idealHeight are not considered
6689 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6690 * the element's natural height changes.
6692 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6693 * overlapped by, the visible area of the nearest scrollable container.
6697 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
6698 var $container
, extraHeight
, extraWidth
, ccOffset
,
6699 $scrollableContainer
, scOffset
, scHeight
, scWidth
,
6700 ccWidth
, scrollerIsWindow
, scrollTop
, scrollLeft
,
6701 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
6702 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
6703 buffer
= 7; // Chosen by fair dice roll
6705 if ( !this.clipping
) {
6706 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
6710 $container
= this.$clippableContainer
|| this.$clippable
;
6711 extraHeight
= $container
.outerHeight() - this.$clippable
.outerHeight();
6712 extraWidth
= $container
.outerWidth() - this.$clippable
.outerWidth();
6713 ccOffset
= $container
.offset();
6714 $scrollableContainer
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
6715 this.$clippableWindow
: this.$clippableScrollableContainer
;
6716 scOffset
= $scrollableContainer
.offset() || { top
: 0, left
: 0 };
6717 scHeight
= $scrollableContainer
.innerHeight() - buffer
;
6718 scWidth
= $scrollableContainer
.innerWidth() - buffer
;
6719 ccWidth
= $container
.outerWidth() + buffer
;
6720 scrollerIsWindow
= this.$clippableScroller
[ 0 ] === this.$clippableWindow
[ 0 ];
6721 scrollTop
= scrollerIsWindow
? this.$clippableScroller
.scrollTop() : 0;
6722 scrollLeft
= scrollerIsWindow
? this.$clippableScroller
.scrollLeft() : 0;
6723 desiredWidth
= ccOffset
.left
< 0 ?
6724 ccWidth
+ ccOffset
.left
:
6725 ( scOffset
.left
+ scrollLeft
+ scWidth
) - ccOffset
.left
;
6726 desiredHeight
= ( scOffset
.top
+ scrollTop
+ scHeight
) - ccOffset
.top
;
6727 allotedWidth
= desiredWidth
- extraWidth
;
6728 allotedHeight
= desiredHeight
- extraHeight
;
6729 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
6730 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
6731 clipWidth
= allotedWidth
< naturalWidth
;
6732 clipHeight
= allotedHeight
< naturalHeight
;
6735 this.$clippable
.css( { overflowX
: 'scroll', width
: Math
.max( 0, allotedWidth
) } );
6737 this.$clippable
.css( { width
: this.idealWidth
? this.idealWidth
- extraWidth
: '', overflowX
: '' } );
6740 this.$clippable
.css( { overflowY
: 'scroll', height
: Math
.max( 0, allotedHeight
) } );
6742 this.$clippable
.css( { height
: this.idealHeight
? this.idealHeight
- extraHeight
: '', overflowY
: '' } );
6745 // If we stopped clipping in at least one of the dimensions
6746 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
6747 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6750 this.clippedHorizontally
= clipWidth
;
6751 this.clippedVertically
= clipHeight
;
6757 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
6758 * Accesskeys allow an user to go to a specific element by using
6759 * a shortcut combination of a browser specific keys + the key
6763 * // AccessKeyedElement provides an 'accesskey' attribute to the
6764 * // ButtonWidget class
6765 * var button = new OO.ui.ButtonWidget( {
6766 * label: 'Button with Accesskey',
6769 * $( 'body' ).append( button.$element );
6775 * @param {Object} [config] Configuration options
6776 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
6777 * If this config is omitted, the accesskey functionality is applied to $element, the
6778 * element created by the class.
6779 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
6780 * this config is omitted, no accesskey will be added.
6782 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
6783 // Configuration initialization
6784 config
= config
|| {};
6787 this.$accessKeyed
= null;
6788 this.accessKey
= null;
6791 this.setAccessKey( config
.accessKey
|| null );
6792 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
6797 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
6799 /* Static Properties */
6802 * The access key, a function that returns a key, or `null` for no accesskey.
6806 * @property {string|Function|null}
6808 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
6813 * Set the accesskeyed element.
6815 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
6816 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
6818 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
6820 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
6821 if ( this.$accessKeyed
) {
6822 this.$accessKeyed
.removeAttr( 'accesskey' );
6825 this.$accessKeyed
= $accessKeyed
;
6826 if ( this.accessKey
) {
6827 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
6834 * @param {string|Function|null} accesskey Key, a function that returns a key, or `null` for no accesskey
6837 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
6838 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
6840 if ( this.accessKey
!== accessKey
) {
6841 if ( this.$accessKeyed
) {
6842 if ( accessKey
!== null ) {
6843 this.$accessKeyed
.attr( 'accesskey', accessKey
);
6845 this.$accessKeyed
.removeAttr( 'accesskey' );
6848 this.accessKey
= accessKey
;
6857 * @return {string} accessKey string
6859 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
6860 return this.accessKey
;
6864 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
6865 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
6866 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
6867 * which creates the tools on demand.
6869 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
6870 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
6871 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
6873 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
6874 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
6878 * @extends OO.ui.Widget
6879 * @mixins OO.ui.mixin.IconElement
6880 * @mixins OO.ui.mixin.FlaggedElement
6881 * @mixins OO.ui.mixin.TabIndexedElement
6884 * @param {OO.ui.ToolGroup} toolGroup
6885 * @param {Object} [config] Configuration options
6886 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
6887 * the {@link #static-title static title} property is used.
6889 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
6890 * 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
6891 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
6893 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
6894 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
6895 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
6897 OO
.ui
.Tool
= function OoUiTool( toolGroup
, config
) {
6898 // Allow passing positional parameters inside the config object
6899 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
6901 toolGroup
= config
.toolGroup
;
6904 // Configuration initialization
6905 config
= config
|| {};
6907 // Parent constructor
6908 OO
.ui
.Tool
.parent
.call( this, config
);
6911 this.toolGroup
= toolGroup
;
6912 this.toolbar
= this.toolGroup
.getToolbar();
6913 this.active
= false;
6914 this.$title
= $( '<span>' );
6915 this.$accel
= $( '<span>' );
6916 this.$link
= $( '<a>' );
6919 // Mixin constructors
6920 OO
.ui
.mixin
.IconElement
.call( this, config
);
6921 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
6922 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$link
} ) );
6925 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
6928 this.$title
.addClass( 'oo-ui-tool-title' );
6930 .addClass( 'oo-ui-tool-accel' )
6932 // This may need to be changed if the key names are ever localized,
6933 // but for now they are essentially written in English
6938 .addClass( 'oo-ui-tool-link' )
6939 .append( this.$icon
, this.$title
, this.$accel
)
6940 .attr( 'role', 'button' );
6942 .data( 'oo-ui-tool', this )
6944 'oo-ui-tool ' + 'oo-ui-tool-name-' +
6945 this.constructor.static.name
.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
6947 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel
)
6948 .append( this.$link
);
6949 this.setTitle( config
.title
|| this.constructor.static.title
);
6954 OO
.inheritClass( OO
.ui
.Tool
, OO
.ui
.Widget
);
6955 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.IconElement
);
6956 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.FlaggedElement
);
6957 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.TabIndexedElement
);
6959 /* Static Properties */
6965 OO
.ui
.Tool
.static.tagName
= 'span';
6968 * Symbolic name of tool.
6970 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
6971 * also be used when adding tools to toolgroups.
6976 * @property {string}
6978 OO
.ui
.Tool
.static.name
= '';
6981 * Symbolic name of the group.
6983 * The group name is used to associate tools with each other so that they can be selected later by
6984 * a {@link OO.ui.ToolGroup toolgroup}.
6989 * @property {string}
6991 OO
.ui
.Tool
.static.group
= '';
6994 * 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.
6999 * @property {string|Function}
7001 OO
.ui
.Tool
.static.title
= '';
7004 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
7005 * Normally only the icon is displayed, or only the label if no icon is given.
7009 * @property {boolean}
7011 OO
.ui
.Tool
.static.displayBothIconAndLabel
= false;
7014 * Add tool to catch-all groups automatically.
7016 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
7017 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
7021 * @property {boolean}
7023 OO
.ui
.Tool
.static.autoAddToCatchall
= true;
7026 * Add tool to named groups automatically.
7028 * By default, tools that are configured with a static ‘group’ property are added
7029 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
7030 * toolgroups include tools by group name).
7033 * @property {boolean}
7036 OO
.ui
.Tool
.static.autoAddToGroup
= true;
7039 * Check if this tool is compatible with given data.
7041 * This is a stub that can be overriden to provide support for filtering tools based on an
7042 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
7043 * must also call this method so that the compatibility check can be performed.
7047 * @param {Mixed} data Data to check
7048 * @return {boolean} Tool can be used with data
7050 OO
.ui
.Tool
.static.isCompatibleWith = function () {
7057 * Handle the toolbar state being updated.
7059 * This is an abstract method that must be overridden in a concrete subclass.
7064 OO
.ui
.Tool
.prototype.onUpdateState = function () {
7066 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
7071 * Handle the tool being selected.
7073 * This is an abstract method that must be overridden in a concrete subclass.
7078 OO
.ui
.Tool
.prototype.onSelect = function () {
7080 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
7085 * Check if the tool is active.
7087 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
7088 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
7090 * @return {boolean} Tool is active
7092 OO
.ui
.Tool
.prototype.isActive = function () {
7097 * Make the tool appear active or inactive.
7099 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
7100 * appear pressed or not.
7102 * @param {boolean} state Make tool appear active
7104 OO
.ui
.Tool
.prototype.setActive = function ( state
) {
7105 this.active
= !!state
;
7106 if ( this.active
) {
7107 this.$element
.addClass( 'oo-ui-tool-active' );
7109 this.$element
.removeClass( 'oo-ui-tool-active' );
7114 * Set the tool #title.
7116 * @param {string|Function} title Title text or a function that returns text
7119 OO
.ui
.Tool
.prototype.setTitle = function ( title
) {
7120 this.title
= OO
.ui
.resolveMsg( title
);
7126 * Get the tool #title.
7128 * @return {string} Title text
7130 OO
.ui
.Tool
.prototype.getTitle = function () {
7135 * Get the tool's symbolic name.
7137 * @return {string} Symbolic name of tool
7139 OO
.ui
.Tool
.prototype.getName = function () {
7140 return this.constructor.static.name
;
7146 OO
.ui
.Tool
.prototype.updateTitle = function () {
7147 var titleTooltips
= this.toolGroup
.constructor.static.titleTooltips
,
7148 accelTooltips
= this.toolGroup
.constructor.static.accelTooltips
,
7149 accel
= this.toolbar
.getToolAccelerator( this.constructor.static.name
),
7152 this.$title
.text( this.title
);
7153 this.$accel
.text( accel
);
7155 if ( titleTooltips
&& typeof this.title
=== 'string' && this.title
.length
) {
7156 tooltipParts
.push( this.title
);
7158 if ( accelTooltips
&& typeof accel
=== 'string' && accel
.length
) {
7159 tooltipParts
.push( accel
);
7161 if ( tooltipParts
.length
) {
7162 this.$link
.attr( 'title', tooltipParts
.join( ' ' ) );
7164 this.$link
.removeAttr( 'title' );
7171 * Destroying the tool removes all event handlers and the tool’s DOM elements.
7172 * Call this method whenever you are done using a tool.
7174 OO
.ui
.Tool
.prototype.destroy = function () {
7175 this.toolbar
.disconnect( this );
7176 this.$element
.remove();
7180 * Toolbars are complex interface components that permit users to easily access a variety
7181 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
7182 * part of the toolbar, but not configured as tools.
7184 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
7185 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
7186 * picture’), and an icon.
7188 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
7189 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
7190 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
7191 * any order, but each can only appear once in the toolbar.
7193 * The following is an example of a basic toolbar.
7196 * // Example of a toolbar
7197 * // Create the toolbar
7198 * var toolFactory = new OO.ui.ToolFactory();
7199 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7200 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7202 * // We will be placing status text in this element when tools are used
7203 * var $area = $( '<p>' ).text( 'Toolbar example' );
7205 * // Define the tools that we're going to place in our toolbar
7207 * // Create a class inheriting from OO.ui.Tool
7208 * function PictureTool() {
7209 * PictureTool.parent.apply( this, arguments );
7211 * OO.inheritClass( PictureTool, OO.ui.Tool );
7212 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7213 * // of 'icon' and 'title' (displayed icon and text).
7214 * PictureTool.static.name = 'picture';
7215 * PictureTool.static.icon = 'picture';
7216 * PictureTool.static.title = 'Insert picture';
7217 * // Defines the action that will happen when this tool is selected (clicked).
7218 * PictureTool.prototype.onSelect = function () {
7219 * $area.text( 'Picture tool clicked!' );
7220 * // Never display this tool as "active" (selected).
7221 * this.setActive( false );
7223 * // Make this tool available in our toolFactory and thus our toolbar
7224 * toolFactory.register( PictureTool );
7226 * // Register two more tools, nothing interesting here
7227 * function SettingsTool() {
7228 * SettingsTool.parent.apply( this, arguments );
7230 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7231 * SettingsTool.static.name = 'settings';
7232 * SettingsTool.static.icon = 'settings';
7233 * SettingsTool.static.title = 'Change settings';
7234 * SettingsTool.prototype.onSelect = function () {
7235 * $area.text( 'Settings tool clicked!' );
7236 * this.setActive( false );
7238 * toolFactory.register( SettingsTool );
7240 * // Register two more tools, nothing interesting here
7241 * function StuffTool() {
7242 * StuffTool.parent.apply( this, arguments );
7244 * OO.inheritClass( StuffTool, OO.ui.Tool );
7245 * StuffTool.static.name = 'stuff';
7246 * StuffTool.static.icon = 'ellipsis';
7247 * StuffTool.static.title = 'More stuff';
7248 * StuffTool.prototype.onSelect = function () {
7249 * $area.text( 'More stuff tool clicked!' );
7250 * this.setActive( false );
7252 * toolFactory.register( StuffTool );
7254 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7255 * // little popup window (a PopupWidget).
7256 * function HelpTool( toolGroup, config ) {
7257 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7262 * this.popup.$body.append( '<p>I am helpful!</p>' );
7264 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7265 * HelpTool.static.name = 'help';
7266 * HelpTool.static.icon = 'help';
7267 * HelpTool.static.title = 'Help';
7268 * toolFactory.register( HelpTool );
7270 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7271 * // used once (but not all defined tools must be used).
7274 * // 'bar' tool groups display tools' icons only, side-by-side.
7276 * include: [ 'picture', 'help' ]
7279 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7281 * indicator: 'down',
7283 * include: [ 'settings', 'stuff' ]
7285 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7286 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7287 * // since it's more complicated to use. (See the next example snippet on this page.)
7290 * // Create some UI around the toolbar and place it in the document
7291 * var frame = new OO.ui.PanelLayout( {
7295 * var contentFrame = new OO.ui.PanelLayout( {
7299 * frame.$element.append(
7301 * contentFrame.$element.append( $area )
7303 * $( 'body' ).append( frame.$element );
7305 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7307 * toolbar.initialize();
7309 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7310 * 'updateState' event.
7313 * // Create the toolbar
7314 * var toolFactory = new OO.ui.ToolFactory();
7315 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7316 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7318 * // We will be placing status text in this element when tools are used
7319 * var $area = $( '<p>' ).text( 'Toolbar example' );
7321 * // Define the tools that we're going to place in our toolbar
7323 * // Create a class inheriting from OO.ui.Tool
7324 * function PictureTool() {
7325 * PictureTool.parent.apply( this, arguments );
7327 * OO.inheritClass( PictureTool, OO.ui.Tool );
7328 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7329 * // of 'icon' and 'title' (displayed icon and text).
7330 * PictureTool.static.name = 'picture';
7331 * PictureTool.static.icon = 'picture';
7332 * PictureTool.static.title = 'Insert picture';
7333 * // Defines the action that will happen when this tool is selected (clicked).
7334 * PictureTool.prototype.onSelect = function () {
7335 * $area.text( 'Picture tool clicked!' );
7336 * // Never display this tool as "active" (selected).
7337 * this.setActive( false );
7339 * // The toolbar can be synchronized with the state of some external stuff, like a text
7340 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
7341 * // when the text cursor was inside bolded text). Here we simply disable this feature.
7342 * PictureTool.prototype.onUpdateState = function () {
7344 * // Make this tool available in our toolFactory and thus our toolbar
7345 * toolFactory.register( PictureTool );
7347 * // Register two more tools, nothing interesting here
7348 * function SettingsTool() {
7349 * SettingsTool.parent.apply( this, arguments );
7350 * this.reallyActive = false;
7352 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7353 * SettingsTool.static.name = 'settings';
7354 * SettingsTool.static.icon = 'settings';
7355 * SettingsTool.static.title = 'Change settings';
7356 * SettingsTool.prototype.onSelect = function () {
7357 * $area.text( 'Settings tool clicked!' );
7358 * // Toggle the active state on each click
7359 * this.reallyActive = !this.reallyActive;
7360 * this.setActive( this.reallyActive );
7361 * // To update the menu label
7362 * this.toolbar.emit( 'updateState' );
7364 * SettingsTool.prototype.onUpdateState = function () {
7366 * toolFactory.register( SettingsTool );
7368 * // Register two more tools, nothing interesting here
7369 * function StuffTool() {
7370 * StuffTool.parent.apply( this, arguments );
7371 * this.reallyActive = false;
7373 * OO.inheritClass( StuffTool, OO.ui.Tool );
7374 * StuffTool.static.name = 'stuff';
7375 * StuffTool.static.icon = 'ellipsis';
7376 * StuffTool.static.title = 'More stuff';
7377 * StuffTool.prototype.onSelect = function () {
7378 * $area.text( 'More stuff tool clicked!' );
7379 * // Toggle the active state on each click
7380 * this.reallyActive = !this.reallyActive;
7381 * this.setActive( this.reallyActive );
7382 * // To update the menu label
7383 * this.toolbar.emit( 'updateState' );
7385 * StuffTool.prototype.onUpdateState = function () {
7387 * toolFactory.register( StuffTool );
7389 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7390 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7391 * function HelpTool( toolGroup, config ) {
7392 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7397 * this.popup.$body.append( '<p>I am helpful!</p>' );
7399 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7400 * HelpTool.static.name = 'help';
7401 * HelpTool.static.icon = 'help';
7402 * HelpTool.static.title = 'Help';
7403 * toolFactory.register( HelpTool );
7405 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7406 * // used once (but not all defined tools must be used).
7409 * // 'bar' tool groups display tools' icons only, side-by-side.
7411 * include: [ 'picture', 'help' ]
7414 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7415 * // Menu label indicates which items are selected.
7417 * indicator: 'down',
7418 * include: [ 'settings', 'stuff' ]
7422 * // Create some UI around the toolbar and place it in the document
7423 * var frame = new OO.ui.PanelLayout( {
7427 * var contentFrame = new OO.ui.PanelLayout( {
7431 * frame.$element.append(
7433 * contentFrame.$element.append( $area )
7435 * $( 'body' ).append( frame.$element );
7437 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7439 * toolbar.initialize();
7440 * toolbar.emit( 'updateState' );
7443 * @extends OO.ui.Element
7444 * @mixins OO.EventEmitter
7445 * @mixins OO.ui.mixin.GroupElement
7448 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7449 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7450 * @param {Object} [config] Configuration options
7451 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7452 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7454 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7456 OO
.ui
.Toolbar
= function OoUiToolbar( toolFactory
, toolGroupFactory
, config
) {
7457 // Allow passing positional parameters inside the config object
7458 if ( OO
.isPlainObject( toolFactory
) && config
=== undefined ) {
7459 config
= toolFactory
;
7460 toolFactory
= config
.toolFactory
;
7461 toolGroupFactory
= config
.toolGroupFactory
;
7464 // Configuration initialization
7465 config
= config
|| {};
7467 // Parent constructor
7468 OO
.ui
.Toolbar
.parent
.call( this, config
);
7470 // Mixin constructors
7471 OO
.EventEmitter
.call( this );
7472 OO
.ui
.mixin
.GroupElement
.call( this, config
);
7475 this.toolFactory
= toolFactory
;
7476 this.toolGroupFactory
= toolGroupFactory
;
7479 this.$bar
= $( '<div>' );
7480 this.$actions
= $( '<div>' );
7481 this.initialized
= false;
7482 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
7486 .add( this.$bar
).add( this.$group
).add( this.$actions
)
7487 .on( 'mousedown keydown', this.onPointerDown
.bind( this ) );
7490 this.$group
.addClass( 'oo-ui-toolbar-tools' );
7491 if ( config
.actions
) {
7492 this.$bar
.append( this.$actions
.addClass( 'oo-ui-toolbar-actions' ) );
7495 .addClass( 'oo-ui-toolbar-bar' )
7496 .append( this.$group
, '<div style="clear:both"></div>' );
7497 if ( config
.shadow
) {
7498 this.$bar
.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7500 this.$element
.addClass( 'oo-ui-toolbar' ).append( this.$bar
);
7505 OO
.inheritClass( OO
.ui
.Toolbar
, OO
.ui
.Element
);
7506 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.EventEmitter
);
7507 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.ui
.mixin
.GroupElement
);
7512 * Get the tool factory.
7514 * @return {OO.ui.ToolFactory} Tool factory
7516 OO
.ui
.Toolbar
.prototype.getToolFactory = function () {
7517 return this.toolFactory
;
7521 * Get the toolgroup factory.
7523 * @return {OO.Factory} Toolgroup factory
7525 OO
.ui
.Toolbar
.prototype.getToolGroupFactory = function () {
7526 return this.toolGroupFactory
;
7530 * Handles mouse down events.
7533 * @param {jQuery.Event} e Mouse down event
7535 OO
.ui
.Toolbar
.prototype.onPointerDown = function ( e
) {
7536 var $closestWidgetToEvent
= $( e
.target
).closest( '.oo-ui-widget' ),
7537 $closestWidgetToToolbar
= this.$element
.closest( '.oo-ui-widget' );
7538 if ( !$closestWidgetToEvent
.length
|| $closestWidgetToEvent
[ 0 ] === $closestWidgetToToolbar
[ 0 ] ) {
7544 * Handle window resize event.
7547 * @param {jQuery.Event} e Window resize event
7549 OO
.ui
.Toolbar
.prototype.onWindowResize = function () {
7550 this.$element
.toggleClass(
7551 'oo-ui-toolbar-narrow',
7552 this.$bar
.width() <= this.narrowThreshold
7557 * Sets up handles and preloads required information for the toolbar to work.
7558 * This must be called after it is attached to a visible document and before doing anything else.
7560 OO
.ui
.Toolbar
.prototype.initialize = function () {
7561 this.initialized
= true;
7562 this.narrowThreshold
= this.$group
.width() + this.$actions
.width();
7563 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
7564 this.onWindowResize();
7568 * Set up the toolbar.
7570 * The toolbar is set up with a list of toolgroup configurations that specify the type of
7571 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
7572 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
7573 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
7575 * @param {Object.<string,Array>} groups List of toolgroup configurations
7576 * @param {Array|string} [groups.include] Tools to include in the toolgroup
7577 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
7578 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
7579 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
7581 OO
.ui
.Toolbar
.prototype.setup = function ( groups
) {
7582 var i
, len
, type
, group
,
7584 defaultType
= 'bar';
7586 // Cleanup previous groups
7589 // Build out new groups
7590 for ( i
= 0, len
= groups
.length
; i
< len
; i
++ ) {
7591 group
= groups
[ i
];
7592 if ( group
.include
=== '*' ) {
7593 // Apply defaults to catch-all groups
7594 if ( group
.type
=== undefined ) {
7595 group
.type
= 'list';
7597 if ( group
.label
=== undefined ) {
7598 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
7601 // Check type has been registered
7602 type
= this.getToolGroupFactory().lookup( group
.type
) ? group
.type
: defaultType
;
7604 this.getToolGroupFactory().create( type
, this, group
)
7607 this.addItems( items
);
7611 * Remove all tools and toolgroups from the toolbar.
7613 OO
.ui
.Toolbar
.prototype.reset = function () {
7618 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7619 this.items
[ i
].destroy();
7625 * Destroy the toolbar.
7627 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
7628 * this method whenever you are done using a toolbar.
7630 OO
.ui
.Toolbar
.prototype.destroy = function () {
7631 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
7633 this.$element
.remove();
7637 * Check if the tool is available.
7639 * Available tools are ones that have not yet been added to the toolbar.
7641 * @param {string} name Symbolic name of tool
7642 * @return {boolean} Tool is available
7644 OO
.ui
.Toolbar
.prototype.isToolAvailable = function ( name
) {
7645 return !this.tools
[ name
];
7649 * Prevent tool from being used again.
7651 * @param {OO.ui.Tool} tool Tool to reserve
7653 OO
.ui
.Toolbar
.prototype.reserveTool = function ( tool
) {
7654 this.tools
[ tool
.getName() ] = tool
;
7658 * Allow tool to be used again.
7660 * @param {OO.ui.Tool} tool Tool to release
7662 OO
.ui
.Toolbar
.prototype.releaseTool = function ( tool
) {
7663 delete this.tools
[ tool
.getName() ];
7667 * Get accelerator label for tool.
7669 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
7670 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
7671 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
7673 * @param {string} name Symbolic name of tool
7674 * @return {string|undefined} Tool accelerator label if available
7676 OO
.ui
.Toolbar
.prototype.getToolAccelerator = function () {
7681 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
7682 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
7683 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
7684 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
7686 * Toolgroups can contain individual tools, groups of tools, or all available tools:
7688 * To include an individual tool (or array of individual tools), specify tools by symbolic name:
7690 * include: [ 'tool-name' ] or [ { name: 'tool-name' }]
7692 * 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.)
7694 * include: [ { group: 'group-name' } ]
7696 * To include all tools that are not yet assigned to a toolgroup, use the catch-all selector, an asterisk (*):
7700 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
7701 * please see the [OOjs UI documentation on MediaWiki][1].
7703 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7707 * @extends OO.ui.Widget
7708 * @mixins OO.ui.mixin.GroupElement
7711 * @param {OO.ui.Toolbar} toolbar
7712 * @param {Object} [config] Configuration options
7713 * @cfg {Array|string} [include=[]] List of tools to include in the toolgroup.
7714 * @cfg {Array|string} [exclude=[]] List of tools to exclude from the toolgroup.
7715 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning of the toolgroup.
7716 * @cfg {Array|string} [demote=[]] List of tools to demote to the end of the toolgroup.
7717 * This setting is particularly useful when tools have been added to the toolgroup
7718 * en masse (e.g., via the catch-all selector).
7720 OO
.ui
.ToolGroup
= function OoUiToolGroup( toolbar
, config
) {
7721 // Allow passing positional parameters inside the config object
7722 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
7724 toolbar
= config
.toolbar
;
7727 // Configuration initialization
7728 config
= config
|| {};
7730 // Parent constructor
7731 OO
.ui
.ToolGroup
.parent
.call( this, config
);
7733 // Mixin constructors
7734 OO
.ui
.mixin
.GroupElement
.call( this, config
);
7737 this.toolbar
= toolbar
;
7739 this.pressed
= null;
7740 this.autoDisabled
= false;
7741 this.include
= config
.include
|| [];
7742 this.exclude
= config
.exclude
|| [];
7743 this.promote
= config
.promote
|| [];
7744 this.demote
= config
.demote
|| [];
7745 this.onCapturedMouseKeyUpHandler
= this.onCapturedMouseKeyUp
.bind( this );
7749 mousedown
: this.onMouseKeyDown
.bind( this ),
7750 mouseup
: this.onMouseKeyUp
.bind( this ),
7751 keydown
: this.onMouseKeyDown
.bind( this ),
7752 keyup
: this.onMouseKeyUp
.bind( this ),
7753 focus
: this.onMouseOverFocus
.bind( this ),
7754 blur
: this.onMouseOutBlur
.bind( this ),
7755 mouseover
: this.onMouseOverFocus
.bind( this ),
7756 mouseout
: this.onMouseOutBlur
.bind( this )
7758 this.toolbar
.getToolFactory().connect( this, { register
: 'onToolFactoryRegister' } );
7759 this.aggregate( { disable
: 'itemDisable' } );
7760 this.connect( this, { itemDisable
: 'updateDisabled' } );
7763 this.$group
.addClass( 'oo-ui-toolGroup-tools' );
7765 .addClass( 'oo-ui-toolGroup' )
7766 .append( this.$group
);
7772 OO
.inheritClass( OO
.ui
.ToolGroup
, OO
.ui
.Widget
);
7773 OO
.mixinClass( OO
.ui
.ToolGroup
, OO
.ui
.mixin
.GroupElement
);
7781 /* Static Properties */
7784 * Show labels in tooltips.
7788 * @property {boolean}
7790 OO
.ui
.ToolGroup
.static.titleTooltips
= false;
7793 * Show acceleration labels in tooltips.
7795 * Note: The OOjs UI library does not include an accelerator system, but does contain
7796 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
7797 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
7798 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
7802 * @property {boolean}
7804 OO
.ui
.ToolGroup
.static.accelTooltips
= false;
7807 * Automatically disable the toolgroup when all tools are disabled
7811 * @property {boolean}
7813 OO
.ui
.ToolGroup
.static.autoDisable
= true;
7820 OO
.ui
.ToolGroup
.prototype.isDisabled = function () {
7821 return this.autoDisabled
|| OO
.ui
.ToolGroup
.parent
.prototype.isDisabled
.apply( this, arguments
);
7827 OO
.ui
.ToolGroup
.prototype.updateDisabled = function () {
7828 var i
, item
, allDisabled
= true;
7830 if ( this.constructor.static.autoDisable
) {
7831 for ( i
= this.items
.length
- 1; i
>= 0; i
-- ) {
7832 item
= this.items
[ i
];
7833 if ( !item
.isDisabled() ) {
7834 allDisabled
= false;
7838 this.autoDisabled
= allDisabled
;
7840 OO
.ui
.ToolGroup
.parent
.prototype.updateDisabled
.apply( this, arguments
);
7844 * Handle mouse down and key down events.
7847 * @param {jQuery.Event} e Mouse down or key down event
7849 OO
.ui
.ToolGroup
.prototype.onMouseKeyDown = function ( e
) {
7851 !this.isDisabled() &&
7852 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
7854 this.pressed
= this.getTargetTool( e
);
7855 if ( this.pressed
) {
7856 this.pressed
.setActive( true );
7857 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler
);
7858 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler
);
7865 * Handle captured mouse up and key up events.
7868 * @param {Event} e Mouse up or key up event
7870 OO
.ui
.ToolGroup
.prototype.onCapturedMouseKeyUp = function ( e
) {
7871 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler
);
7872 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler
);
7873 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
7874 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
7875 this.onMouseKeyUp( e
);
7879 * Handle mouse up and key up events.
7882 * @param {jQuery.Event} e Mouse up or key up event
7884 OO
.ui
.ToolGroup
.prototype.onMouseKeyUp = function ( e
) {
7885 var tool
= this.getTargetTool( e
);
7888 !this.isDisabled() && this.pressed
&& this.pressed
=== tool
&&
7889 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
7891 this.pressed
.onSelect();
7892 this.pressed
= null;
7896 this.pressed
= null;
7900 * Handle mouse over and focus events.
7903 * @param {jQuery.Event} e Mouse over or focus event
7905 OO
.ui
.ToolGroup
.prototype.onMouseOverFocus = function ( e
) {
7906 var tool
= this.getTargetTool( e
);
7908 if ( this.pressed
&& this.pressed
=== tool
) {
7909 this.pressed
.setActive( true );
7914 * Handle mouse out and blur events.
7917 * @param {jQuery.Event} e Mouse out or blur event
7919 OO
.ui
.ToolGroup
.prototype.onMouseOutBlur = function ( e
) {
7920 var tool
= this.getTargetTool( e
);
7922 if ( this.pressed
&& this.pressed
=== tool
) {
7923 this.pressed
.setActive( false );
7928 * Get the closest tool to a jQuery.Event.
7930 * Only tool links are considered, which prevents other elements in the tool such as popups from
7931 * triggering tool group interactions.
7934 * @param {jQuery.Event} e
7935 * @return {OO.ui.Tool|null} Tool, `null` if none was found
7937 OO
.ui
.ToolGroup
.prototype.getTargetTool = function ( e
) {
7939 $item
= $( e
.target
).closest( '.oo-ui-tool-link' );
7941 if ( $item
.length
) {
7942 tool
= $item
.parent().data( 'oo-ui-tool' );
7945 return tool
&& !tool
.isDisabled() ? tool
: null;
7949 * Handle tool registry register events.
7951 * If a tool is registered after the group is created, we must repopulate the list to account for:
7953 * - a tool being added that may be included
7954 * - a tool already included being overridden
7957 * @param {string} name Symbolic name of tool
7959 OO
.ui
.ToolGroup
.prototype.onToolFactoryRegister = function () {
7964 * Get the toolbar that contains the toolgroup.
7966 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
7968 OO
.ui
.ToolGroup
.prototype.getToolbar = function () {
7969 return this.toolbar
;
7973 * Add and remove tools based on configuration.
7975 OO
.ui
.ToolGroup
.prototype.populate = function () {
7976 var i
, len
, name
, tool
,
7977 toolFactory
= this.toolbar
.getToolFactory(),
7981 list
= this.toolbar
.getToolFactory().getTools(
7982 this.include
, this.exclude
, this.promote
, this.demote
7985 // Build a list of needed tools
7986 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
7990 toolFactory
.lookup( name
) &&
7991 // Tool is available or is already in this group
7992 ( this.toolbar
.isToolAvailable( name
) || this.tools
[ name
] )
7994 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
7995 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
7996 this.toolbar
.tools
[ name
] = true;
7997 tool
= this.tools
[ name
];
7999 // Auto-initialize tools on first use
8000 this.tools
[ name
] = tool
= toolFactory
.create( name
, this );
8003 this.toolbar
.reserveTool( tool
);
8005 names
[ name
] = true;
8008 // Remove tools that are no longer needed
8009 for ( name
in this.tools
) {
8010 if ( !names
[ name
] ) {
8011 this.tools
[ name
].destroy();
8012 this.toolbar
.releaseTool( this.tools
[ name
] );
8013 remove
.push( this.tools
[ name
] );
8014 delete this.tools
[ name
];
8017 if ( remove
.length
) {
8018 this.removeItems( remove
);
8020 // Update emptiness state
8022 this.$element
.removeClass( 'oo-ui-toolGroup-empty' );
8024 this.$element
.addClass( 'oo-ui-toolGroup-empty' );
8026 // Re-add tools (moving existing ones to new locations)
8027 this.addItems( add
);
8028 // Disabled state may depend on items
8029 this.updateDisabled();
8033 * Destroy toolgroup.
8035 OO
.ui
.ToolGroup
.prototype.destroy = function () {
8039 this.toolbar
.getToolFactory().disconnect( this );
8040 for ( name
in this.tools
) {
8041 this.toolbar
.releaseTool( this.tools
[ name
] );
8042 this.tools
[ name
].disconnect( this ).destroy();
8043 delete this.tools
[ name
];
8045 this.$element
.remove();
8049 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
8050 * consists of a header that contains the dialog title, a body with the message, and a footer that
8051 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
8052 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
8054 * There are two basic types of message dialogs, confirmation and alert:
8056 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
8057 * more details about the consequences.
8058 * - **alert**: the dialog title describes which event occurred and the message provides more information
8059 * about why the event occurred.
8061 * The MessageDialog class specifies two actions: ‘accept’, the primary
8062 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
8063 * passing along the selected action.
8065 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
8068 * // Example: Creating and opening a message dialog window.
8069 * var messageDialog = new OO.ui.MessageDialog();
8071 * // Create and append a window manager.
8072 * var windowManager = new OO.ui.WindowManager();
8073 * $( 'body' ).append( windowManager.$element );
8074 * windowManager.addWindows( [ messageDialog ] );
8075 * // Open the window.
8076 * windowManager.openWindow( messageDialog, {
8077 * title: 'Basic message dialog',
8078 * message: 'This is the message'
8081 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
8084 * @extends OO.ui.Dialog
8087 * @param {Object} [config] Configuration options
8089 OO
.ui
.MessageDialog
= function OoUiMessageDialog( config
) {
8090 // Parent constructor
8091 OO
.ui
.MessageDialog
.parent
.call( this, config
);
8094 this.verticalActionLayout
= null;
8097 this.$element
.addClass( 'oo-ui-messageDialog' );
8102 OO
.inheritClass( OO
.ui
.MessageDialog
, OO
.ui
.Dialog
);
8104 /* Static Properties */
8106 OO
.ui
.MessageDialog
.static.name
= 'message';
8108 OO
.ui
.MessageDialog
.static.size
= 'small';
8110 OO
.ui
.MessageDialog
.static.verbose
= false;
8115 * The title of a confirmation dialog describes what a progressive action will do. The
8116 * title of an alert dialog describes which event occurred.
8120 * @property {jQuery|string|Function|null}
8122 OO
.ui
.MessageDialog
.static.title
= null;
8125 * The message displayed in the dialog body.
8127 * A confirmation message describes the consequences of a progressive action. An alert
8128 * message describes why an event occurred.
8132 * @property {jQuery|string|Function|null}
8134 OO
.ui
.MessageDialog
.static.message
= null;
8136 OO
.ui
.MessageDialog
.static.actions
= [
8137 { action
: 'accept', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-accept' ), flags
: 'primary' },
8138 { action
: 'reject', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-reject' ), flags
: 'safe' }
8146 OO
.ui
.MessageDialog
.prototype.setManager = function ( manager
) {
8147 OO
.ui
.MessageDialog
.parent
.prototype.setManager
.call( this, manager
);
8150 this.manager
.connect( this, {
8160 OO
.ui
.MessageDialog
.prototype.onActionResize = function ( action
) {
8162 return OO
.ui
.MessageDialog
.parent
.prototype.onActionResize
.call( this, action
);
8166 * Handle window resized events.
8170 OO
.ui
.MessageDialog
.prototype.onResize = function () {
8172 dialog
.fitActions();
8173 // Wait for CSS transition to finish and do it again :(
8174 setTimeout( function () {
8175 dialog
.fitActions();
8180 * Toggle action layout between vertical and horizontal.
8184 * @param {boolean} [value] Layout actions vertically, omit to toggle
8187 OO
.ui
.MessageDialog
.prototype.toggleVerticalActionLayout = function ( value
) {
8188 value
= value
=== undefined ? !this.verticalActionLayout
: !!value
;
8190 if ( value
!== this.verticalActionLayout
) {
8191 this.verticalActionLayout
= value
;
8193 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value
)
8194 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value
);
8203 OO
.ui
.MessageDialog
.prototype.getActionProcess = function ( action
) {
8205 return new OO
.ui
.Process( function () {
8206 this.close( { action
: action
} );
8209 return OO
.ui
.MessageDialog
.parent
.prototype.getActionProcess
.call( this, action
);
8215 * @param {Object} [data] Dialog opening data
8216 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8217 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8218 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8219 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8222 OO
.ui
.MessageDialog
.prototype.getSetupProcess = function ( data
) {
8226 return OO
.ui
.MessageDialog
.parent
.prototype.getSetupProcess
.call( this, data
)
8227 .next( function () {
8228 this.title
.setLabel(
8229 data
.title
!== undefined ? data
.title
: this.constructor.static.title
8231 this.message
.setLabel(
8232 data
.message
!== undefined ? data
.message
: this.constructor.static.message
8234 this.message
.$element
.toggleClass(
8235 'oo-ui-messageDialog-message-verbose',
8236 data
.verbose
!== undefined ? data
.verbose
: this.constructor.static.verbose
8244 OO
.ui
.MessageDialog
.prototype.getReadyProcess = function ( data
) {
8248 return OO
.ui
.MessageDialog
.parent
.prototype.getReadyProcess
.call( this, data
)
8249 .next( function () {
8250 // Focus the primary action button
8251 var actions
= this.actions
.get();
8252 actions
= actions
.filter( function ( action
) {
8253 return action
.getFlags().indexOf( 'primary' ) > -1;
8255 if ( actions
.length
> 0 ) {
8256 actions
[ 0 ].$button
.focus();
8264 OO
.ui
.MessageDialog
.prototype.getBodyHeight = function () {
8265 var bodyHeight
, oldOverflow
,
8266 $scrollable
= this.container
.$element
;
8268 oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
8269 $scrollable
[ 0 ].style
.overflow
= 'hidden';
8271 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
8273 bodyHeight
= this.text
.$element
.outerHeight( true );
8274 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
8282 OO
.ui
.MessageDialog
.prototype.setDimensions = function ( dim
) {
8283 var $scrollable
= this.container
.$element
;
8284 OO
.ui
.MessageDialog
.parent
.prototype.setDimensions
.call( this, dim
);
8286 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8287 // Need to do it after transition completes (250ms), add 50ms just in case.
8288 setTimeout( function () {
8289 var oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
8290 $scrollable
[ 0 ].style
.overflow
= 'hidden';
8292 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
8294 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
8303 OO
.ui
.MessageDialog
.prototype.initialize = function () {
8305 OO
.ui
.MessageDialog
.parent
.prototype.initialize
.call( this );
8308 this.$actions
= $( '<div>' );
8309 this.container
= new OO
.ui
.PanelLayout( {
8310 scrollable
: true, classes
: [ 'oo-ui-messageDialog-container' ]
8312 this.text
= new OO
.ui
.PanelLayout( {
8313 padded
: true, expanded
: false, classes
: [ 'oo-ui-messageDialog-text' ]
8315 this.message
= new OO
.ui
.LabelWidget( {
8316 classes
: [ 'oo-ui-messageDialog-message' ]
8320 this.title
.$element
.addClass( 'oo-ui-messageDialog-title' );
8321 this.$content
.addClass( 'oo-ui-messageDialog-content' );
8322 this.container
.$element
.append( this.text
.$element
);
8323 this.text
.$element
.append( this.title
.$element
, this.message
.$element
);
8324 this.$body
.append( this.container
.$element
);
8325 this.$actions
.addClass( 'oo-ui-messageDialog-actions' );
8326 this.$foot
.append( this.$actions
);
8332 OO
.ui
.MessageDialog
.prototype.attachActions = function () {
8333 var i
, len
, other
, special
, others
;
8336 OO
.ui
.MessageDialog
.parent
.prototype.attachActions
.call( this );
8338 special
= this.actions
.getSpecial();
8339 others
= this.actions
.getOthers();
8341 if ( special
.safe
) {
8342 this.$actions
.append( special
.safe
.$element
);
8343 special
.safe
.toggleFramed( false );
8345 if ( others
.length
) {
8346 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
8347 other
= others
[ i
];
8348 this.$actions
.append( other
.$element
);
8349 other
.toggleFramed( false );
8352 if ( special
.primary
) {
8353 this.$actions
.append( special
.primary
.$element
);
8354 special
.primary
.toggleFramed( false );
8357 if ( !this.isOpening() ) {
8358 // If the dialog is currently opening, this will be called automatically soon.
8359 // This also calls #fitActions.
8365 * Fit action actions into columns or rows.
8367 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8371 OO
.ui
.MessageDialog
.prototype.fitActions = function () {
8373 previous
= this.verticalActionLayout
,
8374 actions
= this.actions
.get();
8377 this.toggleVerticalActionLayout( false );
8378 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
8379 action
= actions
[ i
];
8380 if ( action
.$element
.innerWidth() < action
.$label
.outerWidth( true ) ) {
8381 this.toggleVerticalActionLayout( true );
8386 // Move the body out of the way of the foot
8387 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
8389 if ( this.verticalActionLayout
!== previous
) {
8390 // We changed the layout, window height might need to be updated.
8396 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8397 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8398 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8399 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8400 * required for each process.
8402 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8403 * processes with an animation. The header contains the dialog title as well as
8404 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8405 * a ‘primary’ action on the right (e.g., ‘Done’).
8407 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8408 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8411 * // Example: Creating and opening a process dialog window.
8412 * function MyProcessDialog( config ) {
8413 * MyProcessDialog.parent.call( this, config );
8415 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8417 * MyProcessDialog.static.title = 'Process dialog';
8418 * MyProcessDialog.static.actions = [
8419 * { action: 'save', label: 'Done', flags: 'primary' },
8420 * { label: 'Cancel', flags: 'safe' }
8423 * MyProcessDialog.prototype.initialize = function () {
8424 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8425 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8426 * 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>' );
8427 * this.$body.append( this.content.$element );
8429 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8430 * var dialog = this;
8432 * return new OO.ui.Process( function () {
8433 * dialog.close( { action: action } );
8436 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8439 * var windowManager = new OO.ui.WindowManager();
8440 * $( 'body' ).append( windowManager.$element );
8442 * var dialog = new MyProcessDialog();
8443 * windowManager.addWindows( [ dialog ] );
8444 * windowManager.openWindow( dialog );
8446 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8450 * @extends OO.ui.Dialog
8453 * @param {Object} [config] Configuration options
8455 OO
.ui
.ProcessDialog
= function OoUiProcessDialog( config
) {
8456 // Parent constructor
8457 OO
.ui
.ProcessDialog
.parent
.call( this, config
);
8460 this.fitOnOpen
= false;
8463 this.$element
.addClass( 'oo-ui-processDialog' );
8468 OO
.inheritClass( OO
.ui
.ProcessDialog
, OO
.ui
.Dialog
);
8473 * Handle dismiss button click events.
8479 OO
.ui
.ProcessDialog
.prototype.onDismissErrorButtonClick = function () {
8484 * Handle retry button click events.
8486 * Hides errors and then tries again.
8490 OO
.ui
.ProcessDialog
.prototype.onRetryButtonClick = function () {
8492 this.executeAction( this.currentAction
);
8498 OO
.ui
.ProcessDialog
.prototype.onActionResize = function ( action
) {
8499 if ( this.actions
.isSpecial( action
) ) {
8502 return OO
.ui
.ProcessDialog
.parent
.prototype.onActionResize
.call( this, action
);
8508 OO
.ui
.ProcessDialog
.prototype.initialize = function () {
8510 OO
.ui
.ProcessDialog
.parent
.prototype.initialize
.call( this );
8513 this.$navigation
= $( '<div>' );
8514 this.$location
= $( '<div>' );
8515 this.$safeActions
= $( '<div>' );
8516 this.$primaryActions
= $( '<div>' );
8517 this.$otherActions
= $( '<div>' );
8518 this.dismissButton
= new OO
.ui
.ButtonWidget( {
8519 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' )
8521 this.retryButton
= new OO
.ui
.ButtonWidget();
8522 this.$errors
= $( '<div>' );
8523 this.$errorsTitle
= $( '<div>' );
8526 this.dismissButton
.connect( this, { click
: 'onDismissErrorButtonClick' } );
8527 this.retryButton
.connect( this, { click
: 'onRetryButtonClick' } );
8530 this.title
.$element
.addClass( 'oo-ui-processDialog-title' );
8532 .append( this.title
.$element
)
8533 .addClass( 'oo-ui-processDialog-location' );
8534 this.$safeActions
.addClass( 'oo-ui-processDialog-actions-safe' );
8535 this.$primaryActions
.addClass( 'oo-ui-processDialog-actions-primary' );
8536 this.$otherActions
.addClass( 'oo-ui-processDialog-actions-other' );
8538 .addClass( 'oo-ui-processDialog-errors-title' )
8539 .text( OO
.ui
.msg( 'ooui-dialog-process-error' ) );
8541 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8542 .append( this.$errorsTitle
, this.dismissButton
.$element
, this.retryButton
.$element
);
8544 .addClass( 'oo-ui-processDialog-content' )
8545 .append( this.$errors
);
8547 .addClass( 'oo-ui-processDialog-navigation' )
8548 .append( this.$safeActions
, this.$location
, this.$primaryActions
);
8549 this.$head
.append( this.$navigation
);
8550 this.$foot
.append( this.$otherActions
);
8556 OO
.ui
.ProcessDialog
.prototype.getActionWidgets = function ( actions
) {
8557 var i
, len
, widgets
= [];
8558 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
8560 new OO
.ui
.ActionWidget( $.extend( { framed
: true }, actions
[ i
] ) )
8569 OO
.ui
.ProcessDialog
.prototype.attachActions = function () {
8570 var i
, len
, other
, special
, others
;
8573 OO
.ui
.ProcessDialog
.parent
.prototype.attachActions
.call( this );
8575 special
= this.actions
.getSpecial();
8576 others
= this.actions
.getOthers();
8577 if ( special
.primary
) {
8578 this.$primaryActions
.append( special
.primary
.$element
);
8580 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
8581 other
= others
[ i
];
8582 this.$otherActions
.append( other
.$element
);
8584 if ( special
.safe
) {
8585 this.$safeActions
.append( special
.safe
.$element
);
8589 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
8595 OO
.ui
.ProcessDialog
.prototype.executeAction = function ( action
) {
8597 return OO
.ui
.ProcessDialog
.parent
.prototype.executeAction
.call( this, action
)
8598 .fail( function ( errors
) {
8599 process
.showErrors( errors
|| [] );
8606 OO
.ui
.ProcessDialog
.prototype.setDimensions = function () {
8608 OO
.ui
.ProcessDialog
.parent
.prototype.setDimensions
.apply( this, arguments
);
8614 * Fit label between actions.
8619 OO
.ui
.ProcessDialog
.prototype.fitLabel = function () {
8620 var safeWidth
, primaryWidth
, biggerWidth
, labelWidth
, navigationWidth
, leftWidth
, rightWidth
,
8621 size
= this.getSizeProperties();
8623 if ( typeof size
.width
!== 'number' ) {
8624 if ( this.isOpened() ) {
8625 navigationWidth
= this.$head
.width() - 20;
8626 } else if ( this.isOpening() ) {
8627 if ( !this.fitOnOpen
) {
8628 // Size is relative and the dialog isn't open yet, so wait.
8629 this.manager
.opening
.done( this.fitLabel
.bind( this ) );
8630 this.fitOnOpen
= true;
8637 navigationWidth
= size
.width
- 20;
8640 safeWidth
= this.$safeActions
.is( ':visible' ) ? this.$safeActions
.width() : 0;
8641 primaryWidth
= this.$primaryActions
.is( ':visible' ) ? this.$primaryActions
.width() : 0;
8642 biggerWidth
= Math
.max( safeWidth
, primaryWidth
);
8644 labelWidth
= this.title
.$element
.width();
8646 if ( 2 * biggerWidth
+ labelWidth
< navigationWidth
) {
8647 // We have enough space to center the label
8648 leftWidth
= rightWidth
= biggerWidth
;
8650 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
8651 if ( this.getDir() === 'ltr' ) {
8652 leftWidth
= safeWidth
;
8653 rightWidth
= primaryWidth
;
8655 leftWidth
= primaryWidth
;
8656 rightWidth
= safeWidth
;
8660 this.$location
.css( { paddingLeft
: leftWidth
, paddingRight
: rightWidth
} );
8666 * Handle errors that occurred during accept or reject processes.
8669 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
8671 OO
.ui
.ProcessDialog
.prototype.showErrors = function ( errors
) {
8672 var i
, len
, $item
, actions
,
8678 if ( errors
instanceof OO
.ui
.Error
) {
8679 errors
= [ errors
];
8682 for ( i
= 0, len
= errors
.length
; i
< len
; i
++ ) {
8683 if ( !errors
[ i
].isRecoverable() ) {
8684 recoverable
= false;
8686 if ( errors
[ i
].isWarning() ) {
8689 $item
= $( '<div>' )
8690 .addClass( 'oo-ui-processDialog-error' )
8691 .append( errors
[ i
].getMessage() );
8692 items
.push( $item
[ 0 ] );
8694 this.$errorItems
= $( items
);
8695 if ( recoverable
) {
8696 abilities
[ this.currentAction
] = true;
8697 // Copy the flags from the first matching action
8698 actions
= this.actions
.get( { actions
: this.currentAction
} );
8699 if ( actions
.length
) {
8700 this.retryButton
.clearFlags().setFlags( actions
[ 0 ].getFlags() );
8703 abilities
[ this.currentAction
] = false;
8704 this.actions
.setAbilities( abilities
);
8707 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-continue' ) );
8709 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-retry' ) );
8711 this.retryButton
.toggle( recoverable
);
8712 this.$errorsTitle
.after( this.$errorItems
);
8713 this.$errors
.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
8721 OO
.ui
.ProcessDialog
.prototype.hideErrors = function () {
8722 this.$errors
.addClass( 'oo-ui-element-hidden' );
8723 if ( this.$errorItems
) {
8724 this.$errorItems
.remove();
8725 this.$errorItems
= null;
8732 OO
.ui
.ProcessDialog
.prototype.getTeardownProcess = function ( data
) {
8734 return OO
.ui
.ProcessDialog
.parent
.prototype.getTeardownProcess
.call( this, data
)
8735 .first( function () {
8736 // Make sure to hide errors
8738 this.fitOnOpen
= false;
8743 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8744 * which is a widget that is specified by reference before any optional configuration settings.
8746 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8748 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8749 * A left-alignment is used for forms with many fields.
8750 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8751 * A right-alignment is used for long but familiar forms which users tab through,
8752 * verifying the current field with a quick glance at the label.
8753 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8754 * that users fill out from top to bottom.
8755 * - **inline**: The label is placed after the field-widget and aligned to the left.
8756 * An inline-alignment is best used with checkboxes or radio buttons.
8758 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
8759 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
8761 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8763 * @extends OO.ui.Layout
8764 * @mixins OO.ui.mixin.LabelElement
8765 * @mixins OO.ui.mixin.TitledElement
8768 * @param {OO.ui.Widget} fieldWidget Field widget
8769 * @param {Object} [config] Configuration options
8770 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8771 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
8772 * The array may contain strings or OO.ui.HtmlSnippet instances.
8773 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
8774 * The array may contain strings or OO.ui.HtmlSnippet instances.
8775 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
8776 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
8777 * For important messages, you are advised to use `notices`, as they are always shown.
8779 * @throws {Error} An error is thrown if no widget is specified
8781 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
8782 var hasInputWidget
, div
, i
;
8784 // Allow passing positional parameters inside the config object
8785 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
8786 config
= fieldWidget
;
8787 fieldWidget
= config
.fieldWidget
;
8790 // Make sure we have required constructor arguments
8791 if ( fieldWidget
=== undefined ) {
8792 throw new Error( 'Widget not found' );
8795 hasInputWidget
= fieldWidget
.constructor.static.supportsSimpleLabel
;
8797 // Configuration initialization
8798 config
= $.extend( { align
: 'left' }, config
);
8800 // Parent constructor
8801 OO
.ui
.FieldLayout
.parent
.call( this, config
);
8803 // Mixin constructors
8804 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8805 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
8808 this.fieldWidget
= fieldWidget
;
8809 this.errors
= config
.errors
|| [];
8810 this.notices
= config
.notices
|| [];
8811 this.$field
= $( '<div>' );
8812 this.$messages
= $( '<ul>' );
8813 this.$body
= $( '<' + ( hasInputWidget
? 'label' : 'div' ) + '>' );
8815 if ( config
.help
) {
8816 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
8817 classes
: [ 'oo-ui-fieldLayout-help' ],
8823 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
8824 div
.html( config
.help
.toString() );
8826 div
.text( config
.help
);
8828 this.popupButtonWidget
.getPopup().$body
.append(
8829 div
.addClass( 'oo-ui-fieldLayout-help-content' )
8831 this.$help
= this.popupButtonWidget
.$element
;
8833 this.$help
= $( [] );
8837 if ( hasInputWidget
) {
8838 this.$label
.on( 'click', this.onLabelClick
.bind( this ) );
8840 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
8844 .addClass( 'oo-ui-fieldLayout' )
8845 .append( this.$help
, this.$body
);
8846 if ( this.errors
.length
|| this.notices
.length
) {
8847 this.$element
.append( this.$messages
);
8849 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
8850 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
8852 .addClass( 'oo-ui-fieldLayout-field' )
8853 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget
.isDisabled() )
8854 .append( this.fieldWidget
.$element
);
8856 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
8857 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
8859 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
8860 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
8863 this.setAlignment( config
.align
);
8868 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
8869 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
8870 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
8875 * Handle field disable events.
8878 * @param {boolean} value Field is disabled
8880 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
8881 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
8885 * Handle label mouse click events.
8888 * @param {jQuery.Event} e Mouse click event
8890 OO
.ui
.FieldLayout
.prototype.onLabelClick = function () {
8891 this.fieldWidget
.simulateLabelClick();
8896 * Get the widget contained by the field.
8898 * @return {OO.ui.Widget} Field widget
8900 OO
.ui
.FieldLayout
.prototype.getField = function () {
8901 return this.fieldWidget
;
8905 * @param {string} kind 'error' or 'notice'
8906 * @param {string|OO.ui.HtmlSnippet} text
8909 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
8910 var $listItem
, $icon
, message
;
8911 $listItem
= $( '<li>' );
8912 if ( kind
=== 'error' ) {
8913 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
8914 } else if ( kind
=== 'notice' ) {
8915 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
8919 message
= new OO
.ui
.LabelWidget( { label
: text
} );
8921 .append( $icon
, message
.$element
)
8922 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
8927 * Set the field alignment mode.
8930 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
8933 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
8934 if ( value
!== this.align
) {
8935 // Default to 'left'
8936 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
8940 if ( value
=== 'inline' ) {
8941 this.$body
.append( this.$field
, this.$label
);
8943 this.$body
.append( this.$label
, this.$field
);
8945 // Set classes. The following classes can be used here:
8946 // * oo-ui-fieldLayout-align-left
8947 // * oo-ui-fieldLayout-align-right
8948 // * oo-ui-fieldLayout-align-top
8949 // * oo-ui-fieldLayout-align-inline
8951 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
8953 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
8961 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
8962 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
8963 * is required and is specified before any optional configuration settings.
8965 * Labels can be aligned in one of four ways:
8967 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8968 * A left-alignment is used for forms with many fields.
8969 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8970 * A right-alignment is used for long but familiar forms which users tab through,
8971 * verifying the current field with a quick glance at the label.
8972 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8973 * that users fill out from top to bottom.
8974 * - **inline**: The label is placed after the field-widget and aligned to the left.
8975 * An inline-alignment is best used with checkboxes or radio buttons.
8977 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
8978 * text is specified.
8981 * // Example of an ActionFieldLayout
8982 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
8983 * new OO.ui.TextInputWidget( {
8984 * placeholder: 'Field widget'
8986 * new OO.ui.ButtonWidget( {
8990 * label: 'An ActionFieldLayout. This label is aligned top',
8992 * help: 'This is help text'
8996 * $( 'body' ).append( actionFieldLayout.$element );
9000 * @extends OO.ui.FieldLayout
9003 * @param {OO.ui.Widget} fieldWidget Field widget
9004 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9006 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
9007 // Allow passing positional parameters inside the config object
9008 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
9009 config
= fieldWidget
;
9010 fieldWidget
= config
.fieldWidget
;
9011 buttonWidget
= config
.buttonWidget
;
9014 // Parent constructor
9015 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
9018 this.buttonWidget
= buttonWidget
;
9019 this.$button
= $( '<div>' );
9020 this.$input
= $( '<div>' );
9024 .addClass( 'oo-ui-actionFieldLayout' );
9026 .addClass( 'oo-ui-actionFieldLayout-button' )
9027 .append( this.buttonWidget
.$element
);
9029 .addClass( 'oo-ui-actionFieldLayout-input' )
9030 .append( this.fieldWidget
.$element
);
9032 .append( this.$input
, this.$button
);
9037 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
9040 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9041 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9042 * configured with a label as well. For more information and examples,
9043 * please see the [OOjs UI documentation on MediaWiki][1].
9046 * // Example of a fieldset layout
9047 * var input1 = new OO.ui.TextInputWidget( {
9048 * placeholder: 'A text input field'
9051 * var input2 = new OO.ui.TextInputWidget( {
9052 * placeholder: 'A text input field'
9055 * var fieldset = new OO.ui.FieldsetLayout( {
9056 * label: 'Example of a fieldset layout'
9059 * fieldset.addItems( [
9060 * new OO.ui.FieldLayout( input1, {
9061 * label: 'Field One'
9063 * new OO.ui.FieldLayout( input2, {
9064 * label: 'Field Two'
9067 * $( 'body' ).append( fieldset.$element );
9069 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9072 * @extends OO.ui.Layout
9073 * @mixins OO.ui.mixin.IconElement
9074 * @mixins OO.ui.mixin.LabelElement
9075 * @mixins OO.ui.mixin.GroupElement
9078 * @param {Object} [config] Configuration options
9079 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9081 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
9082 // Configuration initialization
9083 config
= config
|| {};
9085 // Parent constructor
9086 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
9088 // Mixin constructors
9089 OO
.ui
.mixin
.IconElement
.call( this, config
);
9090 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9091 OO
.ui
.mixin
.GroupElement
.call( this, config
);
9093 if ( config
.help
) {
9094 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
9095 classes
: [ 'oo-ui-fieldsetLayout-help' ],
9100 this.popupButtonWidget
.getPopup().$body
.append(
9102 .text( config
.help
)
9103 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9105 this.$help
= this.popupButtonWidget
.$element
;
9107 this.$help
= $( [] );
9112 .addClass( 'oo-ui-fieldsetLayout' )
9113 .prepend( this.$help
, this.$icon
, this.$label
, this.$group
);
9114 if ( Array
.isArray( config
.items
) ) {
9115 this.addItems( config
.items
);
9121 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
9122 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
9123 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
9124 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
9127 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9128 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9129 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9130 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9132 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9133 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9134 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9135 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9136 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9137 * often have simplified APIs to match the capabilities of HTML forms.
9138 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9140 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9141 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9144 * // Example of a form layout that wraps a fieldset layout
9145 * var input1 = new OO.ui.TextInputWidget( {
9146 * placeholder: 'Username'
9148 * var input2 = new OO.ui.TextInputWidget( {
9149 * placeholder: 'Password',
9152 * var submit = new OO.ui.ButtonInputWidget( {
9156 * var fieldset = new OO.ui.FieldsetLayout( {
9157 * label: 'A form layout'
9159 * fieldset.addItems( [
9160 * new OO.ui.FieldLayout( input1, {
9161 * label: 'Username',
9164 * new OO.ui.FieldLayout( input2, {
9165 * label: 'Password',
9168 * new OO.ui.FieldLayout( submit )
9170 * var form = new OO.ui.FormLayout( {
9171 * items: [ fieldset ],
9172 * action: '/api/formhandler',
9175 * $( 'body' ).append( form.$element );
9178 * @extends OO.ui.Layout
9179 * @mixins OO.ui.mixin.GroupElement
9182 * @param {Object} [config] Configuration options
9183 * @cfg {string} [method] HTML form `method` attribute
9184 * @cfg {string} [action] HTML form `action` attribute
9185 * @cfg {string} [enctype] HTML form `enctype` attribute
9186 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9188 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
9189 // Configuration initialization
9190 config
= config
|| {};
9192 // Parent constructor
9193 OO
.ui
.FormLayout
.parent
.call( this, config
);
9195 // Mixin constructors
9196 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
9199 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
9201 // Make sure the action is safe
9202 if ( config
.action
!== undefined && !OO
.ui
.isSafeUrl( config
.action
) ) {
9203 throw new Error( 'Potentially unsafe action provided: ' + config
.action
);
9208 .addClass( 'oo-ui-formLayout' )
9210 method
: config
.method
,
9211 action
: config
.action
,
9212 enctype
: config
.enctype
9214 if ( Array
.isArray( config
.items
) ) {
9215 this.addItems( config
.items
);
9221 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
9222 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
9227 * A 'submit' event is emitted when the form is submitted.
9232 /* Static Properties */
9234 OO
.ui
.FormLayout
.static.tagName
= 'form';
9239 * Handle form submit events.
9242 * @param {jQuery.Event} e Submit event
9245 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
9246 if ( this.emit( 'submit' ) ) {
9252 * 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)
9253 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9256 * var menuLayout = new OO.ui.MenuLayout( {
9259 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9260 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9261 * select = new OO.ui.SelectWidget( {
9263 * new OO.ui.OptionWidget( {
9267 * new OO.ui.OptionWidget( {
9271 * new OO.ui.OptionWidget( {
9275 * new OO.ui.OptionWidget( {
9280 * } ).on( 'select', function ( item ) {
9281 * menuLayout.setMenuPosition( item.getData() );
9284 * menuLayout.$menu.append(
9285 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9287 * menuLayout.$content.append(
9288 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9290 * $( 'body' ).append( menuLayout.$element );
9292 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9293 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9294 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9297 * .oo-ui-menuLayout-menu {
9301 * .oo-ui-menuLayout-content {
9309 * @extends OO.ui.Layout
9312 * @param {Object} [config] Configuration options
9313 * @cfg {boolean} [showMenu=true] Show menu
9314 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9316 OO
.ui
.MenuLayout
= function OoUiMenuLayout( config
) {
9317 // Configuration initialization
9318 config
= $.extend( {
9320 menuPosition
: 'before'
9323 // Parent constructor
9324 OO
.ui
.MenuLayout
.parent
.call( this, config
);
9329 * @property {jQuery}
9331 this.$menu
= $( '<div>' );
9335 * @property {jQuery}
9337 this.$content
= $( '<div>' );
9341 .addClass( 'oo-ui-menuLayout-menu' );
9342 this.$content
.addClass( 'oo-ui-menuLayout-content' );
9344 .addClass( 'oo-ui-menuLayout' )
9345 .append( this.$content
, this.$menu
);
9346 this.setMenuPosition( config
.menuPosition
);
9347 this.toggleMenu( config
.showMenu
);
9352 OO
.inheritClass( OO
.ui
.MenuLayout
, OO
.ui
.Layout
);
9359 * @param {boolean} showMenu Show menu, omit to toggle
9362 OO
.ui
.MenuLayout
.prototype.toggleMenu = function ( showMenu
) {
9363 showMenu
= showMenu
=== undefined ? !this.showMenu
: !!showMenu
;
9365 if ( this.showMenu
!== showMenu
) {
9366 this.showMenu
= showMenu
;
9368 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu
)
9369 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu
);
9376 * Check if menu is visible
9378 * @return {boolean} Menu is visible
9380 OO
.ui
.MenuLayout
.prototype.isMenuVisible = function () {
9381 return this.showMenu
;
9385 * Set menu position.
9387 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9388 * @throws {Error} If position value is not supported
9391 OO
.ui
.MenuLayout
.prototype.setMenuPosition = function ( position
) {
9392 this.$element
.removeClass( 'oo-ui-menuLayout-' + this.menuPosition
);
9393 this.menuPosition
= position
;
9394 this.$element
.addClass( 'oo-ui-menuLayout-' + position
);
9400 * Get menu position.
9402 * @return {string} Menu position
9404 OO
.ui
.MenuLayout
.prototype.getMenuPosition = function () {
9405 return this.menuPosition
;
9409 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9410 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9411 * through the pages and select which one to display. By default, only one page is
9412 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9413 * the booklet layout automatically focuses on the first focusable element, unless the
9414 * default setting is changed. Optionally, booklets can be configured to show
9415 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9418 * // Example of a BookletLayout that contains two PageLayouts.
9420 * function PageOneLayout( name, config ) {
9421 * PageOneLayout.parent.call( this, name, config );
9422 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9424 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9425 * PageOneLayout.prototype.setupOutlineItem = function () {
9426 * this.outlineItem.setLabel( 'Page One' );
9429 * function PageTwoLayout( name, config ) {
9430 * PageTwoLayout.parent.call( this, name, config );
9431 * this.$element.append( '<p>Second page</p>' );
9433 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9434 * PageTwoLayout.prototype.setupOutlineItem = function () {
9435 * this.outlineItem.setLabel( 'Page Two' );
9438 * var page1 = new PageOneLayout( 'one' ),
9439 * page2 = new PageTwoLayout( 'two' );
9441 * var booklet = new OO.ui.BookletLayout( {
9445 * booklet.addPages ( [ page1, page2 ] );
9446 * $( 'body' ).append( booklet.$element );
9449 * @extends OO.ui.MenuLayout
9452 * @param {Object} [config] Configuration options
9453 * @cfg {boolean} [continuous=false] Show all pages, one after another
9454 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9455 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9456 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9458 OO
.ui
.BookletLayout
= function OoUiBookletLayout( config
) {
9459 // Configuration initialization
9460 config
= config
|| {};
9462 // Parent constructor
9463 OO
.ui
.BookletLayout
.parent
.call( this, config
);
9466 this.currentPageName
= null;
9468 this.ignoreFocus
= false;
9469 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
9470 this.$content
.append( this.stackLayout
.$element
);
9471 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
9472 this.outlineVisible
= false;
9473 this.outlined
= !!config
.outlined
;
9474 if ( this.outlined
) {
9475 this.editable
= !!config
.editable
;
9476 this.outlineControlsWidget
= null;
9477 this.outlineSelectWidget
= new OO
.ui
.OutlineSelectWidget();
9478 this.outlinePanel
= new OO
.ui
.PanelLayout( { scrollable
: true } );
9479 this.$menu
.append( this.outlinePanel
.$element
);
9480 this.outlineVisible
= true;
9481 if ( this.editable
) {
9482 this.outlineControlsWidget
= new OO
.ui
.OutlineControlsWidget(
9483 this.outlineSelectWidget
9487 this.toggleMenu( this.outlined
);
9490 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
9491 if ( this.outlined
) {
9492 this.outlineSelectWidget
.connect( this, { select
: 'onOutlineSelectWidgetSelect' } );
9494 if ( this.autoFocus
) {
9495 // Event 'focus' does not bubble, but 'focusin' does
9496 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
9500 this.$element
.addClass( 'oo-ui-bookletLayout' );
9501 this.stackLayout
.$element
.addClass( 'oo-ui-bookletLayout-stackLayout' );
9502 if ( this.outlined
) {
9503 this.outlinePanel
.$element
9504 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
9505 .append( this.outlineSelectWidget
.$element
);
9506 if ( this.editable
) {
9507 this.outlinePanel
.$element
9508 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
9509 .append( this.outlineControlsWidget
.$element
);
9516 OO
.inheritClass( OO
.ui
.BookletLayout
, OO
.ui
.MenuLayout
);
9521 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
9523 * @param {OO.ui.PageLayout} page Current page
9527 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
9530 * @param {OO.ui.PageLayout[]} page Added pages
9531 * @param {number} index Index pages were added at
9535 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
9536 * {@link #removePages removed} from the booklet.
9539 * @param {OO.ui.PageLayout[]} pages Removed pages
9545 * Handle stack layout focus.
9548 * @param {jQuery.Event} e Focusin event
9550 OO
.ui
.BookletLayout
.prototype.onStackLayoutFocus = function ( e
) {
9553 // Find the page that an element was focused within
9554 $target
= $( e
.target
).closest( '.oo-ui-pageLayout' );
9555 for ( name
in this.pages
) {
9556 // Check for page match, exclude current page to find only page changes
9557 if ( this.pages
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentPageName
) {
9558 this.setPage( name
);
9565 * Handle stack layout set events.
9568 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
9570 OO
.ui
.BookletLayout
.prototype.onStackLayoutSet = function ( page
) {
9573 page
.scrollElementIntoView( { complete: function () {
9574 if ( layout
.autoFocus
) {
9582 * Focus the first input in the current page.
9584 * If no page is selected, the first selectable page will be selected.
9585 * If the focus is already in an element on the current page, nothing will happen.
9586 * @param {number} [itemIndex] A specific item to focus on
9588 OO
.ui
.BookletLayout
.prototype.focus = function ( itemIndex
) {
9590 items
= this.stackLayout
.getItems();
9592 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
9593 page
= items
[ itemIndex
];
9595 page
= this.stackLayout
.getCurrentItem();
9598 if ( !page
&& this.outlined
) {
9599 this.selectFirstSelectablePage();
9600 page
= this.stackLayout
.getCurrentItem();
9605 // Only change the focus if is not already in the current page
9606 if ( !page
.$element
.find( ':focus' ).length
) {
9607 $input
= page
.$element
.find( ':input:first' );
9608 if ( $input
.length
) {
9609 $input
[ 0 ].focus();
9615 * Find the first focusable input in the booklet layout and focus
9618 OO
.ui
.BookletLayout
.prototype.focusFirstFocusable = function () {
9621 items
= this.stackLayout
.getItems(),
9622 checkAndFocus = function () {
9623 if ( OO
.ui
.isFocusableElement( $( this ) ) ) {
9630 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
9634 // Find all potentially focusable elements in the item
9635 // and check if they are focusable
9637 .find( 'input, select, textarea, button, object' )
9638 /* jshint loopfunc:true */
9639 .each( checkAndFocus
);
9644 * Handle outline widget select events.
9647 * @param {OO.ui.OptionWidget|null} item Selected item
9649 OO
.ui
.BookletLayout
.prototype.onOutlineSelectWidgetSelect = function ( item
) {
9651 this.setPage( item
.getData() );
9656 * Check if booklet has an outline.
9658 * @return {boolean} Booklet has an outline
9660 OO
.ui
.BookletLayout
.prototype.isOutlined = function () {
9661 return this.outlined
;
9665 * Check if booklet has editing controls.
9667 * @return {boolean} Booklet is editable
9669 OO
.ui
.BookletLayout
.prototype.isEditable = function () {
9670 return this.editable
;
9674 * Check if booklet has a visible outline.
9676 * @return {boolean} Outline is visible
9678 OO
.ui
.BookletLayout
.prototype.isOutlineVisible = function () {
9679 return this.outlined
&& this.outlineVisible
;
9683 * Hide or show the outline.
9685 * @param {boolean} [show] Show outline, omit to invert current state
9688 OO
.ui
.BookletLayout
.prototype.toggleOutline = function ( show
) {
9689 if ( this.outlined
) {
9690 show
= show
=== undefined ? !this.outlineVisible
: !!show
;
9691 this.outlineVisible
= show
;
9692 this.toggleMenu( show
);
9699 * Get the page closest to the specified page.
9701 * @param {OO.ui.PageLayout} page Page to use as a reference point
9702 * @return {OO.ui.PageLayout|null} Page closest to the specified page
9704 OO
.ui
.BookletLayout
.prototype.getClosestPage = function ( page
) {
9705 var next
, prev
, level
,
9706 pages
= this.stackLayout
.getItems(),
9707 index
= pages
.indexOf( page
);
9709 if ( index
!== -1 ) {
9710 next
= pages
[ index
+ 1 ];
9711 prev
= pages
[ index
- 1 ];
9712 // Prefer adjacent pages at the same level
9713 if ( this.outlined
) {
9714 level
= this.outlineSelectWidget
.getItemFromData( page
.getName() ).getLevel();
9717 level
=== this.outlineSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
9723 level
=== this.outlineSelectWidget
.getItemFromData( next
.getName() ).getLevel()
9729 return prev
|| next
|| null;
9733 * Get the outline widget.
9735 * If the booklet is not outlined, the method will return `null`.
9737 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
9739 OO
.ui
.BookletLayout
.prototype.getOutline = function () {
9740 return this.outlineSelectWidget
;
9744 * Get the outline controls widget.
9746 * If the outline is not editable, the method will return `null`.
9748 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
9750 OO
.ui
.BookletLayout
.prototype.getOutlineControls = function () {
9751 return this.outlineControlsWidget
;
9755 * Get a page by its symbolic name.
9757 * @param {string} name Symbolic name of page
9758 * @return {OO.ui.PageLayout|undefined} Page, if found
9760 OO
.ui
.BookletLayout
.prototype.getPage = function ( name
) {
9761 return this.pages
[ name
];
9765 * Get the current page.
9767 * @return {OO.ui.PageLayout|undefined} Current page, if found
9769 OO
.ui
.BookletLayout
.prototype.getCurrentPage = function () {
9770 var name
= this.getCurrentPageName();
9771 return name
? this.getPage( name
) : undefined;
9775 * Get the symbolic name of the current page.
9777 * @return {string|null} Symbolic name of the current page
9779 OO
.ui
.BookletLayout
.prototype.getCurrentPageName = function () {
9780 return this.currentPageName
;
9784 * Add pages to the booklet layout
9786 * When pages are added with the same names as existing pages, the existing pages will be
9787 * automatically removed before the new pages are added.
9789 * @param {OO.ui.PageLayout[]} pages Pages to add
9790 * @param {number} index Index of the insertion point
9794 OO
.ui
.BookletLayout
.prototype.addPages = function ( pages
, index
) {
9795 var i
, len
, name
, page
, item
, currentIndex
,
9796 stackLayoutPages
= this.stackLayout
.getItems(),
9800 // Remove pages with same names
9801 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9803 name
= page
.getName();
9805 if ( Object
.prototype.hasOwnProperty
.call( this.pages
, name
) ) {
9806 // Correct the insertion index
9807 currentIndex
= stackLayoutPages
.indexOf( this.pages
[ name
] );
9808 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
9811 remove
.push( this.pages
[ name
] );
9814 if ( remove
.length
) {
9815 this.removePages( remove
);
9819 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9821 name
= page
.getName();
9822 this.pages
[ page
.getName() ] = page
;
9823 if ( this.outlined
) {
9824 item
= new OO
.ui
.OutlineOptionWidget( { data
: name
} );
9825 page
.setOutlineItem( item
);
9830 if ( this.outlined
&& items
.length
) {
9831 this.outlineSelectWidget
.addItems( items
, index
);
9832 this.selectFirstSelectablePage();
9834 this.stackLayout
.addItems( pages
, index
);
9835 this.emit( 'add', pages
, index
);
9841 * Remove the specified pages from the booklet layout.
9843 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
9845 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
9849 OO
.ui
.BookletLayout
.prototype.removePages = function ( pages
) {
9850 var i
, len
, name
, page
,
9853 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9855 name
= page
.getName();
9856 delete this.pages
[ name
];
9857 if ( this.outlined
) {
9858 items
.push( this.outlineSelectWidget
.getItemFromData( name
) );
9859 page
.setOutlineItem( null );
9862 if ( this.outlined
&& items
.length
) {
9863 this.outlineSelectWidget
.removeItems( items
);
9864 this.selectFirstSelectablePage();
9866 this.stackLayout
.removeItems( pages
);
9867 this.emit( 'remove', pages
);
9873 * Clear all pages from the booklet layout.
9875 * To remove only a subset of pages from the booklet, use the #removePages method.
9880 OO
.ui
.BookletLayout
.prototype.clearPages = function () {
9882 pages
= this.stackLayout
.getItems();
9885 this.currentPageName
= null;
9886 if ( this.outlined
) {
9887 this.outlineSelectWidget
.clearItems();
9888 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9889 pages
[ i
].setOutlineItem( null );
9892 this.stackLayout
.clearItems();
9894 this.emit( 'remove', pages
);
9900 * Set the current page by symbolic name.
9903 * @param {string} name Symbolic name of page
9905 OO
.ui
.BookletLayout
.prototype.setPage = function ( name
) {
9908 page
= this.pages
[ name
];
9910 if ( name
!== this.currentPageName
) {
9911 if ( this.outlined
) {
9912 selectedItem
= this.outlineSelectWidget
.getSelectedItem();
9913 if ( selectedItem
&& selectedItem
.getData() !== name
) {
9914 this.outlineSelectWidget
.selectItemByData( name
);
9918 if ( this.currentPageName
&& this.pages
[ this.currentPageName
] ) {
9919 this.pages
[ this.currentPageName
].setActive( false );
9920 // Blur anything focused if the next page doesn't have anything focusable - this
9921 // is not needed if the next page has something focusable because once it is focused
9922 // this blur happens automatically
9923 if ( this.autoFocus
&& !page
.$element
.find( ':input' ).length
) {
9924 $focused
= this.pages
[ this.currentPageName
].$element
.find( ':focus' );
9925 if ( $focused
.length
) {
9926 $focused
[ 0 ].blur();
9930 this.currentPageName
= name
;
9931 this.stackLayout
.setItem( page
);
9932 page
.setActive( true );
9933 this.emit( 'set', page
);
9939 * Select the first selectable page.
9943 OO
.ui
.BookletLayout
.prototype.selectFirstSelectablePage = function () {
9944 if ( !this.outlineSelectWidget
.getSelectedItem() ) {
9945 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getFirstSelectableItem() );
9952 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
9953 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
9954 * select which one to display. By default, only one card is displayed at a time. When a user
9955 * navigates to a new card, the index layout automatically focuses on the first focusable element,
9956 * unless the default setting is changed.
9958 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
9961 * // Example of a IndexLayout that contains two CardLayouts.
9963 * function CardOneLayout( name, config ) {
9964 * CardOneLayout.parent.call( this, name, config );
9965 * this.$element.append( '<p>First card</p>' );
9967 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
9968 * CardOneLayout.prototype.setupTabItem = function () {
9969 * this.tabItem.setLabel( 'Card One' );
9972 * function CardTwoLayout( name, config ) {
9973 * CardTwoLayout.parent.call( this, name, config );
9974 * this.$element.append( '<p>Second card</p>' );
9976 * OO.inheritClass( CardTwoLayout, OO.ui.CardLayout );
9977 * CardTwoLayout.prototype.setupTabItem = function () {
9978 * this.tabItem.setLabel( 'Card Two' );
9981 * var card1 = new CardOneLayout( 'one' ),
9982 * card2 = new CardTwoLayout( 'two' );
9984 * var index = new OO.ui.IndexLayout();
9986 * index.addCards ( [ card1, card2 ] );
9987 * $( 'body' ).append( index.$element );
9990 * @extends OO.ui.MenuLayout
9993 * @param {Object} [config] Configuration options
9994 * @cfg {boolean} [continuous=false] Show all cards, one after another
9995 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
9997 OO
.ui
.IndexLayout
= function OoUiIndexLayout( config
) {
9998 // Configuration initialization
9999 config
= $.extend( {}, config
, { menuPosition
: 'top' } );
10001 // Parent constructor
10002 OO
.ui
.IndexLayout
.parent
.call( this, config
);
10005 this.currentCardName
= null;
10007 this.ignoreFocus
= false;
10008 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
10009 this.$content
.append( this.stackLayout
.$element
);
10010 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
10012 this.tabSelectWidget
= new OO
.ui
.TabSelectWidget();
10013 this.tabPanel
= new OO
.ui
.PanelLayout();
10014 this.$menu
.append( this.tabPanel
.$element
);
10016 this.toggleMenu( true );
10019 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
10020 this.tabSelectWidget
.connect( this, { select
: 'onTabSelectWidgetSelect' } );
10021 if ( this.autoFocus
) {
10022 // Event 'focus' does not bubble, but 'focusin' does
10023 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
10027 this.$element
.addClass( 'oo-ui-indexLayout' );
10028 this.stackLayout
.$element
.addClass( 'oo-ui-indexLayout-stackLayout' );
10029 this.tabPanel
.$element
10030 .addClass( 'oo-ui-indexLayout-tabPanel' )
10031 .append( this.tabSelectWidget
.$element
);
10036 OO
.inheritClass( OO
.ui
.IndexLayout
, OO
.ui
.MenuLayout
);
10041 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
10043 * @param {OO.ui.CardLayout} card Current card
10047 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
10050 * @param {OO.ui.CardLayout[]} card Added cards
10051 * @param {number} index Index cards were added at
10055 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
10056 * {@link #removeCards removed} from the index.
10059 * @param {OO.ui.CardLayout[]} cards Removed cards
10065 * Handle stack layout focus.
10068 * @param {jQuery.Event} e Focusin event
10070 OO
.ui
.IndexLayout
.prototype.onStackLayoutFocus = function ( e
) {
10073 // Find the card that an element was focused within
10074 $target
= $( e
.target
).closest( '.oo-ui-cardLayout' );
10075 for ( name
in this.cards
) {
10076 // Check for card match, exclude current card to find only card changes
10077 if ( this.cards
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentCardName
) {
10078 this.setCard( name
);
10085 * Handle stack layout set events.
10088 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
10090 OO
.ui
.IndexLayout
.prototype.onStackLayoutSet = function ( card
) {
10093 card
.scrollElementIntoView( { complete: function () {
10094 if ( layout
.autoFocus
) {
10102 * Focus the first input in the current card.
10104 * If no card is selected, the first selectable card will be selected.
10105 * If the focus is already in an element on the current card, nothing will happen.
10106 * @param {number} [itemIndex] A specific item to focus on
10108 OO
.ui
.IndexLayout
.prototype.focus = function ( itemIndex
) {
10110 items
= this.stackLayout
.getItems();
10112 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
10113 card
= items
[ itemIndex
];
10115 card
= this.stackLayout
.getCurrentItem();
10119 this.selectFirstSelectableCard();
10120 card
= this.stackLayout
.getCurrentItem();
10125 // Only change the focus if is not already in the current card
10126 if ( !card
.$element
.find( ':focus' ).length
) {
10127 $input
= card
.$element
.find( ':input:first' );
10128 if ( $input
.length
) {
10129 $input
[ 0 ].focus();
10135 * Find the first focusable input in the index layout and focus
10138 OO
.ui
.IndexLayout
.prototype.focusFirstFocusable = function () {
10141 items
= this.stackLayout
.getItems(),
10142 checkAndFocus = function () {
10143 if ( OO
.ui
.isFocusableElement( $( this ) ) ) {
10150 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
10154 // Find all potentially focusable elements in the item
10155 // and check if they are focusable
10156 items
[ i
].$element
10157 .find( 'input, select, textarea, button, object' )
10158 .each( checkAndFocus
);
10163 * Handle tab widget select events.
10166 * @param {OO.ui.OptionWidget|null} item Selected item
10168 OO
.ui
.IndexLayout
.prototype.onTabSelectWidgetSelect = function ( item
) {
10170 this.setCard( item
.getData() );
10175 * Get the card closest to the specified card.
10177 * @param {OO.ui.CardLayout} card Card to use as a reference point
10178 * @return {OO.ui.CardLayout|null} Card closest to the specified card
10180 OO
.ui
.IndexLayout
.prototype.getClosestCard = function ( card
) {
10181 var next
, prev
, level
,
10182 cards
= this.stackLayout
.getItems(),
10183 index
= cards
.indexOf( card
);
10185 if ( index
!== -1 ) {
10186 next
= cards
[ index
+ 1 ];
10187 prev
= cards
[ index
- 1 ];
10188 // Prefer adjacent cards at the same level
10189 level
= this.tabSelectWidget
.getItemFromData( card
.getName() ).getLevel();
10192 level
=== this.tabSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
10198 level
=== this.tabSelectWidget
.getItemFromData( next
.getName() ).getLevel()
10203 return prev
|| next
|| null;
10207 * Get the tabs widget.
10209 * @return {OO.ui.TabSelectWidget} Tabs widget
10211 OO
.ui
.IndexLayout
.prototype.getTabs = function () {
10212 return this.tabSelectWidget
;
10216 * Get a card by its symbolic name.
10218 * @param {string} name Symbolic name of card
10219 * @return {OO.ui.CardLayout|undefined} Card, if found
10221 OO
.ui
.IndexLayout
.prototype.getCard = function ( name
) {
10222 return this.cards
[ name
];
10226 * Get the current card.
10228 * @return {OO.ui.CardLayout|undefined} Current card, if found
10230 OO
.ui
.IndexLayout
.prototype.getCurrentCard = function () {
10231 var name
= this.getCurrentCardName();
10232 return name
? this.getCard( name
) : undefined;
10236 * Get the symbolic name of the current card.
10238 * @return {string|null} Symbolic name of the current card
10240 OO
.ui
.IndexLayout
.prototype.getCurrentCardName = function () {
10241 return this.currentCardName
;
10245 * Add cards to the index layout
10247 * When cards are added with the same names as existing cards, the existing cards will be
10248 * automatically removed before the new cards are added.
10250 * @param {OO.ui.CardLayout[]} cards Cards to add
10251 * @param {number} index Index of the insertion point
10255 OO
.ui
.IndexLayout
.prototype.addCards = function ( cards
, index
) {
10256 var i
, len
, name
, card
, item
, currentIndex
,
10257 stackLayoutCards
= this.stackLayout
.getItems(),
10261 // Remove cards with same names
10262 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10264 name
= card
.getName();
10266 if ( Object
.prototype.hasOwnProperty
.call( this.cards
, name
) ) {
10267 // Correct the insertion index
10268 currentIndex
= stackLayoutCards
.indexOf( this.cards
[ name
] );
10269 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
10272 remove
.push( this.cards
[ name
] );
10275 if ( remove
.length
) {
10276 this.removeCards( remove
);
10280 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10282 name
= card
.getName();
10283 this.cards
[ card
.getName() ] = card
;
10284 item
= new OO
.ui
.TabOptionWidget( { data
: name
} );
10285 card
.setTabItem( item
);
10286 items
.push( item
);
10289 if ( items
.length
) {
10290 this.tabSelectWidget
.addItems( items
, index
);
10291 this.selectFirstSelectableCard();
10293 this.stackLayout
.addItems( cards
, index
);
10294 this.emit( 'add', cards
, index
);
10300 * Remove the specified cards from the index layout.
10302 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10304 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10308 OO
.ui
.IndexLayout
.prototype.removeCards = function ( cards
) {
10309 var i
, len
, name
, card
,
10312 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10314 name
= card
.getName();
10315 delete this.cards
[ name
];
10316 items
.push( this.tabSelectWidget
.getItemFromData( name
) );
10317 card
.setTabItem( null );
10319 if ( items
.length
) {
10320 this.tabSelectWidget
.removeItems( items
);
10321 this.selectFirstSelectableCard();
10323 this.stackLayout
.removeItems( cards
);
10324 this.emit( 'remove', cards
);
10330 * Clear all cards from the index layout.
10332 * To remove only a subset of cards from the index, use the #removeCards method.
10337 OO
.ui
.IndexLayout
.prototype.clearCards = function () {
10339 cards
= this.stackLayout
.getItems();
10342 this.currentCardName
= null;
10343 this.tabSelectWidget
.clearItems();
10344 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10345 cards
[ i
].setTabItem( null );
10347 this.stackLayout
.clearItems();
10349 this.emit( 'remove', cards
);
10355 * Set the current card by symbolic name.
10358 * @param {string} name Symbolic name of card
10360 OO
.ui
.IndexLayout
.prototype.setCard = function ( name
) {
10363 card
= this.cards
[ name
];
10365 if ( name
!== this.currentCardName
) {
10366 selectedItem
= this.tabSelectWidget
.getSelectedItem();
10367 if ( selectedItem
&& selectedItem
.getData() !== name
) {
10368 this.tabSelectWidget
.selectItemByData( name
);
10371 if ( this.currentCardName
&& this.cards
[ this.currentCardName
] ) {
10372 this.cards
[ this.currentCardName
].setActive( false );
10373 // Blur anything focused if the next card doesn't have anything focusable - this
10374 // is not needed if the next card has something focusable because once it is focused
10375 // this blur happens automatically
10376 if ( this.autoFocus
&& !card
.$element
.find( ':input' ).length
) {
10377 $focused
= this.cards
[ this.currentCardName
].$element
.find( ':focus' );
10378 if ( $focused
.length
) {
10379 $focused
[ 0 ].blur();
10383 this.currentCardName
= name
;
10384 this.stackLayout
.setItem( card
);
10385 card
.setActive( true );
10386 this.emit( 'set', card
);
10392 * Select the first selectable card.
10396 OO
.ui
.IndexLayout
.prototype.selectFirstSelectableCard = function () {
10397 if ( !this.tabSelectWidget
.getSelectedItem() ) {
10398 this.tabSelectWidget
.selectItem( this.tabSelectWidget
.getFirstSelectableItem() );
10405 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10406 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10409 * // Example of a panel layout
10410 * var panel = new OO.ui.PanelLayout( {
10414 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10416 * $( 'body' ).append( panel.$element );
10419 * @extends OO.ui.Layout
10422 * @param {Object} [config] Configuration options
10423 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10424 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10425 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10426 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10428 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
10429 // Configuration initialization
10430 config
= $.extend( {
10437 // Parent constructor
10438 OO
.ui
.PanelLayout
.parent
.call( this, config
);
10441 this.$element
.addClass( 'oo-ui-panelLayout' );
10442 if ( config
.scrollable
) {
10443 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
10445 if ( config
.padded
) {
10446 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
10448 if ( config
.expanded
) {
10449 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
10451 if ( config
.framed
) {
10452 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
10458 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
10461 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10462 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10463 * rather extended to include the required content and functionality.
10465 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10466 * item is customized (with a label) using the #setupTabItem method. See
10467 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10470 * @extends OO.ui.PanelLayout
10473 * @param {string} name Unique symbolic name of card
10474 * @param {Object} [config] Configuration options
10476 OO
.ui
.CardLayout
= function OoUiCardLayout( name
, config
) {
10477 // Allow passing positional parameters inside the config object
10478 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
10480 name
= config
.name
;
10483 // Configuration initialization
10484 config
= $.extend( { scrollable
: true }, config
);
10486 // Parent constructor
10487 OO
.ui
.CardLayout
.parent
.call( this, config
);
10491 this.tabItem
= null;
10492 this.active
= false;
10495 this.$element
.addClass( 'oo-ui-cardLayout' );
10500 OO
.inheritClass( OO
.ui
.CardLayout
, OO
.ui
.PanelLayout
);
10505 * An 'active' event is emitted when the card becomes active. Cards become active when they are
10506 * shown in a index layout that is configured to display only one card at a time.
10509 * @param {boolean} active Card is active
10515 * Get the symbolic name of the card.
10517 * @return {string} Symbolic name of card
10519 OO
.ui
.CardLayout
.prototype.getName = function () {
10524 * Check if card is active.
10526 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
10527 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
10529 * @return {boolean} Card is active
10531 OO
.ui
.CardLayout
.prototype.isActive = function () {
10532 return this.active
;
10538 * The tab item allows users to access the card from the index's tab
10539 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
10541 * @return {OO.ui.TabOptionWidget|null} Tab option widget
10543 OO
.ui
.CardLayout
.prototype.getTabItem = function () {
10544 return this.tabItem
;
10548 * Set or unset the tab item.
10550 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
10551 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
10552 * level), use #setupTabItem instead of this method.
10554 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
10557 OO
.ui
.CardLayout
.prototype.setTabItem = function ( tabItem
) {
10558 this.tabItem
= tabItem
|| null;
10560 this.setupTabItem();
10566 * Set up the tab item.
10568 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
10569 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
10570 * the #setTabItem method instead.
10572 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
10575 OO
.ui
.CardLayout
.prototype.setupTabItem = function () {
10580 * Set the card to its 'active' state.
10582 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
10583 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
10584 * context, setting the active state on a card does nothing.
10586 * @param {boolean} value Card is active
10589 OO
.ui
.CardLayout
.prototype.setActive = function ( active
) {
10592 if ( active
!== this.active
) {
10593 this.active
= active
;
10594 this.$element
.toggleClass( 'oo-ui-cardLayout-active', this.active
);
10595 this.emit( 'active', this.active
);
10600 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
10601 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
10602 * rather extended to include the required content and functionality.
10604 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
10605 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
10606 * {@link OO.ui.BookletLayout BookletLayout} for an example.
10609 * @extends OO.ui.PanelLayout
10612 * @param {string} name Unique symbolic name of page
10613 * @param {Object} [config] Configuration options
10615 OO
.ui
.PageLayout
= function OoUiPageLayout( name
, config
) {
10616 // Allow passing positional parameters inside the config object
10617 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
10619 name
= config
.name
;
10622 // Configuration initialization
10623 config
= $.extend( { scrollable
: true }, config
);
10625 // Parent constructor
10626 OO
.ui
.PageLayout
.parent
.call( this, config
);
10630 this.outlineItem
= null;
10631 this.active
= false;
10634 this.$element
.addClass( 'oo-ui-pageLayout' );
10639 OO
.inheritClass( OO
.ui
.PageLayout
, OO
.ui
.PanelLayout
);
10644 * An 'active' event is emitted when the page becomes active. Pages become active when they are
10645 * shown in a booklet layout that is configured to display only one page at a time.
10648 * @param {boolean} active Page is active
10654 * Get the symbolic name of the page.
10656 * @return {string} Symbolic name of page
10658 OO
.ui
.PageLayout
.prototype.getName = function () {
10663 * Check if page is active.
10665 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
10666 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
10668 * @return {boolean} Page is active
10670 OO
.ui
.PageLayout
.prototype.isActive = function () {
10671 return this.active
;
10675 * Get outline item.
10677 * The outline item allows users to access the page from the booklet's outline
10678 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
10680 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
10682 OO
.ui
.PageLayout
.prototype.getOutlineItem = function () {
10683 return this.outlineItem
;
10687 * Set or unset the outline item.
10689 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
10690 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
10691 * level), use #setupOutlineItem instead of this method.
10693 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
10696 OO
.ui
.PageLayout
.prototype.setOutlineItem = function ( outlineItem
) {
10697 this.outlineItem
= outlineItem
|| null;
10698 if ( outlineItem
) {
10699 this.setupOutlineItem();
10705 * Set up the outline item.
10707 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
10708 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
10709 * the #setOutlineItem method instead.
10711 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
10714 OO
.ui
.PageLayout
.prototype.setupOutlineItem = function () {
10719 * Set the page to its 'active' state.
10721 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
10722 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
10723 * context, setting the active state on a page does nothing.
10725 * @param {boolean} value Page is active
10728 OO
.ui
.PageLayout
.prototype.setActive = function ( active
) {
10731 if ( active
!== this.active
) {
10732 this.active
= active
;
10733 this.$element
.toggleClass( 'oo-ui-pageLayout-active', active
);
10734 this.emit( 'active', this.active
);
10739 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
10740 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
10741 * by setting the #continuous option to 'true'.
10744 * // A stack layout with two panels, configured to be displayed continously
10745 * var myStack = new OO.ui.StackLayout( {
10747 * new OO.ui.PanelLayout( {
10748 * $content: $( '<p>Panel One</p>' ),
10752 * new OO.ui.PanelLayout( {
10753 * $content: $( '<p>Panel Two</p>' ),
10760 * $( 'body' ).append( myStack.$element );
10763 * @extends OO.ui.PanelLayout
10764 * @mixins OO.ui.mixin.GroupElement
10767 * @param {Object} [config] Configuration options
10768 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
10769 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
10771 OO
.ui
.StackLayout
= function OoUiStackLayout( config
) {
10772 // Configuration initialization
10773 config
= $.extend( { scrollable
: true }, config
);
10775 // Parent constructor
10776 OO
.ui
.StackLayout
.parent
.call( this, config
);
10778 // Mixin constructors
10779 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
10782 this.currentItem
= null;
10783 this.continuous
= !!config
.continuous
;
10786 this.$element
.addClass( 'oo-ui-stackLayout' );
10787 if ( this.continuous
) {
10788 this.$element
.addClass( 'oo-ui-stackLayout-continuous' );
10790 if ( Array
.isArray( config
.items
) ) {
10791 this.addItems( config
.items
);
10797 OO
.inheritClass( OO
.ui
.StackLayout
, OO
.ui
.PanelLayout
);
10798 OO
.mixinClass( OO
.ui
.StackLayout
, OO
.ui
.mixin
.GroupElement
);
10803 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
10804 * {@link #clearItems cleared} or {@link #setItem displayed}.
10807 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
10813 * Get the current panel.
10815 * @return {OO.ui.Layout|null}
10817 OO
.ui
.StackLayout
.prototype.getCurrentItem = function () {
10818 return this.currentItem
;
10822 * Unset the current item.
10825 * @param {OO.ui.StackLayout} layout
10828 OO
.ui
.StackLayout
.prototype.unsetCurrentItem = function () {
10829 var prevItem
= this.currentItem
;
10830 if ( prevItem
=== null ) {
10834 this.currentItem
= null;
10835 this.emit( 'set', null );
10839 * Add panel layouts to the stack layout.
10841 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
10842 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
10845 * @param {OO.ui.Layout[]} items Panels to add
10846 * @param {number} [index] Index of the insertion point
10849 OO
.ui
.StackLayout
.prototype.addItems = function ( items
, index
) {
10850 // Update the visibility
10851 this.updateHiddenState( items
, this.currentItem
);
10854 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
, index
);
10856 if ( !this.currentItem
&& items
.length
) {
10857 this.setItem( items
[ 0 ] );
10864 * Remove the specified panels from the stack layout.
10866 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
10867 * you may wish to use the #clearItems method instead.
10869 * @param {OO.ui.Layout[]} items Panels to remove
10873 OO
.ui
.StackLayout
.prototype.removeItems = function ( items
) {
10875 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
10877 if ( items
.indexOf( this.currentItem
) !== -1 ) {
10878 if ( this.items
.length
) {
10879 this.setItem( this.items
[ 0 ] );
10881 this.unsetCurrentItem();
10889 * Clear all panels from the stack layout.
10891 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
10892 * a subset of panels, use the #removeItems method.
10897 OO
.ui
.StackLayout
.prototype.clearItems = function () {
10898 this.unsetCurrentItem();
10899 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
10905 * Show the specified panel.
10907 * If another panel is currently displayed, it will be hidden.
10909 * @param {OO.ui.Layout} item Panel to show
10913 OO
.ui
.StackLayout
.prototype.setItem = function ( item
) {
10914 if ( item
!== this.currentItem
) {
10915 this.updateHiddenState( this.items
, item
);
10917 if ( this.items
.indexOf( item
) !== -1 ) {
10918 this.currentItem
= item
;
10919 this.emit( 'set', item
);
10921 this.unsetCurrentItem();
10929 * Update the visibility of all items in case of non-continuous view.
10931 * Ensure all items are hidden except for the selected one.
10932 * This method does nothing when the stack is continuous.
10935 * @param {OO.ui.Layout[]} items Item list iterate over
10936 * @param {OO.ui.Layout} [selectedItem] Selected item to show
10938 OO
.ui
.StackLayout
.prototype.updateHiddenState = function ( items
, selectedItem
) {
10941 if ( !this.continuous
) {
10942 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
10943 if ( !selectedItem
|| selectedItem
!== items
[ i
] ) {
10944 items
[ i
].$element
.addClass( 'oo-ui-element-hidden' );
10947 if ( selectedItem
) {
10948 selectedItem
.$element
.removeClass( 'oo-ui-element-hidden' );
10954 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
10955 * items), with small margins between them. Convenient when you need to put a number of block-level
10956 * widgets on a single line next to each other.
10958 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
10961 * // HorizontalLayout with a text input and a label
10962 * var layout = new OO.ui.HorizontalLayout( {
10964 * new OO.ui.LabelWidget( { label: 'Label' } ),
10965 * new OO.ui.TextInputWidget( { value: 'Text' } )
10968 * $( 'body' ).append( layout.$element );
10971 * @extends OO.ui.Layout
10972 * @mixins OO.ui.mixin.GroupElement
10975 * @param {Object} [config] Configuration options
10976 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
10978 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
10979 // Configuration initialization
10980 config
= config
|| {};
10982 // Parent constructor
10983 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
10985 // Mixin constructors
10986 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
10989 this.$element
.addClass( 'oo-ui-horizontalLayout' );
10990 if ( Array
.isArray( config
.items
) ) {
10991 this.addItems( config
.items
);
10997 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
10998 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);
11001 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11002 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11003 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
11004 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
11007 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
11011 * // Example of a BarToolGroup with two tools
11012 * var toolFactory = new OO.ui.ToolFactory();
11013 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11014 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11016 * // We will be placing status text in this element when tools are used
11017 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
11019 * // Define the tools that we're going to place in our toolbar
11021 * // Create a class inheriting from OO.ui.Tool
11022 * function PictureTool() {
11023 * PictureTool.parent.apply( this, arguments );
11025 * OO.inheritClass( PictureTool, OO.ui.Tool );
11026 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
11027 * // of 'icon' and 'title' (displayed icon and text).
11028 * PictureTool.static.name = 'picture';
11029 * PictureTool.static.icon = 'picture';
11030 * PictureTool.static.title = 'Insert picture';
11031 * // Defines the action that will happen when this tool is selected (clicked).
11032 * PictureTool.prototype.onSelect = function () {
11033 * $area.text( 'Picture tool clicked!' );
11034 * // Never display this tool as "active" (selected).
11035 * this.setActive( false );
11037 * // Make this tool available in our toolFactory and thus our toolbar
11038 * toolFactory.register( PictureTool );
11040 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
11041 * // little popup window (a PopupWidget).
11042 * function HelpTool( toolGroup, config ) {
11043 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11048 * this.popup.$body.append( '<p>I am helpful!</p>' );
11050 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11051 * HelpTool.static.name = 'help';
11052 * HelpTool.static.icon = 'help';
11053 * HelpTool.static.title = 'Help';
11054 * toolFactory.register( HelpTool );
11056 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11057 * // used once (but not all defined tools must be used).
11060 * // 'bar' tool groups display tools by icon only
11062 * include: [ 'picture', 'help' ]
11066 * // Create some UI around the toolbar and place it in the document
11067 * var frame = new OO.ui.PanelLayout( {
11071 * var contentFrame = new OO.ui.PanelLayout( {
11075 * frame.$element.append(
11076 * toolbar.$element,
11077 * contentFrame.$element.append( $area )
11079 * $( 'body' ).append( frame.$element );
11081 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11083 * toolbar.initialize();
11085 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
11086 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11088 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11091 * @extends OO.ui.ToolGroup
11094 * @param {OO.ui.Toolbar} toolbar
11095 * @param {Object} [config] Configuration options
11097 OO
.ui
.BarToolGroup
= function OoUiBarToolGroup( toolbar
, config
) {
11098 // Allow passing positional parameters inside the config object
11099 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11101 toolbar
= config
.toolbar
;
11104 // Parent constructor
11105 OO
.ui
.BarToolGroup
.parent
.call( this, toolbar
, config
);
11108 this.$element
.addClass( 'oo-ui-barToolGroup' );
11113 OO
.inheritClass( OO
.ui
.BarToolGroup
, OO
.ui
.ToolGroup
);
11115 /* Static Properties */
11117 OO
.ui
.BarToolGroup
.static.titleTooltips
= true;
11119 OO
.ui
.BarToolGroup
.static.accelTooltips
= true;
11121 OO
.ui
.BarToolGroup
.static.name
= 'bar';
11124 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
11125 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
11126 * optional icon and label. This class can be used for other base classes that also use this functionality.
11130 * @extends OO.ui.ToolGroup
11131 * @mixins OO.ui.mixin.IconElement
11132 * @mixins OO.ui.mixin.IndicatorElement
11133 * @mixins OO.ui.mixin.LabelElement
11134 * @mixins OO.ui.mixin.TitledElement
11135 * @mixins OO.ui.mixin.ClippableElement
11136 * @mixins OO.ui.mixin.TabIndexedElement
11139 * @param {OO.ui.Toolbar} toolbar
11140 * @param {Object} [config] Configuration options
11141 * @cfg {string} [header] Text to display at the top of the popup
11143 OO
.ui
.PopupToolGroup
= function OoUiPopupToolGroup( toolbar
, config
) {
11144 // Allow passing positional parameters inside the config object
11145 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11147 toolbar
= config
.toolbar
;
11150 // Configuration initialization
11151 config
= config
|| {};
11153 // Parent constructor
11154 OO
.ui
.PopupToolGroup
.parent
.call( this, toolbar
, config
);
11157 this.active
= false;
11158 this.dragging
= false;
11159 this.onBlurHandler
= this.onBlur
.bind( this );
11160 this.$handle
= $( '<span>' );
11162 // Mixin constructors
11163 OO
.ui
.mixin
.IconElement
.call( this, config
);
11164 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
11165 OO
.ui
.mixin
.LabelElement
.call( this, config
);
11166 OO
.ui
.mixin
.TitledElement
.call( this, config
);
11167 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
11168 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
11172 keydown
: this.onHandleMouseKeyDown
.bind( this ),
11173 keyup
: this.onHandleMouseKeyUp
.bind( this ),
11174 mousedown
: this.onHandleMouseKeyDown
.bind( this ),
11175 mouseup
: this.onHandleMouseKeyUp
.bind( this )
11180 .addClass( 'oo-ui-popupToolGroup-handle' )
11181 .append( this.$icon
, this.$label
, this.$indicator
);
11182 // If the pop-up should have a header, add it to the top of the toolGroup.
11183 // Note: If this feature is useful for other widgets, we could abstract it into an
11184 // OO.ui.HeaderedElement mixin constructor.
11185 if ( config
.header
!== undefined ) {
11187 .prepend( $( '<span>' )
11188 .addClass( 'oo-ui-popupToolGroup-header' )
11189 .text( config
.header
)
11193 .addClass( 'oo-ui-popupToolGroup' )
11194 .prepend( this.$handle
);
11199 OO
.inheritClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ToolGroup
);
11200 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.IconElement
);
11201 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.IndicatorElement
);
11202 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.LabelElement
);
11203 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.TitledElement
);
11204 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.ClippableElement
);
11205 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.TabIndexedElement
);
11212 OO
.ui
.PopupToolGroup
.prototype.setDisabled = function () {
11214 OO
.ui
.PopupToolGroup
.parent
.prototype.setDisabled
.apply( this, arguments
);
11216 if ( this.isDisabled() && this.isElementAttached() ) {
11217 this.setActive( false );
11222 * Handle focus being lost.
11224 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11227 * @param {jQuery.Event} e Mouse up or key up event
11229 OO
.ui
.PopupToolGroup
.prototype.onBlur = function ( e
) {
11230 // Only deactivate when clicking outside the dropdown element
11231 if ( $( e
.target
).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element
[ 0 ] ) {
11232 this.setActive( false );
11239 OO
.ui
.PopupToolGroup
.prototype.onMouseKeyUp = function ( e
) {
11240 // Only close toolgroup when a tool was actually selected
11242 !this.isDisabled() && this.pressed
&& this.pressed
=== this.getTargetTool( e
) &&
11243 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11245 this.setActive( false );
11247 return OO
.ui
.PopupToolGroup
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11251 * Handle mouse up and key up events.
11254 * @param {jQuery.Event} e Mouse up or key up event
11256 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyUp = function ( e
) {
11258 !this.isDisabled() &&
11259 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11266 * Handle mouse down and key down events.
11269 * @param {jQuery.Event} e Mouse down or key down event
11271 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyDown = function ( e
) {
11273 !this.isDisabled() &&
11274 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11276 this.setActive( !this.active
);
11282 * Switch into 'active' mode.
11284 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11287 OO
.ui
.PopupToolGroup
.prototype.setActive = function ( value
) {
11288 var containerWidth
, containerLeft
;
11290 if ( this.active
!== value
) {
11291 this.active
= value
;
11293 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler
);
11294 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler
);
11296 this.$clippable
.css( 'left', '' );
11297 // Try anchoring the popup to the left first
11298 this.$element
.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11299 this.toggleClipping( true );
11300 if ( this.isClippedHorizontally() ) {
11301 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11302 this.toggleClipping( false );
11304 .removeClass( 'oo-ui-popupToolGroup-left' )
11305 .addClass( 'oo-ui-popupToolGroup-right' );
11306 this.toggleClipping( true );
11308 if ( this.isClippedHorizontally() ) {
11309 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11310 containerWidth
= this.$clippableContainer
.width();
11311 containerLeft
= this.$clippableContainer
.offset().left
;
11313 this.toggleClipping( false );
11314 this.$element
.removeClass( 'oo-ui-popupToolGroup-right' );
11316 this.$clippable
.css( {
11317 left
: -( this.$element
.offset().left
- containerLeft
),
11318 width
: containerWidth
11322 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler
);
11323 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler
);
11324 this.$element
.removeClass(
11325 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11327 this.toggleClipping( false );
11333 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11334 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11335 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11336 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11337 * with a label, icon, indicator, header, and title.
11339 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11340 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11341 * users to collapse the list again.
11343 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11344 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11345 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11348 * // Example of a ListToolGroup
11349 * var toolFactory = new OO.ui.ToolFactory();
11350 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11351 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11353 * // Configure and register two tools
11354 * function SettingsTool() {
11355 * SettingsTool.parent.apply( this, arguments );
11357 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11358 * SettingsTool.static.name = 'settings';
11359 * SettingsTool.static.icon = 'settings';
11360 * SettingsTool.static.title = 'Change settings';
11361 * SettingsTool.prototype.onSelect = function () {
11362 * this.setActive( false );
11364 * toolFactory.register( SettingsTool );
11365 * // Register two more tools, nothing interesting here
11366 * function StuffTool() {
11367 * StuffTool.parent.apply( this, arguments );
11369 * OO.inheritClass( StuffTool, OO.ui.Tool );
11370 * StuffTool.static.name = 'stuff';
11371 * StuffTool.static.icon = 'ellipsis';
11372 * StuffTool.static.title = 'Change the world';
11373 * StuffTool.prototype.onSelect = function () {
11374 * this.setActive( false );
11376 * toolFactory.register( StuffTool );
11379 * // Configurations for list toolgroup.
11381 * label: 'ListToolGroup',
11382 * indicator: 'down',
11384 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11385 * header: 'This is the header',
11386 * include: [ 'settings', 'stuff' ],
11387 * allowCollapse: ['stuff']
11391 * // Create some UI around the toolbar and place it in the document
11392 * var frame = new OO.ui.PanelLayout( {
11396 * frame.$element.append(
11399 * $( 'body' ).append( frame.$element );
11400 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11401 * toolbar.initialize();
11403 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11405 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11408 * @extends OO.ui.PopupToolGroup
11411 * @param {OO.ui.Toolbar} toolbar
11412 * @param {Object} [config] Configuration options
11413 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11414 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11415 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11416 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11417 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11418 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11419 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11420 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11421 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11422 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
11424 OO
.ui
.ListToolGroup
= function OoUiListToolGroup( toolbar
, config
) {
11425 // Allow passing positional parameters inside the config object
11426 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11428 toolbar
= config
.toolbar
;
11431 // Configuration initialization
11432 config
= config
|| {};
11434 // Properties (must be set before parent constructor, which calls #populate)
11435 this.allowCollapse
= config
.allowCollapse
;
11436 this.forceExpand
= config
.forceExpand
;
11437 this.expanded
= config
.expanded
!== undefined ? config
.expanded
: false;
11438 this.collapsibleTools
= [];
11440 // Parent constructor
11441 OO
.ui
.ListToolGroup
.parent
.call( this, toolbar
, config
);
11444 this.$element
.addClass( 'oo-ui-listToolGroup' );
11449 OO
.inheritClass( OO
.ui
.ListToolGroup
, OO
.ui
.PopupToolGroup
);
11451 /* Static Properties */
11453 OO
.ui
.ListToolGroup
.static.name
= 'list';
11460 OO
.ui
.ListToolGroup
.prototype.populate = function () {
11461 var i
, len
, allowCollapse
= [];
11463 OO
.ui
.ListToolGroup
.parent
.prototype.populate
.call( this );
11465 // Update the list of collapsible tools
11466 if ( this.allowCollapse
!== undefined ) {
11467 allowCollapse
= this.allowCollapse
;
11468 } else if ( this.forceExpand
!== undefined ) {
11469 allowCollapse
= OO
.simpleArrayDifference( Object
.keys( this.tools
), this.forceExpand
);
11472 this.collapsibleTools
= [];
11473 for ( i
= 0, len
= allowCollapse
.length
; i
< len
; i
++ ) {
11474 if ( this.tools
[ allowCollapse
[ i
] ] !== undefined ) {
11475 this.collapsibleTools
.push( this.tools
[ allowCollapse
[ i
] ] );
11479 // Keep at the end, even when tools are added
11480 this.$group
.append( this.getExpandCollapseTool().$element
);
11482 this.getExpandCollapseTool().toggle( this.collapsibleTools
.length
!== 0 );
11483 this.updateCollapsibleState();
11486 OO
.ui
.ListToolGroup
.prototype.getExpandCollapseTool = function () {
11487 var ExpandCollapseTool
;
11488 if ( this.expandCollapseTool
=== undefined ) {
11489 ExpandCollapseTool = function () {
11490 ExpandCollapseTool
.parent
.apply( this, arguments
);
11493 OO
.inheritClass( ExpandCollapseTool
, OO
.ui
.Tool
);
11495 ExpandCollapseTool
.prototype.onSelect = function () {
11496 this.toolGroup
.expanded
= !this.toolGroup
.expanded
;
11497 this.toolGroup
.updateCollapsibleState();
11498 this.setActive( false );
11500 ExpandCollapseTool
.prototype.onUpdateState = function () {
11501 // Do nothing. Tool interface requires an implementation of this function.
11504 ExpandCollapseTool
.static.name
= 'more-fewer';
11506 this.expandCollapseTool
= new ExpandCollapseTool( this );
11508 return this.expandCollapseTool
;
11514 OO
.ui
.ListToolGroup
.prototype.onMouseKeyUp = function ( e
) {
11515 // Do not close the popup when the user wants to show more/fewer tools
11517 $( e
.target
).closest( '.oo-ui-tool-name-more-fewer' ).length
&&
11518 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11520 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
11521 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
11522 return OO
.ui
.ListToolGroup
.parent
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11524 return OO
.ui
.ListToolGroup
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11528 OO
.ui
.ListToolGroup
.prototype.updateCollapsibleState = function () {
11531 this.getExpandCollapseTool()
11532 .setIcon( this.expanded
? 'collapse' : 'expand' )
11533 .setTitle( OO
.ui
.msg( this.expanded
? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
11535 for ( i
= 0, len
= this.collapsibleTools
.length
; i
< len
; i
++ ) {
11536 this.collapsibleTools
[ i
].toggle( this.expanded
);
11541 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11542 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
11543 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
11544 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
11545 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
11546 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
11548 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
11549 * is set up. Note that all tools must define an {@link OO.ui.Tool#onUpdateState onUpdateState} method if
11550 * a MenuToolGroup is used.
11553 * // Example of a MenuToolGroup
11554 * var toolFactory = new OO.ui.ToolFactory();
11555 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11556 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11558 * // We will be placing status text in this element when tools are used
11559 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
11561 * // Define the tools that we're going to place in our toolbar
11563 * function SettingsTool() {
11564 * SettingsTool.parent.apply( this, arguments );
11565 * this.reallyActive = false;
11567 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11568 * SettingsTool.static.name = 'settings';
11569 * SettingsTool.static.icon = 'settings';
11570 * SettingsTool.static.title = 'Change settings';
11571 * SettingsTool.prototype.onSelect = function () {
11572 * $area.text( 'Settings tool clicked!' );
11573 * // Toggle the active state on each click
11574 * this.reallyActive = !this.reallyActive;
11575 * this.setActive( this.reallyActive );
11576 * // To update the menu label
11577 * this.toolbar.emit( 'updateState' );
11579 * SettingsTool.prototype.onUpdateState = function () {
11581 * toolFactory.register( SettingsTool );
11583 * function StuffTool() {
11584 * StuffTool.parent.apply( this, arguments );
11585 * this.reallyActive = false;
11587 * OO.inheritClass( StuffTool, OO.ui.Tool );
11588 * StuffTool.static.name = 'stuff';
11589 * StuffTool.static.icon = 'ellipsis';
11590 * StuffTool.static.title = 'More stuff';
11591 * StuffTool.prototype.onSelect = function () {
11592 * $area.text( 'More stuff tool clicked!' );
11593 * // Toggle the active state on each click
11594 * this.reallyActive = !this.reallyActive;
11595 * this.setActive( this.reallyActive );
11596 * // To update the menu label
11597 * this.toolbar.emit( 'updateState' );
11599 * StuffTool.prototype.onUpdateState = function () {
11601 * toolFactory.register( StuffTool );
11603 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11604 * // used once (but not all defined tools must be used).
11608 * header: 'This is the (optional) header',
11609 * title: 'This is the (optional) title',
11610 * indicator: 'down',
11611 * include: [ 'settings', 'stuff' ]
11615 * // Create some UI around the toolbar and place it in the document
11616 * var frame = new OO.ui.PanelLayout( {
11620 * var contentFrame = new OO.ui.PanelLayout( {
11624 * frame.$element.append(
11625 * toolbar.$element,
11626 * contentFrame.$element.append( $area )
11628 * $( 'body' ).append( frame.$element );
11630 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11632 * toolbar.initialize();
11633 * toolbar.emit( 'updateState' );
11635 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11636 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
11638 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11641 * @extends OO.ui.PopupToolGroup
11644 * @param {OO.ui.Toolbar} toolbar
11645 * @param {Object} [config] Configuration options
11647 OO
.ui
.MenuToolGroup
= function OoUiMenuToolGroup( toolbar
, config
) {
11648 // Allow passing positional parameters inside the config object
11649 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11651 toolbar
= config
.toolbar
;
11654 // Configuration initialization
11655 config
= config
|| {};
11657 // Parent constructor
11658 OO
.ui
.MenuToolGroup
.parent
.call( this, toolbar
, config
);
11661 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
11664 this.$element
.addClass( 'oo-ui-menuToolGroup' );
11669 OO
.inheritClass( OO
.ui
.MenuToolGroup
, OO
.ui
.PopupToolGroup
);
11671 /* Static Properties */
11673 OO
.ui
.MenuToolGroup
.static.name
= 'menu';
11678 * Handle the toolbar state being updated.
11680 * When the state changes, the title of each active item in the menu will be joined together and
11681 * used as a label for the group. The label will be empty if none of the items are active.
11685 OO
.ui
.MenuToolGroup
.prototype.onUpdateState = function () {
11689 for ( name
in this.tools
) {
11690 if ( this.tools
[ name
].isActive() ) {
11691 labelTexts
.push( this.tools
[ name
].getTitle() );
11695 this.setLabel( labelTexts
.join( ', ' ) || ' ' );
11699 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
11700 * 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
11701 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
11703 * // Example of a popup tool. When selected, a popup tool displays
11704 * // a popup window.
11705 * function HelpTool( toolGroup, config ) {
11706 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11711 * this.popup.$body.append( '<p>I am helpful!</p>' );
11713 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11714 * HelpTool.static.name = 'help';
11715 * HelpTool.static.icon = 'help';
11716 * HelpTool.static.title = 'Help';
11717 * toolFactory.register( HelpTool );
11719 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
11720 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
11722 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11726 * @extends OO.ui.Tool
11727 * @mixins OO.ui.mixin.PopupElement
11730 * @param {OO.ui.ToolGroup} toolGroup
11731 * @param {Object} [config] Configuration options
11733 OO
.ui
.PopupTool
= function OoUiPopupTool( toolGroup
, config
) {
11734 // Allow passing positional parameters inside the config object
11735 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
11736 config
= toolGroup
;
11737 toolGroup
= config
.toolGroup
;
11740 // Parent constructor
11741 OO
.ui
.PopupTool
.parent
.call( this, toolGroup
, config
);
11743 // Mixin constructors
11744 OO
.ui
.mixin
.PopupElement
.call( this, config
);
11748 .addClass( 'oo-ui-popupTool' )
11749 .append( this.popup
.$element
);
11754 OO
.inheritClass( OO
.ui
.PopupTool
, OO
.ui
.Tool
);
11755 OO
.mixinClass( OO
.ui
.PopupTool
, OO
.ui
.mixin
.PopupElement
);
11760 * Handle the tool being selected.
11764 OO
.ui
.PopupTool
.prototype.onSelect = function () {
11765 if ( !this.isDisabled() ) {
11766 this.popup
.toggle();
11768 this.setActive( false );
11773 * Handle the toolbar state being updated.
11777 OO
.ui
.PopupTool
.prototype.onUpdateState = function () {
11778 this.setActive( false );
11782 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
11783 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
11784 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
11785 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
11786 * when the ToolGroupTool is selected.
11788 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
11790 * function SettingsTool() {
11791 * SettingsTool.parent.apply( this, arguments );
11793 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
11794 * SettingsTool.static.name = 'settings';
11795 * SettingsTool.static.title = 'Change settings';
11796 * SettingsTool.static.groupConfig = {
11797 * icon: 'settings',
11798 * label: 'ToolGroupTool',
11799 * include: [ 'setting1', 'setting2' ]
11801 * toolFactory.register( SettingsTool );
11803 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
11805 * Please note that this implementation is subject to change per [T74159] [2].
11807 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
11808 * [2]: https://phabricator.wikimedia.org/T74159
11812 * @extends OO.ui.Tool
11815 * @param {OO.ui.ToolGroup} toolGroup
11816 * @param {Object} [config] Configuration options
11818 OO
.ui
.ToolGroupTool
= function OoUiToolGroupTool( toolGroup
, config
) {
11819 // Allow passing positional parameters inside the config object
11820 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
11821 config
= toolGroup
;
11822 toolGroup
= config
.toolGroup
;
11825 // Parent constructor
11826 OO
.ui
.ToolGroupTool
.parent
.call( this, toolGroup
, config
);
11829 this.innerToolGroup
= this.createGroup( this.constructor.static.groupConfig
);
11832 this.innerToolGroup
.connect( this, { disable
: 'onToolGroupDisable' } );
11835 this.$link
.remove();
11837 .addClass( 'oo-ui-toolGroupTool' )
11838 .append( this.innerToolGroup
.$element
);
11843 OO
.inheritClass( OO
.ui
.ToolGroupTool
, OO
.ui
.Tool
);
11845 /* Static Properties */
11848 * Toolgroup configuration.
11850 * The toolgroup configuration consists of the tools to include, as well as an icon and label
11851 * to use for the bar item. Tools can be included by symbolic name, group, or with the
11852 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
11854 * @property {Object.<string,Array>}
11856 OO
.ui
.ToolGroupTool
.static.groupConfig
= {};
11861 * Handle the tool being selected.
11865 OO
.ui
.ToolGroupTool
.prototype.onSelect = function () {
11866 this.innerToolGroup
.setActive( !this.innerToolGroup
.active
);
11871 * Synchronize disabledness state of the tool with the inner toolgroup.
11874 * @param {boolean} disabled Element is disabled
11876 OO
.ui
.ToolGroupTool
.prototype.onToolGroupDisable = function ( disabled
) {
11877 this.setDisabled( disabled
);
11881 * Handle the toolbar state being updated.
11885 OO
.ui
.ToolGroupTool
.prototype.onUpdateState = function () {
11886 this.setActive( false );
11890 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
11892 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
11893 * more information.
11894 * @return {OO.ui.ListToolGroup}
11896 OO
.ui
.ToolGroupTool
.prototype.createGroup = function ( group
) {
11897 if ( group
.include
=== '*' ) {
11898 // Apply defaults to catch-all groups
11899 if ( group
.label
=== undefined ) {
11900 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
11904 return this.toolbar
.getToolGroupFactory().create( 'list', this.toolbar
, group
);
11908 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
11910 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
11915 * @extends OO.ui.mixin.GroupElement
11918 * @param {Object} [config] Configuration options
11920 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
11921 // Parent constructor
11922 OO
.ui
.mixin
.GroupWidget
.parent
.call( this, config
);
11927 OO
.inheritClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
11932 * Set the disabled state of the widget.
11934 * This will also update the disabled state of child widgets.
11936 * @param {boolean} disabled Disable widget
11939 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
11943 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
11944 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
11946 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
11947 if ( this.items
) {
11948 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
11949 this.items
[ i
].updateDisabled();
11957 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
11959 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
11960 * allows bidirectional communication.
11962 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
11970 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
11977 * Check if widget is disabled.
11979 * Checks parent if present, making disabled state inheritable.
11981 * @return {boolean} Widget is disabled
11983 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
11984 return this.disabled
||
11985 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
11989 * Set group element is in.
11991 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
11994 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
11996 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
11997 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
11999 // Initialize item disabled states
12000 this.updateDisabled();
12006 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
12007 * Controls include moving items up and down, removing items, and adding different kinds of items.
12009 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
12012 * @extends OO.ui.Widget
12013 * @mixins OO.ui.mixin.GroupElement
12014 * @mixins OO.ui.mixin.IconElement
12017 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
12018 * @param {Object} [config] Configuration options
12019 * @cfg {Object} [abilities] List of abilties
12020 * @cfg {boolean} [abilities.move=true] Allow moving movable items
12021 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
12023 OO
.ui
.OutlineControlsWidget
= function OoUiOutlineControlsWidget( outline
, config
) {
12024 // Allow passing positional parameters inside the config object
12025 if ( OO
.isPlainObject( outline
) && config
=== undefined ) {
12027 outline
= config
.outline
;
12030 // Configuration initialization
12031 config
= $.extend( { icon
: 'add' }, config
);
12033 // Parent constructor
12034 OO
.ui
.OutlineControlsWidget
.parent
.call( this, config
);
12036 // Mixin constructors
12037 OO
.ui
.mixin
.GroupElement
.call( this, config
);
12038 OO
.ui
.mixin
.IconElement
.call( this, config
);
12041 this.outline
= outline
;
12042 this.$movers
= $( '<div>' );
12043 this.upButton
= new OO
.ui
.ButtonWidget( {
12046 title
: OO
.ui
.msg( 'ooui-outline-control-move-up' )
12048 this.downButton
= new OO
.ui
.ButtonWidget( {
12051 title
: OO
.ui
.msg( 'ooui-outline-control-move-down' )
12053 this.removeButton
= new OO
.ui
.ButtonWidget( {
12056 title
: OO
.ui
.msg( 'ooui-outline-control-remove' )
12058 this.abilities
= { move: true, remove
: true };
12061 outline
.connect( this, {
12062 select
: 'onOutlineChange',
12063 add
: 'onOutlineChange',
12064 remove
: 'onOutlineChange'
12066 this.upButton
.connect( this, { click
: [ 'emit', 'move', -1 ] } );
12067 this.downButton
.connect( this, { click
: [ 'emit', 'move', 1 ] } );
12068 this.removeButton
.connect( this, { click
: [ 'emit', 'remove' ] } );
12071 this.$element
.addClass( 'oo-ui-outlineControlsWidget' );
12072 this.$group
.addClass( 'oo-ui-outlineControlsWidget-items' );
12074 .addClass( 'oo-ui-outlineControlsWidget-movers' )
12075 .append( this.removeButton
.$element
, this.upButton
.$element
, this.downButton
.$element
);
12076 this.$element
.append( this.$icon
, this.$group
, this.$movers
);
12077 this.setAbilities( config
.abilities
|| {} );
12082 OO
.inheritClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.Widget
);
12083 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.GroupElement
);
12084 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.IconElement
);
12090 * @param {number} places Number of places to move
12102 * @param {Object} abilities List of abilties
12103 * @param {boolean} [abilities.move] Allow moving movable items
12104 * @param {boolean} [abilities.remove] Allow removing removable items
12106 OO
.ui
.OutlineControlsWidget
.prototype.setAbilities = function ( abilities
) {
12109 for ( ability
in this.abilities
) {
12110 if ( abilities
[ ability
] !== undefined ) {
12111 this.abilities
[ ability
] = !!abilities
[ ability
];
12115 this.onOutlineChange();
12121 * Handle outline change events.
12123 OO
.ui
.OutlineControlsWidget
.prototype.onOutlineChange = function () {
12124 var i
, len
, firstMovable
, lastMovable
,
12125 items
= this.outline
.getItems(),
12126 selectedItem
= this.outline
.getSelectedItem(),
12127 movable
= this.abilities
.move && selectedItem
&& selectedItem
.isMovable(),
12128 removable
= this.abilities
.remove
&& selectedItem
&& selectedItem
.isRemovable();
12132 len
= items
.length
;
12133 while ( ++i
< len
) {
12134 if ( items
[ i
].isMovable() ) {
12135 firstMovable
= items
[ i
];
12141 if ( items
[ i
].isMovable() ) {
12142 lastMovable
= items
[ i
];
12147 this.upButton
.setDisabled( !movable
|| selectedItem
=== firstMovable
);
12148 this.downButton
.setDisabled( !movable
|| selectedItem
=== lastMovable
);
12149 this.removeButton
.setDisabled( !removable
);
12153 * ToggleWidget implements basic behavior of widgets with an on/off state.
12154 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
12158 * @extends OO.ui.Widget
12161 * @param {Object} [config] Configuration options
12162 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
12163 * By default, the toggle is in the 'off' state.
12165 OO
.ui
.ToggleWidget
= function OoUiToggleWidget( config
) {
12166 // Configuration initialization
12167 config
= config
|| {};
12169 // Parent constructor
12170 OO
.ui
.ToggleWidget
.parent
.call( this, config
);
12176 this.$element
.addClass( 'oo-ui-toggleWidget' );
12177 this.setValue( !!config
.value
);
12182 OO
.inheritClass( OO
.ui
.ToggleWidget
, OO
.ui
.Widget
);
12189 * A change event is emitted when the on/off state of the toggle changes.
12191 * @param {boolean} value Value representing the new state of the toggle
12197 * Get the value representing the toggle’s state.
12199 * @return {boolean} The on/off state of the toggle
12201 OO
.ui
.ToggleWidget
.prototype.getValue = function () {
12206 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
12208 * @param {boolean} value The state of the toggle
12212 OO
.ui
.ToggleWidget
.prototype.setValue = function ( value
) {
12214 if ( this.value
!== value
) {
12215 this.value
= value
;
12216 this.emit( 'change', value
);
12217 this.$element
.toggleClass( 'oo-ui-toggleWidget-on', value
);
12218 this.$element
.toggleClass( 'oo-ui-toggleWidget-off', !value
);
12219 this.$element
.attr( 'aria-checked', value
.toString() );
12225 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12226 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12227 * removed, and cleared from the group.
12230 * // Example: A ButtonGroupWidget with two buttons
12231 * var button1 = new OO.ui.PopupButtonWidget( {
12232 * label: 'Select a category',
12235 * $content: $( '<p>List of categories...</p>' ),
12240 * var button2 = new OO.ui.ButtonWidget( {
12241 * label: 'Add item'
12243 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12244 * items: [button1, button2]
12246 * $( 'body' ).append( buttonGroup.$element );
12249 * @extends OO.ui.Widget
12250 * @mixins OO.ui.mixin.GroupElement
12253 * @param {Object} [config] Configuration options
12254 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12256 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
12257 // Configuration initialization
12258 config
= config
|| {};
12260 // Parent constructor
12261 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
12263 // Mixin constructors
12264 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
12267 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
12268 if ( Array
.isArray( config
.items
) ) {
12269 this.addItems( config
.items
);
12275 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
12276 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
12279 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12280 * feels, and functionality can be customized via the class’s configuration options
12281 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12284 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12287 * // A button widget
12288 * var button = new OO.ui.ButtonWidget( {
12289 * label: 'Button with Icon',
12291 * iconTitle: 'Remove'
12293 * $( 'body' ).append( button.$element );
12295 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12298 * @extends OO.ui.Widget
12299 * @mixins OO.ui.mixin.ButtonElement
12300 * @mixins OO.ui.mixin.IconElement
12301 * @mixins OO.ui.mixin.IndicatorElement
12302 * @mixins OO.ui.mixin.LabelElement
12303 * @mixins OO.ui.mixin.TitledElement
12304 * @mixins OO.ui.mixin.FlaggedElement
12305 * @mixins OO.ui.mixin.TabIndexedElement
12306 * @mixins OO.ui.mixin.AccessKeyedElement
12309 * @param {Object} [config] Configuration options
12310 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12311 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12312 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12314 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
12315 // Configuration initialization
12316 config
= config
|| {};
12318 // Parent constructor
12319 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
12321 // Mixin constructors
12322 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
12323 OO
.ui
.mixin
.IconElement
.call( this, config
);
12324 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12325 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12326 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
12327 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
12328 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
12329 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
12333 this.target
= null;
12334 this.noFollow
= false;
12337 this.connect( this, { disable
: 'onDisable' } );
12340 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
12342 .addClass( 'oo-ui-buttonWidget' )
12343 .append( this.$button
);
12344 this.setHref( config
.href
);
12345 this.setTarget( config
.target
);
12346 this.setNoFollow( config
.noFollow
);
12351 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
12352 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
12353 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
12354 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
12355 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
12356 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
12357 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
12358 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
12359 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
12366 OO
.ui
.ButtonWidget
.prototype.onMouseDown = function ( e
) {
12367 if ( !this.isDisabled() ) {
12368 // Remove the tab-index while the button is down to prevent the button from stealing focus
12369 this.$button
.removeAttr( 'tabindex' );
12372 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown
.call( this, e
);
12378 OO
.ui
.ButtonWidget
.prototype.onMouseUp = function ( e
) {
12379 if ( !this.isDisabled() ) {
12380 // Restore the tab-index after the button is up to restore the button's accessibility
12381 this.$button
.attr( 'tabindex', this.tabIndex
);
12384 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp
.call( this, e
);
12388 * Get hyperlink location.
12390 * @return {string} Hyperlink location
12392 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
12397 * Get hyperlink target.
12399 * @return {string} Hyperlink target
12401 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
12402 return this.target
;
12406 * Get search engine traversal hint.
12408 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12410 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
12411 return this.noFollow
;
12415 * Set hyperlink location.
12417 * @param {string|null} href Hyperlink location, null to remove
12419 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
12420 href
= typeof href
=== 'string' ? href
: null;
12421 if ( href
!== null ) {
12422 if ( !OO
.ui
.isSafeUrl( href
) ) {
12423 throw new Error( 'Potentially unsafe href provided: ' + href
);
12428 if ( href
!== this.href
) {
12437 * Update the `href` attribute, in case of changes to href or
12443 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
12444 if ( this.href
!== null && !this.isDisabled() ) {
12445 this.$button
.attr( 'href', this.href
);
12447 this.$button
.removeAttr( 'href' );
12454 * Handle disable events.
12457 * @param {boolean} disabled Element is disabled
12459 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
12464 * Set hyperlink target.
12466 * @param {string|null} target Hyperlink target, null to remove
12468 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
12469 target
= typeof target
=== 'string' ? target
: null;
12471 if ( target
!== this.target
) {
12472 this.target
= target
;
12473 if ( target
!== null ) {
12474 this.$button
.attr( 'target', target
);
12476 this.$button
.removeAttr( 'target' );
12484 * Set search engine traversal hint.
12486 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
12488 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
12489 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
12491 if ( noFollow
!== this.noFollow
) {
12492 this.noFollow
= noFollow
;
12494 this.$button
.attr( 'rel', 'nofollow' );
12496 this.$button
.removeAttr( 'rel' );
12504 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
12505 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
12508 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
12509 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12512 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
12515 * @extends OO.ui.ButtonWidget
12516 * @mixins OO.ui.mixin.PendingElement
12519 * @param {Object} [config] Configuration options
12520 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12521 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
12522 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
12523 * for more information about setting modes.
12524 * @cfg {boolean} [framed=false] Render the action button with a frame
12526 OO
.ui
.ActionWidget
= function OoUiActionWidget( config
) {
12527 // Configuration initialization
12528 config
= $.extend( { framed
: false }, config
);
12530 // Parent constructor
12531 OO
.ui
.ActionWidget
.parent
.call( this, config
);
12533 // Mixin constructors
12534 OO
.ui
.mixin
.PendingElement
.call( this, config
);
12537 this.action
= config
.action
|| '';
12538 this.modes
= config
.modes
|| [];
12543 this.$element
.addClass( 'oo-ui-actionWidget' );
12548 OO
.inheritClass( OO
.ui
.ActionWidget
, OO
.ui
.ButtonWidget
);
12549 OO
.mixinClass( OO
.ui
.ActionWidget
, OO
.ui
.mixin
.PendingElement
);
12554 * A resize event is emitted when the size of the widget changes.
12562 * Check if the action is configured to be available in the specified `mode`.
12564 * @param {string} mode Name of mode
12565 * @return {boolean} The action is configured with the mode
12567 OO
.ui
.ActionWidget
.prototype.hasMode = function ( mode
) {
12568 return this.modes
.indexOf( mode
) !== -1;
12572 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12576 OO
.ui
.ActionWidget
.prototype.getAction = function () {
12577 return this.action
;
12581 * Get the symbolic name of the mode or modes for which the action is configured to be available.
12583 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
12584 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
12587 * @return {string[]}
12589 OO
.ui
.ActionWidget
.prototype.getModes = function () {
12590 return this.modes
.slice();
12594 * Emit a resize event if the size has changed.
12599 OO
.ui
.ActionWidget
.prototype.propagateResize = function () {
12602 if ( this.isElementAttached() ) {
12603 width
= this.$element
.width();
12604 height
= this.$element
.height();
12606 if ( width
!== this.width
|| height
!== this.height
) {
12607 this.width
= width
;
12608 this.height
= height
;
12609 this.emit( 'resize' );
12619 OO
.ui
.ActionWidget
.prototype.setIcon = function () {
12621 OO
.ui
.mixin
.IconElement
.prototype.setIcon
.apply( this, arguments
);
12622 this.propagateResize();
12630 OO
.ui
.ActionWidget
.prototype.setLabel = function () {
12632 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.apply( this, arguments
);
12633 this.propagateResize();
12641 OO
.ui
.ActionWidget
.prototype.setFlags = function () {
12643 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags
.apply( this, arguments
);
12644 this.propagateResize();
12652 OO
.ui
.ActionWidget
.prototype.clearFlags = function () {
12654 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags
.apply( this, arguments
);
12655 this.propagateResize();
12661 * Toggle the visibility of the action button.
12663 * @param {boolean} [show] Show button, omit to toggle visibility
12666 OO
.ui
.ActionWidget
.prototype.toggle = function () {
12668 OO
.ui
.ActionWidget
.parent
.prototype.toggle
.apply( this, arguments
);
12669 this.propagateResize();
12675 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
12676 * which is used to display additional information or options.
12679 * // Example of a popup button.
12680 * var popupButton = new OO.ui.PopupButtonWidget( {
12681 * label: 'Popup button with options',
12684 * $content: $( '<p>Additional options here.</p>' ),
12686 * align: 'force-left'
12689 * // Append the button to the DOM.
12690 * $( 'body' ).append( popupButton.$element );
12693 * @extends OO.ui.ButtonWidget
12694 * @mixins OO.ui.mixin.PopupElement
12697 * @param {Object} [config] Configuration options
12699 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
12700 // Parent constructor
12701 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
12703 // Mixin constructors
12704 OO
.ui
.mixin
.PopupElement
.call( this, config
);
12707 this.connect( this, { click
: 'onAction' } );
12711 .addClass( 'oo-ui-popupButtonWidget' )
12712 .attr( 'aria-haspopup', 'true' )
12713 .append( this.popup
.$element
);
12718 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
12719 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
12724 * Handle the button action being triggered.
12728 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
12729 this.popup
.toggle();
12733 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
12734 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
12735 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
12736 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
12737 * and {@link OO.ui.mixin.LabelElement labels}. Please see
12738 * the [OOjs UI documentation][1] on MediaWiki for more information.
12741 * // Toggle buttons in the 'off' and 'on' state.
12742 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
12743 * label: 'Toggle Button off'
12745 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
12746 * label: 'Toggle Button on',
12749 * // Append the buttons to the DOM.
12750 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
12752 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
12755 * @extends OO.ui.ToggleWidget
12756 * @mixins OO.ui.mixin.ButtonElement
12757 * @mixins OO.ui.mixin.IconElement
12758 * @mixins OO.ui.mixin.IndicatorElement
12759 * @mixins OO.ui.mixin.LabelElement
12760 * @mixins OO.ui.mixin.TitledElement
12761 * @mixins OO.ui.mixin.FlaggedElement
12762 * @mixins OO.ui.mixin.TabIndexedElement
12765 * @param {Object} [config] Configuration options
12766 * @cfg {boolean} [value=false] The toggle button’s initial on/off
12767 * state. By default, the button is in the 'off' state.
12769 OO
.ui
.ToggleButtonWidget
= function OoUiToggleButtonWidget( config
) {
12770 // Configuration initialization
12771 config
= config
|| {};
12773 // Parent constructor
12774 OO
.ui
.ToggleButtonWidget
.parent
.call( this, config
);
12776 // Mixin constructors
12777 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
12778 OO
.ui
.mixin
.IconElement
.call( this, config
);
12779 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12780 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12781 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
12782 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
12783 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
12786 this.connect( this, { click
: 'onAction' } );
12789 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
12791 .addClass( 'oo-ui-toggleButtonWidget' )
12792 .append( this.$button
);
12797 OO
.inheritClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ToggleWidget
);
12798 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
12799 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IconElement
);
12800 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
12801 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.LabelElement
);
12802 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TitledElement
);
12803 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
12804 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
12809 * Handle the button action being triggered.
12813 OO
.ui
.ToggleButtonWidget
.prototype.onAction = function () {
12814 this.setValue( !this.value
);
12820 OO
.ui
.ToggleButtonWidget
.prototype.setValue = function ( value
) {
12822 if ( value
!== this.value
) {
12823 // Might be called from parent constructor before ButtonElement constructor
12824 if ( this.$button
) {
12825 this.$button
.attr( 'aria-pressed', value
.toString() );
12827 this.setActive( value
);
12831 OO
.ui
.ToggleButtonWidget
.parent
.prototype.setValue
.call( this, value
);
12839 OO
.ui
.ToggleButtonWidget
.prototype.setButtonElement = function ( $button
) {
12840 if ( this.$button
) {
12841 this.$button
.removeAttr( 'aria-pressed' );
12843 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement
.call( this, $button
);
12844 this.$button
.attr( 'aria-pressed', this.value
.toString() );
12848 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxWidget combo box widget}
12849 * that allows for selecting multiple values.
12851 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
12854 * // Example: A CapsuleMultiSelectWidget.
12855 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
12856 * label: 'CapsuleMultiSelectWidget',
12857 * selected: [ 'Option 1', 'Option 3' ],
12860 * new OO.ui.MenuOptionWidget( {
12861 * data: 'Option 1',
12862 * label: 'Option One'
12864 * new OO.ui.MenuOptionWidget( {
12865 * data: 'Option 2',
12866 * label: 'Option Two'
12868 * new OO.ui.MenuOptionWidget( {
12869 * data: 'Option 3',
12870 * label: 'Option Three'
12872 * new OO.ui.MenuOptionWidget( {
12873 * data: 'Option 4',
12874 * label: 'Option Four'
12876 * new OO.ui.MenuOptionWidget( {
12877 * data: 'Option 5',
12878 * label: 'Option Five'
12883 * $( 'body' ).append( capsule.$element );
12885 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12888 * @extends OO.ui.Widget
12889 * @mixins OO.ui.mixin.TabIndexedElement
12890 * @mixins OO.ui.mixin.GroupElement
12893 * @param {Object} [config] Configuration options
12894 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
12895 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
12896 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
12897 * If specified, this popup will be shown instead of the menu (but the menu
12898 * will still be used for item labels and allowArbitrary=false). The widgets
12899 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
12900 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
12901 * This configuration is useful in cases where the expanded menu is larger than
12902 * its containing `<div>`. The specified overlay layer is usually on top of
12903 * the containing `<div>` and has a larger area. By default, the menu uses
12904 * relative positioning.
12906 OO
.ui
.CapsuleMultiSelectWidget
= function OoUiCapsuleMultiSelectWidget( config
) {
12909 // Configuration initialization
12910 config
= config
|| {};
12912 // Parent constructor
12913 OO
.ui
.CapsuleMultiSelectWidget
.parent
.call( this, config
);
12915 // Properties (must be set before mixin constructor calls)
12916 this.$input
= config
.popup
? null : $( '<input>' );
12917 this.$handle
= $( '<div>' );
12919 // Mixin constructors
12920 OO
.ui
.mixin
.GroupElement
.call( this, config
);
12921 if ( config
.popup
) {
12922 config
.popup
= $.extend( {}, config
.popup
, {
12926 OO
.ui
.mixin
.PopupElement
.call( this, config
);
12927 $tabFocus
= $( '<span>' );
12928 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: $tabFocus
} ) );
12932 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
12934 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12935 OO
.ui
.mixin
.IconElement
.call( this, config
);
12938 this.allowArbitrary
= !!config
.allowArbitrary
;
12939 this.$overlay
= config
.$overlay
|| this.$element
;
12940 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
12943 $input
: this.$input
,
12944 $container
: this.$element
,
12945 filterFromInput
: true,
12946 disabled
: this.isDisabled()
12952 if ( this.popup
) {
12954 focus
: this.onFocusForPopup
.bind( this )
12956 this.popup
.$element
.on( 'focusout', this.onPopupFocusOut
.bind( this ) );
12957 if ( this.popup
.$autoCloseIgnore
) {
12958 this.popup
.$autoCloseIgnore
.on( 'focusout', this.onPopupFocusOut
.bind( this ) );
12960 this.popup
.connect( this, {
12961 toggle: function ( visible
) {
12962 $tabFocus
.toggle( !visible
);
12967 focus
: this.onInputFocus
.bind( this ),
12968 blur
: this.onInputBlur
.bind( this ),
12969 'propertychange change click mouseup keydown keyup input cut paste select': this.onInputChange
.bind( this ),
12970 keydown
: this.onKeyDown
.bind( this ),
12971 keypress
: this.onKeyPress
.bind( this )
12974 this.menu
.connect( this, {
12975 choose
: 'onMenuChoose',
12976 add
: 'onMenuItemsChange',
12977 remove
: 'onMenuItemsChange'
12980 click
: this.onClick
.bind( this )
12984 if ( this.$input
) {
12985 this.$input
.prop( 'disabled', this.isDisabled() );
12986 this.$input
.attr( {
12988 'aria-autocomplete': 'list'
12990 this.$input
.width( '1em' );
12992 if ( config
.data
) {
12993 this.setItemsFromData( config
.data
);
12995 this.$group
.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
12996 this.$handle
.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
12997 .append( this.$indicator
, this.$icon
, this.$group
);
12998 this.$element
.addClass( 'oo-ui-capsuleMultiSelectWidget' )
12999 .append( this.$handle
);
13000 if ( this.popup
) {
13001 this.$handle
.append( $tabFocus
);
13002 this.$overlay
.append( this.popup
.$element
);
13004 this.$handle
.append( this.$input
);
13005 this.$overlay
.append( this.menu
.$element
);
13007 this.onMenuItemsChange();
13012 OO
.inheritClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.Widget
);
13013 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.GroupElement
);
13014 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.PopupElement
);
13015 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13016 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.IndicatorElement
);
13017 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.IconElement
);
13024 * A change event is emitted when the set of selected items changes.
13026 * @param {Mixed[]} datas Data of the now-selected items
13032 * Get the data of the items in the capsule
13033 * @return {Mixed[]}
13035 OO
.ui
.CapsuleMultiSelectWidget
.prototype.getItemsData = function () {
13036 return $.map( this.getItems(), function ( e
) { return e
.data
; } );
13040 * Set the items in the capsule by providing data
13042 * @param {Mixed[]} datas
13043 * @return {OO.ui.CapsuleMultiSelectWidget}
13045 OO
.ui
.CapsuleMultiSelectWidget
.prototype.setItemsFromData = function ( datas
) {
13048 items
= this.getItems();
13050 $.each( datas
, function ( i
, data
) {
13052 item
= menu
.getItemFromData( data
);
13055 label
= item
.label
;
13056 } else if ( widget
.allowArbitrary
) {
13057 label
= String( data
);
13063 for ( j
= 0; j
< items
.length
; j
++ ) {
13064 if ( items
[ j
].data
=== data
&& items
[ j
].label
=== label
) {
13066 items
.splice( j
, 1 );
13071 item
= new OO
.ui
.CapsuleItemWidget( { data
: data
, label
: label
} );
13073 widget
.addItems( [ item
], i
);
13076 if ( items
.length
) {
13077 widget
.removeItems( items
);
13084 * Add items to the capsule by providing their data
13086 * @param {Mixed[]} datas
13087 * @return {OO.ui.CapsuleMultiSelectWidget}
13089 OO
.ui
.CapsuleMultiSelectWidget
.prototype.addItemsFromData = function ( datas
) {
13094 $.each( datas
, function ( i
, data
) {
13097 if ( !widget
.getItemFromData( data
) ) {
13098 item
= menu
.getItemFromData( data
);
13100 items
.push( new OO
.ui
.CapsuleItemWidget( { data
: data
, label
: item
.label
} ) );
13101 } else if ( widget
.allowArbitrary
) {
13102 items
.push( new OO
.ui
.CapsuleItemWidget( { data
: data
, label
: String( data
) } ) );
13107 if ( items
.length
) {
13108 this.addItems( items
);
13115 * Remove items by data
13117 * @param {Mixed[]} datas
13118 * @return {OO.ui.CapsuleMultiSelectWidget}
13120 OO
.ui
.CapsuleMultiSelectWidget
.prototype.removeItemsFromData = function ( datas
) {
13124 $.each( datas
, function ( i
, data
) {
13125 var item
= widget
.getItemFromData( data
);
13127 items
.push( item
);
13131 if ( items
.length
) {
13132 this.removeItems( items
);
13141 OO
.ui
.CapsuleMultiSelectWidget
.prototype.addItems = function ( items
) {
13143 oldItems
= this.items
.slice();
13145 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
);
13147 if ( this.items
.length
!== oldItems
.length
) {
13151 for ( i
= 0, l
= oldItems
.length
; same
&& i
< l
; i
++ ) {
13152 same
= same
&& this.items
[ i
] === oldItems
[ i
];
13156 this.emit( 'change', this.getItemsData() );
13165 OO
.ui
.CapsuleMultiSelectWidget
.prototype.removeItems = function ( items
) {
13167 oldItems
= this.items
.slice();
13169 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
13171 if ( this.items
.length
!== oldItems
.length
) {
13175 for ( i
= 0, l
= oldItems
.length
; same
&& i
< l
; i
++ ) {
13176 same
= same
&& this.items
[ i
] === oldItems
[ i
];
13180 this.emit( 'change', this.getItemsData() );
13189 OO
.ui
.CapsuleMultiSelectWidget
.prototype.clearItems = function () {
13190 if ( this.items
.length
) {
13191 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
13192 this.emit( 'change', this.getItemsData() );
13198 * Get the capsule widget's menu.
13199 * @return {OO.ui.MenuSelectWidget} Menu widget
13201 OO
.ui
.CapsuleMultiSelectWidget
.prototype.getMenu = function () {
13206 * Handle focus events
13209 * @param {jQuery.Event} event
13211 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputFocus = function () {
13212 if ( !this.isDisabled() ) {
13213 this.menu
.toggle( true );
13218 * Handle blur events
13221 * @param {jQuery.Event} event
13223 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputBlur = function () {
13228 * Handle focus events
13231 * @param {jQuery.Event} event
13233 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onFocusForPopup = function () {
13234 if ( !this.isDisabled() ) {
13235 this.popup
.setSize( this.$handle
.width() );
13236 this.popup
.toggle( true );
13237 this.popup
.$element
.find( '*' )
13238 .filter( function () { return OO
.ui
.isFocusableElement( $( this ), true ); } )
13245 * Handles popup focus out events.
13248 * @param {Event} e Focus out event
13250 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onPopupFocusOut = function () {
13251 var widget
= this.popup
;
13253 setTimeout( function () {
13255 widget
.isVisible() &&
13256 !OO
.ui
.contains( widget
.$element
[ 0 ], document
.activeElement
, true ) &&
13257 ( !widget
.$autoCloseIgnore
|| !widget
.$autoCloseIgnore
.has( document
.activeElement
).length
)
13259 widget
.toggle( false );
13265 * Handle mouse click events.
13268 * @param {jQuery.Event} e Mouse click event
13270 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onClick = function ( e
) {
13271 if ( e
.which
=== 1 ) {
13278 * Handle key press events.
13281 * @param {jQuery.Event} e Key press event
13283 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onKeyPress = function ( e
) {
13286 if ( !this.isDisabled() ) {
13287 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
13292 if ( !this.popup
) {
13293 this.menu
.toggle( true );
13294 if ( e
.which
=== OO
.ui
.Keys
.ENTER
) {
13295 item
= this.menu
.getItemFromLabel( this.$input
.val(), true );
13297 this.addItemsFromData( [ item
.data
] );
13299 } else if ( this.allowArbitrary
&& this.$input
.val().trim() !== '' ) {
13300 this.addItemsFromData( [ this.$input
.val() ] );
13306 // Make sure the input gets resized.
13307 setTimeout( this.onInputChange
.bind( this ), 0 );
13313 * Handle key down events.
13316 * @param {jQuery.Event} e Key down event
13318 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onKeyDown = function ( e
) {
13319 if ( !this.isDisabled() ) {
13320 // 'keypress' event is not triggered for Backspace
13321 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.$input
.val() === '' ) {
13322 if ( this.items
.length
) {
13323 this.removeItems( this.items
.slice( -1 ) );
13331 * Handle input change events.
13334 * @param {jQuery.Event} e Event of some sort
13336 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputChange = function () {
13337 if ( !this.isDisabled() ) {
13338 this.$input
.width( this.$input
.val().length
+ 'em' );
13343 * Handle menu choose events.
13346 * @param {OO.ui.OptionWidget} item Chosen item
13348 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onMenuChoose = function ( item
) {
13349 if ( item
&& item
.isVisible() ) {
13350 this.addItemsFromData( [ item
.getData() ] );
13356 * Handle menu item change events.
13360 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onMenuItemsChange = function () {
13361 this.setItemsFromData( this.getItemsData() );
13362 this.$element
.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu
.isEmpty() );
13366 * Clear the input field
13369 OO
.ui
.CapsuleMultiSelectWidget
.prototype.clearInput = function () {
13370 if ( this.$input
) {
13371 this.$input
.val( '' );
13372 this.$input
.width( '1em' );
13374 if ( this.popup
) {
13375 this.popup
.toggle( false );
13377 this.menu
.toggle( false );
13378 this.menu
.selectItem();
13379 this.menu
.highlightItem();
13385 OO
.ui
.CapsuleMultiSelectWidget
.prototype.setDisabled = function ( disabled
) {
13389 OO
.ui
.CapsuleMultiSelectWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
13391 if ( this.$input
) {
13392 this.$input
.prop( 'disabled', this.isDisabled() );
13395 this.menu
.setDisabled( this.isDisabled() );
13397 if ( this.popup
) {
13398 this.popup
.setDisabled( this.isDisabled() );
13401 if ( this.items
) {
13402 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
13403 this.items
[ i
].updateDisabled();
13413 * @return {OO.ui.CapsuleMultiSelectWidget}
13415 OO
.ui
.CapsuleMultiSelectWidget
.prototype.focus = function () {
13416 if ( !this.isDisabled() ) {
13417 if ( this.popup
) {
13418 this.popup
.setSize( this.$handle
.width() );
13419 this.popup
.toggle( true );
13420 this.popup
.$element
.find( '*' )
13421 .filter( function () { return OO
.ui
.isFocusableElement( $( this ), true ); } )
13425 this.menu
.toggle( true );
13426 this.$input
.focus();
13433 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
13434 * CapsuleMultiSelectWidget} to display the selected items.
13437 * @extends OO.ui.Widget
13438 * @mixins OO.ui.mixin.ItemWidget
13439 * @mixins OO.ui.mixin.IndicatorElement
13440 * @mixins OO.ui.mixin.LabelElement
13441 * @mixins OO.ui.mixin.FlaggedElement
13442 * @mixins OO.ui.mixin.TabIndexedElement
13445 * @param {Object} [config] Configuration options
13447 OO
.ui
.CapsuleItemWidget
= function OoUiCapsuleItemWidget( config
) {
13448 // Configuration initialization
13449 config
= config
|| {};
13451 // Parent constructor
13452 OO
.ui
.CapsuleItemWidget
.parent
.call( this, config
);
13454 // Properties (must be set before mixin constructor calls)
13455 this.$indicator
= $( '<span>' );
13457 // Mixin constructors
13458 OO
.ui
.mixin
.ItemWidget
.call( this );
13459 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$indicator
, indicator
: 'clear' } ) );
13460 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13461 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
13462 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
13465 this.$indicator
.on( {
13466 keydown
: this.onCloseKeyDown
.bind( this ),
13467 click
: this.onCloseClick
.bind( this )
13469 this.$element
.on( 'click', false );
13473 .addClass( 'oo-ui-capsuleItemWidget' )
13474 .append( this.$indicator
, this.$label
);
13479 OO
.inheritClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.Widget
);
13480 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.ItemWidget
);
13481 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.IndicatorElement
);
13482 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.LabelElement
);
13483 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.FlaggedElement
);
13484 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13489 * Handle close icon clicks
13490 * @param {jQuery.Event} event
13492 OO
.ui
.CapsuleItemWidget
.prototype.onCloseClick = function () {
13493 var element
= this.getElementGroup();
13495 if ( !this.isDisabled() && element
&& $.isFunction( element
.removeItems
) ) {
13496 element
.removeItems( [ this ] );
13502 * Handle close keyboard events
13503 * @param {jQuery.Event} event Key down event
13505 OO
.ui
.CapsuleItemWidget
.prototype.onCloseKeyDown = function ( e
) {
13506 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems
) ) {
13507 switch ( e
.which
) {
13508 case OO
.ui
.Keys
.ENTER
:
13509 case OO
.ui
.Keys
.BACKSPACE
:
13510 case OO
.ui
.Keys
.SPACE
:
13511 this.getElementGroup().removeItems( [ this ] );
13518 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
13519 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
13520 * users can interact with it.
13522 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
13523 * OO.ui.DropdownInputWidget instead.
13526 * // Example: A DropdownWidget with a menu that contains three options
13527 * var dropDown = new OO.ui.DropdownWidget( {
13528 * label: 'Dropdown menu: Select a menu option',
13531 * new OO.ui.MenuOptionWidget( {
13535 * new OO.ui.MenuOptionWidget( {
13539 * new OO.ui.MenuOptionWidget( {
13547 * $( 'body' ).append( dropDown.$element );
13549 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
13551 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13554 * @extends OO.ui.Widget
13555 * @mixins OO.ui.mixin.IconElement
13556 * @mixins OO.ui.mixin.IndicatorElement
13557 * @mixins OO.ui.mixin.LabelElement
13558 * @mixins OO.ui.mixin.TitledElement
13559 * @mixins OO.ui.mixin.TabIndexedElement
13562 * @param {Object} [config] Configuration options
13563 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
13564 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
13565 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
13566 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
13568 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
13569 // Configuration initialization
13570 config
= $.extend( { indicator
: 'down' }, config
);
13572 // Parent constructor
13573 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
13575 // Properties (must be set before TabIndexedElement constructor call)
13576 this.$handle
= this.$( '<span>' );
13577 this.$overlay
= config
.$overlay
|| this.$element
;
13579 // Mixin constructors
13580 OO
.ui
.mixin
.IconElement
.call( this, config
);
13581 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13582 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13583 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
13584 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
13587 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend( {
13589 $container
: this.$element
13590 }, config
.menu
) );
13594 click
: this.onClick
.bind( this ),
13595 keypress
: this.onKeyPress
.bind( this )
13597 this.menu
.connect( this, { select
: 'onMenuSelect' } );
13601 .addClass( 'oo-ui-dropdownWidget-handle' )
13602 .append( this.$icon
, this.$label
, this.$indicator
);
13604 .addClass( 'oo-ui-dropdownWidget' )
13605 .append( this.$handle
);
13606 this.$overlay
.append( this.menu
.$element
);
13611 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
13612 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
13613 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
13614 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
13615 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
13616 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13623 * @return {OO.ui.MenuSelectWidget} Menu of widget
13625 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
13630 * Handles menu select events.
13633 * @param {OO.ui.MenuOptionWidget} item Selected menu item
13635 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
13639 this.setLabel( null );
13643 selectedLabel
= item
.getLabel();
13645 // If the label is a DOM element, clone it, because setLabel will append() it
13646 if ( selectedLabel
instanceof jQuery
) {
13647 selectedLabel
= selectedLabel
.clone();
13650 this.setLabel( selectedLabel
);
13654 * Handle mouse click events.
13657 * @param {jQuery.Event} e Mouse click event
13659 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
13660 if ( !this.isDisabled() && e
.which
=== 1 ) {
13661 this.menu
.toggle();
13667 * Handle key press events.
13670 * @param {jQuery.Event} e Key press event
13672 OO
.ui
.DropdownWidget
.prototype.onKeyPress = function ( e
) {
13673 if ( !this.isDisabled() &&
13674 ( ( e
.which
=== OO
.ui
.Keys
.SPACE
&& !this.menu
.isVisible() ) || e
.which
=== OO
.ui
.Keys
.ENTER
)
13676 this.menu
.toggle();
13682 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
13683 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
13684 * OO.ui.mixin.IndicatorElement indicators}.
13685 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
13688 * // Example of a file select widget
13689 * var selectFile = new OO.ui.SelectFileWidget();
13690 * $( 'body' ).append( selectFile.$element );
13692 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
13695 * @extends OO.ui.Widget
13696 * @mixins OO.ui.mixin.IconElement
13697 * @mixins OO.ui.mixin.IndicatorElement
13698 * @mixins OO.ui.mixin.PendingElement
13699 * @mixins OO.ui.mixin.LabelElement
13700 * @mixins OO.ui.mixin.TabIndexedElement
13703 * @param {Object} [config] Configuration options
13704 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
13705 * @cfg {string} [placeholder] Text to display when no file is selected.
13706 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
13707 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
13708 * @cfg {boolean} [dragDropUI=false] Whether to render the drag and drop UI.
13710 OO
.ui
.SelectFileWidget
= function OoUiSelectFileWidget( config
) {
13712 placeholderMsg
= ( config
&& config
.dragDropUI
) ?
13713 'ooui-selectfile-dragdrop-placeholder' :
13714 'ooui-selectfile-placeholder';
13716 // Configuration initialization
13717 config
= $.extend( {
13719 placeholder
: OO
.ui
.msg( placeholderMsg
),
13720 notsupported
: OO
.ui
.msg( 'ooui-selectfile-not-supported' ),
13725 // Parent constructor
13726 OO
.ui
.SelectFileWidget
.parent
.call( this, config
);
13728 // Properties (must be set before TabIndexedElement constructor call)
13729 this.$handle
= $( '<span>' );
13731 // Mixin constructors
13732 OO
.ui
.mixin
.IconElement
.call( this, config
);
13733 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13734 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$handle
} ) );
13735 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { autoFitLabel
: true } ) );
13736 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
13739 this.active
= false;
13740 this.dragDropUI
= config
.dragDropUI
;
13741 this.isSupported
= this.constructor.static.isSupported();
13742 this.currentFile
= null;
13743 if ( Array
.isArray( config
.accept
) ) {
13744 this.accept
= config
.accept
;
13746 this.accept
= null;
13748 this.placeholder
= config
.placeholder
;
13749 this.notsupported
= config
.notsupported
;
13750 this.onFileSelectedHandler
= this.onFileSelected
.bind( this );
13752 this.clearButton
= new OO
.ui
.ButtonWidget( {
13753 classes
: [ 'oo-ui-selectFileWidget-clearButton' ],
13756 disabled
: this.disabled
13761 keypress
: this.onKeyPress
.bind( this )
13763 this.clearButton
.connect( this, {
13764 click
: 'onClearClick'
13766 if ( config
.droppable
) {
13767 dragHandler
= this.onDragEnterOrOver
.bind( this );
13769 dragenter
: dragHandler
,
13770 dragover
: dragHandler
,
13771 dragleave
: this.onDragLeave
.bind( this ),
13772 drop
: this.onDrop
.bind( this )
13779 this.$label
.addClass( 'oo-ui-selectFileWidget-label' );
13781 .addClass( 'oo-ui-selectFileWidget-handle' )
13782 .append( this.$icon
, this.$label
, this.clearButton
.$element
, this.$indicator
);
13784 .addClass( 'oo-ui-selectFileWidget' )
13785 .append( this.$handle
);
13786 if ( config
.droppable
) {
13787 if ( config
.dragDropUI
) {
13788 this.$element
.addClass( 'oo-ui-selectFileWidget-dragdrop-ui' );
13789 this.$element
.on( {
13790 mouseover
: this.onMouseOver
.bind( this ),
13791 mouseleave
: this.onMouseLeave
.bind( this )
13794 this.$element
.addClass( 'oo-ui-selectFileWidget-droppable' );
13801 OO
.inheritClass( OO
.ui
.SelectFileWidget
, OO
.ui
.Widget
);
13802 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IconElement
);
13803 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IndicatorElement
);
13804 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.PendingElement
);
13805 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.LabelElement
);
13806 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13808 /* Static Properties */
13811 * Check if this widget is supported
13814 * @return {boolean}
13816 OO
.ui
.SelectFileWidget
.static.isSupported = function () {
13818 if ( OO
.ui
.SelectFileWidget
.static.isSupportedCache
=== null ) {
13819 $input
= $( '<input type="file">' );
13820 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= $input
[ 0 ].files
!== undefined;
13822 return OO
.ui
.SelectFileWidget
.static.isSupportedCache
;
13825 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= null;
13832 * A change event is emitted when the on/off state of the toggle changes.
13834 * @param {File|null} value New value
13840 * Get the current value of the field
13842 * @return {File|null}
13844 OO
.ui
.SelectFileWidget
.prototype.getValue = function () {
13845 return this.currentFile
;
13849 * Set the current value of the field
13851 * @param {File|null} file File to select
13853 OO
.ui
.SelectFileWidget
.prototype.setValue = function ( file
) {
13854 if ( this.currentFile
!== file
) {
13855 this.currentFile
= file
;
13857 this.emit( 'change', this.currentFile
);
13862 * Update the user interface when a file is selected or unselected
13866 OO
.ui
.SelectFileWidget
.prototype.updateUI = function () {
13867 if ( !this.isSupported
) {
13868 this.$element
.addClass( 'oo-ui-selectFileWidget-notsupported' );
13869 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
13870 this.setLabel( this.notsupported
);
13871 } else if ( this.currentFile
) {
13872 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
13873 this.setLabel( this.currentFile
.name
+
13874 ( this.currentFile
.type
!== '' ? OO
.ui
.msg( 'ooui-semicolon-separator' ) + this.currentFile
.type
: '' )
13877 this.$element
.addClass( 'oo-ui-selectFileWidget-empty' );
13878 this.setLabel( this.placeholder
);
13881 if ( this.$input
) {
13882 this.$input
.attr( 'title', this.getLabel() );
13887 * Add the input to the handle
13891 OO
.ui
.SelectFileWidget
.prototype.addInput = function () {
13892 if ( this.$input
) {
13893 this.$input
.remove();
13896 if ( !this.isSupported
) {
13897 this.$input
= null;
13901 this.$input
= $( '<input type="file">' );
13902 this.$input
.on( 'change', this.onFileSelectedHandler
);
13903 this.$input
.attr( {
13905 title
: this.getLabel()
13907 if ( this.accept
) {
13908 this.$input
.attr( 'accept', this.accept
.join( ', ' ) );
13910 this.$handle
.append( this.$input
);
13914 * Determine if we should accept this file
13917 * @param {File} file
13918 * @return {boolean}
13920 OO
.ui
.SelectFileWidget
.prototype.isFileAcceptable = function ( file
) {
13921 var i
, mime
, mimeTest
;
13923 if ( !this.accept
|| file
.type
=== '' ) {
13928 for ( i
= 0; i
< this.accept
.length
; i
++ ) {
13929 mimeTest
= this.accept
[ i
];
13930 if ( mimeTest
=== mime
) {
13932 } else if ( mimeTest
.substr( -2 ) === '/*' ) {
13933 mimeTest
= mimeTest
.substr( 0, mimeTest
.length
- 1 );
13934 if ( mime
.substr( 0, mimeTest
.length
) === mimeTest
) {
13944 * Handle file selection from the input
13947 * @param {jQuery.Event} e
13949 OO
.ui
.SelectFileWidget
.prototype.onFileSelected = function ( e
) {
13952 if ( e
.target
.files
&& e
.target
.files
[ 0 ] ) {
13953 file
= e
.target
.files
[ 0 ];
13954 if ( !this.isFileAcceptable( file
) ) {
13959 this.setValue( file
);
13964 * Handle clear button click events.
13968 OO
.ui
.SelectFileWidget
.prototype.onClearClick = function () {
13969 this.setValue( null );
13974 * Handle key press events.
13977 * @param {jQuery.Event} e Key press event
13979 OO
.ui
.SelectFileWidget
.prototype.onKeyPress = function ( e
) {
13980 if ( this.isSupported
&& !this.isDisabled() && this.$input
&&
13981 ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
13983 this.$input
.click();
13989 * Handle drag enter and over events
13992 * @param {jQuery.Event} e Drag event
13994 OO
.ui
.SelectFileWidget
.prototype.onDragEnterOrOver = function ( e
) {
13996 dt
= e
.originalEvent
.dataTransfer
;
13998 e
.preventDefault();
13999 e
.stopPropagation();
14001 if ( this.isDisabled() || !this.isSupported
) {
14002 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14003 this.setActive( false );
14004 dt
.dropEffect
= 'none';
14008 if ( dt
&& dt
.files
&& dt
.files
[ 0 ] ) {
14009 file
= dt
.files
[ 0 ];
14010 if ( !this.isFileAcceptable( file
) ) {
14013 } else if ( dt
&& dt
.types
&& dt
.types
.indexOf( 'Files' ) !== -1 ) {
14014 // We know we have files so set 'file' to something truthy, we just
14015 // can't know any details about them.
14016 // * https://bugzilla.mozilla.org/show_bug.cgi?id=640534
14017 file
= 'Files exist, but details are unknown';
14020 this.$element
.addClass( 'oo-ui-selectFileWidget-canDrop' );
14021 this.setActive( true );
14023 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14024 this.setActive( false );
14025 dt
.dropEffect
= 'none';
14032 * Handle drag leave events
14035 * @param {jQuery.Event} e Drag event
14037 OO
.ui
.SelectFileWidget
.prototype.onDragLeave = function () {
14038 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14039 this.setActive( false );
14043 * Handle drop events
14046 * @param {jQuery.Event} e Drop event
14048 OO
.ui
.SelectFileWidget
.prototype.onDrop = function ( e
) {
14050 dt
= e
.originalEvent
.dataTransfer
;
14052 e
.preventDefault();
14053 e
.stopPropagation();
14054 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14055 this.setActive( false );
14057 if ( this.isDisabled() || !this.isSupported
) {
14061 if ( dt
&& dt
.files
&& dt
.files
[ 0 ] ) {
14062 file
= dt
.files
[ 0 ];
14063 if ( !this.isFileAcceptable( file
) ) {
14068 this.setValue( file
);
14075 * Handle mouse over events.
14078 * @param {jQuery.Event} e Mouse over event
14080 OO
.ui
.SelectFileWidget
.prototype.onMouseOver = function () {
14081 this.setActive( true );
14085 * Handle mouse leave events.
14088 * @param {jQuery.Event} e Mouse over event
14090 OO
.ui
.SelectFileWidget
.prototype.onMouseLeave = function () {
14091 this.setActive( false );
14097 OO
.ui
.SelectFileWidget
.prototype.setDisabled = function ( state
) {
14098 OO
.ui
.SelectFileWidget
.parent
.prototype.setDisabled
.call( this, state
);
14099 if ( this.clearButton
) {
14100 this.clearButton
.setDisabled( state
);
14106 * Set 'active' (hover) state, only matters for widgets with `dragDropUI: true`.
14108 * @param {boolean} value Whether widget is active
14111 OO
.ui
.SelectFileWidget
.prototype.setActive = function ( value
) {
14112 if ( this.dragDropUI
) {
14113 this.active
= value
;
14114 this.updateThemeClasses();
14120 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
14121 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
14122 * for a list of icons included in the library.
14125 * // An icon widget with a label
14126 * var myIcon = new OO.ui.IconWidget( {
14128 * iconTitle: 'Help'
14130 * // Create a label.
14131 * var iconLabel = new OO.ui.LabelWidget( {
14134 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
14136 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
14139 * @extends OO.ui.Widget
14140 * @mixins OO.ui.mixin.IconElement
14141 * @mixins OO.ui.mixin.TitledElement
14142 * @mixins OO.ui.mixin.FlaggedElement
14145 * @param {Object} [config] Configuration options
14147 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
14148 // Configuration initialization
14149 config
= config
|| {};
14151 // Parent constructor
14152 OO
.ui
.IconWidget
.parent
.call( this, config
);
14154 // Mixin constructors
14155 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
14156 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
14157 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
14160 this.$element
.addClass( 'oo-ui-iconWidget' );
14165 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
14166 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
14167 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
14168 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
14170 /* Static Properties */
14172 OO
.ui
.IconWidget
.static.tagName
= 'span';
14175 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
14176 * attention to the status of an item or to clarify the function of a control. For a list of
14177 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
14180 * // Example of an indicator widget
14181 * var indicator1 = new OO.ui.IndicatorWidget( {
14182 * indicator: 'alert'
14185 * // Create a fieldset layout to add a label
14186 * var fieldset = new OO.ui.FieldsetLayout();
14187 * fieldset.addItems( [
14188 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
14190 * $( 'body' ).append( fieldset.$element );
14192 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
14195 * @extends OO.ui.Widget
14196 * @mixins OO.ui.mixin.IndicatorElement
14197 * @mixins OO.ui.mixin.TitledElement
14200 * @param {Object} [config] Configuration options
14202 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
14203 // Configuration initialization
14204 config
= config
|| {};
14206 // Parent constructor
14207 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
14209 // Mixin constructors
14210 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
14211 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
14214 this.$element
.addClass( 'oo-ui-indicatorWidget' );
14219 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
14220 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
14221 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
14223 /* Static Properties */
14225 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
14228 * InputWidget is the base class for all input widgets, which
14229 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
14230 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
14231 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14233 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14237 * @extends OO.ui.Widget
14238 * @mixins OO.ui.mixin.FlaggedElement
14239 * @mixins OO.ui.mixin.TabIndexedElement
14240 * @mixins OO.ui.mixin.TitledElement
14241 * @mixins OO.ui.mixin.AccessKeyedElement
14244 * @param {Object} [config] Configuration options
14245 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
14246 * @cfg {string} [value=''] The value of the input.
14247 * @cfg {string} [accessKey=''] The access key of the input.
14248 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
14249 * before it is accepted.
14251 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
14252 // Configuration initialization
14253 config
= config
|| {};
14255 // Parent constructor
14256 OO
.ui
.InputWidget
.parent
.call( this, config
);
14259 this.$input
= this.getInputElement( config
);
14261 this.inputFilter
= config
.inputFilter
;
14263 // Mixin constructors
14264 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
14265 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
14266 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
14267 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
14270 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
14274 .addClass( 'oo-ui-inputWidget-input' )
14275 .attr( 'name', config
.name
)
14276 .prop( 'disabled', this.isDisabled() );
14278 .addClass( 'oo-ui-inputWidget' )
14279 .append( this.$input
);
14280 this.setValue( config
.value
);
14281 this.setAccessKey( config
.accessKey
);
14286 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
14287 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
14288 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
14289 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
14290 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
14292 /* Static Properties */
14294 OO
.ui
.InputWidget
.static.supportsSimpleLabel
= true;
14301 * A change event is emitted when the value of the input changes.
14303 * @param {string} value
14309 * Get input element.
14311 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14312 * different circumstances. The element must have a `value` property (like form elements).
14315 * @param {Object} config Configuration options
14316 * @return {jQuery} Input element
14318 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
14319 return $( '<input>' );
14323 * Handle potentially value-changing events.
14326 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14328 OO
.ui
.InputWidget
.prototype.onEdit = function () {
14330 if ( !this.isDisabled() ) {
14331 // Allow the stack to clear so the value will be updated
14332 setTimeout( function () {
14333 widget
.setValue( widget
.$input
.val() );
14339 * Get the value of the input.
14341 * @return {string} Input value
14343 OO
.ui
.InputWidget
.prototype.getValue = function () {
14344 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14345 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14346 var value
= this.$input
.val();
14347 if ( this.value
!== value
) {
14348 this.setValue( value
);
14354 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
14356 * @param {boolean} isRTL
14357 * Direction is right-to-left
14359 OO
.ui
.InputWidget
.prototype.setRTL = function ( isRTL
) {
14360 this.$input
.prop( 'dir', isRTL
? 'rtl' : 'ltr' );
14364 * Set the value of the input.
14366 * @param {string} value New value
14370 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
14371 value
= this.cleanUpValue( value
);
14372 // Update the DOM if it has changed. Note that with cleanUpValue, it
14373 // is possible for the DOM value to change without this.value changing.
14374 if ( this.$input
.val() !== value
) {
14375 this.$input
.val( value
);
14377 if ( this.value
!== value
) {
14378 this.value
= value
;
14379 this.emit( 'change', this.value
);
14385 * Set the input's access key.
14386 * FIXME: This is the same code as in OO.ui.mixin.ButtonElement, maybe find a better place for it?
14388 * @param {string} accessKey Input's access key, use empty string to remove
14391 OO
.ui
.InputWidget
.prototype.setAccessKey = function ( accessKey
) {
14392 accessKey
= typeof accessKey
=== 'string' && accessKey
.length
? accessKey
: null;
14394 if ( this.accessKey
!== accessKey
) {
14395 if ( this.$input
) {
14396 if ( accessKey
!== null ) {
14397 this.$input
.attr( 'accesskey', accessKey
);
14399 this.$input
.removeAttr( 'accesskey' );
14402 this.accessKey
= accessKey
;
14409 * Clean up incoming value.
14411 * Ensures value is a string, and converts undefined and null to empty string.
14414 * @param {string} value Original value
14415 * @return {string} Cleaned up value
14417 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
14418 if ( value
=== undefined || value
=== null ) {
14420 } else if ( this.inputFilter
) {
14421 return this.inputFilter( String( value
) );
14423 return String( value
);
14428 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
14429 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
14432 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
14433 if ( !this.isDisabled() ) {
14434 if ( this.$input
.is( ':checkbox, :radio' ) ) {
14435 this.$input
.click();
14437 if ( this.$input
.is( ':input' ) ) {
14438 this.$input
[ 0 ].focus();
14446 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
14447 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
14448 if ( this.$input
) {
14449 this.$input
.prop( 'disabled', this.isDisabled() );
14459 OO
.ui
.InputWidget
.prototype.focus = function () {
14460 this.$input
[ 0 ].focus();
14469 OO
.ui
.InputWidget
.prototype.blur = function () {
14470 this.$input
[ 0 ].blur();
14477 OO
.ui
.InputWidget
.prototype.gatherPreInfuseState = function ( node
) {
14479 state
= OO
.ui
.InputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
),
14480 $input
= state
.$input
|| $( node
).find( '.oo-ui-inputWidget-input' );
14481 state
.value
= $input
.val();
14482 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14483 state
.focus
= $input
.is( ':focus' );
14490 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
14491 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
14492 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
14493 this.setValue( state
.value
);
14495 if ( state
.focus
) {
14501 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
14502 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
14503 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
14504 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
14505 * [OOjs UI documentation on MediaWiki] [1] for more information.
14508 * // A ButtonInputWidget rendered as an HTML button, the default.
14509 * var button = new OO.ui.ButtonInputWidget( {
14510 * label: 'Input button',
14514 * $( 'body' ).append( button.$element );
14516 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
14519 * @extends OO.ui.InputWidget
14520 * @mixins OO.ui.mixin.ButtonElement
14521 * @mixins OO.ui.mixin.IconElement
14522 * @mixins OO.ui.mixin.IndicatorElement
14523 * @mixins OO.ui.mixin.LabelElement
14524 * @mixins OO.ui.mixin.TitledElement
14527 * @param {Object} [config] Configuration options
14528 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
14529 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
14530 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
14531 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
14532 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
14534 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
14535 // Configuration initialization
14536 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
14538 // Properties (must be set before parent constructor, which calls #setValue)
14539 this.useInputTag
= config
.useInputTag
;
14541 // Parent constructor
14542 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
14544 // Mixin constructors
14545 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
14546 OO
.ui
.mixin
.IconElement
.call( this, config
);
14547 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
14548 OO
.ui
.mixin
.LabelElement
.call( this, config
);
14549 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
14552 if ( !config
.useInputTag
) {
14553 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
14555 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
14560 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
14561 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
14562 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
14563 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
14564 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
14565 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
14567 /* Static Properties */
14570 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
14571 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
14573 OO
.ui
.ButtonInputWidget
.static.supportsSimpleLabel
= false;
14581 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
14582 var type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ?
14585 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
14591 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
14593 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
14594 * text, or `null` for no label
14597 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
14598 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
14600 if ( this.useInputTag
) {
14601 if ( typeof label
=== 'function' ) {
14602 label
= OO
.ui
.resolveMsg( label
);
14604 if ( label
instanceof jQuery
) {
14605 label
= label
.text();
14610 this.$input
.val( label
);
14617 * Set the value of the input.
14619 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
14620 * they do not support {@link #value values}.
14622 * @param {string} value New value
14625 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
14626 if ( !this.useInputTag
) {
14627 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
14633 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
14634 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
14635 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
14636 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
14638 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14641 * // An example of selected, unselected, and disabled checkbox inputs
14642 * var checkbox1=new OO.ui.CheckboxInputWidget( {
14646 * var checkbox2=new OO.ui.CheckboxInputWidget( {
14649 * var checkbox3=new OO.ui.CheckboxInputWidget( {
14653 * // Create a fieldset layout with fields for each checkbox.
14654 * var fieldset = new OO.ui.FieldsetLayout( {
14655 * label: 'Checkboxes'
14657 * fieldset.addItems( [
14658 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
14659 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
14660 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
14662 * $( 'body' ).append( fieldset.$element );
14664 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14667 * @extends OO.ui.InputWidget
14670 * @param {Object} [config] Configuration options
14671 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
14673 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
14674 // Configuration initialization
14675 config
= config
|| {};
14677 // Parent constructor
14678 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
14682 .addClass( 'oo-ui-checkboxInputWidget' )
14683 // Required for pretty styling in MediaWiki theme
14684 .append( $( '<span>' ) );
14685 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
14690 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
14698 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
14699 return $( '<input type="checkbox" />' );
14705 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
14707 if ( !this.isDisabled() ) {
14708 // Allow the stack to clear so the value will be updated
14709 setTimeout( function () {
14710 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
14716 * Set selection state of this checkbox.
14718 * @param {boolean} state `true` for selected
14721 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
14723 if ( this.selected
!== state
) {
14724 this.selected
= state
;
14725 this.$input
.prop( 'checked', this.selected
);
14726 this.emit( 'change', this.selected
);
14732 * Check if this checkbox is selected.
14734 * @return {boolean} Checkbox is selected
14736 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
14737 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14738 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14739 var selected
= this.$input
.prop( 'checked' );
14740 if ( this.selected
!== selected
) {
14741 this.setSelected( selected
);
14743 return this.selected
;
14749 OO
.ui
.CheckboxInputWidget
.prototype.gatherPreInfuseState = function ( node
) {
14751 state
= OO
.ui
.CheckboxInputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
),
14752 $input
= $( node
).find( '.oo-ui-inputWidget-input' );
14753 state
.$input
= $input
; // shortcut for performance, used in InputWidget
14754 state
.checked
= $input
.prop( 'checked' );
14761 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
14762 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
14763 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
14764 this.setSelected( state
.checked
);
14769 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
14770 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
14771 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
14772 * more information about input widgets.
14774 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
14775 * are no options. If no `value` configuration option is provided, the first option is selected.
14776 * If you need a state representing no value (no option being selected), use a DropdownWidget.
14778 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
14781 * // Example: A DropdownInputWidget with three options
14782 * var dropdownInput = new OO.ui.DropdownInputWidget( {
14784 * { data: 'a', label: 'First' },
14785 * { data: 'b', label: 'Second'},
14786 * { data: 'c', label: 'Third' }
14789 * $( 'body' ).append( dropdownInput.$element );
14791 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14794 * @extends OO.ui.InputWidget
14795 * @mixins OO.ui.mixin.TitledElement
14798 * @param {Object} [config] Configuration options
14799 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
14800 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
14802 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
14803 // Configuration initialization
14804 config
= config
|| {};
14806 // Properties (must be done before parent constructor which calls #setDisabled)
14807 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
14809 // Parent constructor
14810 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
14812 // Mixin constructors
14813 OO
.ui
.mixin
.TitledElement
.call( this, config
);
14816 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
14819 this.setOptions( config
.options
|| [] );
14821 .addClass( 'oo-ui-dropdownInputWidget' )
14822 .append( this.dropdownWidget
.$element
);
14827 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
14828 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
14836 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
14837 return $( '<input type="hidden">' );
14841 * Handles menu select events.
14844 * @param {OO.ui.MenuOptionWidget} item Selected menu item
14846 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
14847 this.setValue( item
.getData() );
14853 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
14854 value
= this.cleanUpValue( value
);
14855 this.dropdownWidget
.getMenu().selectItemByData( value
);
14856 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
14863 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
14864 this.dropdownWidget
.setDisabled( state
);
14865 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
14870 * Set the options available for this input.
14872 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
14875 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
14877 value
= this.getValue(),
14880 // Rebuild the dropdown menu
14881 this.dropdownWidget
.getMenu()
14883 .addItems( options
.map( function ( opt
) {
14884 var optValue
= widget
.cleanUpValue( opt
.data
);
14885 return new OO
.ui
.MenuOptionWidget( {
14887 label
: opt
.label
!== undefined ? opt
.label
: optValue
14891 // Restore the previous value, or reset to something sensible
14892 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
14893 // Previous value is still available, ensure consistency with the dropdown
14894 this.setValue( value
);
14896 // No longer valid, reset
14897 if ( options
.length
) {
14898 this.setValue( options
[ 0 ].data
);
14908 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
14909 this.dropdownWidget
.getMenu().toggle( true );
14916 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
14917 this.dropdownWidget
.getMenu().toggle( false );
14922 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
14923 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
14924 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
14925 * please see the [OOjs UI documentation on MediaWiki][1].
14927 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14930 * // An example of selected, unselected, and disabled radio inputs
14931 * var radio1 = new OO.ui.RadioInputWidget( {
14935 * var radio2 = new OO.ui.RadioInputWidget( {
14938 * var radio3 = new OO.ui.RadioInputWidget( {
14942 * // Create a fieldset layout with fields for each radio button.
14943 * var fieldset = new OO.ui.FieldsetLayout( {
14944 * label: 'Radio inputs'
14946 * fieldset.addItems( [
14947 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
14948 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
14949 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
14951 * $( 'body' ).append( fieldset.$element );
14953 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14956 * @extends OO.ui.InputWidget
14959 * @param {Object} [config] Configuration options
14960 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
14962 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
14963 // Configuration initialization
14964 config
= config
|| {};
14966 // Parent constructor
14967 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
14971 .addClass( 'oo-ui-radioInputWidget' )
14972 // Required for pretty styling in MediaWiki theme
14973 .append( $( '<span>' ) );
14974 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
14979 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
14987 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
14988 return $( '<input type="radio" />' );
14994 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
14995 // RadioInputWidget doesn't track its state.
14999 * Set selection state of this radio button.
15001 * @param {boolean} state `true` for selected
15004 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
15005 // RadioInputWidget doesn't track its state.
15006 this.$input
.prop( 'checked', state
);
15011 * Check if this radio button is selected.
15013 * @return {boolean} Radio is selected
15015 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
15016 return this.$input
.prop( 'checked' );
15022 OO
.ui
.RadioInputWidget
.prototype.gatherPreInfuseState = function ( node
) {
15024 state
= OO
.ui
.RadioInputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
),
15025 $input
= $( node
).find( '.oo-ui-inputWidget-input' );
15026 state
.$input
= $input
; // shortcut for performance, used in InputWidget
15027 state
.checked
= $input
.prop( 'checked' );
15034 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
15035 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
15036 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
15037 this.setSelected( state
.checked
);
15042 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
15043 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15044 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15045 * more information about input widgets.
15047 * This and OO.ui.DropdownInputWidget support the same configuration options.
15050 * // Example: A RadioSelectInputWidget with three options
15051 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
15053 * { data: 'a', label: 'First' },
15054 * { data: 'b', label: 'Second'},
15055 * { data: 'c', label: 'Third' }
15058 * $( 'body' ).append( radioSelectInput.$element );
15060 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15063 * @extends OO.ui.InputWidget
15066 * @param {Object} [config] Configuration options
15067 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15069 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
15070 // Configuration initialization
15071 config
= config
|| {};
15073 // Properties (must be done before parent constructor which calls #setDisabled)
15074 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
15076 // Parent constructor
15077 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
15080 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
15083 this.setOptions( config
.options
|| [] );
15085 .addClass( 'oo-ui-radioSelectInputWidget' )
15086 .append( this.radioSelectWidget
.$element
);
15091 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
15093 /* Static Properties */
15095 OO
.ui
.RadioSelectInputWidget
.static.supportsSimpleLabel
= false;
15103 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
15104 return $( '<input type="hidden">' );
15108 * Handles menu select events.
15111 * @param {OO.ui.RadioOptionWidget} item Selected menu item
15113 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
15114 this.setValue( item
.getData() );
15120 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
15121 value
= this.cleanUpValue( value
);
15122 this.radioSelectWidget
.selectItemByData( value
);
15123 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
15130 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
15131 this.radioSelectWidget
.setDisabled( state
);
15132 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
15137 * Set the options available for this input.
15139 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15142 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
15144 value
= this.getValue(),
15147 // Rebuild the radioSelect menu
15148 this.radioSelectWidget
15150 .addItems( options
.map( function ( opt
) {
15151 var optValue
= widget
.cleanUpValue( opt
.data
);
15152 return new OO
.ui
.RadioOptionWidget( {
15154 label
: opt
.label
!== undefined ? opt
.label
: optValue
15158 // Restore the previous value, or reset to something sensible
15159 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
15160 // Previous value is still available, ensure consistency with the radioSelect
15161 this.setValue( value
);
15163 // No longer valid, reset
15164 if ( options
.length
) {
15165 this.setValue( options
[ 0 ].data
);
15175 OO
.ui
.RadioSelectInputWidget
.prototype.gatherPreInfuseState = function ( node
) {
15176 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
);
15177 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
15182 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
15183 * size of the field as well as its presentation. In addition, these widgets can be configured
15184 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
15185 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
15186 * which modifies incoming values rather than validating them.
15187 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
15189 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15192 * // Example of a text input widget
15193 * var textInput = new OO.ui.TextInputWidget( {
15194 * value: 'Text input'
15196 * $( 'body' ).append( textInput.$element );
15198 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15201 * @extends OO.ui.InputWidget
15202 * @mixins OO.ui.mixin.IconElement
15203 * @mixins OO.ui.mixin.IndicatorElement
15204 * @mixins OO.ui.mixin.PendingElement
15205 * @mixins OO.ui.mixin.LabelElement
15208 * @param {Object} [config] Configuration options
15209 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
15210 * 'email' or 'url'. Ignored if `multiline` is true.
15212 * Some values of `type` result in additional behaviors:
15214 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
15215 * empties the text field
15216 * @cfg {string} [placeholder] Placeholder text
15217 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
15218 * instruct the browser to focus this widget.
15219 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
15220 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
15221 * @cfg {boolean} [multiline=false] Allow multiple lines of text
15222 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
15223 * specifies minimum number of rows to display.
15224 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
15225 * Use the #maxRows config to specify a maximum number of displayed rows.
15226 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
15227 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
15228 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
15229 * the value or placeholder text: `'before'` or `'after'`
15230 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
15231 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
15232 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
15233 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
15234 * (the value must contain only numbers); when RegExp, a regular expression that must match the
15235 * value for it to be considered valid; when Function, a function receiving the value as parameter
15236 * that must return true, or promise resolving to true, for it to be considered valid.
15238 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
15239 // Configuration initialization
15240 config
= $.extend( {
15242 labelPosition
: 'after'
15244 if ( config
.type
=== 'search' ) {
15245 if ( config
.icon
=== undefined ) {
15246 config
.icon
= 'search';
15248 // indicator: 'clear' is set dynamically later, depending on value
15250 if ( config
.required
) {
15251 if ( config
.indicator
=== undefined ) {
15252 config
.indicator
= 'required';
15256 // Parent constructor
15257 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
15259 // Mixin constructors
15260 OO
.ui
.mixin
.IconElement
.call( this, config
);
15261 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
15262 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
15263 OO
.ui
.mixin
.LabelElement
.call( this, config
);
15266 this.type
= this.getSaneType( config
);
15267 this.readOnly
= false;
15268 this.multiline
= !!config
.multiline
;
15269 this.autosize
= !!config
.autosize
;
15270 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
15271 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
15272 this.validate
= null;
15274 // Clone for resizing
15275 if ( this.autosize
) {
15276 this.$clone
= this.$input
15278 .insertAfter( this.$input
)
15279 .attr( 'aria-hidden', 'true' )
15280 .addClass( 'oo-ui-element-hidden' );
15283 this.setValidation( config
.validate
);
15284 this.setLabelPosition( config
.labelPosition
);
15288 keypress
: this.onKeyPress
.bind( this ),
15289 blur
: this.onBlur
.bind( this )
15292 focus
: this.onElementAttach
.bind( this )
15294 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
15295 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
15296 this.on( 'labelChange', this.updatePosition
.bind( this ) );
15297 this.connect( this, {
15298 change
: 'onChange',
15299 disable
: 'onDisable'
15304 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
15305 .append( this.$icon
, this.$indicator
);
15306 this.setReadOnly( !!config
.readOnly
);
15307 this.updateSearchIndicator();
15308 if ( config
.placeholder
) {
15309 this.$input
.attr( 'placeholder', config
.placeholder
);
15311 if ( config
.maxLength
!== undefined ) {
15312 this.$input
.attr( 'maxlength', config
.maxLength
);
15314 if ( config
.autofocus
) {
15315 this.$input
.attr( 'autofocus', 'autofocus' );
15317 if ( config
.required
) {
15318 this.$input
.attr( 'required', 'required' );
15319 this.$input
.attr( 'aria-required', 'true' );
15321 if ( config
.autocomplete
=== false ) {
15322 this.$input
.attr( 'autocomplete', 'off' );
15324 if ( this.multiline
&& config
.rows
) {
15325 this.$input
.attr( 'rows', config
.rows
);
15327 if ( this.label
|| config
.autosize
) {
15328 this.installParentChangeDetector();
15334 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
15335 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
15336 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
15337 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
15338 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
15340 /* Static Properties */
15342 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
15350 * An `enter` event is emitted when the user presses 'enter' inside the text box.
15352 * Not emitted if the input is multiline.
15360 * Handle icon mouse down events.
15363 * @param {jQuery.Event} e Mouse down event
15366 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
15367 if ( e
.which
=== 1 ) {
15368 this.$input
[ 0 ].focus();
15374 * Handle indicator mouse down events.
15377 * @param {jQuery.Event} e Mouse down event
15380 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
15381 if ( e
.which
=== 1 ) {
15382 if ( this.type
=== 'search' ) {
15383 // Clear the text field
15384 this.setValue( '' );
15386 this.$input
[ 0 ].focus();
15392 * Handle key press events.
15395 * @param {jQuery.Event} e Key press event
15396 * @fires enter If enter key is pressed and input is not multiline
15398 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
15399 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
15400 this.emit( 'enter', e
);
15405 * Handle blur events.
15408 * @param {jQuery.Event} e Blur event
15410 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
15411 this.setValidityFlag();
15415 * Handle element attach events.
15418 * @param {jQuery.Event} e Element attach event
15420 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
15421 // Any previously calculated size is now probably invalid if we reattached elsewhere
15422 this.valCache
= null;
15424 this.positionLabel();
15428 * Handle change events.
15430 * @param {string} value
15433 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
15434 this.updateSearchIndicator();
15435 this.setValidityFlag();
15440 * Handle disable events.
15442 * @param {boolean} disabled Element is disabled
15445 OO
.ui
.TextInputWidget
.prototype.onDisable = function () {
15446 this.updateSearchIndicator();
15450 * Check if the input is {@link #readOnly read-only}.
15452 * @return {boolean}
15454 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
15455 return this.readOnly
;
15459 * Set the {@link #readOnly read-only} state of the input.
15461 * @param {boolean} state Make input read-only
15464 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
15465 this.readOnly
= !!state
;
15466 this.$input
.prop( 'readOnly', this.readOnly
);
15467 this.updateSearchIndicator();
15472 * Support function for making #onElementAttach work across browsers.
15474 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
15475 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
15477 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
15478 * first time that the element gets attached to the documented.
15480 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
15481 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
15482 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
15485 if ( MutationObserver
) {
15486 // The new way. If only it wasn't so ugly.
15488 if ( this.$element
.closest( 'html' ).length
) {
15489 // Widget is attached already, do nothing. This breaks the functionality of this function when
15490 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
15491 // would require observation of the whole document, which would hurt performance of other,
15492 // more important code.
15496 // Find topmost node in the tree
15497 topmostNode
= this.$element
[ 0 ];
15498 while ( topmostNode
.parentNode
) {
15499 topmostNode
= topmostNode
.parentNode
;
15502 // We have no way to detect the $element being attached somewhere without observing the entire
15503 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
15504 // parent node of $element, and instead detect when $element is removed from it (and thus
15505 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
15506 // doesn't get attached, we end up back here and create the parent.
15508 mutationObserver
= new MutationObserver( function ( mutations
) {
15509 var i
, j
, removedNodes
;
15510 for ( i
= 0; i
< mutations
.length
; i
++ ) {
15511 removedNodes
= mutations
[ i
].removedNodes
;
15512 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
15513 if ( removedNodes
[ j
] === topmostNode
) {
15514 setTimeout( onRemove
, 0 );
15521 onRemove = function () {
15522 // If the node was attached somewhere else, report it
15523 if ( widget
.$element
.closest( 'html' ).length
) {
15524 widget
.onElementAttach();
15526 mutationObserver
.disconnect();
15527 widget
.installParentChangeDetector();
15530 // Create a fake parent and observe it
15531 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
15532 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
15534 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
15535 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
15536 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
15541 * Automatically adjust the size of the text input.
15543 * This only affects #multiline inputs that are {@link #autosize autosized}.
15547 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
15548 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
, idealHeight
;
15550 if ( this.multiline
&& this.autosize
&& this.$input
.val() !== this.valCache
) {
15552 .val( this.$input
.val() )
15553 .attr( 'rows', this.minRows
)
15554 // Set inline height property to 0 to measure scroll height
15555 .css( 'height', 0 );
15557 this.$clone
.removeClass( 'oo-ui-element-hidden' );
15559 this.valCache
= this.$input
.val();
15561 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
15563 // Remove inline height property to measure natural heights
15564 this.$clone
.css( 'height', '' );
15565 innerHeight
= this.$clone
.innerHeight();
15566 outerHeight
= this.$clone
.outerHeight();
15568 // Measure max rows height
15570 .attr( 'rows', this.maxRows
)
15571 .css( 'height', 'auto' )
15573 maxInnerHeight
= this.$clone
.innerHeight();
15575 // Difference between reported innerHeight and scrollHeight with no scrollbars present
15576 // Equals 1 on Blink-based browsers and 0 everywhere else
15577 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
15578 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
15580 this.$clone
.addClass( 'oo-ui-element-hidden' );
15582 // Only apply inline height when expansion beyond natural height is needed
15583 if ( idealHeight
> innerHeight
) {
15584 // Use the difference between the inner and outer height as a buffer
15585 this.$input
.css( 'height', idealHeight
+ ( outerHeight
- innerHeight
) );
15587 this.$input
.css( 'height', '' );
15597 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
15598 return config
.multiline
?
15599 $( '<textarea>' ) :
15600 $( '<input type="' + this.getSaneType( config
) + '" />' );
15604 * Get sanitized value for 'type' for given config.
15606 * @param {Object} config Configuration options
15607 * @return {string|null}
15610 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
15611 var type
= [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config
.type
) !== -1 ?
15614 return config
.multiline
? 'multiline' : type
;
15618 * Check if the input supports multiple lines.
15620 * @return {boolean}
15622 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
15623 return !!this.multiline
;
15627 * Check if the input automatically adjusts its size.
15629 * @return {boolean}
15631 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
15632 return !!this.autosize
;
15636 * Select the entire text of the input.
15640 OO
.ui
.TextInputWidget
.prototype.select = function () {
15641 this.$input
.select();
15646 * Focus the input and move the cursor to the end.
15648 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
15650 element
= this.$input
[ 0 ];
15652 if ( element
.selectionStart
!== undefined ) {
15653 element
.selectionStart
= element
.selectionEnd
= element
.value
.length
;
15654 } else if ( element
.createTextRange
) {
15656 textRange
= element
.createTextRange();
15657 textRange
.collapse( false );
15658 textRange
.select();
15663 * Set the validation pattern.
15665 * The validation pattern is either a regular expression, a function, or the symbolic name of a
15666 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
15667 * value must contain only numbers).
15669 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
15670 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
15672 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
15673 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
15674 this.validate
= validate
;
15676 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
15681 * Sets the 'invalid' flag appropriately.
15683 * @param {boolean} [isValid] Optionally override validation result
15685 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
15687 setFlag = function ( valid
) {
15689 widget
.$input
.attr( 'aria-invalid', 'true' );
15691 widget
.$input
.removeAttr( 'aria-invalid' );
15693 widget
.setFlags( { invalid
: !valid
} );
15696 if ( isValid
!== undefined ) {
15697 setFlag( isValid
);
15699 this.getValidity().then( function () {
15708 * Check if a value is valid.
15710 * This method returns a promise that resolves with a boolean `true` if the current value is
15711 * considered valid according to the supplied {@link #validate validation pattern}.
15714 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
15716 OO
.ui
.TextInputWidget
.prototype.isValid = function () {
15719 if ( this.validate
instanceof Function
) {
15720 result
= this.validate( this.getValue() );
15721 if ( $.isFunction( result
.promise
) ) {
15722 return result
.promise();
15724 return $.Deferred().resolve( !!result
).promise();
15727 return $.Deferred().resolve( !!this.getValue().match( this.validate
) ).promise();
15732 * Get the validity of current value.
15734 * This method returns a promise that resolves if the value is valid and rejects if
15735 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
15737 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
15739 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
15740 var result
, promise
;
15742 function rejectOrResolve( valid
) {
15744 return $.Deferred().resolve().promise();
15746 return $.Deferred().reject().promise();
15750 if ( this.validate
instanceof Function
) {
15751 result
= this.validate( this.getValue() );
15753 if ( $.isFunction( result
.promise
) ) {
15754 promise
= $.Deferred();
15756 result
.then( function ( valid
) {
15766 return promise
.promise();
15768 return rejectOrResolve( result
);
15771 return rejectOrResolve( this.getValue().match( this.validate
) );
15776 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
15778 * @param {string} labelPosition Label position, 'before' or 'after'
15781 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
15782 this.labelPosition
= labelPosition
;
15783 this.updatePosition();
15788 * Deprecated alias of #setLabelPosition
15790 * @deprecated Use setLabelPosition instead.
15792 OO
.ui
.TextInputWidget
.prototype.setPosition
=
15793 OO
.ui
.TextInputWidget
.prototype.setLabelPosition
;
15796 * Update the position of the inline label.
15798 * This method is called by #setLabelPosition, and can also be called on its own if
15799 * something causes the label to be mispositioned.
15803 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
15804 var after
= this.labelPosition
=== 'after';
15807 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
15808 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
15810 this.positionLabel();
15816 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
15817 * already empty or when it's not editable.
15819 OO
.ui
.TextInputWidget
.prototype.updateSearchIndicator = function () {
15820 if ( this.type
=== 'search' ) {
15821 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
15822 this.setIndicator( null );
15824 this.setIndicator( 'clear' );
15830 * Position the label by setting the correct padding on the input.
15835 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
15836 var after
, rtl
, property
;
15837 // Clear old values
15839 // Clear old values if present
15841 'padding-right': '',
15845 if ( this.label
) {
15846 this.$element
.append( this.$label
);
15848 this.$label
.detach();
15852 after
= this.labelPosition
=== 'after';
15853 rtl
= this.$element
.css( 'direction' ) === 'rtl';
15854 property
= after
=== rtl
? 'padding-left' : 'padding-right';
15856 this.$input
.css( property
, this.$label
.outerWidth( true ) );
15864 OO
.ui
.TextInputWidget
.prototype.gatherPreInfuseState = function ( node
) {
15866 state
= OO
.ui
.TextInputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
),
15867 $input
= $( node
).find( '.oo-ui-inputWidget-input' );
15868 state
.$input
= $input
; // shortcut for performance, used in InputWidget
15869 if ( this.multiline
) {
15870 state
.scrollTop
= $input
.scrollTop();
15878 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
15879 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
15880 if ( state
.scrollTop
!== undefined ) {
15881 this.$input
.scrollTop( state
.scrollTop
);
15886 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
15887 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
15888 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
15890 * - by typing a value in the text input field. If the value exactly matches the value of a menu
15891 * option, that option will appear to be selected.
15892 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
15895 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
15898 * // Example: A ComboBoxWidget.
15899 * var comboBox = new OO.ui.ComboBoxWidget( {
15900 * label: 'ComboBoxWidget',
15901 * input: { value: 'Option One' },
15904 * new OO.ui.MenuOptionWidget( {
15905 * data: 'Option 1',
15906 * label: 'Option One'
15908 * new OO.ui.MenuOptionWidget( {
15909 * data: 'Option 2',
15910 * label: 'Option Two'
15912 * new OO.ui.MenuOptionWidget( {
15913 * data: 'Option 3',
15914 * label: 'Option Three'
15916 * new OO.ui.MenuOptionWidget( {
15917 * data: 'Option 4',
15918 * label: 'Option Four'
15920 * new OO.ui.MenuOptionWidget( {
15921 * data: 'Option 5',
15922 * label: 'Option Five'
15927 * $( 'body' ).append( comboBox.$element );
15929 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
15932 * @extends OO.ui.Widget
15933 * @mixins OO.ui.mixin.TabIndexedElement
15936 * @param {Object} [config] Configuration options
15937 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
15938 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
15939 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
15940 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
15941 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
15943 OO
.ui
.ComboBoxWidget
= function OoUiComboBoxWidget( config
) {
15944 // Configuration initialization
15945 config
= config
|| {};
15947 // Parent constructor
15948 OO
.ui
.ComboBoxWidget
.parent
.call( this, config
);
15950 // Properties (must be set before TabIndexedElement constructor call)
15951 this.$indicator
= this.$( '<span>' );
15953 // Mixin constructors
15954 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
15957 this.$overlay
= config
.$overlay
|| this.$element
;
15958 this.input
= new OO
.ui
.TextInputWidget( $.extend(
15961 $indicator
: this.$indicator
,
15962 disabled
: this.isDisabled()
15966 this.input
.$input
.eq( 0 ).attr( {
15968 'aria-autocomplete': 'list'
15970 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
15974 $container
: this.input
.$element
,
15975 disabled
: this.isDisabled()
15981 this.$indicator
.on( {
15982 click
: this.onClick
.bind( this ),
15983 keypress
: this.onKeyPress
.bind( this )
15985 this.input
.connect( this, {
15986 change
: 'onInputChange',
15987 enter
: 'onInputEnter'
15989 this.menu
.connect( this, {
15990 choose
: 'onMenuChoose',
15991 add
: 'onMenuItemsChange',
15992 remove
: 'onMenuItemsChange'
15996 this.$element
.addClass( 'oo-ui-comboBoxWidget' ).append( this.input
.$element
);
15997 this.$overlay
.append( this.menu
.$element
);
15998 this.onMenuItemsChange();
16003 OO
.inheritClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.Widget
);
16004 OO
.mixinClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.mixin
.TabIndexedElement
);
16009 * Get the combobox's menu.
16010 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
16012 OO
.ui
.ComboBoxWidget
.prototype.getMenu = function () {
16017 * Get the combobox's text input widget.
16018 * @return {OO.ui.TextInputWidget} Text input widget
16020 OO
.ui
.ComboBoxWidget
.prototype.getInput = function () {
16025 * Handle input change events.
16028 * @param {string} value New value
16030 OO
.ui
.ComboBoxWidget
.prototype.onInputChange = function ( value
) {
16031 var match
= this.menu
.getItemFromData( value
);
16033 this.menu
.selectItem( match
);
16034 if ( this.menu
.getHighlightedItem() ) {
16035 this.menu
.highlightItem( match
);
16038 if ( !this.isDisabled() ) {
16039 this.menu
.toggle( true );
16044 * Handle mouse click events.
16048 * @param {jQuery.Event} e Mouse click event
16050 OO
.ui
.ComboBoxWidget
.prototype.onClick = function ( e
) {
16051 if ( !this.isDisabled() && e
.which
=== 1 ) {
16052 this.menu
.toggle();
16053 this.input
.$input
[ 0 ].focus();
16059 * Handle key press events.
16063 * @param {jQuery.Event} e Key press event
16065 OO
.ui
.ComboBoxWidget
.prototype.onKeyPress = function ( e
) {
16066 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
16067 this.menu
.toggle();
16068 this.input
.$input
[ 0 ].focus();
16074 * Handle input enter events.
16078 OO
.ui
.ComboBoxWidget
.prototype.onInputEnter = function () {
16079 if ( !this.isDisabled() ) {
16080 this.menu
.toggle( false );
16085 * Handle menu choose events.
16088 * @param {OO.ui.OptionWidget} item Chosen item
16090 OO
.ui
.ComboBoxWidget
.prototype.onMenuChoose = function ( item
) {
16091 this.input
.setValue( item
.getData() );
16095 * Handle menu item change events.
16099 OO
.ui
.ComboBoxWidget
.prototype.onMenuItemsChange = function () {
16100 var match
= this.menu
.getItemFromData( this.input
.getValue() );
16101 this.menu
.selectItem( match
);
16102 if ( this.menu
.getHighlightedItem() ) {
16103 this.menu
.highlightItem( match
);
16105 this.$element
.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu
.isEmpty() );
16111 OO
.ui
.ComboBoxWidget
.prototype.setDisabled = function ( disabled
) {
16113 OO
.ui
.ComboBoxWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
16115 if ( this.input
) {
16116 this.input
.setDisabled( this.isDisabled() );
16119 this.menu
.setDisabled( this.isDisabled() );
16126 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
16127 * be configured with a `label` option that is set to a string, a label node, or a function:
16129 * - String: a plaintext string
16130 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
16131 * label that includes a link or special styling, such as a gray color or additional graphical elements.
16132 * - Function: a function that will produce a string in the future. Functions are used
16133 * in cases where the value of the label is not currently defined.
16135 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
16136 * will come into focus when the label is clicked.
16139 * // Examples of LabelWidgets
16140 * var label1 = new OO.ui.LabelWidget( {
16141 * label: 'plaintext label'
16143 * var label2 = new OO.ui.LabelWidget( {
16144 * label: $( '<a href="default.html">jQuery label</a>' )
16146 * // Create a fieldset layout with fields for each example
16147 * var fieldset = new OO.ui.FieldsetLayout();
16148 * fieldset.addItems( [
16149 * new OO.ui.FieldLayout( label1 ),
16150 * new OO.ui.FieldLayout( label2 )
16152 * $( 'body' ).append( fieldset.$element );
16156 * @extends OO.ui.Widget
16157 * @mixins OO.ui.mixin.LabelElement
16160 * @param {Object} [config] Configuration options
16161 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
16162 * Clicking the label will focus the specified input field.
16164 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
16165 // Configuration initialization
16166 config
= config
|| {};
16168 // Parent constructor
16169 OO
.ui
.LabelWidget
.parent
.call( this, config
);
16171 // Mixin constructors
16172 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
16173 OO
.ui
.mixin
.TitledElement
.call( this, config
);
16176 this.input
= config
.input
;
16179 if ( this.input
instanceof OO
.ui
.InputWidget
) {
16180 this.$element
.on( 'click', this.onClick
.bind( this ) );
16184 this.$element
.addClass( 'oo-ui-labelWidget' );
16189 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
16190 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
16191 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
16193 /* Static Properties */
16195 OO
.ui
.LabelWidget
.static.tagName
= 'span';
16200 * Handles label mouse click events.
16203 * @param {jQuery.Event} e Mouse click event
16205 OO
.ui
.LabelWidget
.prototype.onClick = function () {
16206 this.input
.simulateLabelClick();
16211 * OptionWidgets are special elements that can be selected and configured with data. The
16212 * data is often unique for each option, but it does not have to be. OptionWidgets are used
16213 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
16214 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
16216 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16219 * @extends OO.ui.Widget
16220 * @mixins OO.ui.mixin.LabelElement
16221 * @mixins OO.ui.mixin.FlaggedElement
16224 * @param {Object} [config] Configuration options
16226 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
16227 // Configuration initialization
16228 config
= config
|| {};
16230 // Parent constructor
16231 OO
.ui
.OptionWidget
.parent
.call( this, config
);
16233 // Mixin constructors
16234 OO
.ui
.mixin
.ItemWidget
.call( this );
16235 OO
.ui
.mixin
.LabelElement
.call( this, config
);
16236 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
16239 this.selected
= false;
16240 this.highlighted
= false;
16241 this.pressed
= false;
16245 .data( 'oo-ui-optionWidget', this )
16246 .attr( 'role', 'option' )
16247 .attr( 'aria-selected', 'false' )
16248 .addClass( 'oo-ui-optionWidget' )
16249 .append( this.$label
);
16254 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
16255 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
16256 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
16257 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
16259 /* Static Properties */
16261 OO
.ui
.OptionWidget
.static.selectable
= true;
16263 OO
.ui
.OptionWidget
.static.highlightable
= true;
16265 OO
.ui
.OptionWidget
.static.pressable
= true;
16267 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
16272 * Check if the option can be selected.
16274 * @return {boolean} Item is selectable
16276 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
16277 return this.constructor.static.selectable
&& !this.isDisabled() && this.isVisible();
16281 * Check if the option can be highlighted. A highlight indicates that the option
16282 * may be selected when a user presses enter or clicks. Disabled items cannot
16285 * @return {boolean} Item is highlightable
16287 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
16288 return this.constructor.static.highlightable
&& !this.isDisabled() && this.isVisible();
16292 * Check if the option can be pressed. The pressed state occurs when a user mouses
16293 * down on an item, but has not yet let go of the mouse.
16295 * @return {boolean} Item is pressable
16297 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
16298 return this.constructor.static.pressable
&& !this.isDisabled() && this.isVisible();
16302 * Check if the option is selected.
16304 * @return {boolean} Item is selected
16306 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
16307 return this.selected
;
16311 * Check if the option is highlighted. A highlight indicates that the
16312 * item may be selected when a user presses enter or clicks.
16314 * @return {boolean} Item is highlighted
16316 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
16317 return this.highlighted
;
16321 * Check if the option is pressed. The pressed state occurs when a user mouses
16322 * down on an item, but has not yet let go of the mouse. The item may appear
16323 * selected, but it will not be selected until the user releases the mouse.
16325 * @return {boolean} Item is pressed
16327 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
16328 return this.pressed
;
16332 * Set the option’s selected state. In general, all modifications to the selection
16333 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
16334 * method instead of this method.
16336 * @param {boolean} [state=false] Select option
16339 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
16340 if ( this.constructor.static.selectable
) {
16341 this.selected
= !!state
;
16343 .toggleClass( 'oo-ui-optionWidget-selected', state
)
16344 .attr( 'aria-selected', state
.toString() );
16345 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
16346 this.scrollElementIntoView();
16348 this.updateThemeClasses();
16354 * Set the option’s highlighted state. In general, all programmatic
16355 * modifications to the highlight should be handled by the
16356 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
16357 * method instead of this method.
16359 * @param {boolean} [state=false] Highlight option
16362 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
16363 if ( this.constructor.static.highlightable
) {
16364 this.highlighted
= !!state
;
16365 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
16366 this.updateThemeClasses();
16372 * Set the option’s pressed state. In general, all
16373 * programmatic modifications to the pressed state should be handled by the
16374 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
16375 * method instead of this method.
16377 * @param {boolean} [state=false] Press option
16380 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
16381 if ( this.constructor.static.pressable
) {
16382 this.pressed
= !!state
;
16383 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
16384 this.updateThemeClasses();
16390 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
16391 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
16392 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
16393 * options. For more information about options and selects, please see the
16394 * [OOjs UI documentation on MediaWiki][1].
16397 * // Decorated options in a select widget
16398 * var select = new OO.ui.SelectWidget( {
16400 * new OO.ui.DecoratedOptionWidget( {
16402 * label: 'Option with icon',
16405 * new OO.ui.DecoratedOptionWidget( {
16407 * label: 'Option with indicator',
16408 * indicator: 'next'
16412 * $( 'body' ).append( select.$element );
16414 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16417 * @extends OO.ui.OptionWidget
16418 * @mixins OO.ui.mixin.IconElement
16419 * @mixins OO.ui.mixin.IndicatorElement
16422 * @param {Object} [config] Configuration options
16424 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
16425 // Parent constructor
16426 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
16428 // Mixin constructors
16429 OO
.ui
.mixin
.IconElement
.call( this, config
);
16430 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
16434 .addClass( 'oo-ui-decoratedOptionWidget' )
16435 .prepend( this.$icon
)
16436 .append( this.$indicator
);
16441 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
16442 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
16443 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
16446 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
16447 * can be selected and configured with data. The class is
16448 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
16449 * [OOjs UI documentation on MediaWiki] [1] for more information.
16451 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
16454 * @extends OO.ui.DecoratedOptionWidget
16455 * @mixins OO.ui.mixin.ButtonElement
16456 * @mixins OO.ui.mixin.TabIndexedElement
16457 * @mixins OO.ui.mixin.TitledElement
16460 * @param {Object} [config] Configuration options
16462 OO
.ui
.ButtonOptionWidget
= function OoUiButtonOptionWidget( config
) {
16463 // Configuration initialization
16464 config
= config
|| {};
16466 // Parent constructor
16467 OO
.ui
.ButtonOptionWidget
.parent
.call( this, config
);
16469 // Mixin constructors
16470 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
16471 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
16472 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, {
16473 $tabIndexed
: this.$button
,
16478 this.$element
.addClass( 'oo-ui-buttonOptionWidget' );
16479 this.$button
.append( this.$element
.contents() );
16480 this.$element
.append( this.$button
);
16485 OO
.inheritClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
16486 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.ButtonElement
);
16487 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.TitledElement
);
16488 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.TabIndexedElement
);
16490 /* Static Properties */
16492 // Allow button mouse down events to pass through so they can be handled by the parent select widget
16493 OO
.ui
.ButtonOptionWidget
.static.cancelButtonMouseDownEvents
= false;
16495 OO
.ui
.ButtonOptionWidget
.static.highlightable
= false;
16502 OO
.ui
.ButtonOptionWidget
.prototype.setSelected = function ( state
) {
16503 OO
.ui
.ButtonOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
16505 if ( this.constructor.static.selectable
) {
16506 this.setActive( state
);
16513 * RadioOptionWidget is an option widget that looks like a radio button.
16514 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
16515 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
16517 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
16520 * @extends OO.ui.OptionWidget
16523 * @param {Object} [config] Configuration options
16525 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
16526 // Configuration initialization
16527 config
= config
|| {};
16529 // Properties (must be done before parent constructor which calls #setDisabled)
16530 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
16532 // Parent constructor
16533 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
16536 this.radio
.$input
.on( 'focus', this.onInputFocus
.bind( this ) );
16539 // Remove implicit role, we're handling it ourselves
16540 this.radio
.$input
.attr( 'role', 'presentation' );
16542 .addClass( 'oo-ui-radioOptionWidget' )
16543 .attr( 'role', 'radio' )
16544 .attr( 'aria-checked', 'false' )
16545 .removeAttr( 'aria-selected' )
16546 .prepend( this.radio
.$element
);
16551 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
16553 /* Static Properties */
16555 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
16557 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
16559 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
16561 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
16566 * @param {jQuery.Event} e Focus event
16569 OO
.ui
.RadioOptionWidget
.prototype.onInputFocus = function () {
16570 this.radio
.$input
.blur();
16571 this.$element
.parent().focus();
16577 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
16578 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
16580 this.radio
.setSelected( state
);
16582 .attr( 'aria-checked', state
.toString() )
16583 .removeAttr( 'aria-selected' );
16591 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
16592 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
16594 this.radio
.setDisabled( this.isDisabled() );
16600 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
16601 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
16602 * the [OOjs UI documentation on MediaWiki] [1] for more information.
16604 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16607 * @extends OO.ui.DecoratedOptionWidget
16610 * @param {Object} [config] Configuration options
16612 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
16613 // Configuration initialization
16614 config
= $.extend( { icon
: 'check' }, config
);
16616 // Parent constructor
16617 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
16621 .attr( 'role', 'menuitem' )
16622 .addClass( 'oo-ui-menuOptionWidget' );
16627 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
16629 /* Static Properties */
16631 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
16634 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
16635 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
16638 * var myDropdown = new OO.ui.DropdownWidget( {
16641 * new OO.ui.MenuSectionOptionWidget( {
16644 * new OO.ui.MenuOptionWidget( {
16646 * label: 'Welsh Corgi'
16648 * new OO.ui.MenuOptionWidget( {
16650 * label: 'Standard Poodle'
16652 * new OO.ui.MenuSectionOptionWidget( {
16655 * new OO.ui.MenuOptionWidget( {
16662 * $( 'body' ).append( myDropdown.$element );
16666 * @extends OO.ui.DecoratedOptionWidget
16669 * @param {Object} [config] Configuration options
16671 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
16672 // Parent constructor
16673 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
16676 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
16681 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
16683 /* Static Properties */
16685 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
16687 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
16690 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
16692 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
16693 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
16697 * @extends OO.ui.DecoratedOptionWidget
16700 * @param {Object} [config] Configuration options
16701 * @cfg {number} [level] Indentation level
16702 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
16704 OO
.ui
.OutlineOptionWidget
= function OoUiOutlineOptionWidget( config
) {
16705 // Configuration initialization
16706 config
= config
|| {};
16708 // Parent constructor
16709 OO
.ui
.OutlineOptionWidget
.parent
.call( this, config
);
16713 this.movable
= !!config
.movable
;
16714 this.removable
= !!config
.removable
;
16717 this.$element
.addClass( 'oo-ui-outlineOptionWidget' );
16718 this.setLevel( config
.level
);
16723 OO
.inheritClass( OO
.ui
.OutlineOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
16725 /* Static Properties */
16727 OO
.ui
.OutlineOptionWidget
.static.highlightable
= false;
16729 OO
.ui
.OutlineOptionWidget
.static.scrollIntoViewOnSelect
= true;
16731 OO
.ui
.OutlineOptionWidget
.static.levelClass
= 'oo-ui-outlineOptionWidget-level-';
16733 OO
.ui
.OutlineOptionWidget
.static.levels
= 3;
16738 * Check if item is movable.
16740 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16742 * @return {boolean} Item is movable
16744 OO
.ui
.OutlineOptionWidget
.prototype.isMovable = function () {
16745 return this.movable
;
16749 * Check if item is removable.
16751 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16753 * @return {boolean} Item is removable
16755 OO
.ui
.OutlineOptionWidget
.prototype.isRemovable = function () {
16756 return this.removable
;
16760 * Get indentation level.
16762 * @return {number} Indentation level
16764 OO
.ui
.OutlineOptionWidget
.prototype.getLevel = function () {
16771 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16773 * @param {boolean} movable Item is movable
16776 OO
.ui
.OutlineOptionWidget
.prototype.setMovable = function ( movable
) {
16777 this.movable
= !!movable
;
16778 this.updateThemeClasses();
16783 * Set removability.
16785 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16787 * @param {boolean} movable Item is removable
16790 OO
.ui
.OutlineOptionWidget
.prototype.setRemovable = function ( removable
) {
16791 this.removable
= !!removable
;
16792 this.updateThemeClasses();
16797 * Set indentation level.
16799 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
16802 OO
.ui
.OutlineOptionWidget
.prototype.setLevel = function ( level
) {
16803 var levels
= this.constructor.static.levels
,
16804 levelClass
= this.constructor.static.levelClass
,
16807 this.level
= level
? Math
.max( 0, Math
.min( levels
- 1, level
) ) : 0;
16809 if ( this.level
=== i
) {
16810 this.$element
.addClass( levelClass
+ i
);
16812 this.$element
.removeClass( levelClass
+ i
);
16815 this.updateThemeClasses();
16821 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
16823 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
16824 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
16828 * @extends OO.ui.OptionWidget
16831 * @param {Object} [config] Configuration options
16833 OO
.ui
.TabOptionWidget
= function OoUiTabOptionWidget( config
) {
16834 // Configuration initialization
16835 config
= config
|| {};
16837 // Parent constructor
16838 OO
.ui
.TabOptionWidget
.parent
.call( this, config
);
16841 this.$element
.addClass( 'oo-ui-tabOptionWidget' );
16846 OO
.inheritClass( OO
.ui
.TabOptionWidget
, OO
.ui
.OptionWidget
);
16848 /* Static Properties */
16850 OO
.ui
.TabOptionWidget
.static.highlightable
= false;
16853 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
16854 * By default, each popup has an anchor that points toward its origin.
16855 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
16858 * // A popup widget.
16859 * var popup = new OO.ui.PopupWidget( {
16860 * $content: $( '<p>Hi there!</p>' ),
16865 * $( 'body' ).append( popup.$element );
16866 * // To display the popup, toggle the visibility to 'true'.
16867 * popup.toggle( true );
16869 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
16872 * @extends OO.ui.Widget
16873 * @mixins OO.ui.mixin.LabelElement
16876 * @param {Object} [config] Configuration options
16877 * @cfg {number} [width=320] Width of popup in pixels
16878 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
16879 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
16880 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
16881 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
16882 * popup is leaning towards the right of the screen.
16883 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
16884 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
16885 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
16886 * sentence in the given language.
16887 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
16888 * See the [OOjs UI docs on MediaWiki][3] for an example.
16889 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
16890 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
16891 * @cfg {jQuery} [$content] Content to append to the popup's body
16892 * @cfg {jQuery} [$footer] Content to append to the popup's footer
16893 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
16894 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
16895 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
16897 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
16898 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
16900 * @cfg {boolean} [padded] Add padding to the popup's body
16902 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
16903 // Configuration initialization
16904 config
= config
|| {};
16906 // Parent constructor
16907 OO
.ui
.PopupWidget
.parent
.call( this, config
);
16909 // Properties (must be set before ClippableElement constructor call)
16910 this.$body
= $( '<div>' );
16911 this.$popup
= $( '<div>' );
16913 // Mixin constructors
16914 OO
.ui
.mixin
.LabelElement
.call( this, config
);
16915 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
16916 $clippable
: this.$body
,
16917 $clippableContainer
: this.$popup
16921 this.$head
= $( '<div>' );
16922 this.$footer
= $( '<div>' );
16923 this.$anchor
= $( '<div>' );
16924 // If undefined, will be computed lazily in updateDimensions()
16925 this.$container
= config
.$container
;
16926 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
16927 this.autoClose
= !!config
.autoClose
;
16928 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
16929 this.transitionTimeout
= null;
16930 this.anchor
= null;
16931 this.width
= config
.width
!== undefined ? config
.width
: 320;
16932 this.height
= config
.height
!== undefined ? config
.height
: null;
16933 this.setAlignment( config
.align
);
16934 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
16935 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
16936 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
16939 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
16942 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
16943 this.$body
.addClass( 'oo-ui-popupWidget-body' );
16944 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
16946 .addClass( 'oo-ui-popupWidget-head' )
16947 .append( this.$label
, this.closeButton
.$element
);
16948 this.$footer
.addClass( 'oo-ui-popupWidget-footer' );
16949 if ( !config
.head
) {
16950 this.$head
.addClass( 'oo-ui-element-hidden' );
16952 if ( !config
.$footer
) {
16953 this.$footer
.addClass( 'oo-ui-element-hidden' );
16956 .addClass( 'oo-ui-popupWidget-popup' )
16957 .append( this.$head
, this.$body
, this.$footer
);
16959 .addClass( 'oo-ui-popupWidget' )
16960 .append( this.$popup
, this.$anchor
);
16961 // Move content, which was added to #$element by OO.ui.Widget, to the body
16962 if ( config
.$content
instanceof jQuery
) {
16963 this.$body
.append( config
.$content
);
16965 if ( config
.$footer
instanceof jQuery
) {
16966 this.$footer
.append( config
.$footer
);
16968 if ( config
.padded
) {
16969 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
16972 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
16973 // that reference properties not initialized at that time of parent class construction
16974 // TODO: Find a better way to handle post-constructor setup
16975 this.visible
= false;
16976 this.$element
.addClass( 'oo-ui-element-hidden' );
16981 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
16982 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
16983 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
16988 * Handles mouse down events.
16991 * @param {MouseEvent} e Mouse down event
16993 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
16995 this.isVisible() &&
16996 !$.contains( this.$element
[ 0 ], e
.target
) &&
16997 ( !this.$autoCloseIgnore
|| !this.$autoCloseIgnore
.has( e
.target
).length
)
16999 this.toggle( false );
17004 * Bind mouse down listener.
17008 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
17009 // Capture clicks outside popup
17010 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler
);
17014 * Handles close button click events.
17018 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
17019 if ( this.isVisible() ) {
17020 this.toggle( false );
17025 * Unbind mouse down listener.
17029 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
17030 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler
);
17034 * Handles key down events.
17037 * @param {KeyboardEvent} e Key down event
17039 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
17041 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
17044 this.toggle( false );
17045 e
.preventDefault();
17046 e
.stopPropagation();
17051 * Bind key down listener.
17055 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
17056 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler
);
17060 * Unbind key down listener.
17064 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
17065 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler
);
17069 * Show, hide, or toggle the visibility of the anchor.
17071 * @param {boolean} [show] Show anchor, omit to toggle
17073 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
17074 show
= show
=== undefined ? !this.anchored
: !!show
;
17076 if ( this.anchored
!== show
) {
17078 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
17080 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
17082 this.anchored
= show
;
17087 * Check if the anchor is visible.
17089 * @return {boolean} Anchor is visible
17091 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
17092 return this.anchor
;
17098 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
17100 show
= show
=== undefined ? !this.isVisible() : !!show
;
17102 change
= show
!== this.isVisible();
17105 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
17109 if ( this.autoClose
) {
17110 this.bindMouseDownListener();
17111 this.bindKeyDownListener();
17113 this.updateDimensions();
17114 this.toggleClipping( true );
17116 this.toggleClipping( false );
17117 if ( this.autoClose
) {
17118 this.unbindMouseDownListener();
17119 this.unbindKeyDownListener();
17128 * Set the size of the popup.
17130 * Changing the size may also change the popup's position depending on the alignment.
17132 * @param {number} width Width in pixels
17133 * @param {number} height Height in pixels
17134 * @param {boolean} [transition=false] Use a smooth transition
17137 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
17138 this.width
= width
;
17139 this.height
= height
!== undefined ? height
: null;
17140 if ( this.isVisible() ) {
17141 this.updateDimensions( transition
);
17146 * Update the size and position.
17148 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
17149 * be called automatically.
17151 * @param {boolean} [transition=false] Use a smooth transition
17154 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
17155 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
17156 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
17157 align
= this.align
,
17160 if ( !this.$container
) {
17161 // Lazy-initialize $container if not specified in constructor
17162 this.$container
= $( this.getClosestScrollableElementContainer() );
17165 // Set height and width before measuring things, since it might cause our measurements
17166 // to change (e.g. due to scrollbars appearing or disappearing)
17169 height
: this.height
!== null ? this.height
: 'auto'
17172 // If we are in RTL, we need to flip the alignment, unless it is center
17173 if ( align
=== 'forwards' || align
=== 'backwards' ) {
17174 if ( this.$container
.css( 'direction' ) === 'rtl' ) {
17175 align
= ( { forwards
: 'force-left', backwards
: 'force-right' } )[ this.align
];
17177 align
= ( { forwards
: 'force-right', backwards
: 'force-left' } )[ this.align
];
17182 // Compute initial popupOffset based on alignment
17183 popupOffset
= this.width
* ( { 'force-left': -1, center
: -0.5, 'force-right': 0 } )[ align
];
17185 // Figure out if this will cause the popup to go beyond the edge of the container
17186 originOffset
= this.$element
.offset().left
;
17187 containerLeft
= this.$container
.offset().left
;
17188 containerWidth
= this.$container
.innerWidth();
17189 containerRight
= containerLeft
+ containerWidth
;
17190 popupLeft
= popupOffset
- this.containerPadding
;
17191 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
17192 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
17193 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
17195 // Adjust offset to make the popup not go beyond the edge, if needed
17196 if ( overlapRight
< 0 ) {
17197 popupOffset
+= overlapRight
;
17198 } else if ( overlapLeft
< 0 ) {
17199 popupOffset
-= overlapLeft
;
17202 // Adjust offset to avoid anchor being rendered too close to the edge
17203 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
17204 // TODO: Find a measurement that works for CSS anchors and image anchors
17205 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
17206 if ( popupOffset
+ this.width
< anchorWidth
) {
17207 popupOffset
= anchorWidth
- this.width
;
17208 } else if ( -popupOffset
< anchorWidth
) {
17209 popupOffset
= -anchorWidth
;
17212 // Prevent transition from being interrupted
17213 clearTimeout( this.transitionTimeout
);
17214 if ( transition
) {
17215 // Enable transition
17216 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
17219 // Position body relative to anchor
17220 this.$popup
.css( 'margin-left', popupOffset
);
17222 if ( transition
) {
17223 // Prevent transitioning after transition is complete
17224 this.transitionTimeout
= setTimeout( function () {
17225 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
17228 // Prevent transitioning immediately
17229 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
17232 // Reevaluate clipping state since we've relocated and resized the popup
17239 * Set popup alignment
17240 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17241 * `backwards` or `forwards`.
17243 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
17244 // Validate alignment and transform deprecated values
17245 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
17246 this.align
= { left
: 'force-right', right
: 'force-left' }[ align
] || align
;
17248 this.align
= 'center';
17253 * Get popup alignment
17254 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17255 * `backwards` or `forwards`.
17257 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
17262 * Progress bars visually display the status of an operation, such as a download,
17263 * and can be either determinate or indeterminate:
17265 * - **determinate** process bars show the percent of an operation that is complete.
17267 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
17268 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
17269 * not use percentages.
17271 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
17274 * // Examples of determinate and indeterminate progress bars.
17275 * var progressBar1 = new OO.ui.ProgressBarWidget( {
17278 * var progressBar2 = new OO.ui.ProgressBarWidget();
17280 * // Create a FieldsetLayout to layout progress bars
17281 * var fieldset = new OO.ui.FieldsetLayout;
17282 * fieldset.addItems( [
17283 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
17284 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
17286 * $( 'body' ).append( fieldset.$element );
17289 * @extends OO.ui.Widget
17292 * @param {Object} [config] Configuration options
17293 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
17294 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
17295 * By default, the progress bar is indeterminate.
17297 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
17298 // Configuration initialization
17299 config
= config
|| {};
17301 // Parent constructor
17302 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
17305 this.$bar
= $( '<div>' );
17306 this.progress
= null;
17309 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
17310 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
17313 role
: 'progressbar',
17314 'aria-valuemin': 0,
17315 'aria-valuemax': 100
17317 .addClass( 'oo-ui-progressBarWidget' )
17318 .append( this.$bar
);
17323 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
17325 /* Static Properties */
17327 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
17332 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
17334 * @return {number|boolean} Progress percent
17336 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
17337 return this.progress
;
17341 * Set the percent of the process completed or `false` for an indeterminate process.
17343 * @param {number|boolean} progress Progress percent or `false` for indeterminate
17345 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
17346 this.progress
= progress
;
17348 if ( progress
!== false ) {
17349 this.$bar
.css( 'width', this.progress
+ '%' );
17350 this.$element
.attr( 'aria-valuenow', this.progress
);
17352 this.$bar
.css( 'width', '' );
17353 this.$element
.removeAttr( 'aria-valuenow' );
17355 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress
);
17359 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
17360 * and a menu of search results, which is displayed beneath the query
17361 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
17362 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
17363 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
17365 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
17366 * the [OOjs UI demos][1] for an example.
17368 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
17371 * @extends OO.ui.Widget
17374 * @param {Object} [config] Configuration options
17375 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
17376 * @cfg {string} [value] Initial query value
17378 OO
.ui
.SearchWidget
= function OoUiSearchWidget( config
) {
17379 // Configuration initialization
17380 config
= config
|| {};
17382 // Parent constructor
17383 OO
.ui
.SearchWidget
.parent
.call( this, config
);
17386 this.query
= new OO
.ui
.TextInputWidget( {
17388 placeholder
: config
.placeholder
,
17389 value
: config
.value
17391 this.results
= new OO
.ui
.SelectWidget();
17392 this.$query
= $( '<div>' );
17393 this.$results
= $( '<div>' );
17396 this.query
.connect( this, {
17397 change
: 'onQueryChange',
17398 enter
: 'onQueryEnter'
17400 this.query
.$input
.on( 'keydown', this.onQueryKeydown
.bind( this ) );
17404 .addClass( 'oo-ui-searchWidget-query' )
17405 .append( this.query
.$element
);
17407 .addClass( 'oo-ui-searchWidget-results' )
17408 .append( this.results
.$element
);
17410 .addClass( 'oo-ui-searchWidget' )
17411 .append( this.$results
, this.$query
);
17416 OO
.inheritClass( OO
.ui
.SearchWidget
, OO
.ui
.Widget
);
17421 * Handle query key down events.
17424 * @param {jQuery.Event} e Key down event
17426 OO
.ui
.SearchWidget
.prototype.onQueryKeydown = function ( e
) {
17427 var highlightedItem
, nextItem
,
17428 dir
= e
.which
=== OO
.ui
.Keys
.DOWN
? 1 : ( e
.which
=== OO
.ui
.Keys
.UP
? -1 : 0 );
17431 highlightedItem
= this.results
.getHighlightedItem();
17432 if ( !highlightedItem
) {
17433 highlightedItem
= this.results
.getSelectedItem();
17435 nextItem
= this.results
.getRelativeSelectableItem( highlightedItem
, dir
);
17436 this.results
.highlightItem( nextItem
);
17437 nextItem
.scrollElementIntoView();
17442 * Handle select widget select events.
17444 * Clears existing results. Subclasses should repopulate items according to new query.
17447 * @param {string} value New value
17449 OO
.ui
.SearchWidget
.prototype.onQueryChange = function () {
17451 this.results
.clearItems();
17455 * Handle select widget enter key events.
17457 * Chooses highlighted item.
17460 * @param {string} value New value
17462 OO
.ui
.SearchWidget
.prototype.onQueryEnter = function () {
17464 this.results
.chooseItem( this.results
.getHighlightedItem() );
17468 * Get the query input.
17470 * @return {OO.ui.TextInputWidget} Query input
17472 OO
.ui
.SearchWidget
.prototype.getQuery = function () {
17477 * Get the search results menu.
17479 * @return {OO.ui.SelectWidget} Menu of search results
17481 OO
.ui
.SearchWidget
.prototype.getResults = function () {
17482 return this.results
;
17486 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
17487 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
17488 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
17491 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
17492 * information, please see the [OOjs UI documentation on MediaWiki][1].
17495 * // Example of a select widget with three options
17496 * var select = new OO.ui.SelectWidget( {
17498 * new OO.ui.OptionWidget( {
17500 * label: 'Option One',
17502 * new OO.ui.OptionWidget( {
17504 * label: 'Option Two',
17506 * new OO.ui.OptionWidget( {
17508 * label: 'Option Three',
17512 * $( 'body' ).append( select.$element );
17514 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17518 * @extends OO.ui.Widget
17519 * @mixins OO.ui.mixin.GroupWidget
17522 * @param {Object} [config] Configuration options
17523 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
17524 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
17525 * the [OOjs UI documentation on MediaWiki] [2] for examples.
17526 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17528 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
17529 // Configuration initialization
17530 config
= config
|| {};
17532 // Parent constructor
17533 OO
.ui
.SelectWidget
.parent
.call( this, config
);
17535 // Mixin constructors
17536 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
17539 this.pressed
= false;
17540 this.selecting
= null;
17541 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
17542 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
17543 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
17544 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
17545 this.keyPressBuffer
= '';
17546 this.keyPressBufferTimer
= null;
17549 this.connect( this, {
17552 this.$element
.on( {
17553 mousedown
: this.onMouseDown
.bind( this ),
17554 mouseover
: this.onMouseOver
.bind( this ),
17555 mouseleave
: this.onMouseLeave
.bind( this )
17560 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
17561 .attr( 'role', 'listbox' );
17562 if ( Array
.isArray( config
.items
) ) {
17563 this.addItems( config
.items
);
17569 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
17571 // Need to mixin base class as well
17572 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupElement
);
17573 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
17576 OO
.ui
.SelectWidget
.static.passAllFilter = function () {
17585 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
17587 * @param {OO.ui.OptionWidget|null} item Highlighted item
17593 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
17594 * pressed state of an option.
17596 * @param {OO.ui.OptionWidget|null} item Pressed item
17602 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
17604 * @param {OO.ui.OptionWidget|null} item Selected item
17609 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
17610 * @param {OO.ui.OptionWidget} item Chosen item
17616 * An `add` event is emitted when options are added to the select with the #addItems method.
17618 * @param {OO.ui.OptionWidget[]} items Added items
17619 * @param {number} index Index of insertion point
17625 * A `remove` event is emitted when options are removed from the select with the #clearItems
17626 * or #removeItems methods.
17628 * @param {OO.ui.OptionWidget[]} items Removed items
17634 * Handle mouse down events.
17637 * @param {jQuery.Event} e Mouse down event
17639 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
17642 if ( !this.isDisabled() && e
.which
=== 1 ) {
17643 this.togglePressed( true );
17644 item
= this.getTargetItem( e
);
17645 if ( item
&& item
.isSelectable() ) {
17646 this.pressItem( item
);
17647 this.selecting
= item
;
17648 OO
.ui
.addCaptureEventListener(
17649 this.getElementDocument(),
17651 this.onMouseUpHandler
17653 OO
.ui
.addCaptureEventListener(
17654 this.getElementDocument(),
17656 this.onMouseMoveHandler
17664 * Handle mouse up events.
17667 * @param {jQuery.Event} e Mouse up event
17669 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
17672 this.togglePressed( false );
17673 if ( !this.selecting
) {
17674 item
= this.getTargetItem( e
);
17675 if ( item
&& item
.isSelectable() ) {
17676 this.selecting
= item
;
17679 if ( !this.isDisabled() && e
.which
=== 1 && this.selecting
) {
17680 this.pressItem( null );
17681 this.chooseItem( this.selecting
);
17682 this.selecting
= null;
17685 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup',
17686 this.onMouseUpHandler
);
17687 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mousemove',
17688 this.onMouseMoveHandler
);
17694 * Handle mouse move events.
17697 * @param {jQuery.Event} e Mouse move event
17699 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
17702 if ( !this.isDisabled() && this.pressed
) {
17703 item
= this.getTargetItem( e
);
17704 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
17705 this.pressItem( item
);
17706 this.selecting
= item
;
17713 * Handle mouse over events.
17716 * @param {jQuery.Event} e Mouse over event
17718 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
17721 if ( !this.isDisabled() ) {
17722 item
= this.getTargetItem( e
);
17723 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
17729 * Handle mouse leave events.
17732 * @param {jQuery.Event} e Mouse over event
17734 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
17735 if ( !this.isDisabled() ) {
17736 this.highlightItem( null );
17742 * Handle key down events.
17745 * @param {jQuery.Event} e Key down event
17747 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
17750 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
17752 if ( !this.isDisabled() && this.isVisible() ) {
17753 switch ( e
.keyCode
) {
17754 case OO
.ui
.Keys
.ENTER
:
17755 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
17756 // Was only highlighted, now let's select it. No-op if already selected.
17757 this.chooseItem( currentItem
);
17761 case OO
.ui
.Keys
.UP
:
17762 case OO
.ui
.Keys
.LEFT
:
17763 this.clearKeyPressBuffer();
17764 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
17767 case OO
.ui
.Keys
.DOWN
:
17768 case OO
.ui
.Keys
.RIGHT
:
17769 this.clearKeyPressBuffer();
17770 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
17773 case OO
.ui
.Keys
.ESCAPE
:
17774 case OO
.ui
.Keys
.TAB
:
17775 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
17776 currentItem
.setHighlighted( false );
17778 this.unbindKeyDownListener();
17779 this.unbindKeyPressListener();
17780 // Don't prevent tabbing away / defocusing
17786 if ( nextItem
.constructor.static.highlightable
) {
17787 this.highlightItem( nextItem
);
17789 this.chooseItem( nextItem
);
17791 nextItem
.scrollElementIntoView();
17795 // Can't just return false, because e is not always a jQuery event
17796 e
.preventDefault();
17797 e
.stopPropagation();
17803 * Bind key down listener.
17807 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
17808 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler
);
17812 * Unbind key down listener.
17816 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
17817 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler
);
17821 * Clear the key-press buffer
17825 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
17826 if ( this.keyPressBufferTimer
) {
17827 clearTimeout( this.keyPressBufferTimer
);
17828 this.keyPressBufferTimer
= null;
17830 this.keyPressBuffer
= '';
17834 * Handle key press events.
17837 * @param {jQuery.Event} e Key press event
17839 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
17840 var c
, filter
, item
;
17842 if ( !e
.charCode
) {
17843 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
17844 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
17849 if ( String
.fromCodePoint
) {
17850 c
= String
.fromCodePoint( e
.charCode
);
17852 c
= String
.fromCharCode( e
.charCode
);
17855 if ( this.keyPressBufferTimer
) {
17856 clearTimeout( this.keyPressBufferTimer
);
17858 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
17860 item
= this.getHighlightedItem() || this.getSelectedItem();
17862 if ( this.keyPressBuffer
=== c
) {
17863 // Common (if weird) special case: typing "xxxx" will cycle through all
17864 // the items beginning with "x".
17866 item
= this.getRelativeSelectableItem( item
, 1 );
17869 this.keyPressBuffer
+= c
;
17872 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
17873 if ( !item
|| !filter( item
) ) {
17874 item
= this.getRelativeSelectableItem( item
, 1, filter
);
17877 if ( item
.constructor.static.highlightable
) {
17878 this.highlightItem( item
);
17880 this.chooseItem( item
);
17882 item
.scrollElementIntoView();
17889 * Get a matcher for the specific string
17892 * @param {string} s String to match against items
17893 * @param {boolean} [exact=false] Only accept exact matches
17894 * @return {Function} function ( OO.ui.OptionItem ) => boolean
17896 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
17899 if ( s
.normalize
) {
17902 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
17903 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
17907 re
= new RegExp( re
, 'i' );
17908 return function ( item
) {
17909 var l
= item
.getLabel();
17910 if ( typeof l
!== 'string' ) {
17911 l
= item
.$label
.text();
17913 if ( l
.normalize
) {
17916 return re
.test( l
);
17921 * Bind key press listener.
17925 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
17926 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler
);
17930 * Unbind key down listener.
17932 * If you override this, be sure to call this.clearKeyPressBuffer() from your
17937 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
17938 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler
);
17939 this.clearKeyPressBuffer();
17943 * Visibility change handler
17946 * @param {boolean} visible
17948 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
17950 this.clearKeyPressBuffer();
17955 * Get the closest item to a jQuery.Event.
17958 * @param {jQuery.Event} e
17959 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
17961 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
17962 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
17966 * Get selected item.
17968 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
17970 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
17973 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
17974 if ( this.items
[ i
].isSelected() ) {
17975 return this.items
[ i
];
17982 * Get highlighted item.
17984 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
17986 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
17989 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
17990 if ( this.items
[ i
].isHighlighted() ) {
17991 return this.items
[ i
];
17998 * Toggle pressed state.
18000 * Press is a state that occurs when a user mouses down on an item, but
18001 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
18002 * until the user releases the mouse.
18004 * @param {boolean} pressed An option is being pressed
18006 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
18007 if ( pressed
=== undefined ) {
18008 pressed
= !this.pressed
;
18010 if ( pressed
!== this.pressed
) {
18012 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
18013 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
18014 this.pressed
= pressed
;
18019 * Highlight an option. If the `item` param is omitted, no options will be highlighted
18020 * and any existing highlight will be removed. The highlight is mutually exclusive.
18022 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
18026 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
18027 var i
, len
, highlighted
,
18030 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18031 highlighted
= this.items
[ i
] === item
;
18032 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
18033 this.items
[ i
].setHighlighted( highlighted
);
18038 this.emit( 'highlight', item
);
18045 * Fetch an item by its label.
18047 * @param {string} label Label of the item to select.
18048 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18049 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
18051 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
18052 var i
, item
, found
,
18053 len
= this.items
.length
,
18054 filter
= this.getItemMatcher( label
, true );
18056 for ( i
= 0; i
< len
; i
++ ) {
18057 item
= this.items
[ i
];
18058 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18065 filter
= this.getItemMatcher( label
, false );
18066 for ( i
= 0; i
< len
; i
++ ) {
18067 item
= this.items
[ i
];
18068 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18084 * Programmatically select an option by its label. If the item does not exist,
18085 * all options will be deselected.
18087 * @param {string} [label] Label of the item to select.
18088 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18092 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
18093 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
18094 if ( label
=== undefined || !itemFromLabel
) {
18095 return this.selectItem();
18097 return this.selectItem( itemFromLabel
);
18101 * Programmatically select an option by its data. If the `data` parameter is omitted,
18102 * or if the item does not exist, all options will be deselected.
18104 * @param {Object|string} [data] Value of the item to select, omit to deselect all
18108 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
18109 var itemFromData
= this.getItemFromData( data
);
18110 if ( data
=== undefined || !itemFromData
) {
18111 return this.selectItem();
18113 return this.selectItem( itemFromData
);
18117 * Programmatically select an option by its reference. If the `item` parameter is omitted,
18118 * all options will be deselected.
18120 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
18124 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
18125 var i
, len
, selected
,
18128 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18129 selected
= this.items
[ i
] === item
;
18130 if ( this.items
[ i
].isSelected() !== selected
) {
18131 this.items
[ i
].setSelected( selected
);
18136 this.emit( 'select', item
);
18145 * Press is a state that occurs when a user mouses down on an item, but has not
18146 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
18147 * releases the mouse.
18149 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
18153 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
18154 var i
, len
, pressed
,
18157 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18158 pressed
= this.items
[ i
] === item
;
18159 if ( this.items
[ i
].isPressed() !== pressed
) {
18160 this.items
[ i
].setPressed( pressed
);
18165 this.emit( 'press', item
);
18174 * Note that ‘choose’ should never be modified programmatically. A user can choose
18175 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
18176 * use the #selectItem method.
18178 * This method is identical to #selectItem, but may vary in subclasses that take additional action
18179 * when users choose an item with the keyboard or mouse.
18181 * @param {OO.ui.OptionWidget} item Item to choose
18185 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
18186 this.selectItem( item
);
18187 this.emit( 'choose', item
);
18193 * Get an option by its position relative to the specified item (or to the start of the option array,
18194 * if item is `null`). The direction in which to search through the option array is specified with a
18195 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
18196 * `null` if there are no options in the array.
18198 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
18199 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
18200 * @param {Function} filter Only consider items for which this function returns
18201 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
18202 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
18204 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
18205 var currentIndex
, nextIndex
, i
,
18206 increase
= direction
> 0 ? 1 : -1,
18207 len
= this.items
.length
;
18209 if ( !$.isFunction( filter
) ) {
18210 filter
= OO
.ui
.SelectWidget
.static.passAllFilter
;
18213 if ( item
instanceof OO
.ui
.OptionWidget
) {
18214 currentIndex
= this.items
.indexOf( item
);
18215 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
18217 // If no item is selected and moving forward, start at the beginning.
18218 // If moving backward, start at the end.
18219 nextIndex
= direction
> 0 ? 0 : len
- 1;
18222 for ( i
= 0; i
< len
; i
++ ) {
18223 item
= this.items
[ nextIndex
];
18224 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18227 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
18233 * Get the next selectable item or `null` if there are no selectable items.
18234 * Disabled options and menu-section markers and breaks are not selectable.
18236 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
18238 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
18241 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18242 item
= this.items
[ i
];
18243 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
18252 * Add an array of options to the select. Optionally, an index number can be used to
18253 * specify an insertion point.
18255 * @param {OO.ui.OptionWidget[]} items Items to add
18256 * @param {number} [index] Index to insert items after
18260 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
18262 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
18264 // Always provide an index, even if it was omitted
18265 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
18271 * Remove the specified array of options from the select. Options will be detached
18272 * from the DOM, not removed, so they can be reused later. To remove all options from
18273 * the select, you may wish to use the #clearItems method instead.
18275 * @param {OO.ui.OptionWidget[]} items Items to remove
18279 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
18282 // Deselect items being removed
18283 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
18285 if ( item
.isSelected() ) {
18286 this.selectItem( null );
18291 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
18293 this.emit( 'remove', items
);
18299 * Clear all options from the select. Options will be detached from the DOM, not removed,
18300 * so that they can be reused later. To remove a subset of options from the select, use
18301 * the #removeItems method.
18306 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
18307 var items
= this.items
.slice();
18310 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
18313 this.selectItem( null );
18315 this.emit( 'remove', items
);
18321 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
18322 * button options and is used together with
18323 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
18324 * highlighting, choosing, and selecting mutually exclusive options. Please see
18325 * the [OOjs UI documentation on MediaWiki] [1] for more information.
18328 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
18329 * var option1 = new OO.ui.ButtonOptionWidget( {
18331 * label: 'Option 1',
18332 * title: 'Button option 1'
18335 * var option2 = new OO.ui.ButtonOptionWidget( {
18337 * label: 'Option 2',
18338 * title: 'Button option 2'
18341 * var option3 = new OO.ui.ButtonOptionWidget( {
18343 * label: 'Option 3',
18344 * title: 'Button option 3'
18347 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
18348 * items: [ option1, option2, option3 ]
18350 * $( 'body' ).append( buttonSelect.$element );
18352 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18355 * @extends OO.ui.SelectWidget
18356 * @mixins OO.ui.mixin.TabIndexedElement
18359 * @param {Object} [config] Configuration options
18361 OO
.ui
.ButtonSelectWidget
= function OoUiButtonSelectWidget( config
) {
18362 // Parent constructor
18363 OO
.ui
.ButtonSelectWidget
.parent
.call( this, config
);
18365 // Mixin constructors
18366 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
18369 this.$element
.on( {
18370 focus
: this.bindKeyDownListener
.bind( this ),
18371 blur
: this.unbindKeyDownListener
.bind( this )
18375 this.$element
.addClass( 'oo-ui-buttonSelectWidget' );
18380 OO
.inheritClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.SelectWidget
);
18381 OO
.mixinClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
18384 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
18385 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
18386 * an interface for adding, removing and selecting options.
18387 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18389 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
18390 * OO.ui.RadioSelectInputWidget instead.
18393 * // A RadioSelectWidget with RadioOptions.
18394 * var option1 = new OO.ui.RadioOptionWidget( {
18396 * label: 'Selected radio option'
18399 * var option2 = new OO.ui.RadioOptionWidget( {
18401 * label: 'Unselected radio option'
18404 * var radioSelect=new OO.ui.RadioSelectWidget( {
18405 * items: [ option1, option2 ]
18408 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
18409 * radioSelect.selectItem( option1 );
18411 * $( 'body' ).append( radioSelect.$element );
18413 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18417 * @extends OO.ui.SelectWidget
18418 * @mixins OO.ui.mixin.TabIndexedElement
18421 * @param {Object} [config] Configuration options
18423 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
18424 // Parent constructor
18425 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
18427 // Mixin constructors
18428 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
18431 this.$element
.on( {
18432 focus
: this.bindKeyDownListener
.bind( this ),
18433 blur
: this.unbindKeyDownListener
.bind( this )
18438 .addClass( 'oo-ui-radioSelectWidget' )
18439 .attr( 'role', 'radiogroup' );
18444 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
18445 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
18448 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
18449 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
18450 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
18451 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
18452 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
18453 * and customized to be opened, closed, and displayed as needed.
18455 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
18456 * mouse outside the menu.
18458 * Menus also have support for keyboard interaction:
18460 * - Enter/Return key: choose and select a menu option
18461 * - Up-arrow key: highlight the previous menu option
18462 * - Down-arrow key: highlight the next menu option
18463 * - Esc key: hide the menu
18465 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18466 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18469 * @extends OO.ui.SelectWidget
18470 * @mixins OO.ui.mixin.ClippableElement
18473 * @param {Object} [config] Configuration options
18474 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
18475 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
18476 * and {@link OO.ui.mixin.LookupElement LookupElement}
18477 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
18478 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
18479 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
18480 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
18481 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
18482 * that button, unless the button (or its parent widget) is passed in here.
18483 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
18484 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
18486 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
18487 // Configuration initialization
18488 config
= config
|| {};
18490 // Parent constructor
18491 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
18493 // Mixin constructors
18494 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
18497 this.newItems
= null;
18498 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
18499 this.filterFromInput
= !!config
.filterFromInput
;
18500 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
18501 this.$widget
= config
.widget
? config
.widget
.$element
: null;
18502 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
18503 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
18507 .addClass( 'oo-ui-menuSelectWidget' )
18508 .attr( 'role', 'menu' );
18510 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
18511 // that reference properties not initialized at that time of parent class construction
18512 // TODO: Find a better way to handle post-constructor setup
18513 this.visible
= false;
18514 this.$element
.addClass( 'oo-ui-element-hidden' );
18519 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
18520 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
18525 * Handles document mouse down events.
18528 * @param {jQuery.Event} e Key down event
18530 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
18532 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
18533 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
18535 this.toggle( false );
18542 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
18543 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
18545 if ( !this.isDisabled() && this.isVisible() ) {
18546 switch ( e
.keyCode
) {
18547 case OO
.ui
.Keys
.LEFT
:
18548 case OO
.ui
.Keys
.RIGHT
:
18549 // Do nothing if a text field is associated, arrow keys will be handled natively
18550 if ( !this.$input
) {
18551 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
18554 case OO
.ui
.Keys
.ESCAPE
:
18555 case OO
.ui
.Keys
.TAB
:
18556 if ( currentItem
) {
18557 currentItem
.setHighlighted( false );
18559 this.toggle( false );
18560 // Don't prevent tabbing away, prevent defocusing
18561 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
18562 e
.preventDefault();
18563 e
.stopPropagation();
18567 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
18574 * Update menu item visibility after input changes.
18577 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
18579 len
= this.items
.length
,
18580 showAll
= !this.isVisible(),
18581 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
18583 for ( i
= 0; i
< len
; i
++ ) {
18584 item
= this.items
[ i
];
18585 if ( item
instanceof OO
.ui
.OptionWidget
) {
18586 item
.toggle( showAll
|| filter( item
) );
18590 // Reevaluate clipping
18597 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
18598 if ( this.$input
) {
18599 this.$input
.on( 'keydown', this.onKeyDownHandler
);
18601 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
18608 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
18609 if ( this.$input
) {
18610 this.$input
.off( 'keydown', this.onKeyDownHandler
);
18612 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
18619 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
18620 if ( this.$input
) {
18621 if ( this.filterFromInput
) {
18622 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
18625 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
18632 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
18633 if ( this.$input
) {
18634 if ( this.filterFromInput
) {
18635 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
18636 this.updateItemVisibility();
18639 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
18646 * When a user chooses an item, the menu is closed.
18648 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
18649 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
18650 * @param {OO.ui.OptionWidget} item Item to choose
18653 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
18654 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
18655 this.toggle( false );
18662 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
18666 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
18669 if ( !this.newItems
) {
18670 this.newItems
= [];
18673 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
18675 if ( this.isVisible() ) {
18676 // Defer fitting label until item has been attached
18679 this.newItems
.push( item
);
18683 // Reevaluate clipping
18692 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
18694 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
18696 // Reevaluate clipping
18705 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
18707 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
18709 // Reevaluate clipping
18718 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
18719 var i
, len
, change
;
18721 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
18722 change
= visible
!== this.isVisible();
18725 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
18729 this.bindKeyDownListener();
18730 this.bindKeyPressListener();
18732 if ( this.newItems
&& this.newItems
.length
) {
18733 for ( i
= 0, len
= this.newItems
.length
; i
< len
; i
++ ) {
18734 this.newItems
[ i
].fitLabel();
18736 this.newItems
= null;
18738 this.toggleClipping( true );
18741 if ( this.autoHide
) {
18742 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler
);
18745 this.unbindKeyDownListener();
18746 this.unbindKeyPressListener();
18747 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler
);
18748 this.toggleClipping( false );
18756 * FloatingMenuSelectWidget is a menu that will stick under a specified
18757 * container, even when it is inserted elsewhere in the document (for example,
18758 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
18759 * menu from being clipped too aggresively.
18761 * The menu's position is automatically calculated and maintained when the menu
18762 * is toggled or the window is resized.
18764 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
18767 * @extends OO.ui.MenuSelectWidget
18770 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
18771 * Deprecated, omit this parameter and specify `$container` instead.
18772 * @param {Object} [config] Configuration options
18773 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
18775 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
18776 // Allow 'inputWidget' parameter and config for backwards compatibility
18777 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
18778 config
= inputWidget
;
18779 inputWidget
= config
.inputWidget
;
18782 // Configuration initialization
18783 config
= config
|| {};
18785 // Parent constructor
18786 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, config
);
18789 this.inputWidget
= inputWidget
; // For backwards compatibility
18790 this.$container
= config
.$container
|| this.inputWidget
.$element
;
18791 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
18794 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
18795 // For backwards compatibility
18796 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
18801 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
18803 // For backwards compatibility
18804 OO
.ui
.TextInputMenuSelectWidget
= OO
.ui
.FloatingMenuSelectWidget
;
18809 * Handle window resize event.
18812 * @param {jQuery.Event} e Window resize event
18814 OO
.ui
.FloatingMenuSelectWidget
.prototype.onWindowResize = function () {
18821 OO
.ui
.FloatingMenuSelectWidget
.prototype.toggle = function ( visible
) {
18823 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
18825 change
= visible
!== this.isVisible();
18827 if ( change
&& visible
) {
18828 // Make sure the width is set before the parent method runs.
18829 // After this we have to call this.position(); again to actually
18830 // position ourselves correctly.
18835 OO
.ui
.FloatingMenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
18838 if ( this.isVisible() ) {
18840 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
18842 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
18850 * Position the menu.
18855 OO
.ui
.FloatingMenuSelectWidget
.prototype.position = function () {
18856 var $container
= this.$container
,
18857 pos
= OO
.ui
.Element
.static.getRelativePosition( $container
, this.$element
.offsetParent() );
18859 // Position under input
18860 pos
.top
+= $container
.height();
18861 this.$element
.css( pos
);
18864 this.setIdealSize( $container
.width() );
18865 // We updated the position, so re-evaluate the clipping state
18872 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
18873 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
18875 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
18878 * @extends OO.ui.SelectWidget
18879 * @mixins OO.ui.mixin.TabIndexedElement
18882 * @param {Object} [config] Configuration options
18884 OO
.ui
.OutlineSelectWidget
= function OoUiOutlineSelectWidget( config
) {
18885 // Parent constructor
18886 OO
.ui
.OutlineSelectWidget
.parent
.call( this, config
);
18888 // Mixin constructors
18889 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
18892 this.$element
.on( {
18893 focus
: this.bindKeyDownListener
.bind( this ),
18894 blur
: this.unbindKeyDownListener
.bind( this )
18898 this.$element
.addClass( 'oo-ui-outlineSelectWidget' );
18903 OO
.inheritClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.SelectWidget
);
18904 OO
.mixinClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
18907 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
18909 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
18912 * @extends OO.ui.SelectWidget
18913 * @mixins OO.ui.mixin.TabIndexedElement
18916 * @param {Object} [config] Configuration options
18918 OO
.ui
.TabSelectWidget
= function OoUiTabSelectWidget( config
) {
18919 // Parent constructor
18920 OO
.ui
.TabSelectWidget
.parent
.call( this, config
);
18922 // Mixin constructors
18923 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
18926 this.$element
.on( {
18927 focus
: this.bindKeyDownListener
.bind( this ),
18928 blur
: this.unbindKeyDownListener
.bind( this )
18932 this.$element
.addClass( 'oo-ui-tabSelectWidget' );
18937 OO
.inheritClass( OO
.ui
.TabSelectWidget
, OO
.ui
.SelectWidget
);
18938 OO
.mixinClass( OO
.ui
.TabSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
18941 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
18942 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
18943 * (to adjust the value in increments) to allow the user to enter a number.
18946 * // Example: A NumberInputWidget.
18947 * var numberInput = new OO.ui.NumberInputWidget( {
18948 * label: 'NumberInputWidget',
18949 * input: { value: 5, min: 1, max: 10 }
18951 * $( 'body' ).append( numberInput.$element );
18954 * @extends OO.ui.Widget
18957 * @param {Object} [config] Configuration options
18958 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
18959 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
18960 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
18961 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
18962 * @cfg {number} [min=-Infinity] Minimum allowed value
18963 * @cfg {number} [max=Infinity] Maximum allowed value
18964 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
18965 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
18967 OO
.ui
.NumberInputWidget
= function OoUiNumberInputWidget( config
) {
18968 // Configuration initialization
18969 config
= $.extend( {
18977 // Parent constructor
18978 OO
.ui
.NumberInputWidget
.parent
.call( this, config
);
18981 this.input
= new OO
.ui
.TextInputWidget( $.extend(
18983 disabled
: this.isDisabled()
18987 this.minusButton
= new OO
.ui
.ButtonWidget( $.extend(
18989 disabled
: this.isDisabled(),
18992 config
.minusButton
,
18994 classes
: [ 'oo-ui-numberInputWidget-minusButton' ],
18998 this.plusButton
= new OO
.ui
.ButtonWidget( $.extend(
19000 disabled
: this.isDisabled(),
19005 classes
: [ 'oo-ui-numberInputWidget-plusButton' ],
19011 this.input
.connect( this, {
19012 change
: this.emit
.bind( this, 'change' ),
19013 enter
: this.emit
.bind( this, 'enter' )
19015 this.input
.$input
.on( {
19016 keydown
: this.onKeyDown
.bind( this ),
19017 'wheel mousewheel DOMMouseScroll': this.onWheel
.bind( this )
19019 this.plusButton
.connect( this, {
19020 click
: [ 'onButtonClick', +1 ]
19022 this.minusButton
.connect( this, {
19023 click
: [ 'onButtonClick', -1 ]
19027 this.setIsInteger( !!config
.isInteger
);
19028 this.setRange( config
.min
, config
.max
);
19029 this.setStep( config
.step
, config
.pageStep
);
19031 this.$field
= $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
19033 this.minusButton
.$element
,
19034 this.input
.$element
,
19035 this.plusButton
.$element
19037 this.$element
.addClass( 'oo-ui-numberInputWidget' ).append( this.$field
);
19038 this.input
.setValidation( this.validateNumber
.bind( this ) );
19043 OO
.inheritClass( OO
.ui
.NumberInputWidget
, OO
.ui
.Widget
);
19048 * A `change` event is emitted when the value of the input changes.
19054 * An `enter` event is emitted when the user presses 'enter' inside the text box.
19062 * Set whether only integers are allowed
19063 * @param {boolean} flag
19065 OO
.ui
.NumberInputWidget
.prototype.setIsInteger = function ( flag
) {
19066 this.isInteger
= !!flag
;
19067 this.input
.setValidityFlag();
19071 * Get whether only integers are allowed
19072 * @return {boolean} Flag value
19074 OO
.ui
.NumberInputWidget
.prototype.getIsInteger = function () {
19075 return this.isInteger
;
19079 * Set the range of allowed values
19080 * @param {number} min Minimum allowed value
19081 * @param {number} max Maximum allowed value
19083 OO
.ui
.NumberInputWidget
.prototype.setRange = function ( min
, max
) {
19085 throw new Error( 'Minimum (' + min
+ ') must not be greater than maximum (' + max
+ ')' );
19089 this.input
.setValidityFlag();
19093 * Get the current range
19094 * @return {number[]} Minimum and maximum values
19096 OO
.ui
.NumberInputWidget
.prototype.getRange = function () {
19097 return [ this.min
, this.max
];
19101 * Set the stepping deltas
19102 * @param {number} step Normal step
19103 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
19105 OO
.ui
.NumberInputWidget
.prototype.setStep = function ( step
, pageStep
) {
19107 throw new Error( 'Step value must be positive' );
19109 if ( pageStep
=== null ) {
19110 pageStep
= step
* 10;
19111 } else if ( pageStep
<= 0 ) {
19112 throw new Error( 'Page step value must be positive' );
19115 this.pageStep
= pageStep
;
19119 * Get the current stepping values
19120 * @return {number[]} Step and page step
19122 OO
.ui
.NumberInputWidget
.prototype.getStep = function () {
19123 return [ this.step
, this.pageStep
];
19127 * Get the current value of the widget
19130 OO
.ui
.NumberInputWidget
.prototype.getValue = function () {
19131 return this.input
.getValue();
19135 * Get the current value of the widget as a number
19136 * @return {number} May be NaN, or an invalid number
19138 OO
.ui
.NumberInputWidget
.prototype.getNumericValue = function () {
19139 return +this.input
.getValue();
19143 * Set the value of the widget
19144 * @param {string} value Invalid values are allowed
19146 OO
.ui
.NumberInputWidget
.prototype.setValue = function ( value
) {
19147 this.input
.setValue( value
);
19151 * Adjust the value of the widget
19152 * @param {number} delta Adjustment amount
19154 OO
.ui
.NumberInputWidget
.prototype.adjustValue = function ( delta
) {
19155 var n
, v
= this.getNumericValue();
19158 if ( isNaN( delta
) || !isFinite( delta
) ) {
19159 throw new Error( 'Delta must be a finite number' );
19162 if ( isNaN( v
) ) {
19166 n
= Math
.max( Math
.min( n
, this.max
), this.min
);
19167 if ( this.isInteger
) {
19168 n
= Math
.round( n
);
19173 this.setValue( n
);
19180 * @param {string} value Field value
19181 * @return {boolean}
19183 OO
.ui
.NumberInputWidget
.prototype.validateNumber = function ( value
) {
19185 if ( isNaN( n
) || !isFinite( n
) ) {
19189 /*jshint bitwise: false */
19190 if ( this.isInteger
&& ( n
| 0 ) !== n
) {
19193 /*jshint bitwise: true */
19195 if ( n
< this.min
|| n
> this.max
) {
19203 * Handle mouse click events.
19206 * @param {number} dir +1 or -1
19208 OO
.ui
.NumberInputWidget
.prototype.onButtonClick = function ( dir
) {
19209 this.adjustValue( dir
* this.step
);
19213 * Handle mouse wheel events.
19216 * @param {jQuery.Event} event
19218 OO
.ui
.NumberInputWidget
.prototype.onWheel = function ( event
) {
19221 // Standard 'wheel' event
19222 if ( event
.originalEvent
.deltaMode
!== undefined ) {
19223 this.sawWheelEvent
= true;
19225 if ( event
.originalEvent
.deltaY
) {
19226 delta
= -event
.originalEvent
.deltaY
;
19227 } else if ( event
.originalEvent
.deltaX
) {
19228 delta
= event
.originalEvent
.deltaX
;
19231 // Non-standard events
19232 if ( !this.sawWheelEvent
) {
19233 if ( event
.originalEvent
.wheelDeltaX
) {
19234 delta
= -event
.originalEvent
.wheelDeltaX
;
19235 } else if ( event
.originalEvent
.wheelDeltaY
) {
19236 delta
= event
.originalEvent
.wheelDeltaY
;
19237 } else if ( event
.originalEvent
.wheelDelta
) {
19238 delta
= event
.originalEvent
.wheelDelta
;
19239 } else if ( event
.originalEvent
.detail
) {
19240 delta
= -event
.originalEvent
.detail
;
19245 delta
= delta
< 0 ? -1 : 1;
19246 this.adjustValue( delta
* this.step
);
19253 * Handle key down events.
19257 * @param {jQuery.Event} e Key down event
19259 OO
.ui
.NumberInputWidget
.prototype.onKeyDown = function ( e
) {
19260 if ( !this.isDisabled() ) {
19261 switch ( e
.which
) {
19262 case OO
.ui
.Keys
.UP
:
19263 this.adjustValue( this.step
);
19265 case OO
.ui
.Keys
.DOWN
:
19266 this.adjustValue( -this.step
);
19268 case OO
.ui
.Keys
.PAGEUP
:
19269 this.adjustValue( this.pageStep
);
19271 case OO
.ui
.Keys
.PAGEDOWN
:
19272 this.adjustValue( -this.pageStep
);
19281 OO
.ui
.NumberInputWidget
.prototype.setDisabled = function ( disabled
) {
19283 OO
.ui
.NumberInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
19285 if ( this.input
) {
19286 this.input
.setDisabled( this.isDisabled() );
19288 if ( this.minusButton
) {
19289 this.minusButton
.setDisabled( this.isDisabled() );
19291 if ( this.plusButton
) {
19292 this.plusButton
.setDisabled( this.isDisabled() );
19299 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
19300 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
19301 * visually by a slider in the leftmost position.
19304 * // Toggle switches in the 'off' and 'on' position.
19305 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
19306 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
19310 * // Create a FieldsetLayout to layout and label switches
19311 * var fieldset = new OO.ui.FieldsetLayout( {
19312 * label: 'Toggle switches'
19314 * fieldset.addItems( [
19315 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
19316 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
19318 * $( 'body' ).append( fieldset.$element );
19321 * @extends OO.ui.ToggleWidget
19322 * @mixins OO.ui.mixin.TabIndexedElement
19325 * @param {Object} [config] Configuration options
19326 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
19327 * By default, the toggle switch is in the 'off' position.
19329 OO
.ui
.ToggleSwitchWidget
= function OoUiToggleSwitchWidget( config
) {
19330 // Parent constructor
19331 OO
.ui
.ToggleSwitchWidget
.parent
.call( this, config
);
19333 // Mixin constructors
19334 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19337 this.dragging
= false;
19338 this.dragStart
= null;
19339 this.sliding
= false;
19340 this.$glow
= $( '<span>' );
19341 this.$grip
= $( '<span>' );
19344 this.$element
.on( {
19345 click
: this.onClick
.bind( this ),
19346 keypress
: this.onKeyPress
.bind( this )
19350 this.$glow
.addClass( 'oo-ui-toggleSwitchWidget-glow' );
19351 this.$grip
.addClass( 'oo-ui-toggleSwitchWidget-grip' );
19353 .addClass( 'oo-ui-toggleSwitchWidget' )
19354 .attr( 'role', 'checkbox' )
19355 .append( this.$glow
, this.$grip
);
19360 OO
.inheritClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.ToggleWidget
);
19361 OO
.mixinClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19366 * Handle mouse click events.
19369 * @param {jQuery.Event} e Mouse click event
19371 OO
.ui
.ToggleSwitchWidget
.prototype.onClick = function ( e
) {
19372 if ( !this.isDisabled() && e
.which
=== 1 ) {
19373 this.setValue( !this.value
);
19379 * Handle key press events.
19382 * @param {jQuery.Event} e Key press event
19384 OO
.ui
.ToggleSwitchWidget
.prototype.onKeyPress = function ( e
) {
19385 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
19386 this.setValue( !this.value
);
19392 * Deprecated aliases for classes in the `OO.ui.mixin` namespace.
19396 * @inheritdoc OO.ui.mixin.ButtonElement
19397 * @deprecated Use {@link OO.ui.mixin.ButtonElement} instead.
19399 OO
.ui
.ButtonElement
= OO
.ui
.mixin
.ButtonElement
;
19402 * @inheritdoc OO.ui.mixin.ClippableElement
19403 * @deprecated Use {@link OO.ui.mixin.ClippableElement} instead.
19405 OO
.ui
.ClippableElement
= OO
.ui
.mixin
.ClippableElement
;
19408 * @inheritdoc OO.ui.mixin.DraggableElement
19409 * @deprecated Use {@link OO.ui.mixin.DraggableElement} instead.
19411 OO
.ui
.DraggableElement
= OO
.ui
.mixin
.DraggableElement
;
19414 * @inheritdoc OO.ui.mixin.DraggableGroupElement
19415 * @deprecated Use {@link OO.ui.mixin.DraggableGroupElement} instead.
19417 OO
.ui
.DraggableGroupElement
= OO
.ui
.mixin
.DraggableGroupElement
;
19420 * @inheritdoc OO.ui.mixin.FlaggedElement
19421 * @deprecated Use {@link OO.ui.mixin.FlaggedElement} instead.
19423 OO
.ui
.FlaggedElement
= OO
.ui
.mixin
.FlaggedElement
;
19426 * @inheritdoc OO.ui.mixin.GroupElement
19427 * @deprecated Use {@link OO.ui.mixin.GroupElement} instead.
19429 OO
.ui
.GroupElement
= OO
.ui
.mixin
.GroupElement
;
19432 * @inheritdoc OO.ui.mixin.GroupWidget
19433 * @deprecated Use {@link OO.ui.mixin.GroupWidget} instead.
19435 OO
.ui
.GroupWidget
= OO
.ui
.mixin
.GroupWidget
;
19438 * @inheritdoc OO.ui.mixin.IconElement
19439 * @deprecated Use {@link OO.ui.mixin.IconElement} instead.
19441 OO
.ui
.IconElement
= OO
.ui
.mixin
.IconElement
;
19444 * @inheritdoc OO.ui.mixin.IndicatorElement
19445 * @deprecated Use {@link OO.ui.mixin.IndicatorElement} instead.
19447 OO
.ui
.IndicatorElement
= OO
.ui
.mixin
.IndicatorElement
;
19450 * @inheritdoc OO.ui.mixin.ItemWidget
19451 * @deprecated Use {@link OO.ui.mixin.ItemWidget} instead.
19453 OO
.ui
.ItemWidget
= OO
.ui
.mixin
.ItemWidget
;
19456 * @inheritdoc OO.ui.mixin.LabelElement
19457 * @deprecated Use {@link OO.ui.mixin.LabelElement} instead.
19459 OO
.ui
.LabelElement
= OO
.ui
.mixin
.LabelElement
;
19462 * @inheritdoc OO.ui.mixin.LookupElement
19463 * @deprecated Use {@link OO.ui.mixin.LookupElement} instead.
19465 OO
.ui
.LookupElement
= OO
.ui
.mixin
.LookupElement
;
19468 * @inheritdoc OO.ui.mixin.PendingElement
19469 * @deprecated Use {@link OO.ui.mixin.PendingElement} instead.
19471 OO
.ui
.PendingElement
= OO
.ui
.mixin
.PendingElement
;
19474 * @inheritdoc OO.ui.mixin.PopupElement
19475 * @deprecated Use {@link OO.ui.mixin.PopupElement} instead.
19477 OO
.ui
.PopupElement
= OO
.ui
.mixin
.PopupElement
;
19480 * @inheritdoc OO.ui.mixin.TabIndexedElement
19481 * @deprecated Use {@link OO.ui.mixin.TabIndexedElement} instead.
19483 OO
.ui
.TabIndexedElement
= OO
.ui
.mixin
.TabIndexedElement
;
19486 * @inheritdoc OO.ui.mixin.TitledElement
19487 * @deprecated Use {@link OO.ui.mixin.TitledElement} instead.
19489 OO
.ui
.TitledElement
= OO
.ui
.mixin
.TitledElement
;