3 * https://www.mediawiki.org/wiki/OOjs_UI
5 * Copyright 2011–2016 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2016-01-12T23:06:31Z
16 * Namespace for all classes, static methods and static properties.
48 * Constants for MouseEvent.which
52 OO
.ui
.MouseButtons
= {
64 * Generate a unique ID for element
66 * @return {String} [id]
68 OO
.ui
.generateElementId = function () {
70 return 'oojsui-' + OO
.ui
.elementId
;
74 * Check if an element is focusable.
75 * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14
77 * @param {jQuery} element Element to test
80 OO
.ui
.isFocusableElement = function ( $element
) {
82 element
= $element
[ 0 ];
84 // Anything disabled is not focusable
85 if ( element
.disabled
) {
89 // Check if the element is visible
91 // This is quicker than calling $element.is( ':visible' )
92 $.expr
.filters
.visible( element
) &&
93 // Check that all parents are visible
94 !$element
.parents().addBack().filter( function () {
95 return $.css( this, 'visibility' ) === 'hidden';
101 // Check if the element is ContentEditable, which is the string 'true'
102 if ( element
.contentEditable
=== 'true' ) {
106 // Anything with a non-negative numeric tabIndex is focusable.
107 // Use .prop to avoid browser bugs
108 if ( $element
.prop( 'tabIndex' ) >= 0 ) {
112 // Some element types are naturally focusable
113 // (indexOf is much faster than regex in Chrome and about the
114 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
115 nodeName
= element
.nodeName
.toLowerCase();
116 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName
) !== -1 ) {
120 // Links and areas are focusable if they have an href
121 if ( ( nodeName
=== 'a' || nodeName
=== 'area' ) && $element
.attr( 'href' ) !== undefined ) {
129 * Find a focusable child
131 * @param {jQuery} $container Container to search in
132 * @param {boolean} [backwards] Search backwards
133 * @return {jQuery} Focusable child, an empty jQuery object if none found
135 OO
.ui
.findFocusable = function ( $container
, backwards
) {
136 var $focusable
= $( [] ),
137 // $focusableCandidates is a superset of things that
138 // could get matched by isFocusableElement
139 $focusableCandidates
= $container
140 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
143 $focusableCandidates
= Array
.prototype.reverse
.call( $focusableCandidates
);
146 $focusableCandidates
.each( function () {
147 var $this = $( this );
148 if ( OO
.ui
.isFocusableElement( $this ) ) {
157 * Get the user's language and any fallback languages.
159 * These language codes are used to localize user interface elements in the user's language.
161 * In environments that provide a localization system, this function should be overridden to
162 * return the user's language(s). The default implementation returns English (en) only.
164 * @return {string[]} Language codes, in descending order of priority
166 OO
.ui
.getUserLanguages = function () {
171 * Get a value in an object keyed by language code.
173 * @param {Object.<string,Mixed>} obj Object keyed by language code
174 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
175 * @param {string} [fallback] Fallback code, used if no matching language can be found
176 * @return {Mixed} Local value
178 OO
.ui
.getLocalValue = function ( obj
, lang
, fallback
) {
181 // Requested language
185 // Known user language
186 langs
= OO
.ui
.getUserLanguages();
187 for ( i
= 0, len
= langs
.length
; i
< len
; i
++ ) {
194 if ( obj
[ fallback
] ) {
195 return obj
[ fallback
];
197 // First existing language
198 for ( lang
in obj
) {
206 * Check if a node is contained within another node
208 * Similar to jQuery#contains except a list of containers can be supplied
209 * and a boolean argument allows you to include the container in the match list
211 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
212 * @param {HTMLElement} contained Node to find
213 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
214 * @return {boolean} The node is in the list of target nodes
216 OO
.ui
.contains = function ( containers
, contained
, matchContainers
) {
218 if ( !Array
.isArray( containers
) ) {
219 containers
= [ containers
];
221 for ( i
= containers
.length
- 1; i
>= 0; i
-- ) {
222 if ( ( matchContainers
&& contained
=== containers
[ i
] ) || $.contains( containers
[ i
], contained
) ) {
230 * Return a function, that, as long as it continues to be invoked, will not
231 * be triggered. The function will be called after it stops being called for
232 * N milliseconds. If `immediate` is passed, trigger the function on the
233 * leading edge, instead of the trailing.
235 * Ported from: http://underscorejs.org/underscore.js
237 * @param {Function} func
238 * @param {number} wait
239 * @param {boolean} immediate
242 OO
.ui
.debounce = function ( func
, wait
, immediate
) {
247 later = function () {
250 func
.apply( context
, args
);
253 if ( immediate
&& !timeout
) {
254 func
.apply( context
, args
);
256 clearTimeout( timeout
);
257 timeout
= setTimeout( later
, wait
);
262 * Proxy for `node.addEventListener( eventName, handler, true )`.
264 * @param {HTMLElement} node
265 * @param {string} eventName
266 * @param {Function} handler
269 OO
.ui
.addCaptureEventListener = function ( node
, eventName
, handler
) {
270 node
.addEventListener( eventName
, handler
, true );
274 * Proxy for `node.removeEventListener( eventName, handler, true )`.
276 * @param {HTMLElement} node
277 * @param {string} eventName
278 * @param {Function} handler
281 OO
.ui
.removeCaptureEventListener = function ( node
, eventName
, handler
) {
282 node
.removeEventListener( eventName
, handler
, true );
286 * Reconstitute a JavaScript object corresponding to a widget created by
287 * the PHP implementation.
289 * This is an alias for `OO.ui.Element.static.infuse()`.
291 * @param {string|HTMLElement|jQuery} idOrNode
292 * A DOM id (if a string) or node for the widget to infuse.
293 * @return {OO.ui.Element}
294 * The `OO.ui.Element` corresponding to this (infusable) document node.
296 OO
.ui
.infuse = function ( idOrNode
) {
297 return OO
.ui
.Element
.static.infuse( idOrNode
);
302 * Message store for the default implementation of OO.ui.msg
304 * Environments that provide a localization system should not use this, but should override
305 * OO.ui.msg altogether.
310 // Tool tip for a button that moves items in a list down one place
311 'ooui-outline-control-move-down': 'Move item down',
312 // Tool tip for a button that moves items in a list up one place
313 'ooui-outline-control-move-up': 'Move item up',
314 // Tool tip for a button that removes items from a list
315 'ooui-outline-control-remove': 'Remove item',
316 // Label for the toolbar group that contains a list of all other available tools
317 'ooui-toolbar-more': 'More',
318 // Label for the fake tool that expands the full list of tools in a toolbar group
319 'ooui-toolgroup-expand': 'More',
320 // Label for the fake tool that collapses the full list of tools in a toolbar group
321 'ooui-toolgroup-collapse': 'Fewer',
322 // Default label for the accept button of a confirmation dialog
323 'ooui-dialog-message-accept': 'OK',
324 // Default label for the reject button of a confirmation dialog
325 'ooui-dialog-message-reject': 'Cancel',
326 // Title for process dialog error description
327 'ooui-dialog-process-error': 'Something went wrong',
328 // Label for process dialog dismiss error button, visible when describing errors
329 'ooui-dialog-process-dismiss': 'Dismiss',
330 // Label for process dialog retry action button, visible when describing only recoverable errors
331 'ooui-dialog-process-retry': 'Try again',
332 // Label for process dialog retry action button, visible when describing only warnings
333 'ooui-dialog-process-continue': 'Continue',
334 // Label for the file selection widget's select file button
335 'ooui-selectfile-button-select': 'Select a file',
336 // Label for the file selection widget if file selection is not supported
337 'ooui-selectfile-not-supported': 'File selection is not supported',
338 // Label for the file selection widget when no file is currently selected
339 'ooui-selectfile-placeholder': 'No file is selected',
340 // Label for the file selection widget's drop target
341 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
345 * Get a localized message.
347 * In environments that provide a localization system, this function should be overridden to
348 * return the message translated in the user's language. The default implementation always returns
351 * After the message key, message parameters may optionally be passed. In the default implementation,
352 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
353 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
354 * they support unnamed, ordered message parameters.
356 * @param {string} key Message key
357 * @param {Mixed...} [params] Message parameters
358 * @return {string} Translated message with parameters substituted
360 OO
.ui
.msg = function ( key
) {
361 var message
= messages
[ key
],
362 params
= Array
.prototype.slice
.call( arguments
, 1 );
363 if ( typeof message
=== 'string' ) {
364 // Perform $1 substitution
365 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
366 var i
= parseInt( n
, 10 );
367 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
370 // Return placeholder if message not found
371 message
= '[' + key
+ ']';
378 * Package a message and arguments for deferred resolution.
380 * Use this when you are statically specifying a message and the message may not yet be present.
382 * @param {string} key Message key
383 * @param {Mixed...} [params] Message parameters
384 * @return {Function} Function that returns the resolved message when executed
386 OO
.ui
.deferMsg = function () {
387 var args
= arguments
;
389 return OO
.ui
.msg
.apply( OO
.ui
, args
);
396 * If the message is a function it will be executed, otherwise it will pass through directly.
398 * @param {Function|string} msg Deferred message, or message text
399 * @return {string} Resolved message
401 OO
.ui
.resolveMsg = function ( msg
) {
402 if ( $.isFunction( msg
) ) {
409 * @param {string} url
412 OO
.ui
.isSafeUrl = function ( url
) {
414 // Keep in sync with php/Tag.php
416 'bitcoin:', 'ftp:', 'ftps:', 'geo:', 'git:', 'gopher:', 'http:', 'https:', 'irc:', 'ircs:',
417 'magnet:', 'mailto:', 'mms:', 'news:', 'nntp:', 'redis:', 'sftp:', 'sip:', 'sips:', 'sms:', 'ssh:',
418 'svn:', 'tel:', 'telnet:', 'urn:', 'worldwind:', 'xmpp:'
421 if ( url
.indexOf( ':' ) === -1 ) {
426 protocol
= url
.split( ':', 1 )[ 0 ] + ':';
427 if ( !protocol
.match( /^([A-za-z0-9\+\.\-])+:/ ) ) {
428 // Not a valid protocol, safe
432 // Safe if in the whitelist
433 return whitelist
.indexOf( protocol
) !== -1;
437 * Lazy-initialize and return a global OO.ui.WindowManager instance, used by OO.ui.alert and
441 * @return {OO.ui.WindowManager}
443 OO
.ui
.getWindowManager = function () {
444 if ( !OO
.ui
.windowManager
) {
445 OO
.ui
.windowManager
= new OO
.ui
.WindowManager();
446 $( 'body' ).append( OO
.ui
.windowManager
.$element
);
447 OO
.ui
.windowManager
.addWindows( {
448 messageDialog
: new OO
.ui
.MessageDialog()
451 return OO
.ui
.windowManager
;
455 * Display a quick modal alert dialog, using a OO.ui.MessageDialog. While the dialog is open, the
456 * rest of the page will be dimmed out and the user won't be able to interact with it. The dialog
457 * has only one action button, labelled "OK", clicking it will simply close the dialog.
459 * A window manager is created automatically when this function is called for the first time.
462 * OO.ui.alert( 'Something happened!' ).done( function () {
463 * console.log( 'User closed the dialog.' );
466 * @param {jQuery|string} text Message text to display
467 * @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
468 * @return {jQuery.Promise} Promise resolved when the user closes the dialog
470 OO
.ui
.alert = function ( text
, options
) {
471 return OO
.ui
.getWindowManager().openWindow( 'messageDialog', $.extend( {
474 actions
: [ OO
.ui
.MessageDialog
.static.actions
[ 0 ] ]
475 }, options
) ).then( function ( opened
) {
476 return opened
.then( function ( closing
) {
477 return closing
.then( function () {
478 return $.Deferred().resolve();
485 * Display a quick modal confirmation dialog, using a OO.ui.MessageDialog. While the dialog is open,
486 * the rest of the page will be dimmed out and the user won't be able to interact with it. The
487 * dialog has two action buttons, one to confirm an operation (labelled "OK") and one to cancel it
488 * (labelled "Cancel").
490 * A window manager is created automatically when this function is called for the first time.
493 * OO.ui.confirm( 'Are you sure?' ).done( function ( confirmed ) {
495 * console.log( 'User clicked "OK"!' );
497 * console.log( 'User clicked "Cancel" or closed the dialog.' );
501 * @param {jQuery|string} text Message text to display
502 * @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
503 * @return {jQuery.Promise} Promise resolved when the user closes the dialog. If the user chose to
504 * confirm, the promise will resolve to boolean `true`; otherwise, it will resolve to boolean
507 OO
.ui
.confirm = function ( text
, options
) {
508 return OO
.ui
.getWindowManager().openWindow( 'messageDialog', $.extend( {
511 }, options
) ).then( function ( opened
) {
512 return opened
.then( function ( closing
) {
513 return closing
.then( function ( data
) {
514 return $.Deferred().resolve( !!( data
&& data
.action
=== 'accept' ) );
525 * Namespace for OOjs UI mixins.
527 * Mixins are named according to the type of object they are intended to
528 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
529 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
530 * is intended to be mixed in to an instance of OO.ui.Widget.
538 * PendingElement is a mixin that is used to create elements that notify users that something is happening
539 * and that they should wait before proceeding. The pending state is visually represented with a pending
540 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
541 * field of a {@link OO.ui.TextInputWidget text input widget}.
543 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
544 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
545 * in process dialogs.
548 * function MessageDialog( config ) {
549 * MessageDialog.parent.call( this, config );
551 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
553 * MessageDialog.static.actions = [
554 * { action: 'save', label: 'Done', flags: 'primary' },
555 * { label: 'Cancel', flags: 'safe' }
558 * MessageDialog.prototype.initialize = function () {
559 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
560 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
561 * 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>' );
562 * this.$body.append( this.content.$element );
564 * MessageDialog.prototype.getBodyHeight = function () {
567 * MessageDialog.prototype.getActionProcess = function ( action ) {
569 * if ( action === 'save' ) {
570 * dialog.getActions().get({actions: 'save'})[0].pushPending();
571 * return new OO.ui.Process()
573 * .next( function () {
574 * dialog.getActions().get({actions: 'save'})[0].popPending();
577 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
580 * var windowManager = new OO.ui.WindowManager();
581 * $( 'body' ).append( windowManager.$element );
583 * var dialog = new MessageDialog();
584 * windowManager.addWindows( [ dialog ] );
585 * windowManager.openWindow( dialog );
591 * @param {Object} [config] Configuration options
592 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
594 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
595 // Configuration initialization
596 config
= config
|| {};
600 this.$pending
= null;
603 this.setPendingElement( config
.$pending
|| this.$element
);
608 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
613 * Set the pending element (and clean up any existing one).
615 * @param {jQuery} $pending The element to set to pending.
617 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
618 if ( this.$pending
) {
619 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
622 this.$pending
= $pending
;
623 if ( this.pending
> 0 ) {
624 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
629 * Check if an element is pending.
631 * @return {boolean} Element is pending
633 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
634 return !!this.pending
;
638 * Increase the pending counter. The pending state will remain active until the counter is zero
639 * (i.e., the number of calls to #pushPending and #popPending is the same).
643 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
644 if ( this.pending
=== 0 ) {
645 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
646 this.updateThemeClasses();
654 * Decrease the pending counter. The pending state will remain active until the counter is zero
655 * (i.e., the number of calls to #pushPending and #popPending is the same).
659 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
660 if ( this.pending
=== 1 ) {
661 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
662 this.updateThemeClasses();
664 this.pending
= Math
.max( 0, this.pending
- 1 );
670 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
671 * Actions can be made available for specific contexts (modes) and circumstances
672 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
674 * ActionSets contain two types of actions:
676 * - 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.
677 * - Other: Other actions include all non-special visible actions.
679 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
682 * // Example: An action set used in a process dialog
683 * function MyProcessDialog( config ) {
684 * MyProcessDialog.parent.call( this, config );
686 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
687 * MyProcessDialog.static.title = 'An action set in a process dialog';
688 * // An action set that uses modes ('edit' and 'help' mode, in this example).
689 * MyProcessDialog.static.actions = [
690 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
691 * { action: 'help', modes: 'edit', label: 'Help' },
692 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
693 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
696 * MyProcessDialog.prototype.initialize = function () {
697 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
698 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
699 * 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>' );
700 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
701 * 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>' );
702 * this.stackLayout = new OO.ui.StackLayout( {
703 * items: [ this.panel1, this.panel2 ]
705 * this.$body.append( this.stackLayout.$element );
707 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
708 * return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
709 * .next( function () {
710 * this.actions.setMode( 'edit' );
713 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
714 * if ( action === 'help' ) {
715 * this.actions.setMode( 'help' );
716 * this.stackLayout.setItem( this.panel2 );
717 * } else if ( action === 'back' ) {
718 * this.actions.setMode( 'edit' );
719 * this.stackLayout.setItem( this.panel1 );
720 * } else if ( action === 'continue' ) {
722 * return new OO.ui.Process( function () {
726 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
728 * MyProcessDialog.prototype.getBodyHeight = function () {
729 * return this.panel1.$element.outerHeight( true );
731 * var windowManager = new OO.ui.WindowManager();
732 * $( 'body' ).append( windowManager.$element );
733 * var dialog = new MyProcessDialog( {
736 * windowManager.addWindows( [ dialog ] );
737 * windowManager.openWindow( dialog );
739 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
743 * @mixins OO.EventEmitter
746 * @param {Object} [config] Configuration options
748 OO
.ui
.ActionSet
= function OoUiActionSet( config
) {
749 // Configuration initialization
750 config
= config
|| {};
752 // Mixin constructors
753 OO
.EventEmitter
.call( this );
758 actions
: 'getAction',
762 this.categorized
= {};
765 this.organized
= false;
766 this.changing
= false;
767 this.changed
= false;
772 OO
.mixinClass( OO
.ui
.ActionSet
, OO
.EventEmitter
);
774 /* Static Properties */
777 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
778 * header of a {@link OO.ui.ProcessDialog process dialog}.
779 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
781 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
788 OO
.ui
.ActionSet
.static.specialFlags
= [ 'safe', 'primary' ];
795 * A 'click' event is emitted when an action is clicked.
797 * @param {OO.ui.ActionWidget} action Action that was clicked
803 * A 'resize' event is emitted when an action widget is resized.
805 * @param {OO.ui.ActionWidget} action Action that was resized
811 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
813 * @param {OO.ui.ActionWidget[]} added Actions added
819 * A 'remove' event is emitted when actions are {@link #method-remove removed}
820 * or {@link #clear cleared}.
822 * @param {OO.ui.ActionWidget[]} added Actions removed
828 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
829 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
836 * Handle action change events.
841 OO
.ui
.ActionSet
.prototype.onActionChange = function () {
842 this.organized
= false;
843 if ( this.changing
) {
846 this.emit( 'change' );
851 * Check if an action is one of the special actions.
853 * @param {OO.ui.ActionWidget} action Action to check
854 * @return {boolean} Action is special
856 OO
.ui
.ActionSet
.prototype.isSpecial = function ( action
) {
859 for ( flag
in this.special
) {
860 if ( action
=== this.special
[ flag
] ) {
869 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
872 * @param {Object} [filters] Filters to use, omit to get all actions
873 * @param {string|string[]} [filters.actions] Actions that action widgets must have
874 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
875 * @param {string|string[]} [filters.modes] Modes that action widgets must have
876 * @param {boolean} [filters.visible] Action widgets must be visible
877 * @param {boolean} [filters.disabled] Action widgets must be disabled
878 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
880 OO
.ui
.ActionSet
.prototype.get = function ( filters
) {
881 var i
, len
, list
, category
, actions
, index
, match
, matches
;
886 // Collect category candidates
888 for ( category
in this.categorized
) {
889 list
= filters
[ category
];
891 if ( !Array
.isArray( list
) ) {
894 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
895 actions
= this.categorized
[ category
][ list
[ i
] ];
896 if ( Array
.isArray( actions
) ) {
897 matches
.push
.apply( matches
, actions
);
902 // Remove by boolean filters
903 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
904 match
= matches
[ i
];
906 ( filters
.visible
!== undefined && match
.isVisible() !== filters
.visible
) ||
907 ( filters
.disabled
!== undefined && match
.isDisabled() !== filters
.disabled
)
909 matches
.splice( i
, 1 );
915 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
916 match
= matches
[ i
];
917 index
= matches
.lastIndexOf( match
);
918 while ( index
!== i
) {
919 matches
.splice( index
, 1 );
921 index
= matches
.lastIndexOf( match
);
926 return this.list
.slice();
930 * Get 'special' actions.
932 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
933 * Special flags can be configured in subclasses by changing the static #specialFlags property.
935 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
937 OO
.ui
.ActionSet
.prototype.getSpecial = function () {
939 return $.extend( {}, this.special
);
943 * Get 'other' actions.
945 * Other actions include all non-special visible action widgets.
947 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
949 OO
.ui
.ActionSet
.prototype.getOthers = function () {
951 return this.others
.slice();
955 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
956 * to be available in the specified mode will be made visible. All other actions will be hidden.
958 * @param {string} mode The mode. Only actions configured to be available in the specified
959 * mode will be made visible.
964 OO
.ui
.ActionSet
.prototype.setMode = function ( mode
) {
967 this.changing
= true;
968 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
969 action
= this.list
[ i
];
970 action
.toggle( action
.hasMode( mode
) );
973 this.organized
= false;
974 this.changing
= false;
975 this.emit( 'change' );
981 * Set the abilities of the specified actions.
983 * Action widgets that are configured with the specified actions will be enabled
984 * or disabled based on the boolean values specified in the `actions`
987 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
988 * values that indicate whether or not the action should be enabled.
991 OO
.ui
.ActionSet
.prototype.setAbilities = function ( actions
) {
992 var i
, len
, action
, item
;
994 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
995 item
= this.list
[ i
];
996 action
= item
.getAction();
997 if ( actions
[ action
] !== undefined ) {
998 item
.setDisabled( !actions
[ action
] );
1006 * Executes a function once per action.
1008 * When making changes to multiple actions, use this method instead of iterating over the actions
1009 * manually to defer emitting a #change event until after all actions have been changed.
1011 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
1012 * @param {Function} callback Callback to run for each action; callback is invoked with three
1013 * arguments: the action, the action's index, the list of actions being iterated over
1016 OO
.ui
.ActionSet
.prototype.forEach = function ( filter
, callback
) {
1017 this.changed
= false;
1018 this.changing
= true;
1019 this.get( filter
).forEach( callback
);
1020 this.changing
= false;
1021 if ( this.changed
) {
1022 this.emit( 'change' );
1029 * Add action widgets to the action set.
1031 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
1036 OO
.ui
.ActionSet
.prototype.add = function ( actions
) {
1039 this.changing
= true;
1040 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
1041 action
= actions
[ i
];
1042 action
.connect( this, {
1043 click
: [ 'emit', 'click', action
],
1044 resize
: [ 'emit', 'resize', action
],
1045 toggle
: [ 'onActionChange' ]
1047 this.list
.push( action
);
1049 this.organized
= false;
1050 this.emit( 'add', actions
);
1051 this.changing
= false;
1052 this.emit( 'change' );
1058 * Remove action widgets from the set.
1060 * To remove all actions, you may wish to use the #clear method instead.
1062 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
1067 OO
.ui
.ActionSet
.prototype.remove = function ( actions
) {
1068 var i
, len
, index
, action
;
1070 this.changing
= true;
1071 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
1072 action
= actions
[ i
];
1073 index
= this.list
.indexOf( action
);
1074 if ( index
!== -1 ) {
1075 action
.disconnect( this );
1076 this.list
.splice( index
, 1 );
1079 this.organized
= false;
1080 this.emit( 'remove', actions
);
1081 this.changing
= false;
1082 this.emit( 'change' );
1088 * Remove all action widets from the set.
1090 * To remove only specified actions, use the {@link #method-remove remove} method instead.
1096 OO
.ui
.ActionSet
.prototype.clear = function () {
1098 removed
= this.list
.slice();
1100 this.changing
= true;
1101 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
1102 action
= this.list
[ i
];
1103 action
.disconnect( this );
1108 this.organized
= false;
1109 this.emit( 'remove', removed
);
1110 this.changing
= false;
1111 this.emit( 'change' );
1119 * This is called whenever organized information is requested. It will only reorganize the actions
1120 * if something has changed since the last time it ran.
1125 OO
.ui
.ActionSet
.prototype.organize = function () {
1126 var i
, iLen
, j
, jLen
, flag
, action
, category
, list
, item
, special
,
1127 specialFlags
= this.constructor.static.specialFlags
;
1129 if ( !this.organized
) {
1130 this.categorized
= {};
1133 for ( i
= 0, iLen
= this.list
.length
; i
< iLen
; i
++ ) {
1134 action
= this.list
[ i
];
1135 if ( action
.isVisible() ) {
1136 // Populate categories
1137 for ( category
in this.categories
) {
1138 if ( !this.categorized
[ category
] ) {
1139 this.categorized
[ category
] = {};
1141 list
= action
[ this.categories
[ category
] ]();
1142 if ( !Array
.isArray( list
) ) {
1145 for ( j
= 0, jLen
= list
.length
; j
< jLen
; j
++ ) {
1147 if ( !this.categorized
[ category
][ item
] ) {
1148 this.categorized
[ category
][ item
] = [];
1150 this.categorized
[ category
][ item
].push( action
);
1153 // Populate special/others
1155 for ( j
= 0, jLen
= specialFlags
.length
; j
< jLen
; j
++ ) {
1156 flag
= specialFlags
[ j
];
1157 if ( !this.special
[ flag
] && action
.hasFlag( flag
) ) {
1158 this.special
[ flag
] = action
;
1164 this.others
.push( action
);
1168 this.organized
= true;
1175 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
1176 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
1177 * connected to them and can't be interacted with.
1183 * @param {Object} [config] Configuration options
1184 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
1185 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
1187 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
1188 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
1189 * @cfg {string} [text] Text to insert
1190 * @cfg {Array} [content] An array of content elements to append (after #text).
1191 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
1192 * Instances of OO.ui.Element will have their $element appended.
1193 * @cfg {jQuery} [$content] Content elements to append (after #text).
1194 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
1195 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
1196 * Data can also be specified with the #setData method.
1198 OO
.ui
.Element
= function OoUiElement( config
) {
1199 // Configuration initialization
1200 config
= config
|| {};
1204 this.visible
= true;
1205 this.data
= config
.data
;
1206 this.$element
= config
.$element
||
1207 $( document
.createElement( this.getTagName() ) );
1208 this.elementGroup
= null;
1209 this.debouncedUpdateThemeClassesHandler
= OO
.ui
.debounce( this.debouncedUpdateThemeClasses
);
1212 if ( Array
.isArray( config
.classes
) ) {
1213 this.$element
.addClass( config
.classes
.join( ' ' ) );
1216 this.$element
.attr( 'id', config
.id
);
1218 if ( config
.text
) {
1219 this.$element
.text( config
.text
);
1221 if ( config
.content
) {
1222 // The `content` property treats plain strings as text; use an
1223 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
1224 // appropriate $element appended.
1225 this.$element
.append( config
.content
.map( function ( v
) {
1226 if ( typeof v
=== 'string' ) {
1227 // Escape string so it is properly represented in HTML.
1228 return document
.createTextNode( v
);
1229 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
1231 return v
.toString();
1232 } else if ( v
instanceof OO
.ui
.Element
) {
1238 if ( config
.$content
) {
1239 // The `$content` property treats plain strings as HTML.
1240 this.$element
.append( config
.$content
);
1246 OO
.initClass( OO
.ui
.Element
);
1248 /* Static Properties */
1251 * The name of the HTML tag used by the element.
1253 * The static value may be ignored if the #getTagName method is overridden.
1257 * @property {string}
1259 OO
.ui
.Element
.static.tagName
= 'div';
1261 /* Static Methods */
1264 * Reconstitute a JavaScript object corresponding to a widget created
1265 * by the PHP implementation.
1267 * @param {string|HTMLElement|jQuery} idOrNode
1268 * A DOM id (if a string) or node for the widget to infuse.
1269 * @return {OO.ui.Element}
1270 * The `OO.ui.Element` corresponding to this (infusable) document node.
1271 * For `Tag` objects emitted on the HTML side (used occasionally for content)
1272 * the value returned is a newly-created Element wrapping around the existing
1275 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
1276 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, false );
1277 // Verify that the type matches up.
1278 // FIXME: uncomment after T89721 is fixed (see T90929)
1280 if ( !( obj instanceof this['class'] ) ) {
1281 throw new Error( 'Infusion type mismatch!' );
1288 * Implementation helper for `infuse`; skips the type check and has an
1289 * extra property so that only the top-level invocation touches the DOM.
1291 * @param {string|HTMLElement|jQuery} idOrNode
1292 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
1293 * when the top-level widget of this infusion is inserted into DOM,
1294 * replacing the original node; or false for top-level invocation.
1295 * @return {OO.ui.Element}
1297 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, domPromise
) {
1298 // look for a cached result of a previous infusion.
1299 var id
, $elem
, data
, cls
, parts
, parent
, obj
, top
, state
;
1300 if ( typeof idOrNode
=== 'string' ) {
1302 $elem
= $( document
.getElementById( id
) );
1304 $elem
= $( idOrNode
);
1305 id
= $elem
.attr( 'id' );
1307 if ( !$elem
.length
) {
1308 throw new Error( 'Widget not found: ' + id
);
1310 data
= $elem
.data( 'ooui-infused' ) || $elem
[ 0 ].oouiInfused
;
1313 if ( data
=== true ) {
1314 throw new Error( 'Circular dependency! ' + id
);
1318 data
= $elem
.attr( 'data-ooui' );
1320 throw new Error( 'No infusion data found: ' + id
);
1323 data
= $.parseJSON( data
);
1327 if ( !( data
&& data
._
) ) {
1328 throw new Error( 'No valid infusion data found: ' + id
);
1330 if ( data
._
=== 'Tag' ) {
1331 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1332 return new OO
.ui
.Element( { $element
: $elem
} );
1334 parts
= data
._
.split( '.' );
1335 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
1336 if ( cls
=== undefined ) {
1337 // The PHP output might be old and not including the "OO.ui" prefix
1338 // TODO: Remove this back-compat after next major release
1339 cls
= OO
.getProp
.apply( OO
, [ OO
.ui
].concat( parts
) );
1340 if ( cls
=== undefined ) {
1341 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
1345 // Verify that we're creating an OO.ui.Element instance
1346 parent
= cls
.parent
;
1348 while ( parent
!== undefined ) {
1349 if ( parent
=== OO
.ui
.Element
) {
1354 parent
= parent
.parent
;
1357 if ( parent
!== OO
.ui
.Element
) {
1358 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
1361 if ( domPromise
=== false ) {
1363 domPromise
= top
.promise();
1365 $elem
.data( 'ooui-infused', true ); // prevent loops
1366 data
.id
= id
; // implicit
1367 data
= OO
.copy( data
, null, function deserialize( value
) {
1368 if ( OO
.isPlainObject( value
) ) {
1370 return OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, domPromise
);
1373 return new OO
.ui
.HtmlSnippet( value
.html
);
1377 // allow widgets to reuse parts of the DOM
1378 data
= cls
.static.reusePreInfuseDOM( $elem
[ 0 ], data
);
1379 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
1380 state
= cls
.static.gatherPreInfuseState( $elem
[ 0 ], data
);
1382 // jscs:disable requireCapitalizedConstructors
1383 obj
= new cls( data
);
1384 // jscs:enable requireCapitalizedConstructors
1385 // now replace old DOM with this new DOM.
1387 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
1388 // so only mutate the DOM if we need to.
1389 if ( $elem
[ 0 ] !== obj
.$element
[ 0 ] ) {
1390 $elem
.replaceWith( obj
.$element
);
1391 // This element is now gone from the DOM, but if anyone is holding a reference to it,
1392 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
1393 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
1394 $elem
[ 0 ].oouiInfused
= obj
;
1398 obj
.$element
.data( 'ooui-infused', obj
);
1399 // set the 'data-ooui' attribute so we can identify infused widgets
1400 obj
.$element
.attr( 'data-ooui', '' );
1401 // restore dynamic state after the new element is inserted into DOM
1402 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
1407 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
1409 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
1410 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
1411 * constructor, which will be given the enhanced config.
1414 * @param {HTMLElement} node
1415 * @param {Object} config
1418 OO
.ui
.Element
.static.reusePreInfuseDOM = function ( node
, config
) {
1423 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
1424 * (and its children) that represent an Element of the same class and the given configuration,
1425 * generated by the PHP implementation.
1427 * This method is called just before `node` is detached from the DOM. The return value of this
1428 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
1429 * is inserted into DOM to replace `node`.
1432 * @param {HTMLElement} node
1433 * @param {Object} config
1436 OO
.ui
.Element
.static.gatherPreInfuseState = function () {
1441 * Get a jQuery function within a specific document.
1444 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1445 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1447 * @return {Function} Bound jQuery function
1449 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
1450 function wrapper( selector
) {
1451 return $( selector
, wrapper
.context
);
1454 wrapper
.context
= this.getDocument( context
);
1457 wrapper
.$iframe
= $iframe
;
1464 * Get the document of an element.
1467 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1468 * @return {HTMLDocument|null} Document object
1470 OO
.ui
.Element
.static.getDocument = function ( obj
) {
1471 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1472 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
1473 // Empty jQuery selections might have a context
1476 obj
.ownerDocument
||
1480 ( obj
.nodeType
=== 9 && obj
) ||
1485 * Get the window of an element or document.
1488 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1489 * @return {Window} Window object
1491 OO
.ui
.Element
.static.getWindow = function ( obj
) {
1492 var doc
= this.getDocument( obj
);
1493 return doc
.defaultView
;
1497 * Get the direction of an element or document.
1500 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1501 * @return {string} Text direction, either 'ltr' or 'rtl'
1503 OO
.ui
.Element
.static.getDir = function ( obj
) {
1506 if ( obj
instanceof jQuery
) {
1509 isDoc
= obj
.nodeType
=== 9;
1510 isWin
= obj
.document
!== undefined;
1511 if ( isDoc
|| isWin
) {
1517 return $( obj
).css( 'direction' );
1521 * Get the offset between two frames.
1523 * TODO: Make this function not use recursion.
1526 * @param {Window} from Window of the child frame
1527 * @param {Window} [to=window] Window of the parent frame
1528 * @param {Object} [offset] Offset to start with, used internally
1529 * @return {Object} Offset object, containing left and top properties
1531 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
1532 var i
, len
, frames
, frame
, rect
;
1538 offset
= { top
: 0, left
: 0 };
1540 if ( from.parent
=== from ) {
1544 // Get iframe element
1545 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
1546 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
1547 if ( frames
[ i
].contentWindow
=== from ) {
1548 frame
= frames
[ i
];
1553 // Recursively accumulate offset values
1555 rect
= frame
.getBoundingClientRect();
1556 offset
.left
+= rect
.left
;
1557 offset
.top
+= rect
.top
;
1558 if ( from !== to
) {
1559 this.getFrameOffset( from.parent
, offset
);
1566 * Get the offset between two elements.
1568 * The two elements may be in a different frame, but in that case the frame $element is in must
1569 * be contained in the frame $anchor is in.
1572 * @param {jQuery} $element Element whose position to get
1573 * @param {jQuery} $anchor Element to get $element's position relative to
1574 * @return {Object} Translated position coordinates, containing top and left properties
1576 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
1577 var iframe
, iframePos
,
1578 pos
= $element
.offset(),
1579 anchorPos
= $anchor
.offset(),
1580 elementDocument
= this.getDocument( $element
),
1581 anchorDocument
= this.getDocument( $anchor
);
1583 // If $element isn't in the same document as $anchor, traverse up
1584 while ( elementDocument
!== anchorDocument
) {
1585 iframe
= elementDocument
.defaultView
.frameElement
;
1587 throw new Error( '$element frame is not contained in $anchor frame' );
1589 iframePos
= $( iframe
).offset();
1590 pos
.left
+= iframePos
.left
;
1591 pos
.top
+= iframePos
.top
;
1592 elementDocument
= iframe
.ownerDocument
;
1594 pos
.left
-= anchorPos
.left
;
1595 pos
.top
-= anchorPos
.top
;
1600 * Get element border sizes.
1603 * @param {HTMLElement} el Element to measure
1604 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1606 OO
.ui
.Element
.static.getBorders = function ( el
) {
1607 var doc
= el
.ownerDocument
,
1608 win
= doc
.defaultView
,
1609 style
= win
.getComputedStyle( el
, null ),
1611 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1612 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1613 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1614 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1625 * Get dimensions of an element or window.
1628 * @param {HTMLElement|Window} el Element to measure
1629 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1631 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1633 doc
= el
.ownerDocument
|| el
.document
,
1634 win
= doc
.defaultView
;
1636 if ( win
=== el
|| el
=== doc
.documentElement
) {
1639 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1641 top
: $win
.scrollTop(),
1642 left
: $win
.scrollLeft()
1644 scrollbar
: { right
: 0, bottom
: 0 },
1648 bottom
: $win
.innerHeight(),
1649 right
: $win
.innerWidth()
1655 borders
: this.getBorders( el
),
1657 top
: $el
.scrollTop(),
1658 left
: $el
.scrollLeft()
1661 right
: $el
.innerWidth() - el
.clientWidth
,
1662 bottom
: $el
.innerHeight() - el
.clientHeight
1664 rect
: el
.getBoundingClientRect()
1670 * Get scrollable object parent
1672 * documentElement can't be used to get or set the scrollTop
1673 * property on Blink. Changing and testing its value lets us
1674 * use 'body' or 'documentElement' based on what is working.
1676 * https://code.google.com/p/chromium/issues/detail?id=303131
1679 * @param {HTMLElement} el Element to find scrollable parent for
1680 * @return {HTMLElement} Scrollable parent
1682 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1683 var scrollTop
, body
;
1685 if ( OO
.ui
.scrollableElement
=== undefined ) {
1686 body
= el
.ownerDocument
.body
;
1687 scrollTop
= body
.scrollTop
;
1690 if ( body
.scrollTop
=== 1 ) {
1691 body
.scrollTop
= scrollTop
;
1692 OO
.ui
.scrollableElement
= 'body';
1694 OO
.ui
.scrollableElement
= 'documentElement';
1698 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1702 * Get closest scrollable container.
1704 * Traverses up until either a scrollable element or the root is reached, in which case the window
1708 * @param {HTMLElement} el Element to find scrollable container for
1709 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1710 * @return {HTMLElement} Closest scrollable container
1712 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1714 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1715 props
= [ 'overflow-x', 'overflow-y' ],
1716 $parent
= $( el
).parent();
1718 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1719 props
= [ 'overflow-' + dimension
];
1722 while ( $parent
.length
) {
1723 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1724 return $parent
[ 0 ];
1728 val
= $parent
.css( props
[ i
] );
1729 if ( val
=== 'auto' || val
=== 'scroll' ) {
1730 return $parent
[ 0 ];
1733 $parent
= $parent
.parent();
1735 return this.getDocument( el
).body
;
1739 * Scroll element into view.
1742 * @param {HTMLElement} el Element to scroll into view
1743 * @param {Object} [config] Configuration options
1744 * @param {string} [config.duration] jQuery animation duration value
1745 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1746 * to scroll in both directions
1747 * @param {Function} [config.complete] Function to call when scrolling completes
1749 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1750 var rel
, anim
, callback
, sc
, $sc
, eld
, scd
, $win
;
1752 // Configuration initialization
1753 config
= config
|| {};
1756 callback
= typeof config
.complete
=== 'function' && config
.complete
;
1757 sc
= this.getClosestScrollableContainer( el
, config
.direction
);
1759 eld
= this.getDimensions( el
);
1760 scd
= this.getDimensions( sc
);
1761 $win
= $( this.getWindow( el
) );
1763 // Compute the distances between the edges of el and the edges of the scroll viewport
1764 if ( $sc
.is( 'html, body' ) ) {
1765 // If the scrollable container is the root, this is easy
1768 bottom
: $win
.innerHeight() - eld
.rect
.bottom
,
1769 left
: eld
.rect
.left
,
1770 right
: $win
.innerWidth() - eld
.rect
.right
1773 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1775 top
: eld
.rect
.top
- ( scd
.rect
.top
+ scd
.borders
.top
),
1776 bottom
: scd
.rect
.bottom
- scd
.borders
.bottom
- scd
.scrollbar
.bottom
- eld
.rect
.bottom
,
1777 left
: eld
.rect
.left
- ( scd
.rect
.left
+ scd
.borders
.left
),
1778 right
: scd
.rect
.right
- scd
.borders
.right
- scd
.scrollbar
.right
- eld
.rect
.right
1782 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1783 if ( rel
.top
< 0 ) {
1784 anim
.scrollTop
= scd
.scroll
.top
+ rel
.top
;
1785 } else if ( rel
.top
> 0 && rel
.bottom
< 0 ) {
1786 anim
.scrollTop
= scd
.scroll
.top
+ Math
.min( rel
.top
, -rel
.bottom
);
1789 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1790 if ( rel
.left
< 0 ) {
1791 anim
.scrollLeft
= scd
.scroll
.left
+ rel
.left
;
1792 } else if ( rel
.left
> 0 && rel
.right
< 0 ) {
1793 anim
.scrollLeft
= scd
.scroll
.left
+ Math
.min( rel
.left
, -rel
.right
);
1796 if ( !$.isEmptyObject( anim
) ) {
1797 $sc
.stop( true ).animate( anim
, config
.duration
|| 'fast' );
1799 $sc
.queue( function ( next
) {
1812 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1813 * and reserve space for them, because it probably doesn't.
1815 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1816 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1817 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1818 * and then reattach (or show) them back.
1821 * @param {HTMLElement} el Element to reconsider the scrollbars on
1823 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1824 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1825 // Save scroll position
1826 scrollLeft
= el
.scrollLeft
;
1827 scrollTop
= el
.scrollTop
;
1828 // Detach all children
1829 while ( el
.firstChild
) {
1830 nodes
.push( el
.firstChild
);
1831 el
.removeChild( el
.firstChild
);
1834 void el
.offsetHeight
;
1835 // Reattach all children
1836 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1837 el
.appendChild( nodes
[ i
] );
1839 // Restore scroll position (no-op if scrollbars disappeared)
1840 el
.scrollLeft
= scrollLeft
;
1841 el
.scrollTop
= scrollTop
;
1847 * Toggle visibility of an element.
1849 * @param {boolean} [show] Make element visible, omit to toggle visibility
1853 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1854 show
= show
=== undefined ? !this.visible
: !!show
;
1856 if ( show
!== this.isVisible() ) {
1857 this.visible
= show
;
1858 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1859 this.emit( 'toggle', show
);
1866 * Check if element is visible.
1868 * @return {boolean} element is visible
1870 OO
.ui
.Element
.prototype.isVisible = function () {
1871 return this.visible
;
1877 * @return {Mixed} Element data
1879 OO
.ui
.Element
.prototype.getData = function () {
1886 * @param {Mixed} Element data
1889 OO
.ui
.Element
.prototype.setData = function ( data
) {
1895 * Check if element supports one or more methods.
1897 * @param {string|string[]} methods Method or list of methods to check
1898 * @return {boolean} All methods are supported
1900 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1904 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1905 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1906 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1911 return methods
.length
=== support
;
1915 * Update the theme-provided classes.
1917 * @localdoc This is called in element mixins and widget classes any time state changes.
1918 * Updating is debounced, minimizing overhead of changing multiple attributes and
1919 * guaranteeing that theme updates do not occur within an element's constructor
1921 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1922 this.debouncedUpdateThemeClassesHandler();
1927 * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to
1928 * make them synchronous.
1930 OO
.ui
.Element
.prototype.debouncedUpdateThemeClasses = function () {
1931 OO
.ui
.theme
.updateElementClasses( this );
1935 * Get the HTML tag name.
1937 * Override this method to base the result on instance information.
1939 * @return {string} HTML tag name
1941 OO
.ui
.Element
.prototype.getTagName = function () {
1942 return this.constructor.static.tagName
;
1946 * Check if the element is attached to the DOM
1947 * @return {boolean} The element is attached to the DOM
1949 OO
.ui
.Element
.prototype.isElementAttached = function () {
1950 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1954 * Get the DOM document.
1956 * @return {HTMLDocument} Document object
1958 OO
.ui
.Element
.prototype.getElementDocument = function () {
1959 // Don't cache this in other ways either because subclasses could can change this.$element
1960 return OO
.ui
.Element
.static.getDocument( this.$element
);
1964 * Get the DOM window.
1966 * @return {Window} Window object
1968 OO
.ui
.Element
.prototype.getElementWindow = function () {
1969 return OO
.ui
.Element
.static.getWindow( this.$element
);
1973 * Get closest scrollable container.
1975 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1976 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1980 * Get group element is in.
1982 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1984 OO
.ui
.Element
.prototype.getElementGroup = function () {
1985 return this.elementGroup
;
1989 * Set group element is in.
1991 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1994 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1995 this.elementGroup
= group
;
2000 * Scroll element into view.
2002 * @param {Object} [config] Configuration options
2004 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
2005 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
2009 * Restore the pre-infusion dynamic state for this widget.
2011 * This method is called after #$element has been inserted into DOM. The parameter is the return
2012 * value of #gatherPreInfuseState.
2015 * @param {Object} state
2017 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
2021 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
2022 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
2023 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
2024 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
2025 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
2029 * @extends OO.ui.Element
2030 * @mixins OO.EventEmitter
2033 * @param {Object} [config] Configuration options
2035 OO
.ui
.Layout
= function OoUiLayout( config
) {
2036 // Configuration initialization
2037 config
= config
|| {};
2039 // Parent constructor
2040 OO
.ui
.Layout
.parent
.call( this, config
);
2042 // Mixin constructors
2043 OO
.EventEmitter
.call( this );
2046 this.$element
.addClass( 'oo-ui-layout' );
2051 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
2052 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
2055 * Widgets are compositions of one or more OOjs UI elements that users can both view
2056 * and interact with. All widgets can be configured and modified via a standard API,
2057 * and their state can change dynamically according to a model.
2061 * @extends OO.ui.Element
2062 * @mixins OO.EventEmitter
2065 * @param {Object} [config] Configuration options
2066 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
2067 * appearance reflects this state.
2069 OO
.ui
.Widget
= function OoUiWidget( config
) {
2070 // Initialize config
2071 config
= $.extend( { disabled
: false }, config
);
2073 // Parent constructor
2074 OO
.ui
.Widget
.parent
.call( this, config
);
2076 // Mixin constructors
2077 OO
.EventEmitter
.call( this );
2080 this.disabled
= null;
2081 this.wasDisabled
= null;
2084 this.$element
.addClass( 'oo-ui-widget' );
2085 this.setDisabled( !!config
.disabled
);
2090 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
2091 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
2093 /* Static Properties */
2096 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
2097 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
2102 * @property {boolean}
2104 OO
.ui
.Widget
.static.supportsSimpleLabel
= false;
2111 * A 'disable' event is emitted when the disabled state of the widget changes
2112 * (i.e. on disable **and** enable).
2114 * @param {boolean} disabled Widget is disabled
2120 * A 'toggle' event is emitted when the visibility of the widget changes.
2122 * @param {boolean} visible Widget is visible
2128 * Check if the widget is disabled.
2130 * @return {boolean} Widget is disabled
2132 OO
.ui
.Widget
.prototype.isDisabled = function () {
2133 return this.disabled
;
2137 * Set the 'disabled' state of the widget.
2139 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
2141 * @param {boolean} disabled Disable widget
2144 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
2147 this.disabled
= !!disabled
;
2148 isDisabled
= this.isDisabled();
2149 if ( isDisabled
!== this.wasDisabled
) {
2150 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
2151 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
2152 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
2153 this.emit( 'disable', isDisabled
);
2154 this.updateThemeClasses();
2156 this.wasDisabled
= isDisabled
;
2162 * Update the disabled state, in case of changes in parent widget.
2166 OO
.ui
.Widget
.prototype.updateDisabled = function () {
2167 this.setDisabled( this.disabled
);
2172 * A window is a container for elements that are in a child frame. They are used with
2173 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
2174 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
2175 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
2176 * the window manager will choose a sensible fallback.
2178 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
2179 * different processes are executed:
2181 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
2182 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
2185 * - {@link #getSetupProcess} method is called and its result executed
2186 * - {@link #getReadyProcess} method is called and its result executed
2188 * **opened**: The window is now open
2190 * **closing**: The closing stage begins when the window manager's
2191 * {@link OO.ui.WindowManager#closeWindow closeWindow}
2192 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
2194 * - {@link #getHoldProcess} method is called and its result executed
2195 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
2197 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
2198 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
2199 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
2200 * processing can complete. Always assume window processes are executed asynchronously.
2202 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2204 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
2208 * @extends OO.ui.Element
2209 * @mixins OO.EventEmitter
2212 * @param {Object} [config] Configuration options
2213 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
2214 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
2216 OO
.ui
.Window
= function OoUiWindow( config
) {
2217 // Configuration initialization
2218 config
= config
|| {};
2220 // Parent constructor
2221 OO
.ui
.Window
.parent
.call( this, config
);
2223 // Mixin constructors
2224 OO
.EventEmitter
.call( this );
2227 this.manager
= null;
2228 this.size
= config
.size
|| this.constructor.static.size
;
2229 this.$frame
= $( '<div>' );
2230 this.$overlay
= $( '<div>' );
2231 this.$content
= $( '<div>' );
2233 this.$focusTrapBefore
= $( '<div>' ).prop( 'tabIndex', 0 );
2234 this.$focusTrapAfter
= $( '<div>' ).prop( 'tabIndex', 0 );
2235 this.$focusTraps
= this.$focusTrapBefore
.add( this.$focusTrapAfter
);
2238 this.$overlay
.addClass( 'oo-ui-window-overlay' );
2240 .addClass( 'oo-ui-window-content' )
2241 .attr( 'tabindex', 0 );
2243 .addClass( 'oo-ui-window-frame' )
2244 .append( this.$focusTrapBefore
, this.$content
, this.$focusTrapAfter
);
2247 .addClass( 'oo-ui-window' )
2248 .append( this.$frame
, this.$overlay
);
2250 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
2251 // that reference properties not initialized at that time of parent class construction
2252 // TODO: Find a better way to handle post-constructor setup
2253 this.visible
= false;
2254 this.$element
.addClass( 'oo-ui-element-hidden' );
2259 OO
.inheritClass( OO
.ui
.Window
, OO
.ui
.Element
);
2260 OO
.mixinClass( OO
.ui
.Window
, OO
.EventEmitter
);
2262 /* Static Properties */
2265 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
2267 * The static size is used if no #size is configured during construction.
2271 * @property {string}
2273 OO
.ui
.Window
.static.size
= 'medium';
2278 * Handle mouse down events.
2281 * @param {jQuery.Event} e Mouse down event
2283 OO
.ui
.Window
.prototype.onMouseDown = function ( e
) {
2284 // Prevent clicking on the click-block from stealing focus
2285 if ( e
.target
=== this.$element
[ 0 ] ) {
2291 * Check if the window has been initialized.
2293 * Initialization occurs when a window is added to a manager.
2295 * @return {boolean} Window has been initialized
2297 OO
.ui
.Window
.prototype.isInitialized = function () {
2298 return !!this.manager
;
2302 * Check if the window is visible.
2304 * @return {boolean} Window is visible
2306 OO
.ui
.Window
.prototype.isVisible = function () {
2307 return this.visible
;
2311 * Check if the window is opening.
2313 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2316 * @return {boolean} Window is opening
2318 OO
.ui
.Window
.prototype.isOpening = function () {
2319 return this.manager
.isOpening( this );
2323 * Check if the window is closing.
2325 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2327 * @return {boolean} Window is closing
2329 OO
.ui
.Window
.prototype.isClosing = function () {
2330 return this.manager
.isClosing( this );
2334 * Check if the window is opened.
2336 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2338 * @return {boolean} Window is opened
2340 OO
.ui
.Window
.prototype.isOpened = function () {
2341 return this.manager
.isOpened( this );
2345 * Get the window manager.
2347 * All windows must be attached to a window manager, which is used to open
2348 * and close the window and control its presentation.
2350 * @return {OO.ui.WindowManager} Manager of window
2352 OO
.ui
.Window
.prototype.getManager = function () {
2353 return this.manager
;
2357 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2359 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2361 OO
.ui
.Window
.prototype.getSize = function () {
2362 var viewport
= OO
.ui
.Element
.static.getDimensions( this.getElementWindow() ),
2363 sizes
= this.manager
.constructor.static.sizes
,
2366 if ( !sizes
[ size
] ) {
2367 size
= this.manager
.constructor.static.defaultSize
;
2369 if ( size
!== 'full' && viewport
.rect
.right
- viewport
.rect
.left
< sizes
[ size
].width
) {
2377 * Get the size properties associated with the current window size
2379 * @return {Object} Size properties
2381 OO
.ui
.Window
.prototype.getSizeProperties = function () {
2382 return this.manager
.constructor.static.sizes
[ this.getSize() ];
2386 * Disable transitions on window's frame for the duration of the callback function, then enable them
2390 * @param {Function} callback Function to call while transitions are disabled
2392 OO
.ui
.Window
.prototype.withoutSizeTransitions = function ( callback
) {
2393 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2394 // Disable transitions first, otherwise we'll get values from when the window was animating.
2396 styleObj
= this.$frame
[ 0 ].style
;
2397 oldTransition
= styleObj
.transition
|| styleObj
.OTransition
|| styleObj
.MsTransition
||
2398 styleObj
.MozTransition
|| styleObj
.WebkitTransition
;
2399 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
2400 styleObj
.MozTransition
= styleObj
.WebkitTransition
= 'none';
2402 // Force reflow to make sure the style changes done inside callback really are not transitioned
2403 this.$frame
.height();
2404 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
2405 styleObj
.MozTransition
= styleObj
.WebkitTransition
= oldTransition
;
2409 * Get the height of the full window contents (i.e., the window head, body and foot together).
2411 * What consistitutes the head, body, and foot varies depending on the window type.
2412 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2413 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2414 * and special actions in the head, and dialog content in the body.
2416 * To get just the height of the dialog body, use the #getBodyHeight method.
2418 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2420 OO
.ui
.Window
.prototype.getContentHeight = function () {
2423 bodyStyleObj
= this.$body
[ 0 ].style
,
2424 frameStyleObj
= this.$frame
[ 0 ].style
;
2426 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2427 // Disable transitions first, otherwise we'll get values from when the window was animating.
2428 this.withoutSizeTransitions( function () {
2429 var oldHeight
= frameStyleObj
.height
,
2430 oldPosition
= bodyStyleObj
.position
;
2431 frameStyleObj
.height
= '1px';
2432 // Force body to resize to new width
2433 bodyStyleObj
.position
= 'relative';
2434 bodyHeight
= win
.getBodyHeight();
2435 frameStyleObj
.height
= oldHeight
;
2436 bodyStyleObj
.position
= oldPosition
;
2440 // Add buffer for border
2441 ( this.$frame
.outerHeight() - this.$frame
.innerHeight() ) +
2442 // Use combined heights of children
2443 ( this.$head
.outerHeight( true ) + bodyHeight
+ this.$foot
.outerHeight( true ) )
2448 * Get the height of the window body.
2450 * To get the height of the full window contents (the window body, head, and foot together),
2451 * use #getContentHeight.
2453 * When this function is called, the window will temporarily have been resized
2454 * to height=1px, so .scrollHeight measurements can be taken accurately.
2456 * @return {number} Height of the window body in pixels
2458 OO
.ui
.Window
.prototype.getBodyHeight = function () {
2459 return this.$body
[ 0 ].scrollHeight
;
2463 * Get the directionality of the frame (right-to-left or left-to-right).
2465 * @return {string} Directionality: `'ltr'` or `'rtl'`
2467 OO
.ui
.Window
.prototype.getDir = function () {
2468 return OO
.ui
.Element
.static.getDir( this.$content
) || 'ltr';
2472 * Get the 'setup' process.
2474 * The setup process is used to set up a window for use in a particular context,
2475 * based on the `data` argument. This method is called during the opening phase of the window’s
2478 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2479 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2482 * To add window content that persists between openings, you may wish to use the #initialize method
2485 * @param {Object} [data] Window opening data
2486 * @return {OO.ui.Process} Setup process
2488 OO
.ui
.Window
.prototype.getSetupProcess = function () {
2489 return new OO
.ui
.Process();
2493 * Get the ‘ready’ process.
2495 * The ready process is used to ready a window for use in a particular
2496 * context, based on the `data` argument. This method is called during the opening phase of
2497 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2499 * Override this method to add additional steps to the ‘ready’ process the parent method
2500 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2501 * methods of OO.ui.Process.
2503 * @param {Object} [data] Window opening data
2504 * @return {OO.ui.Process} Ready process
2506 OO
.ui
.Window
.prototype.getReadyProcess = function () {
2507 return new OO
.ui
.Process();
2511 * Get the 'hold' process.
2513 * The hold proccess is used to keep a window from being used in a particular context,
2514 * based on the `data` argument. This method is called during the closing phase of the window’s
2517 * Override this method to add additional steps to the 'hold' process the parent method provides
2518 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2521 * @param {Object} [data] Window closing data
2522 * @return {OO.ui.Process} Hold process
2524 OO
.ui
.Window
.prototype.getHoldProcess = function () {
2525 return new OO
.ui
.Process();
2529 * Get the ‘teardown’ process.
2531 * The teardown process is used to teardown a window after use. During teardown,
2532 * user interactions within the window are conveyed and the window is closed, based on the `data`
2533 * argument. This method is called during the closing phase of the window’s lifecycle.
2535 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2536 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2539 * @param {Object} [data] Window closing data
2540 * @return {OO.ui.Process} Teardown process
2542 OO
.ui
.Window
.prototype.getTeardownProcess = function () {
2543 return new OO
.ui
.Process();
2547 * Set the window manager.
2549 * This will cause the window to initialize. Calling it more than once will cause an error.
2551 * @param {OO.ui.WindowManager} manager Manager for this window
2552 * @throws {Error} An error is thrown if the method is called more than once
2555 OO
.ui
.Window
.prototype.setManager = function ( manager
) {
2556 if ( this.manager
) {
2557 throw new Error( 'Cannot set window manager, window already has a manager' );
2560 this.manager
= manager
;
2567 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2569 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2573 OO
.ui
.Window
.prototype.setSize = function ( size
) {
2580 * Update the window size.
2582 * @throws {Error} An error is thrown if the window is not attached to a window manager
2585 OO
.ui
.Window
.prototype.updateSize = function () {
2586 if ( !this.manager
) {
2587 throw new Error( 'Cannot update window size, must be attached to a manager' );
2590 this.manager
.updateWindowSize( this );
2596 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2597 * when the window is opening. In general, setDimensions should not be called directly.
2599 * To set the size of the window, use the #setSize method.
2601 * @param {Object} dim CSS dimension properties
2602 * @param {string|number} [dim.width] Width
2603 * @param {string|number} [dim.minWidth] Minimum width
2604 * @param {string|number} [dim.maxWidth] Maximum width
2605 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2606 * @param {string|number} [dim.minWidth] Minimum height
2607 * @param {string|number} [dim.maxWidth] Maximum height
2610 OO
.ui
.Window
.prototype.setDimensions = function ( dim
) {
2613 styleObj
= this.$frame
[ 0 ].style
;
2615 // Calculate the height we need to set using the correct width
2616 if ( dim
.height
=== undefined ) {
2617 this.withoutSizeTransitions( function () {
2618 var oldWidth
= styleObj
.width
;
2619 win
.$frame
.css( 'width', dim
.width
|| '' );
2620 height
= win
.getContentHeight();
2621 styleObj
.width
= oldWidth
;
2624 height
= dim
.height
;
2628 width
: dim
.width
|| '',
2629 minWidth
: dim
.minWidth
|| '',
2630 maxWidth
: dim
.maxWidth
|| '',
2631 height
: height
|| '',
2632 minHeight
: dim
.minHeight
|| '',
2633 maxHeight
: dim
.maxHeight
|| ''
2640 * Initialize window contents.
2642 * Before the window is opened for the first time, #initialize is called so that content that
2643 * persists between openings can be added to the window.
2645 * To set up a window with new content each time the window opens, use #getSetupProcess.
2647 * @throws {Error} An error is thrown if the window is not attached to a window manager
2650 OO
.ui
.Window
.prototype.initialize = function () {
2651 if ( !this.manager
) {
2652 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2656 this.$head
= $( '<div>' );
2657 this.$body
= $( '<div>' );
2658 this.$foot
= $( '<div>' );
2659 this.$document
= $( this.getElementDocument() );
2662 this.$element
.on( 'mousedown', this.onMouseDown
.bind( this ) );
2665 this.$head
.addClass( 'oo-ui-window-head' );
2666 this.$body
.addClass( 'oo-ui-window-body' );
2667 this.$foot
.addClass( 'oo-ui-window-foot' );
2668 this.$content
.append( this.$head
, this.$body
, this.$foot
);
2674 * Called when someone tries to focus the hidden element at the end of the dialog.
2675 * Sends focus back to the start of the dialog.
2677 * @param {jQuery.Event} event Focus event
2679 OO
.ui
.Window
.prototype.onFocusTrapFocused = function ( event
) {
2680 if ( this.$focusTrapBefore
.is( event
.target
) ) {
2681 OO
.ui
.findFocusable( this.$content
, true ).focus();
2683 // this.$content is the part of the focus cycle, and is the first focusable element
2684 this.$content
.focus();
2691 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2692 * method, which returns a promise resolved when the window is done opening.
2694 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2696 * @param {Object} [data] Window opening data
2697 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2698 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2699 * value is a new promise, which is resolved when the window begins closing.
2700 * @throws {Error} An error is thrown if the window is not attached to a window manager
2702 OO
.ui
.Window
.prototype.open = function ( data
) {
2703 if ( !this.manager
) {
2704 throw new Error( 'Cannot open window, must be attached to a manager' );
2707 return this.manager
.openWindow( this, data
);
2713 * This method is a wrapper around a call to the window
2714 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2715 * which returns a closing promise resolved when the window is done closing.
2717 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2718 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2719 * the window closes.
2721 * @param {Object} [data] Window closing data
2722 * @return {jQuery.Promise} Promise resolved when window is closed
2723 * @throws {Error} An error is thrown if the window is not attached to a window manager
2725 OO
.ui
.Window
.prototype.close = function ( data
) {
2726 if ( !this.manager
) {
2727 throw new Error( 'Cannot close window, must be attached to a manager' );
2730 return this.manager
.closeWindow( this, data
);
2736 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2739 * @param {Object} [data] Window opening data
2740 * @return {jQuery.Promise} Promise resolved when window is setup
2742 OO
.ui
.Window
.prototype.setup = function ( data
) {
2745 this.toggle( true );
2747 this.focusTrapHandler
= OO
.ui
.bind( this.onFocusTrapFocused
, this );
2748 this.$focusTraps
.on( 'focus', this.focusTrapHandler
);
2750 return this.getSetupProcess( data
).execute().then( function () {
2751 // Force redraw by asking the browser to measure the elements' widths
2752 win
.$element
.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2753 win
.$content
.addClass( 'oo-ui-window-content-setup' ).width();
2760 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2763 * @param {Object} [data] Window opening data
2764 * @return {jQuery.Promise} Promise resolved when window is ready
2766 OO
.ui
.Window
.prototype.ready = function ( data
) {
2769 this.$content
.focus();
2770 return this.getReadyProcess( data
).execute().then( function () {
2771 // Force redraw by asking the browser to measure the elements' widths
2772 win
.$element
.addClass( 'oo-ui-window-ready' ).width();
2773 win
.$content
.addClass( 'oo-ui-window-content-ready' ).width();
2780 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2783 * @param {Object} [data] Window closing data
2784 * @return {jQuery.Promise} Promise resolved when window is held
2786 OO
.ui
.Window
.prototype.hold = function ( data
) {
2789 return this.getHoldProcess( data
).execute().then( function () {
2790 // Get the focused element within the window's content
2791 var $focus
= win
.$content
.find( OO
.ui
.Element
.static.getDocument( win
.$content
).activeElement
);
2793 // Blur the focused element
2794 if ( $focus
.length
) {
2798 // Force redraw by asking the browser to measure the elements' widths
2799 win
.$element
.removeClass( 'oo-ui-window-ready' ).width();
2800 win
.$content
.removeClass( 'oo-ui-window-content-ready' ).width();
2807 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2810 * @param {Object} [data] Window closing data
2811 * @return {jQuery.Promise} Promise resolved when window is torn down
2813 OO
.ui
.Window
.prototype.teardown = function ( data
) {
2816 return this.getTeardownProcess( data
).execute().then( function () {
2817 // Force redraw by asking the browser to measure the elements' widths
2818 win
.$element
.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2819 win
.$content
.removeClass( 'oo-ui-window-content-setup' ).width();
2820 win
.$focusTraps
.off( 'focus', win
.focusTrapHandler
);
2821 win
.toggle( false );
2826 * The Dialog class serves as the base class for the other types of dialogs.
2827 * Unless extended to include controls, the rendered dialog box is a simple window
2828 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2829 * which opens, closes, and controls the presentation of the window. See the
2830 * [OOjs UI documentation on MediaWiki] [1] for more information.
2833 * // A simple dialog window.
2834 * function MyDialog( config ) {
2835 * MyDialog.parent.call( this, config );
2837 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2838 * MyDialog.prototype.initialize = function () {
2839 * MyDialog.parent.prototype.initialize.call( this );
2840 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2841 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2842 * this.$body.append( this.content.$element );
2844 * MyDialog.prototype.getBodyHeight = function () {
2845 * return this.content.$element.outerHeight( true );
2847 * var myDialog = new MyDialog( {
2850 * // Create and append a window manager, which opens and closes the window.
2851 * var windowManager = new OO.ui.WindowManager();
2852 * $( 'body' ).append( windowManager.$element );
2853 * windowManager.addWindows( [ myDialog ] );
2854 * // Open the window!
2855 * windowManager.openWindow( myDialog );
2857 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2861 * @extends OO.ui.Window
2862 * @mixins OO.ui.mixin.PendingElement
2865 * @param {Object} [config] Configuration options
2867 OO
.ui
.Dialog
= function OoUiDialog( config
) {
2868 // Parent constructor
2869 OO
.ui
.Dialog
.parent
.call( this, config
);
2871 // Mixin constructors
2872 OO
.ui
.mixin
.PendingElement
.call( this );
2875 this.actions
= new OO
.ui
.ActionSet();
2876 this.attachedActions
= [];
2877 this.currentAction
= null;
2878 this.onDialogKeyDownHandler
= this.onDialogKeyDown
.bind( this );
2881 this.actions
.connect( this, {
2882 click
: 'onActionClick',
2883 resize
: 'onActionResize',
2884 change
: 'onActionsChange'
2889 .addClass( 'oo-ui-dialog' )
2890 .attr( 'role', 'dialog' );
2895 OO
.inheritClass( OO
.ui
.Dialog
, OO
.ui
.Window
);
2896 OO
.mixinClass( OO
.ui
.Dialog
, OO
.ui
.mixin
.PendingElement
);
2898 /* Static Properties */
2901 * Symbolic name of dialog.
2903 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2904 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2906 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2911 * @property {string}
2913 OO
.ui
.Dialog
.static.name
= '';
2918 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2919 * that will produce a Label node or string. The title can also be specified with data passed to the
2920 * constructor (see #getSetupProcess). In this case, the static value will be overridden.
2925 * @property {jQuery|string|Function}
2927 OO
.ui
.Dialog
.static.title
= '';
2930 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2932 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2933 * value will be overridden.
2935 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2939 * @property {Object[]}
2941 OO
.ui
.Dialog
.static.actions
= [];
2944 * Close the dialog when the 'Esc' key is pressed.
2949 * @property {boolean}
2951 OO
.ui
.Dialog
.static.escapable
= true;
2956 * Handle frame document key down events.
2959 * @param {jQuery.Event} e Key down event
2961 OO
.ui
.Dialog
.prototype.onDialogKeyDown = function ( e
) {
2962 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
2963 this.executeAction( '' );
2965 e
.stopPropagation();
2970 * Handle action resized events.
2973 * @param {OO.ui.ActionWidget} action Action that was resized
2975 OO
.ui
.Dialog
.prototype.onActionResize = function () {
2976 // Override in subclass
2980 * Handle action click events.
2983 * @param {OO.ui.ActionWidget} action Action that was clicked
2985 OO
.ui
.Dialog
.prototype.onActionClick = function ( action
) {
2986 if ( !this.isPending() ) {
2987 this.executeAction( action
.getAction() );
2992 * Handle actions change event.
2996 OO
.ui
.Dialog
.prototype.onActionsChange = function () {
2997 this.detachActions();
2998 if ( !this.isClosing() ) {
2999 this.attachActions();
3004 * Get the set of actions used by the dialog.
3006 * @return {OO.ui.ActionSet}
3008 OO
.ui
.Dialog
.prototype.getActions = function () {
3009 return this.actions
;
3013 * Get a process for taking action.
3015 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
3016 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
3017 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
3019 * @param {string} [action] Symbolic name of action
3020 * @return {OO.ui.Process} Action process
3022 OO
.ui
.Dialog
.prototype.getActionProcess = function ( action
) {
3023 return new OO
.ui
.Process()
3024 .next( function () {
3026 // An empty action always closes the dialog without data, which should always be
3027 // safe and make no changes
3036 * @param {Object} [data] Dialog opening data
3037 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
3038 * the {@link #static-title static title}
3039 * @param {Object[]} [data.actions] List of configuration options for each
3040 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
3042 OO
.ui
.Dialog
.prototype.getSetupProcess = function ( data
) {
3046 return OO
.ui
.Dialog
.parent
.prototype.getSetupProcess
.call( this, data
)
3047 .next( function () {
3048 var config
= this.constructor.static,
3049 actions
= data
.actions
!== undefined ? data
.actions
: config
.actions
;
3051 this.title
.setLabel(
3052 data
.title
!== undefined ? data
.title
: this.constructor.static.title
3054 this.actions
.add( this.getActionWidgets( actions
) );
3056 if ( this.constructor.static.escapable
) {
3057 this.$element
.on( 'keydown', this.onDialogKeyDownHandler
);
3065 OO
.ui
.Dialog
.prototype.getTeardownProcess = function ( data
) {
3067 return OO
.ui
.Dialog
.parent
.prototype.getTeardownProcess
.call( this, data
)
3068 .first( function () {
3069 if ( this.constructor.static.escapable
) {
3070 this.$element
.off( 'keydown', this.onDialogKeyDownHandler
);
3073 this.actions
.clear();
3074 this.currentAction
= null;
3081 OO
.ui
.Dialog
.prototype.initialize = function () {
3085 OO
.ui
.Dialog
.parent
.prototype.initialize
.call( this );
3087 titleId
= OO
.ui
.generateElementId();
3090 this.title
= new OO
.ui
.LabelWidget( {
3095 this.$content
.addClass( 'oo-ui-dialog-content' );
3096 this.$element
.attr( 'aria-labelledby', titleId
);
3097 this.setPendingElement( this.$head
);
3101 * Get action widgets from a list of configs
3103 * @param {Object[]} actions Action widget configs
3104 * @return {OO.ui.ActionWidget[]} Action widgets
3106 OO
.ui
.Dialog
.prototype.getActionWidgets = function ( actions
) {
3107 var i
, len
, widgets
= [];
3108 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
3110 new OO
.ui
.ActionWidget( actions
[ i
] )
3117 * Attach action actions.
3121 OO
.ui
.Dialog
.prototype.attachActions = function () {
3122 // Remember the list of potentially attached actions
3123 this.attachedActions
= this.actions
.get();
3127 * Detach action actions.
3132 OO
.ui
.Dialog
.prototype.detachActions = function () {
3135 // Detach all actions that may have been previously attached
3136 for ( i
= 0, len
= this.attachedActions
.length
; i
< len
; i
++ ) {
3137 this.attachedActions
[ i
].$element
.detach();
3139 this.attachedActions
= [];
3143 * Execute an action.
3145 * @param {string} action Symbolic name of action to execute
3146 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
3148 OO
.ui
.Dialog
.prototype.executeAction = function ( action
) {
3150 this.currentAction
= action
;
3151 return this.getActionProcess( action
).execute()
3152 .always( this.popPending
.bind( this ) );
3156 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
3157 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
3158 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
3159 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
3160 * pertinent data and reused.
3162 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
3163 * `opened`, and `closing`, which represent the primary stages of the cycle:
3165 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
3166 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
3168 * - an `opening` event is emitted with an `opening` promise
3169 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
3170 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
3171 * window and its result executed
3172 * - a `setup` progress notification is emitted from the `opening` promise
3173 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
3174 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
3175 * window and its result executed
3176 * - a `ready` progress notification is emitted from the `opening` promise
3177 * - the `opening` promise is resolved with an `opened` promise
3179 * **Opened**: the window is now open.
3181 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
3182 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
3183 * to close the window.
3185 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
3186 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
3187 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
3188 * window and its result executed
3189 * - a `hold` progress notification is emitted from the `closing` promise
3190 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
3191 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
3192 * window and its result executed
3193 * - a `teardown` progress notification is emitted from the `closing` promise
3194 * - the `closing` promise is resolved. The window is now closed
3196 * See the [OOjs UI documentation on MediaWiki][1] for more information.
3198 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3201 * @extends OO.ui.Element
3202 * @mixins OO.EventEmitter
3205 * @param {Object} [config] Configuration options
3206 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
3207 * Note that window classes that are instantiated with a factory must have
3208 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
3209 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
3211 OO
.ui
.WindowManager
= function OoUiWindowManager( config
) {
3212 // Configuration initialization
3213 config
= config
|| {};
3215 // Parent constructor
3216 OO
.ui
.WindowManager
.parent
.call( this, config
);
3218 // Mixin constructors
3219 OO
.EventEmitter
.call( this );
3222 this.factory
= config
.factory
;
3223 this.modal
= config
.modal
=== undefined || !!config
.modal
;
3225 this.opening
= null;
3227 this.closing
= null;
3228 this.preparingToOpen
= null;
3229 this.preparingToClose
= null;
3230 this.currentWindow
= null;
3231 this.globalEvents
= false;
3232 this.$ariaHidden
= null;
3233 this.onWindowResizeTimeout
= null;
3234 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
3235 this.afterWindowResizeHandler
= this.afterWindowResize
.bind( this );
3239 .addClass( 'oo-ui-windowManager' )
3240 .toggleClass( 'oo-ui-windowManager-modal', this.modal
);
3245 OO
.inheritClass( OO
.ui
.WindowManager
, OO
.ui
.Element
);
3246 OO
.mixinClass( OO
.ui
.WindowManager
, OO
.EventEmitter
);
3251 * An 'opening' event is emitted when the window begins to be opened.
3254 * @param {OO.ui.Window} win Window that's being opened
3255 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
3256 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
3257 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
3258 * @param {Object} data Window opening data
3262 * A 'closing' event is emitted when the window begins to be closed.
3265 * @param {OO.ui.Window} win Window that's being closed
3266 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
3267 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
3268 * processes are complete. When the `closing` promise is resolved, the first argument of its value
3269 * is the closing data.
3270 * @param {Object} data Window closing data
3274 * A 'resize' event is emitted when a window is resized.
3277 * @param {OO.ui.Window} win Window that was resized
3280 /* Static Properties */
3283 * Map of the symbolic name of each window size and its CSS properties.
3287 * @property {Object}
3289 OO
.ui
.WindowManager
.static.sizes
= {
3303 // These can be non-numeric because they are never used in calculations
3310 * Symbolic name of the default window size.
3312 * The default size is used if the window's requested size is not recognized.
3316 * @property {string}
3318 OO
.ui
.WindowManager
.static.defaultSize
= 'medium';
3323 * Handle window resize events.
3326 * @param {jQuery.Event} e Window resize event
3328 OO
.ui
.WindowManager
.prototype.onWindowResize = function () {
3329 clearTimeout( this.onWindowResizeTimeout
);
3330 this.onWindowResizeTimeout
= setTimeout( this.afterWindowResizeHandler
, 200 );
3334 * Handle window resize events.
3337 * @param {jQuery.Event} e Window resize event
3339 OO
.ui
.WindowManager
.prototype.afterWindowResize = function () {
3340 if ( this.currentWindow
) {
3341 this.updateWindowSize( this.currentWindow
);
3346 * Check if window is opening.
3348 * @return {boolean} Window is opening
3350 OO
.ui
.WindowManager
.prototype.isOpening = function ( win
) {
3351 return win
=== this.currentWindow
&& !!this.opening
&& this.opening
.state() === 'pending';
3355 * Check if window is closing.
3357 * @return {boolean} Window is closing
3359 OO
.ui
.WindowManager
.prototype.isClosing = function ( win
) {
3360 return win
=== this.currentWindow
&& !!this.closing
&& this.closing
.state() === 'pending';
3364 * Check if window is opened.
3366 * @return {boolean} Window is opened
3368 OO
.ui
.WindowManager
.prototype.isOpened = function ( win
) {
3369 return win
=== this.currentWindow
&& !!this.opened
&& this.opened
.state() === 'pending';
3373 * Check if a window is being managed.
3375 * @param {OO.ui.Window} win Window to check
3376 * @return {boolean} Window is being managed
3378 OO
.ui
.WindowManager
.prototype.hasWindow = function ( win
) {
3381 for ( name
in this.windows
) {
3382 if ( this.windows
[ name
] === win
) {
3391 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
3393 * @param {OO.ui.Window} win Window being opened
3394 * @param {Object} [data] Window opening data
3395 * @return {number} Milliseconds to wait
3397 OO
.ui
.WindowManager
.prototype.getSetupDelay = function () {
3402 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3404 * @param {OO.ui.Window} win Window being opened
3405 * @param {Object} [data] Window opening data
3406 * @return {number} Milliseconds to wait
3408 OO
.ui
.WindowManager
.prototype.getReadyDelay = function () {
3413 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3415 * @param {OO.ui.Window} win Window being closed
3416 * @param {Object} [data] Window closing data
3417 * @return {number} Milliseconds to wait
3419 OO
.ui
.WindowManager
.prototype.getHoldDelay = function () {
3424 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3425 * executing the ‘teardown’ process.
3427 * @param {OO.ui.Window} win Window being closed
3428 * @param {Object} [data] Window closing data
3429 * @return {number} Milliseconds to wait
3431 OO
.ui
.WindowManager
.prototype.getTeardownDelay = function () {
3432 return this.modal
? 250 : 0;
3436 * Get a window by its symbolic name.
3438 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3439 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3440 * for more information about using factories.
3441 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3443 * @param {string} name Symbolic name of the window
3444 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3445 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3446 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3448 OO
.ui
.WindowManager
.prototype.getWindow = function ( name
) {
3449 var deferred
= $.Deferred(),
3450 win
= this.windows
[ name
];
3452 if ( !( win
instanceof OO
.ui
.Window
) ) {
3453 if ( this.factory
) {
3454 if ( !this.factory
.lookup( name
) ) {
3455 deferred
.reject( new OO
.ui
.Error(
3456 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3459 win
= this.factory
.create( name
);
3460 this.addWindows( [ win
] );
3461 deferred
.resolve( win
);
3464 deferred
.reject( new OO
.ui
.Error(
3465 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3469 deferred
.resolve( win
);
3472 return deferred
.promise();
3476 * Get current window.
3478 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3480 OO
.ui
.WindowManager
.prototype.getCurrentWindow = function () {
3481 return this.currentWindow
;
3487 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3488 * @param {Object} [data] Window opening data
3489 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3490 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3493 OO
.ui
.WindowManager
.prototype.openWindow = function ( win
, data
) {
3495 opening
= $.Deferred();
3497 // Argument handling
3498 if ( typeof win
=== 'string' ) {
3499 return this.getWindow( win
).then( function ( win
) {
3500 return manager
.openWindow( win
, data
);
3505 if ( !this.hasWindow( win
) ) {
3506 opening
.reject( new OO
.ui
.Error(
3507 'Cannot open window: window is not attached to manager'
3509 } else if ( this.preparingToOpen
|| this.opening
|| this.opened
) {
3510 opening
.reject( new OO
.ui
.Error(
3511 'Cannot open window: another window is opening or open'
3516 if ( opening
.state() !== 'rejected' ) {
3517 // If a window is currently closing, wait for it to complete
3518 this.preparingToOpen
= $.when( this.closing
);
3519 // Ensure handlers get called after preparingToOpen is set
3520 this.preparingToOpen
.done( function () {
3521 if ( manager
.modal
) {
3522 manager
.toggleGlobalEvents( true );
3523 manager
.toggleAriaIsolation( true );
3525 manager
.currentWindow
= win
;
3526 manager
.opening
= opening
;
3527 manager
.preparingToOpen
= null;
3528 manager
.emit( 'opening', win
, opening
, data
);
3529 setTimeout( function () {
3530 win
.setup( data
).then( function () {
3531 manager
.updateWindowSize( win
);
3532 manager
.opening
.notify( { state
: 'setup' } );
3533 setTimeout( function () {
3534 win
.ready( data
).then( function () {
3535 manager
.opening
.notify( { state
: 'ready' } );
3536 manager
.opening
= null;
3537 manager
.opened
= $.Deferred();
3538 opening
.resolve( manager
.opened
.promise(), data
);
3540 manager
.opening
= null;
3541 manager
.opened
= $.Deferred();
3543 manager
.closeWindow( win
);
3545 }, manager
.getReadyDelay() );
3547 manager
.opening
= null;
3548 manager
.opened
= $.Deferred();
3550 manager
.closeWindow( win
);
3552 }, manager
.getSetupDelay() );
3556 return opening
.promise();
3562 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3563 * @param {Object} [data] Window closing data
3564 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3565 * See {@link #event-closing 'closing' event} for more information about closing promises.
3566 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3569 OO
.ui
.WindowManager
.prototype.closeWindow = function ( win
, data
) {
3571 closing
= $.Deferred(),
3574 // Argument handling
3575 if ( typeof win
=== 'string' ) {
3576 win
= this.windows
[ win
];
3577 } else if ( !this.hasWindow( win
) ) {
3583 closing
.reject( new OO
.ui
.Error(
3584 'Cannot close window: window is not attached to manager'
3586 } else if ( win
!== this.currentWindow
) {
3587 closing
.reject( new OO
.ui
.Error(
3588 'Cannot close window: window already closed with different data'
3590 } else if ( this.preparingToClose
|| this.closing
) {
3591 closing
.reject( new OO
.ui
.Error(
3592 'Cannot close window: window already closing with different data'
3597 if ( closing
.state() !== 'rejected' ) {
3598 // If the window is currently opening, close it when it's done
3599 this.preparingToClose
= $.when( this.opening
);
3600 // Ensure handlers get called after preparingToClose is set
3601 this.preparingToClose
.always( function () {
3602 manager
.closing
= closing
;
3603 manager
.preparingToClose
= null;
3604 manager
.emit( 'closing', win
, closing
, data
);
3605 opened
= manager
.opened
;
3606 manager
.opened
= null;
3607 opened
.resolve( closing
.promise(), data
);
3608 setTimeout( function () {
3609 win
.hold( data
).then( function () {
3610 closing
.notify( { state
: 'hold' } );
3611 setTimeout( function () {
3612 win
.teardown( data
).then( function () {
3613 closing
.notify( { state
: 'teardown' } );
3614 if ( manager
.modal
) {
3615 manager
.toggleGlobalEvents( false );
3616 manager
.toggleAriaIsolation( false );
3618 manager
.closing
= null;
3619 manager
.currentWindow
= null;
3620 closing
.resolve( data
);
3622 }, manager
.getTeardownDelay() );
3624 }, manager
.getHoldDelay() );
3628 return closing
.promise();
3632 * Add windows to the window manager.
3634 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3635 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3636 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3638 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3639 * by reference, symbolic name, or explicitly defined symbolic names.
3640 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3641 * explicit nor a statically configured symbolic name.
3643 OO
.ui
.WindowManager
.prototype.addWindows = function ( windows
) {
3644 var i
, len
, win
, name
, list
;
3646 if ( Array
.isArray( windows
) ) {
3647 // Convert to map of windows by looking up symbolic names from static configuration
3649 for ( i
= 0, len
= windows
.length
; i
< len
; i
++ ) {
3650 name
= windows
[ i
].constructor.static.name
;
3651 if ( typeof name
!== 'string' ) {
3652 throw new Error( 'Cannot add window' );
3654 list
[ name
] = windows
[ i
];
3656 } else if ( OO
.isPlainObject( windows
) ) {
3661 for ( name
in list
) {
3663 this.windows
[ name
] = win
.toggle( false );
3664 this.$element
.append( win
.$element
);
3665 win
.setManager( this );
3670 * Remove the specified windows from the windows manager.
3672 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3673 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3674 * longer listens to events, use the #destroy method.
3676 * @param {string[]} names Symbolic names of windows to remove
3677 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3678 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3680 OO
.ui
.WindowManager
.prototype.removeWindows = function ( names
) {
3681 var i
, len
, win
, name
, cleanupWindow
,
3684 cleanup = function ( name
, win
) {
3685 delete manager
.windows
[ name
];
3686 win
.$element
.detach();
3689 for ( i
= 0, len
= names
.length
; i
< len
; i
++ ) {
3691 win
= this.windows
[ name
];
3693 throw new Error( 'Cannot remove window' );
3695 cleanupWindow
= cleanup
.bind( null, name
, win
);
3696 promises
.push( this.closeWindow( name
).then( cleanupWindow
, cleanupWindow
) );
3699 return $.when
.apply( $, promises
);
3703 * Remove all windows from the window manager.
3705 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3706 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3707 * To remove just a subset of windows, use the #removeWindows method.
3709 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3711 OO
.ui
.WindowManager
.prototype.clearWindows = function () {
3712 return this.removeWindows( Object
.keys( this.windows
) );
3716 * Set dialog size. In general, this method should not be called directly.
3718 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3722 OO
.ui
.WindowManager
.prototype.updateWindowSize = function ( win
) {
3725 // Bypass for non-current, and thus invisible, windows
3726 if ( win
!== this.currentWindow
) {
3730 isFullscreen
= win
.getSize() === 'full';
3732 this.$element
.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen
);
3733 this.$element
.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen
);
3734 win
.setDimensions( win
.getSizeProperties() );
3736 this.emit( 'resize', win
);
3742 * Bind or unbind global events for scrolling.
3745 * @param {boolean} [on] Bind global events
3748 OO
.ui
.WindowManager
.prototype.toggleGlobalEvents = function ( on
) {
3749 var scrollWidth
, bodyMargin
,
3750 $body
= $( this.getElementDocument().body
),
3751 // We could have multiple window managers open so only modify
3752 // the body css at the bottom of the stack
3753 stackDepth
= $body
.data( 'windowManagerGlobalEvents' ) || 0 ;
3755 on
= on
=== undefined ? !!this.globalEvents
: !!on
;
3758 if ( !this.globalEvents
) {
3759 $( this.getElementWindow() ).on( {
3760 // Start listening for top-level window dimension changes
3761 'orientationchange resize': this.onWindowResizeHandler
3763 if ( stackDepth
=== 0 ) {
3764 scrollWidth
= window
.innerWidth
- document
.documentElement
.clientWidth
;
3765 bodyMargin
= parseFloat( $body
.css( 'margin-right' ) ) || 0;
3768 'margin-right': bodyMargin
+ scrollWidth
3772 this.globalEvents
= true;
3774 } else if ( this.globalEvents
) {
3775 $( this.getElementWindow() ).off( {
3776 // Stop listening for top-level window dimension changes
3777 'orientationchange resize': this.onWindowResizeHandler
3780 if ( stackDepth
=== 0 ) {
3786 this.globalEvents
= false;
3788 $body
.data( 'windowManagerGlobalEvents', stackDepth
);
3794 * Toggle screen reader visibility of content other than the window manager.
3797 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3800 OO
.ui
.WindowManager
.prototype.toggleAriaIsolation = function ( isolate
) {
3801 isolate
= isolate
=== undefined ? !this.$ariaHidden
: !!isolate
;
3804 if ( !this.$ariaHidden
) {
3805 // Hide everything other than the window manager from screen readers
3806 this.$ariaHidden
= $( 'body' )
3808 .not( this.$element
.parentsUntil( 'body' ).last() )
3809 .attr( 'aria-hidden', '' );
3811 } else if ( this.$ariaHidden
) {
3812 // Restore screen reader visibility
3813 this.$ariaHidden
.removeAttr( 'aria-hidden' );
3814 this.$ariaHidden
= null;
3821 * Destroy the window manager.
3823 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3824 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3827 OO
.ui
.WindowManager
.prototype.destroy = function () {
3828 this.toggleGlobalEvents( false );
3829 this.toggleAriaIsolation( false );
3830 this.clearWindows();
3831 this.$element
.remove();
3835 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3836 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3837 * appearance and functionality of the error interface.
3839 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3840 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3841 * that initiated the failed process will be disabled.
3843 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3846 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3848 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3853 * @param {string|jQuery} message Description of error
3854 * @param {Object} [config] Configuration options
3855 * @cfg {boolean} [recoverable=true] Error is recoverable.
3856 * By default, errors are recoverable, and users can try the process again.
3857 * @cfg {boolean} [warning=false] Error is a warning.
3858 * If the error is a warning, the error interface will include a
3859 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3860 * is not triggered a second time if the user chooses to continue.
3862 OO
.ui
.Error
= function OoUiError( message
, config
) {
3863 // Allow passing positional parameters inside the config object
3864 if ( OO
.isPlainObject( message
) && config
=== undefined ) {
3866 message
= config
.message
;
3869 // Configuration initialization
3870 config
= config
|| {};
3873 this.message
= message
instanceof jQuery
? message
: String( message
);
3874 this.recoverable
= config
.recoverable
=== undefined || !!config
.recoverable
;
3875 this.warning
= !!config
.warning
;
3880 OO
.initClass( OO
.ui
.Error
);
3885 * Check if the error is recoverable.
3887 * If the error is recoverable, users are able to try the process again.
3889 * @return {boolean} Error is recoverable
3891 OO
.ui
.Error
.prototype.isRecoverable = function () {
3892 return this.recoverable
;
3896 * Check if the error is a warning.
3898 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3900 * @return {boolean} Error is warning
3902 OO
.ui
.Error
.prototype.isWarning = function () {
3903 return this.warning
;
3907 * Get error message as DOM nodes.
3909 * @return {jQuery} Error message in DOM nodes
3911 OO
.ui
.Error
.prototype.getMessage = function () {
3912 return this.message
instanceof jQuery
?
3913 this.message
.clone() :
3914 $( '<div>' ).text( this.message
).contents();
3918 * Get the error message text.
3920 * @return {string} Error message
3922 OO
.ui
.Error
.prototype.getMessageText = function () {
3923 return this.message
instanceof jQuery
? this.message
.text() : this.message
;
3927 * Wraps an HTML snippet for use with configuration values which default
3928 * to strings. This bypasses the default html-escaping done to string
3934 * @param {string} [content] HTML content
3936 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
3938 this.content
= content
;
3943 OO
.initClass( OO
.ui
.HtmlSnippet
);
3950 * @return {string} Unchanged HTML snippet.
3952 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
3953 return this.content
;
3957 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3960 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3961 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3962 * or stop if the promise is rejected.
3963 * - **function**: the process will execute the function. The process will stop if the function returns
3964 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3965 * will wait for that number of milliseconds before proceeding.
3967 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3968 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3969 * its remaining steps will not be performed.
3974 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3975 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3976 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3977 * a number or promise.
3978 * @return {Object} Step object, with `callback` and `context` properties
3980 OO
.ui
.Process = function ( step
, context
) {
3985 if ( step
!== undefined ) {
3986 this.next( step
, context
);
3992 OO
.initClass( OO
.ui
.Process
);
3997 * Start the process.
3999 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
4000 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
4001 * and any remaining steps are not performed.
4003 OO
.ui
.Process
.prototype.execute = function () {
4004 var i
, len
, promise
;
4007 * Continue execution.
4010 * @param {Array} step A function and the context it should be called in
4011 * @return {Function} Function that continues the process
4013 function proceed( step
) {
4014 return function () {
4015 // Execute step in the correct context
4017 result
= step
.callback
.call( step
.context
);
4019 if ( result
=== false ) {
4020 // Use rejected promise for boolean false results
4021 return $.Deferred().reject( [] ).promise();
4023 if ( typeof result
=== 'number' ) {
4025 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
4027 // Use a delayed promise for numbers, expecting them to be in milliseconds
4028 deferred
= $.Deferred();
4029 setTimeout( deferred
.resolve
, result
);
4030 return deferred
.promise();
4032 if ( result
instanceof OO
.ui
.Error
) {
4033 // Use rejected promise for error
4034 return $.Deferred().reject( [ result
] ).promise();
4036 if ( Array
.isArray( result
) && result
.length
&& result
[ 0 ] instanceof OO
.ui
.Error
) {
4037 // Use rejected promise for list of errors
4038 return $.Deferred().reject( result
).promise();
4040 // Duck-type the object to see if it can produce a promise
4041 if ( result
&& $.isFunction( result
.promise
) ) {
4042 // Use a promise generated from the result
4043 return result
.promise();
4045 // Use resolved promise for other results
4046 return $.Deferred().resolve().promise();
4050 if ( this.steps
.length
) {
4051 // Generate a chain reaction of promises
4052 promise
= proceed( this.steps
[ 0 ] )();
4053 for ( i
= 1, len
= this.steps
.length
; i
< len
; i
++ ) {
4054 promise
= promise
.then( proceed( this.steps
[ i
] ) );
4057 promise
= $.Deferred().resolve().promise();
4064 * Create a process step.
4067 * @param {number|jQuery.Promise|Function} step
4069 * - Number of milliseconds to wait before proceeding
4070 * - Promise that must be resolved before proceeding
4071 * - Function to execute
4072 * - If the function returns a boolean false the process will stop
4073 * - If the function returns a promise, the process will continue to the next
4074 * step when the promise is resolved or stop if the promise is rejected
4075 * - If the function returns a number, the process will wait for that number of
4076 * milliseconds before proceeding
4077 * @param {Object} [context=null] Execution context of the function. The context is
4078 * ignored if the step is a number or promise.
4079 * @return {Object} Step object, with `callback` and `context` properties
4081 OO
.ui
.Process
.prototype.createStep = function ( step
, context
) {
4082 if ( typeof step
=== 'number' || $.isFunction( step
.promise
) ) {
4084 callback: function () {
4090 if ( $.isFunction( step
) ) {
4096 throw new Error( 'Cannot create process step: number, promise or function expected' );
4100 * Add step to the beginning of the process.
4102 * @inheritdoc #createStep
4103 * @return {OO.ui.Process} this
4106 OO
.ui
.Process
.prototype.first = function ( step
, context
) {
4107 this.steps
.unshift( this.createStep( step
, context
) );
4112 * Add step to the end of the process.
4114 * @inheritdoc #createStep
4115 * @return {OO.ui.Process} this
4118 OO
.ui
.Process
.prototype.next = function ( step
, context
) {
4119 this.steps
.push( this.createStep( step
, context
) );
4124 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
4125 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
4126 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
4128 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4130 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4133 * @extends OO.Factory
4136 OO
.ui
.ToolFactory
= function OoUiToolFactory() {
4137 // Parent constructor
4138 OO
.ui
.ToolFactory
.parent
.call( this );
4143 OO
.inheritClass( OO
.ui
.ToolFactory
, OO
.Factory
);
4148 * Get tools from the factory
4150 * @param {Array|string} [include] Included tools, see #extract for format
4151 * @param {Array|string} [exclude] Excluded tools, see #extract for format
4152 * @param {Array|string} [promote] Promoted tools, see #extract for format
4153 * @param {Array|string} [demote] Demoted tools, see #extract for format
4154 * @return {string[]} List of tools
4156 OO
.ui
.ToolFactory
.prototype.getTools = function ( include
, exclude
, promote
, demote
) {
4157 var i
, len
, included
, promoted
, demoted
,
4161 // Collect included and not excluded tools
4162 included
= OO
.simpleArrayDifference( this.extract( include
), this.extract( exclude
) );
4165 promoted
= this.extract( promote
, used
);
4166 demoted
= this.extract( demote
, used
);
4169 for ( i
= 0, len
= included
.length
; i
< len
; i
++ ) {
4170 if ( !used
[ included
[ i
] ] ) {
4171 auto
.push( included
[ i
] );
4175 return promoted
.concat( auto
).concat( demoted
);
4179 * Get a flat list of names from a list of names or groups.
4181 * Normally, `collection` is an array of tool specifications. Tools can be specified in the
4184 * - To include an individual tool, use the symbolic name: `{ name: 'tool-name' }` or `'tool-name'`.
4185 * - To include all tools in a group, use the group name: `{ group: 'group-name' }`. (To assign the
4186 * tool to a group, use OO.ui.Tool.static.group.)
4188 * Alternatively, to include all tools that are not yet assigned to any other toolgroup, use the
4189 * catch-all selector `'*'`.
4191 * If `used` is passed, tool names that appear as properties in this object will be considered
4192 * already assigned, and will not be returned even if specified otherwise. The tool names extracted
4193 * by this function call will be added as new properties in the object.
4196 * @param {Array|string} collection List of tools, see above
4197 * @param {Object} [used] Object containing information about used tools, see above
4198 * @return {string[]} List of extracted tool names
4200 OO
.ui
.ToolFactory
.prototype.extract = function ( collection
, used
) {
4201 var i
, len
, item
, name
, tool
,
4204 if ( collection
=== '*' ) {
4205 for ( name
in this.registry
) {
4206 tool
= this.registry
[ name
];
4208 // Only add tools by group name when auto-add is enabled
4209 tool
.static.autoAddToCatchall
&&
4210 // Exclude already used tools
4211 ( !used
|| !used
[ name
] )
4215 used
[ name
] = true;
4219 } else if ( Array
.isArray( collection
) ) {
4220 for ( i
= 0, len
= collection
.length
; i
< len
; i
++ ) {
4221 item
= collection
[ i
];
4222 // Allow plain strings as shorthand for named tools
4223 if ( typeof item
=== 'string' ) {
4224 item
= { name
: item
};
4226 if ( OO
.isPlainObject( item
) ) {
4228 for ( name
in this.registry
) {
4229 tool
= this.registry
[ name
];
4231 // Include tools with matching group
4232 tool
.static.group
=== item
.group
&&
4233 // Only add tools by group name when auto-add is enabled
4234 tool
.static.autoAddToGroup
&&
4235 // Exclude already used tools
4236 ( !used
|| !used
[ name
] )
4240 used
[ name
] = true;
4244 // Include tools with matching name and exclude already used tools
4245 } else if ( item
.name
&& ( !used
|| !used
[ item
.name
] ) ) {
4246 names
.push( item
.name
);
4248 used
[ item
.name
] = true;
4258 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
4259 * specify a symbolic name and be registered with the factory. The following classes are registered by
4262 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
4263 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
4264 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
4266 * See {@link OO.ui.Toolbar toolbars} for an example.
4268 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4270 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4272 * @extends OO.Factory
4275 OO
.ui
.ToolGroupFactory
= function OoUiToolGroupFactory() {
4276 var i
, l
, defaultClasses
;
4277 // Parent constructor
4278 OO
.Factory
.call( this );
4280 defaultClasses
= this.constructor.static.getDefaultClasses();
4282 // Register default toolgroups
4283 for ( i
= 0, l
= defaultClasses
.length
; i
< l
; i
++ ) {
4284 this.register( defaultClasses
[ i
] );
4290 OO
.inheritClass( OO
.ui
.ToolGroupFactory
, OO
.Factory
);
4292 /* Static Methods */
4295 * Get a default set of classes to be registered on construction.
4297 * @return {Function[]} Default classes
4299 OO
.ui
.ToolGroupFactory
.static.getDefaultClasses = function () {
4302 OO
.ui
.ListToolGroup
,
4314 * @param {Object} [config] Configuration options
4316 OO
.ui
.Theme
= function OoUiTheme( config
) {
4317 // Configuration initialization
4318 config
= config
|| {};
4323 OO
.initClass( OO
.ui
.Theme
);
4328 * Get a list of classes to be applied to a widget.
4330 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4331 * otherwise state transitions will not work properly.
4333 * @param {OO.ui.Element} element Element for which to get classes
4334 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4336 OO
.ui
.Theme
.prototype.getElementClasses = function () {
4337 return { on
: [], off
: [] };
4341 * Update CSS classes provided by the theme.
4343 * For elements with theme logic hooks, this should be called any time there's a state change.
4345 * @param {OO.ui.Element} element Element for which to update classes
4346 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4348 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
4349 var $elements
= $( [] ),
4350 classes
= this.getElementClasses( element
);
4352 if ( element
.$icon
) {
4353 $elements
= $elements
.add( element
.$icon
);
4355 if ( element
.$indicator
) {
4356 $elements
= $elements
.add( element
.$indicator
);
4360 .removeClass( classes
.off
.join( ' ' ) )
4361 .addClass( classes
.on
.join( ' ' ) );
4365 * RequestManager is a mixin that manages the lifecycle of a promise-backed request for a widget, such as
4366 * the {@link OO.ui.mixin.LookupElement}.
4373 OO
.ui
.mixin
.RequestManager
= function OoUiMixinRequestManager() {
4374 this.requestCache
= {};
4375 this.requestQuery
= null;
4376 this.requestRequest
= null;
4381 OO
.initClass( OO
.ui
.mixin
.RequestManager
);
4384 * Get request results for the current query.
4386 * @return {jQuery.Promise} Promise object which will be passed response data as the first argument of
4387 * the done event. If the request was aborted to make way for a subsequent request, this promise
4388 * may not be rejected, depending on what jQuery feels like doing.
4390 OO
.ui
.mixin
.RequestManager
.prototype.getRequestData = function () {
4392 value
= this.getRequestQuery(),
4393 deferred
= $.Deferred(),
4396 this.abortRequest();
4397 if ( Object
.prototype.hasOwnProperty
.call( this.requestCache
, value
) ) {
4398 deferred
.resolve( this.requestCache
[ value
] );
4400 if ( this.pushPending
) {
4403 this.requestQuery
= value
;
4404 ourRequest
= this.requestRequest
= this.getRequest();
4406 .always( function () {
4407 // We need to pop pending even if this is an old request, otherwise
4408 // the widget will remain pending forever.
4409 // TODO: this assumes that an aborted request will fail or succeed soon after
4410 // being aborted, or at least eventually. It would be nice if we could popPending()
4411 // at abort time, but only if we knew that we hadn't already called popPending()
4412 // for that request.
4413 if ( widget
.popPending
) {
4414 widget
.popPending();
4417 .done( function ( response
) {
4418 // If this is an old request (and aborting it somehow caused it to still succeed),
4419 // ignore its success completely
4420 if ( ourRequest
=== widget
.requestRequest
) {
4421 widget
.requestQuery
= null;
4422 widget
.requestRequest
= null;
4423 widget
.requestCache
[ value
] = widget
.getRequestCacheDataFromResponse( response
);
4424 deferred
.resolve( widget
.requestCache
[ value
] );
4427 .fail( function () {
4428 // If this is an old request (or a request failing because it's being aborted),
4429 // ignore its failure completely
4430 if ( ourRequest
=== widget
.requestRequest
) {
4431 widget
.requestQuery
= null;
4432 widget
.requestRequest
= null;
4437 return deferred
.promise();
4441 * Abort the currently pending request, if any.
4445 OO
.ui
.mixin
.RequestManager
.prototype.abortRequest = function () {
4446 var oldRequest
= this.requestRequest
;
4448 // First unset this.requestRequest to the fail handler will notice
4449 // that the request is no longer current
4450 this.requestRequest
= null;
4451 this.requestQuery
= null;
4457 * Get the query to be made.
4462 * @return {string} query to be used
4464 OO
.ui
.mixin
.RequestManager
.prototype.getRequestQuery
= null;
4467 * Get a new request object of the current query value.
4472 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
4474 OO
.ui
.mixin
.RequestManager
.prototype.getRequest
= null;
4477 * Pre-process data returned by the request from #getRequest.
4479 * The return value of this function will be cached, and any further queries for the given value
4480 * will use the cache rather than doing API requests.
4485 * @param {Mixed} response Response from server
4486 * @return {Mixed} Cached result data
4488 OO
.ui
.mixin
.RequestManager
.prototype.getRequestCacheDataFromResponse
= null;
4491 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4492 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4493 * order in which users will navigate through the focusable elements via the "tab" key.
4496 * // TabIndexedElement is mixed into the ButtonWidget class
4497 * // to provide a tabIndex property.
4498 * var button1 = new OO.ui.ButtonWidget( {
4502 * var button2 = new OO.ui.ButtonWidget( {
4506 * var button3 = new OO.ui.ButtonWidget( {
4510 * var button4 = new OO.ui.ButtonWidget( {
4514 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4520 * @param {Object} [config] Configuration options
4521 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4522 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4523 * functionality will be applied to it instead.
4524 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4525 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4526 * to remove the element from the tab-navigation flow.
4528 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
4529 // Configuration initialization
4530 config
= $.extend( { tabIndex
: 0 }, config
);
4533 this.$tabIndexed
= null;
4534 this.tabIndex
= null;
4537 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
4540 this.setTabIndex( config
.tabIndex
);
4541 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
4546 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
4551 * Set the element that should use the tabindex functionality.
4553 * This method is used to retarget a tabindex mixin so that its functionality applies
4554 * to the specified element. If an element is currently using the functionality, the mixin’s
4555 * effect on that element is removed before the new element is set up.
4557 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4560 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
4561 var tabIndex
= this.tabIndex
;
4562 // Remove attributes from old $tabIndexed
4563 this.setTabIndex( null );
4564 // Force update of new $tabIndexed
4565 this.$tabIndexed
= $tabIndexed
;
4566 this.tabIndex
= tabIndex
;
4567 return this.updateTabIndex();
4571 * Set the value of the tabindex.
4573 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4576 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
4577 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
4579 if ( this.tabIndex
!== tabIndex
) {
4580 this.tabIndex
= tabIndex
;
4581 this.updateTabIndex();
4588 * Update the `tabindex` attribute, in case of changes to tab index or
4594 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
4595 if ( this.$tabIndexed
) {
4596 if ( this.tabIndex
!== null ) {
4597 // Do not index over disabled elements
4598 this.$tabIndexed
.attr( {
4599 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
4600 // Support: ChromeVox and NVDA
4601 // These do not seem to inherit aria-disabled from parent elements
4602 'aria-disabled': this.isDisabled().toString()
4605 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
4612 * Handle disable events.
4615 * @param {boolean} disabled Element is disabled
4617 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
4618 this.updateTabIndex();
4622 * Get the value of the tabindex.
4624 * @return {number|null} Tabindex value
4626 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
4627 return this.tabIndex
;
4631 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4632 * interface element that can be configured with access keys for accessibility.
4633 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4635 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4640 * @param {Object} [config] Configuration options
4641 * @cfg {jQuery} [$button] The button element created by the class.
4642 * If this configuration is omitted, the button element will use a generated `<a>`.
4643 * @cfg {boolean} [framed=true] Render the button with a frame
4645 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
4646 // Configuration initialization
4647 config
= config
|| {};
4650 this.$button
= null;
4652 this.active
= false;
4653 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
4654 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4655 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
4656 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
4657 this.onClickHandler
= this.onClick
.bind( this );
4658 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
4661 this.$element
.addClass( 'oo-ui-buttonElement' );
4662 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
4663 this.setButtonElement( config
.$button
|| $( '<a>' ) );
4668 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
4670 /* Static Properties */
4673 * Cancel mouse down events.
4675 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4676 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4677 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4682 * @property {boolean}
4684 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
4689 * A 'click' event is emitted when the button element is clicked.
4697 * Set the button element.
4699 * This method is used to retarget a button mixin so that its functionality applies to
4700 * the specified button element instead of the one created by the class. If a button element
4701 * is already set, the method will remove the mixin’s effect on that element.
4703 * @param {jQuery} $button Element to use as button
4705 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
4706 if ( this.$button
) {
4708 .removeClass( 'oo-ui-buttonElement-button' )
4709 .removeAttr( 'role accesskey' )
4711 mousedown
: this.onMouseDownHandler
,
4712 keydown
: this.onKeyDownHandler
,
4713 click
: this.onClickHandler
,
4714 keypress
: this.onKeyPressHandler
4718 this.$button
= $button
4719 .addClass( 'oo-ui-buttonElement-button' )
4720 .attr( { role
: 'button' } )
4722 mousedown
: this.onMouseDownHandler
,
4723 keydown
: this.onKeyDownHandler
,
4724 click
: this.onClickHandler
,
4725 keypress
: this.onKeyPressHandler
4730 * Handles mouse down events.
4733 * @param {jQuery.Event} e Mouse down event
4735 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
4736 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
4739 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4740 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4741 // reliably remove the pressed class
4742 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
4743 // Prevent change of focus unless specifically configured otherwise
4744 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
4750 * Handles mouse up events.
4753 * @param {jQuery.Event} e Mouse up event
4755 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
4756 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
4759 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4760 // Stop listening for mouseup, since we only needed this once
4761 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
4765 * Handles mouse click events.
4768 * @param {jQuery.Event} e Mouse click event
4771 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
4772 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
4773 if ( this.emit( 'click' ) ) {
4780 * Handles key down events.
4783 * @param {jQuery.Event} e Key down event
4785 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
4786 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4789 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4790 // Run the keyup handler no matter where the key is when the button is let go, so we can
4791 // reliably remove the pressed class
4792 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler
, true );
4796 * Handles key up events.
4799 * @param {jQuery.Event} e Key up event
4801 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
4802 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4805 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4806 // Stop listening for keyup, since we only needed this once
4807 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler
, true );
4811 * Handles key press events.
4814 * @param {jQuery.Event} e Key press event
4817 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
4818 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
4819 if ( this.emit( 'click' ) ) {
4826 * Check if button has a frame.
4828 * @return {boolean} Button is framed
4830 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
4835 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4837 * @param {boolean} [framed] Make button framed, omit to toggle
4840 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
4841 framed
= framed
=== undefined ? !this.framed
: !!framed
;
4842 if ( framed
!== this.framed
) {
4843 this.framed
= framed
;
4845 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
4846 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
4847 this.updateThemeClasses();
4854 * Set the button's active state.
4856 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4857 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4858 * for other button types.
4860 * @param {boolean} value Make button active
4863 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
4864 this.active
= !!value
;
4865 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
4870 * Check if the button is active
4872 * @return {boolean} The button is active
4874 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
4879 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4880 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4881 * items from the group is done through the interface the class provides.
4882 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4884 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4890 * @param {Object} [config] Configuration options
4891 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4892 * is omitted, the group element will use a generated `<div>`.
4894 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
4895 // Configuration initialization
4896 config
= config
|| {};
4901 this.aggregateItemEvents
= {};
4904 this.setGroupElement( config
.$group
|| $( '<div>' ) );
4910 * Set the group element.
4912 * If an element is already set, items will be moved to the new element.
4914 * @param {jQuery} $group Element to use as group
4916 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
4919 this.$group
= $group
;
4920 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4921 this.$group
.append( this.items
[ i
].$element
);
4926 * Check if a group contains no items.
4928 * @return {boolean} Group is empty
4930 OO
.ui
.mixin
.GroupElement
.prototype.isEmpty = function () {
4931 return !this.items
.length
;
4935 * Get all items in the group.
4937 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4938 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4941 * @return {OO.ui.Element[]} An array of items.
4943 OO
.ui
.mixin
.GroupElement
.prototype.getItems = function () {
4944 return this.items
.slice( 0 );
4948 * Get an item by its data.
4950 * Only the first item with matching data will be returned. To return all matching items,
4951 * use the #getItemsFromData method.
4953 * @param {Object} data Item data to search for
4954 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4956 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
4958 hash
= OO
.getHash( data
);
4960 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4961 item
= this.items
[ i
];
4962 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4971 * Get items by their data.
4973 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4975 * @param {Object} data Item data to search for
4976 * @return {OO.ui.Element[]} Items with equivalent data
4978 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
4980 hash
= OO
.getHash( data
),
4983 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4984 item
= this.items
[ i
];
4985 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4994 * Aggregate the events emitted by the group.
4996 * When events are aggregated, the group will listen to all contained items for the event,
4997 * and then emit the event under a new name. The new event will contain an additional leading
4998 * parameter containing the item that emitted the original event. Other arguments emitted from
4999 * the original event are passed through.
5001 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
5002 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
5003 * A `null` value will remove aggregated events.
5005 * @throws {Error} An error is thrown if aggregation already exists.
5007 OO
.ui
.mixin
.GroupElement
.prototype.aggregate = function ( events
) {
5008 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
5010 for ( itemEvent
in events
) {
5011 groupEvent
= events
[ itemEvent
];
5013 // Remove existing aggregated event
5014 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
5015 // Don't allow duplicate aggregations
5017 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
5019 // Remove event aggregation from existing items
5020 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5021 item
= this.items
[ i
];
5022 if ( item
.connect
&& item
.disconnect
) {
5024 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
5025 item
.disconnect( this, remove
);
5028 // Prevent future items from aggregating event
5029 delete this.aggregateItemEvents
[ itemEvent
];
5032 // Add new aggregate event
5034 // Make future items aggregate event
5035 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
5036 // Add event aggregation to existing items
5037 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5038 item
= this.items
[ i
];
5039 if ( item
.connect
&& item
.disconnect
) {
5041 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
5042 item
.connect( this, add
);
5050 * Add items to the group.
5052 * Items will be added to the end of the group array unless the optional `index` parameter specifies
5053 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
5055 * @param {OO.ui.Element[]} items An array of items to add to the group
5056 * @param {number} [index] Index of the insertion point
5059 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
5060 var i
, len
, item
, event
, events
, currentIndex
,
5063 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
5066 // Check if item exists then remove it first, effectively "moving" it
5067 currentIndex
= this.items
.indexOf( item
);
5068 if ( currentIndex
>= 0 ) {
5069 this.removeItems( [ item
] );
5070 // Adjust index to compensate for removal
5071 if ( currentIndex
< index
) {
5076 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
5078 for ( event
in this.aggregateItemEvents
) {
5079 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
5081 item
.connect( this, events
);
5083 item
.setElementGroup( this );
5084 itemElements
.push( item
.$element
.get( 0 ) );
5087 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
5088 this.$group
.append( itemElements
);
5089 this.items
.push
.apply( this.items
, items
);
5090 } else if ( index
=== 0 ) {
5091 this.$group
.prepend( itemElements
);
5092 this.items
.unshift
.apply( this.items
, items
);
5094 this.items
[ index
].$element
.before( itemElements
);
5095 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
5102 * Remove the specified items from a group.
5104 * Removed items are detached (not removed) from the DOM so that they may be reused.
5105 * To remove all items from a group, you may wish to use the #clearItems method instead.
5107 * @param {OO.ui.Element[]} items An array of items to remove
5110 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
5111 var i
, len
, item
, index
, remove
, itemEvent
;
5113 // Remove specific items
5114 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
5116 index
= this.items
.indexOf( item
);
5117 if ( index
!== -1 ) {
5119 item
.connect
&& item
.disconnect
&&
5120 !$.isEmptyObject( this.aggregateItemEvents
)
5123 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
5124 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
5126 item
.disconnect( this, remove
);
5128 item
.setElementGroup( null );
5129 this.items
.splice( index
, 1 );
5130 item
.$element
.detach();
5138 * Clear all items from the group.
5140 * Cleared items are detached from the DOM, not removed, so that they may be reused.
5141 * To remove only a subset of items from a group, use the #removeItems method.
5145 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
5146 var i
, len
, item
, remove
, itemEvent
;
5149 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5150 item
= this.items
[ i
];
5152 item
.connect
&& item
.disconnect
&&
5153 !$.isEmptyObject( this.aggregateItemEvents
)
5156 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
5157 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
5159 item
.disconnect( this, remove
);
5161 item
.setElementGroup( null );
5162 item
.$element
.detach();
5170 * DraggableElement is a mixin class used to create elements that can be clicked
5171 * and dragged by a mouse to a new position within a group. This class must be used
5172 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
5173 * the draggable elements.
5180 OO
.ui
.mixin
.DraggableElement
= function OoUiMixinDraggableElement() {
5184 // Initialize and events
5186 .attr( 'draggable', true )
5187 .addClass( 'oo-ui-draggableElement' )
5189 dragstart
: this.onDragStart
.bind( this ),
5190 dragover
: this.onDragOver
.bind( this ),
5191 dragend
: this.onDragEnd
.bind( this ),
5192 drop
: this.onDrop
.bind( this )
5196 OO
.initClass( OO
.ui
.mixin
.DraggableElement
);
5203 * A dragstart event is emitted when the user clicks and begins dragging an item.
5204 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
5209 * A dragend event is emitted when the user drags an item and releases the mouse,
5210 * thus terminating the drag operation.
5215 * A drop event is emitted when the user drags an item and then releases the mouse button
5216 * over a valid target.
5219 /* Static Properties */
5222 * @inheritdoc OO.ui.mixin.ButtonElement
5224 OO
.ui
.mixin
.DraggableElement
.static.cancelButtonMouseDownEvents
= false;
5229 * Respond to dragstart event.
5232 * @param {jQuery.Event} event jQuery event
5235 OO
.ui
.mixin
.DraggableElement
.prototype.onDragStart = function ( e
) {
5236 var dataTransfer
= e
.originalEvent
.dataTransfer
;
5237 // Define drop effect
5238 dataTransfer
.dropEffect
= 'none';
5239 dataTransfer
.effectAllowed
= 'move';
5241 // We must set up a dataTransfer data property or Firefox seems to
5242 // ignore the fact the element is draggable.
5244 dataTransfer
.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
5246 // The above is only for Firefox. Move on if it fails.
5248 // Add dragging class
5249 this.$element
.addClass( 'oo-ui-draggableElement-dragging' );
5251 this.emit( 'dragstart', this );
5256 * Respond to dragend event.
5261 OO
.ui
.mixin
.DraggableElement
.prototype.onDragEnd = function () {
5262 this.$element
.removeClass( 'oo-ui-draggableElement-dragging' );
5263 this.emit( 'dragend' );
5267 * Handle drop event.
5270 * @param {jQuery.Event} event jQuery event
5273 OO
.ui
.mixin
.DraggableElement
.prototype.onDrop = function ( e
) {
5275 this.emit( 'drop', e
);
5279 * In order for drag/drop to work, the dragover event must
5280 * return false and stop propogation.
5284 OO
.ui
.mixin
.DraggableElement
.prototype.onDragOver = function ( e
) {
5290 * Store it in the DOM so we can access from the widget drag event
5293 * @param {number} Item index
5295 OO
.ui
.mixin
.DraggableElement
.prototype.setIndex = function ( index
) {
5296 if ( this.index
!== index
) {
5298 this.$element
.data( 'index', index
);
5306 * @return {number} Item index
5308 OO
.ui
.mixin
.DraggableElement
.prototype.getIndex = function () {
5313 * DraggableGroupElement is a mixin class used to create a group element to
5314 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
5315 * The class is used with OO.ui.mixin.DraggableElement.
5319 * @mixins OO.ui.mixin.GroupElement
5322 * @param {Object} [config] Configuration options
5323 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
5324 * should match the layout of the items. Items displayed in a single row
5325 * or in several rows should use horizontal orientation. The vertical orientation should only be
5326 * used when the items are displayed in a single column. Defaults to 'vertical'
5328 OO
.ui
.mixin
.DraggableGroupElement
= function OoUiMixinDraggableGroupElement( config
) {
5329 // Configuration initialization
5330 config
= config
|| {};
5332 // Parent constructor
5333 OO
.ui
.mixin
.GroupElement
.call( this, config
);
5336 this.orientation
= config
.orientation
|| 'vertical';
5337 this.dragItem
= null;
5338 this.itemDragOver
= null;
5340 this.sideInsertion
= '';
5344 dragstart
: 'itemDragStart',
5345 dragend
: 'itemDragEnd',
5348 this.connect( this, {
5349 itemDragStart
: 'onItemDragStart',
5350 itemDrop
: 'onItemDrop',
5351 itemDragEnd
: 'onItemDragEnd'
5354 dragover
: this.onDragOver
.bind( this ),
5355 dragleave
: this.onDragLeave
.bind( this )
5359 if ( Array
.isArray( config
.items
) ) {
5360 this.addItems( config
.items
);
5362 this.$placeholder
= $( '<div>' )
5363 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
5365 .addClass( 'oo-ui-draggableGroupElement' )
5366 .append( this.$status
)
5367 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation
=== 'horizontal' )
5368 .prepend( this.$placeholder
);
5372 OO
.mixinClass( OO
.ui
.mixin
.DraggableGroupElement
, OO
.ui
.mixin
.GroupElement
);
5377 * A 'reorder' event is emitted when the order of items in the group changes.
5380 * @param {OO.ui.mixin.DraggableElement} item Reordered item
5381 * @param {number} [newIndex] New index for the item
5387 * Respond to item drag start event
5390 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5392 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDragStart = function ( item
) {
5395 // Map the index of each object
5396 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5397 this.items
[ i
].setIndex( i
);
5400 if ( this.orientation
=== 'horizontal' ) {
5401 // Set the height of the indicator
5402 this.$placeholder
.css( {
5403 height
: item
.$element
.outerHeight(),
5407 // Set the width of the indicator
5408 this.$placeholder
.css( {
5410 width
: item
.$element
.outerWidth()
5413 this.setDragItem( item
);
5417 * Respond to item drag end event
5421 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDragEnd = function () {
5422 this.unsetDragItem();
5427 * Handle drop event and switch the order of the items accordingly
5430 * @param {OO.ui.mixin.DraggableElement} item Dropped item
5433 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDrop = function ( item
) {
5434 var toIndex
= item
.getIndex();
5435 // Check if the dropped item is from the current group
5436 // TODO: Figure out a way to configure a list of legally droppable
5437 // elements even if they are not yet in the list
5438 if ( this.getDragItem() ) {
5439 // If the insertion point is 'after', the insertion index
5440 // is shifted to the right (or to the left in RTL, hence 'after')
5441 if ( this.sideInsertion
=== 'after' ) {
5444 // Emit change event
5445 this.emit( 'reorder', this.getDragItem(), toIndex
);
5447 this.unsetDragItem();
5448 // Return false to prevent propogation
5453 * Handle dragleave event.
5457 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onDragLeave = function () {
5458 // This means the item was dragged outside the widget
5461 .addClass( 'oo-ui-element-hidden' );
5465 * Respond to dragover event
5468 * @param {jQuery.Event} event Event details
5470 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onDragOver = function ( e
) {
5471 var dragOverObj
, $optionWidget
, itemOffset
, itemMidpoint
, itemBoundingRect
,
5472 itemSize
, cssOutput
, dragPosition
, itemIndex
, itemPosition
,
5473 clientX
= e
.originalEvent
.clientX
,
5474 clientY
= e
.originalEvent
.clientY
;
5476 // Get the OptionWidget item we are dragging over
5477 dragOverObj
= this.getElementDocument().elementFromPoint( clientX
, clientY
);
5478 $optionWidget
= $( dragOverObj
).closest( '.oo-ui-draggableElement' );
5479 if ( $optionWidget
[ 0 ] ) {
5480 itemOffset
= $optionWidget
.offset();
5481 itemBoundingRect
= $optionWidget
[ 0 ].getBoundingClientRect();
5482 itemPosition
= $optionWidget
.position();
5483 itemIndex
= $optionWidget
.data( 'index' );
5488 this.isDragging() &&
5489 itemIndex
!== this.getDragItem().getIndex()
5491 if ( this.orientation
=== 'horizontal' ) {
5492 // Calculate where the mouse is relative to the item width
5493 itemSize
= itemBoundingRect
.width
;
5494 itemMidpoint
= itemBoundingRect
.left
+ itemSize
/ 2;
5495 dragPosition
= clientX
;
5496 // Which side of the item we hover over will dictate
5497 // where the placeholder will appear, on the left or
5500 left
: dragPosition
< itemMidpoint
? itemPosition
.left
: itemPosition
.left
+ itemSize
,
5501 top
: itemPosition
.top
5504 // Calculate where the mouse is relative to the item height
5505 itemSize
= itemBoundingRect
.height
;
5506 itemMidpoint
= itemBoundingRect
.top
+ itemSize
/ 2;
5507 dragPosition
= clientY
;
5508 // Which side of the item we hover over will dictate
5509 // where the placeholder will appear, on the top or
5512 top
: dragPosition
< itemMidpoint
? itemPosition
.top
: itemPosition
.top
+ itemSize
,
5513 left
: itemPosition
.left
5516 // Store whether we are before or after an item to rearrange
5517 // For horizontal layout, we need to account for RTL, as this is flipped
5518 if ( this.orientation
=== 'horizontal' && this.$element
.css( 'direction' ) === 'rtl' ) {
5519 this.sideInsertion
= dragPosition
< itemMidpoint
? 'after' : 'before';
5521 this.sideInsertion
= dragPosition
< itemMidpoint
? 'before' : 'after';
5523 // Add drop indicator between objects
5526 .removeClass( 'oo-ui-element-hidden' );
5528 // This means the item was dragged outside the widget
5531 .addClass( 'oo-ui-element-hidden' );
5538 * Set a dragged item
5540 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5542 OO
.ui
.mixin
.DraggableGroupElement
.prototype.setDragItem = function ( item
) {
5543 this.dragItem
= item
;
5547 * Unset the current dragged item
5549 OO
.ui
.mixin
.DraggableGroupElement
.prototype.unsetDragItem = function () {
5550 this.dragItem
= null;
5551 this.itemDragOver
= null;
5552 this.$placeholder
.addClass( 'oo-ui-element-hidden' );
5553 this.sideInsertion
= '';
5557 * Get the item that is currently being dragged.
5559 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5561 OO
.ui
.mixin
.DraggableGroupElement
.prototype.getDragItem = function () {
5562 return this.dragItem
;
5566 * Check if an item in the group is currently being dragged.
5568 * @return {Boolean} Item is being dragged
5570 OO
.ui
.mixin
.DraggableGroupElement
.prototype.isDragging = function () {
5571 return this.getDragItem() !== null;
5575 * IconElement is often mixed into other classes to generate an icon.
5576 * Icons are graphics, about the size of normal text. They are used to aid the user
5577 * in locating a control or to convey information in a space-efficient way. See the
5578 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5579 * included in the library.
5581 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5587 * @param {Object} [config] Configuration options
5588 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5589 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5590 * the icon element be set to an existing icon instead of the one generated by this class, set a
5591 * value using a jQuery selection. For example:
5593 * // Use a <div> tag instead of a <span>
5595 * // Use an existing icon element instead of the one generated by the class
5596 * $icon: this.$element
5597 * // Use an icon element from a child widget
5598 * $icon: this.childwidget.$element
5599 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5600 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5601 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5602 * by the user's language.
5604 * Example of an i18n map:
5606 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5607 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5608 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5609 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5610 * text. The icon title is displayed when users move the mouse over the icon.
5612 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
5613 // Configuration initialization
5614 config
= config
|| {};
5619 this.iconTitle
= null;
5622 this.setIcon( config
.icon
|| this.constructor.static.icon
);
5623 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
5624 this.setIconElement( config
.$icon
|| $( '<span>' ) );
5629 OO
.initClass( OO
.ui
.mixin
.IconElement
);
5631 /* Static Properties */
5634 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5635 * for i18n purposes and contains a `default` icon name and additional names keyed by
5636 * language code. The `default` name is used when no icon is keyed by the user's language.
5638 * Example of an i18n map:
5640 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5642 * Note: the static property will be overridden if the #icon configuration is used.
5646 * @property {Object|string}
5648 OO
.ui
.mixin
.IconElement
.static.icon
= null;
5651 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5652 * function that returns title text, or `null` for no title.
5654 * The static property will be overridden if the #iconTitle configuration is used.
5658 * @property {string|Function|null}
5660 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
5665 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5666 * applies to the specified icon element instead of the one created by the class. If an icon
5667 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5668 * and mixin methods will no longer affect the element.
5670 * @param {jQuery} $icon Element to use as icon
5672 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
5675 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
5676 .removeAttr( 'title' );
5680 .addClass( 'oo-ui-iconElement-icon' )
5681 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
5682 if ( this.iconTitle
!== null ) {
5683 this.$icon
.attr( 'title', this.iconTitle
);
5686 this.updateThemeClasses();
5690 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5691 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5694 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5695 * by language code, or `null` to remove the icon.
5698 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
5699 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
5700 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
5702 if ( this.icon
!== icon
) {
5704 if ( this.icon
!== null ) {
5705 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
5707 if ( icon
!== null ) {
5708 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
5714 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
5715 this.updateThemeClasses();
5721 * Set the icon title. Use `null` to remove the title.
5723 * @param {string|Function|null} iconTitle A text string used as the icon title,
5724 * a function that returns title text, or `null` for no title.
5727 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
5728 iconTitle
= typeof iconTitle
=== 'function' ||
5729 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
5730 OO
.ui
.resolveMsg( iconTitle
) : null;
5732 if ( this.iconTitle
!== iconTitle
) {
5733 this.iconTitle
= iconTitle
;
5735 if ( this.iconTitle
!== null ) {
5736 this.$icon
.attr( 'title', iconTitle
);
5738 this.$icon
.removeAttr( 'title' );
5747 * Get the symbolic name of the icon.
5749 * @return {string} Icon name
5751 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
5756 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5758 * @return {string} Icon title text
5760 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
5761 return this.iconTitle
;
5765 * IndicatorElement is often mixed into other classes to generate an indicator.
5766 * Indicators are small graphics that are generally used in two ways:
5768 * - To draw attention to the status of an item. For example, an indicator might be
5769 * used to show that an item in a list has errors that need to be resolved.
5770 * - To clarify the function of a control that acts in an exceptional way (a button
5771 * that opens a menu instead of performing an action directly, for example).
5773 * For a list of indicators included in the library, please see the
5774 * [OOjs UI documentation on MediaWiki] [1].
5776 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5782 * @param {Object} [config] Configuration options
5783 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5784 * configuration is omitted, the indicator element will use a generated `<span>`.
5785 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5786 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5788 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5789 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5790 * or a function that returns title text. The indicator title is displayed when users move
5791 * the mouse over the indicator.
5793 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
5794 // Configuration initialization
5795 config
= config
|| {};
5798 this.$indicator
= null;
5799 this.indicator
= null;
5800 this.indicatorTitle
= null;
5803 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
5804 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
5805 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
5810 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
5812 /* Static Properties */
5815 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5816 * The static property will be overridden if the #indicator configuration is used.
5820 * @property {string|null}
5822 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
5825 * A text string used as the indicator title, a function that returns title text, or `null`
5826 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5830 * @property {string|Function|null}
5832 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
5837 * Set the indicator element.
5839 * If an element is already set, it will be cleaned up before setting up the new element.
5841 * @param {jQuery} $indicator Element to use as indicator
5843 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
5844 if ( this.$indicator
) {
5846 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
5847 .removeAttr( 'title' );
5850 this.$indicator
= $indicator
5851 .addClass( 'oo-ui-indicatorElement-indicator' )
5852 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
5853 if ( this.indicatorTitle
!== null ) {
5854 this.$indicator
.attr( 'title', this.indicatorTitle
);
5857 this.updateThemeClasses();
5861 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5863 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5866 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
5867 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
5869 if ( this.indicator
!== indicator
) {
5870 if ( this.$indicator
) {
5871 if ( this.indicator
!== null ) {
5872 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
5874 if ( indicator
!== null ) {
5875 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
5878 this.indicator
= indicator
;
5881 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
5882 this.updateThemeClasses();
5888 * Set the indicator title.
5890 * The title is displayed when a user moves the mouse over the indicator.
5892 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5893 * `null` for no indicator title
5896 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
5897 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
5898 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
5899 OO
.ui
.resolveMsg( indicatorTitle
) : null;
5901 if ( this.indicatorTitle
!== indicatorTitle
) {
5902 this.indicatorTitle
= indicatorTitle
;
5903 if ( this.$indicator
) {
5904 if ( this.indicatorTitle
!== null ) {
5905 this.$indicator
.attr( 'title', indicatorTitle
);
5907 this.$indicator
.removeAttr( 'title' );
5916 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5918 * @return {string} Symbolic name of indicator
5920 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
5921 return this.indicator
;
5925 * Get the indicator title.
5927 * The title is displayed when a user moves the mouse over the indicator.
5929 * @return {string} Indicator title text
5931 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
5932 return this.indicatorTitle
;
5936 * LabelElement is often mixed into other classes to generate a label, which
5937 * helps identify the function of an interface element.
5938 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5940 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5946 * @param {Object} [config] Configuration options
5947 * @cfg {jQuery} [$label] The label element created by the class. If this
5948 * configuration is omitted, the label element will use a generated `<span>`.
5949 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5950 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5951 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5952 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5953 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5954 * The label will be truncated to fit if necessary.
5956 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
5957 // Configuration initialization
5958 config
= config
|| {};
5963 this.autoFitLabel
= config
.autoFitLabel
=== undefined || !!config
.autoFitLabel
;
5966 this.setLabel( config
.label
|| this.constructor.static.label
);
5967 this.setLabelElement( config
.$label
|| $( '<span>' ) );
5972 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
5977 * @event labelChange
5978 * @param {string} value
5981 /* Static Properties */
5984 * The label text. The label can be specified as a plaintext string, a function that will
5985 * produce a string in the future, or `null` for no label. The static value will
5986 * be overridden if a label is specified with the #label config option.
5990 * @property {string|Function|null}
5992 OO
.ui
.mixin
.LabelElement
.static.label
= null;
5997 * Set the label element.
5999 * If an element is already set, it will be cleaned up before setting up the new element.
6001 * @param {jQuery} $label Element to use as label
6003 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
6004 if ( this.$label
) {
6005 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
6008 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
6009 this.setLabelContent( this.label
);
6015 * An empty string will result in the label being hidden. A string containing only whitespace will
6016 * be converted to a single ` `.
6018 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
6019 * text; or null for no label
6022 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
6023 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
6024 label
= ( ( typeof label
=== 'string' && label
.length
) || label
instanceof jQuery
|| label
instanceof OO
.ui
.HtmlSnippet
) ? label
: null;
6026 this.$element
.toggleClass( 'oo-ui-labelElement', !!label
);
6028 if ( this.label
!== label
) {
6029 if ( this.$label
) {
6030 this.setLabelContent( label
);
6033 this.emit( 'labelChange' );
6042 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
6043 * text; or null for no label
6045 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
6054 OO
.ui
.mixin
.LabelElement
.prototype.fitLabel = function () {
6055 if ( this.$label
&& this.$label
.autoEllipsis
&& this.autoFitLabel
) {
6056 this.$label
.autoEllipsis( { hasSpan
: false, tooltip
: true } );
6063 * Set the content of the label.
6065 * Do not call this method until after the label element has been set by #setLabelElement.
6068 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
6069 * text; or null for no label
6071 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
6072 if ( typeof label
=== 'string' ) {
6073 if ( label
.match( /^\s*$/ ) ) {
6074 // Convert whitespace only string to a single non-breaking space
6075 this.$label
.html( ' ' );
6077 this.$label
.text( label
);
6079 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
6080 this.$label
.html( label
.toString() );
6081 } else if ( label
instanceof jQuery
) {
6082 this.$label
.empty().append( label
);
6084 this.$label
.empty();
6089 * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
6090 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
6091 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
6092 * from the lookup menu, that value becomes the value of the input field.
6094 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
6095 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
6096 * re-enable lookups.
6098 * See the [OOjs UI demos][1] for an example.
6100 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
6106 * @param {Object} [config] Configuration options
6107 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
6108 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
6109 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
6110 * By default, the lookup menu is not generated and displayed until the user begins to type.
6111 * @cfg {boolean} [highlightFirst=true] Whether the first lookup result should be highlighted (so, that the user can
6112 * take it over into the input with simply pressing return) automatically or not.
6114 OO
.ui
.mixin
.LookupElement
= function OoUiMixinLookupElement( config
) {
6115 // Configuration initialization
6116 config
= $.extend( { highlightFirst
: true }, config
);
6118 // Mixin constructors
6119 OO
.ui
.mixin
.RequestManager
.call( this, config
);
6122 this.$overlay
= config
.$overlay
|| this.$element
;
6123 this.lookupMenu
= new OO
.ui
.FloatingMenuSelectWidget( {
6126 $container
: config
.$container
|| this.$element
6129 this.allowSuggestionsWhenEmpty
= config
.allowSuggestionsWhenEmpty
|| false;
6131 this.lookupsDisabled
= false;
6132 this.lookupInputFocused
= false;
6133 this.lookupHighlightFirstItem
= config
.highlightFirst
;
6137 focus
: this.onLookupInputFocus
.bind( this ),
6138 blur
: this.onLookupInputBlur
.bind( this ),
6139 mousedown
: this.onLookupInputMouseDown
.bind( this )
6141 this.connect( this, { change
: 'onLookupInputChange' } );
6142 this.lookupMenu
.connect( this, {
6143 toggle
: 'onLookupMenuToggle',
6144 choose
: 'onLookupMenuItemChoose'
6148 this.$element
.addClass( 'oo-ui-lookupElement' );
6149 this.lookupMenu
.$element
.addClass( 'oo-ui-lookupElement-menu' );
6150 this.$overlay
.append( this.lookupMenu
.$element
);
6155 OO
.mixinClass( OO
.ui
.mixin
.LookupElement
, OO
.ui
.mixin
.RequestManager
);
6160 * Handle input focus event.
6163 * @param {jQuery.Event} e Input focus event
6165 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputFocus = function () {
6166 this.lookupInputFocused
= true;
6167 this.populateLookupMenu();
6171 * Handle input blur event.
6174 * @param {jQuery.Event} e Input blur event
6176 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputBlur = function () {
6177 this.closeLookupMenu();
6178 this.lookupInputFocused
= false;
6182 * Handle input mouse down event.
6185 * @param {jQuery.Event} e Input mouse down event
6187 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputMouseDown = function () {
6188 // Only open the menu if the input was already focused.
6189 // This way we allow the user to open the menu again after closing it with Esc
6190 // by clicking in the input. Opening (and populating) the menu when initially
6191 // clicking into the input is handled by the focus handler.
6192 if ( this.lookupInputFocused
&& !this.lookupMenu
.isVisible() ) {
6193 this.populateLookupMenu();
6198 * Handle input change event.
6201 * @param {string} value New input value
6203 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputChange = function () {
6204 if ( this.lookupInputFocused
) {
6205 this.populateLookupMenu();
6210 * Handle the lookup menu being shown/hidden.
6213 * @param {boolean} visible Whether the lookup menu is now visible.
6215 OO
.ui
.mixin
.LookupElement
.prototype.onLookupMenuToggle = function ( visible
) {
6217 // When the menu is hidden, abort any active request and clear the menu.
6218 // This has to be done here in addition to closeLookupMenu(), because
6219 // MenuSelectWidget will close itself when the user presses Esc.
6220 this.abortLookupRequest();
6221 this.lookupMenu
.clearItems();
6226 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
6229 * @param {OO.ui.MenuOptionWidget} item Selected item
6231 OO
.ui
.mixin
.LookupElement
.prototype.onLookupMenuItemChoose = function ( item
) {
6232 this.setValue( item
.getData() );
6239 * @return {OO.ui.FloatingMenuSelectWidget}
6241 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenu = function () {
6242 return this.lookupMenu
;
6246 * Disable or re-enable lookups.
6248 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
6250 * @param {boolean} disabled Disable lookups
6252 OO
.ui
.mixin
.LookupElement
.prototype.setLookupsDisabled = function ( disabled
) {
6253 this.lookupsDisabled
= !!disabled
;
6257 * Open the menu. If there are no entries in the menu, this does nothing.
6262 OO
.ui
.mixin
.LookupElement
.prototype.openLookupMenu = function () {
6263 if ( !this.lookupMenu
.isEmpty() ) {
6264 this.lookupMenu
.toggle( true );
6270 * Close the menu, empty it, and abort any pending request.
6275 OO
.ui
.mixin
.LookupElement
.prototype.closeLookupMenu = function () {
6276 this.lookupMenu
.toggle( false );
6277 this.abortLookupRequest();
6278 this.lookupMenu
.clearItems();
6283 * Request menu items based on the input's current value, and when they arrive,
6284 * populate the menu with these items and show the menu.
6286 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
6291 OO
.ui
.mixin
.LookupElement
.prototype.populateLookupMenu = function () {
6293 value
= this.getValue();
6295 if ( this.lookupsDisabled
|| this.isReadOnly() ) {
6299 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
6300 if ( !this.allowSuggestionsWhenEmpty
&& value
=== '' ) {
6301 this.closeLookupMenu();
6302 // Skip population if there is already a request pending for the current value
6303 } else if ( value
!== this.lookupQuery
) {
6304 this.getLookupMenuItems()
6305 .done( function ( items
) {
6306 widget
.lookupMenu
.clearItems();
6307 if ( items
.length
) {
6311 widget
.initializeLookupMenuSelection();
6313 widget
.lookupMenu
.toggle( false );
6316 .fail( function () {
6317 widget
.lookupMenu
.clearItems();
6325 * Highlight the first selectable item in the menu, if configured.
6330 OO
.ui
.mixin
.LookupElement
.prototype.initializeLookupMenuSelection = function () {
6331 if ( this.lookupHighlightFirstItem
&& !this.lookupMenu
.getSelectedItem() ) {
6332 this.lookupMenu
.highlightItem( this.lookupMenu
.getFirstSelectableItem() );
6337 * Get lookup menu items for the current query.
6340 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
6341 * the done event. If the request was aborted to make way for a subsequent request, this promise
6342 * will not be rejected: it will remain pending forever.
6344 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenuItems = function () {
6345 return this.getRequestData().then( function ( data
) {
6346 return this.getLookupMenuOptionsFromData( data
);
6351 * Abort the currently pending lookup request, if any.
6355 OO
.ui
.mixin
.LookupElement
.prototype.abortLookupRequest = function () {
6356 this.abortRequest();
6360 * Get a new request object of the current lookup query value.
6365 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
6367 OO
.ui
.mixin
.LookupElement
.prototype.getLookupRequest
= null;
6370 * Pre-process data returned by the request from #getLookupRequest.
6372 * The return value of this function will be cached, and any further queries for the given value
6373 * will use the cache rather than doing API requests.
6378 * @param {Mixed} response Response from server
6379 * @return {Mixed} Cached result data
6381 OO
.ui
.mixin
.LookupElement
.prototype.getLookupCacheDataFromResponse
= null;
6384 * Get a list of menu option widgets from the (possibly cached) data returned by
6385 * #getLookupCacheDataFromResponse.
6390 * @param {Mixed} data Cached result data, usually an array
6391 * @return {OO.ui.MenuOptionWidget[]} Menu items
6393 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenuOptionsFromData
= null;
6396 * Set the read-only state of the widget.
6398 * This will also disable/enable the lookups functionality.
6400 * @param {boolean} readOnly Make input read-only
6403 OO
.ui
.mixin
.LookupElement
.prototype.setReadOnly = function ( readOnly
) {
6405 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
6406 OO
.ui
.TextInputWidget
.prototype.setReadOnly
.call( this, readOnly
);
6408 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
6409 if ( this.isReadOnly() && this.lookupMenu
) {
6410 this.closeLookupMenu();
6417 * @inheritdoc OO.ui.mixin.RequestManager
6419 OO
.ui
.mixin
.LookupElement
.prototype.getRequestQuery = function () {
6420 return this.getValue();
6424 * @inheritdoc OO.ui.mixin.RequestManager
6426 OO
.ui
.mixin
.LookupElement
.prototype.getRequest = function () {
6427 return this.getLookupRequest();
6431 * @inheritdoc OO.ui.mixin.RequestManager
6433 OO
.ui
.mixin
.LookupElement
.prototype.getRequestCacheDataFromResponse = function ( response
) {
6434 return this.getLookupCacheDataFromResponse( response
);
6438 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
6439 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
6440 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
6441 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
6447 * @param {Object} [config] Configuration options
6448 * @cfg {Object} [popup] Configuration to pass to popup
6449 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
6451 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
6452 // Configuration initialization
6453 config
= config
|| {};
6456 this.popup
= new OO
.ui
.PopupWidget( $.extend(
6457 { autoClose
: true },
6459 { $autoCloseIgnore
: this.$element
}
6468 * @return {OO.ui.PopupWidget} Popup widget
6470 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
6475 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
6476 * additional functionality to an element created by another class. The class provides
6477 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
6478 * which are used to customize the look and feel of a widget to better describe its
6479 * importance and functionality.
6481 * The library currently contains the following styling flags for general use:
6483 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
6484 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
6485 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
6487 * The flags affect the appearance of the buttons:
6490 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
6491 * var button1 = new OO.ui.ButtonWidget( {
6492 * label: 'Constructive',
6493 * flags: 'constructive'
6495 * var button2 = new OO.ui.ButtonWidget( {
6496 * label: 'Destructive',
6497 * flags: 'destructive'
6499 * var button3 = new OO.ui.ButtonWidget( {
6500 * label: 'Progressive',
6501 * flags: 'progressive'
6503 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
6505 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
6506 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6508 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6514 * @param {Object} [config] Configuration options
6515 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
6516 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
6517 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6518 * @cfg {jQuery} [$flagged] The flagged element. By default,
6519 * the flagged functionality is applied to the element created by the class ($element).
6520 * If a different element is specified, the flagged functionality will be applied to it instead.
6522 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
6523 // Configuration initialization
6524 config
= config
|| {};
6528 this.$flagged
= null;
6531 this.setFlags( config
.flags
);
6532 this.setFlaggedElement( config
.$flagged
|| this.$element
);
6539 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
6540 * parameter contains the name of each modified flag and indicates whether it was
6543 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
6544 * that the flag was added, `false` that the flag was removed.
6550 * Set the flagged element.
6552 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
6553 * If an element is already set, the method will remove the mixin’s effect on that element.
6555 * @param {jQuery} $flagged Element that should be flagged
6557 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
6558 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
6559 return 'oo-ui-flaggedElement-' + flag
;
6562 if ( this.$flagged
) {
6563 this.$flagged
.removeClass( classNames
);
6566 this.$flagged
= $flagged
.addClass( classNames
);
6570 * Check if the specified flag is set.
6572 * @param {string} flag Name of flag
6573 * @return {boolean} The flag is set
6575 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
6576 // This may be called before the constructor, thus before this.flags is set
6577 return this.flags
&& ( flag
in this.flags
);
6581 * Get the names of all flags set.
6583 * @return {string[]} Flag names
6585 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
6586 // This may be called before the constructor, thus before this.flags is set
6587 return Object
.keys( this.flags
|| {} );
6596 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
6597 var flag
, className
,
6600 classPrefix
= 'oo-ui-flaggedElement-';
6602 for ( flag
in this.flags
) {
6603 className
= classPrefix
+ flag
;
6604 changes
[ flag
] = false;
6605 delete this.flags
[ flag
];
6606 remove
.push( className
);
6609 if ( this.$flagged
) {
6610 this.$flagged
.removeClass( remove
.join( ' ' ) );
6613 this.updateThemeClasses();
6614 this.emit( 'flag', changes
);
6620 * Add one or more flags.
6622 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6623 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6624 * be added (`true`) or removed (`false`).
6628 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
6629 var i
, len
, flag
, className
,
6633 classPrefix
= 'oo-ui-flaggedElement-';
6635 if ( typeof flags
=== 'string' ) {
6636 className
= classPrefix
+ flags
;
6638 if ( !this.flags
[ flags
] ) {
6639 this.flags
[ flags
] = true;
6640 add
.push( className
);
6642 } else if ( Array
.isArray( flags
) ) {
6643 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
6645 className
= classPrefix
+ flag
;
6647 if ( !this.flags
[ flag
] ) {
6648 changes
[ flag
] = true;
6649 this.flags
[ flag
] = true;
6650 add
.push( className
);
6653 } else if ( OO
.isPlainObject( flags
) ) {
6654 for ( flag
in flags
) {
6655 className
= classPrefix
+ flag
;
6656 if ( flags
[ flag
] ) {
6658 if ( !this.flags
[ flag
] ) {
6659 changes
[ flag
] = true;
6660 this.flags
[ flag
] = true;
6661 add
.push( className
);
6665 if ( this.flags
[ flag
] ) {
6666 changes
[ flag
] = false;
6667 delete this.flags
[ flag
];
6668 remove
.push( className
);
6674 if ( this.$flagged
) {
6676 .addClass( add
.join( ' ' ) )
6677 .removeClass( remove
.join( ' ' ) );
6680 this.updateThemeClasses();
6681 this.emit( 'flag', changes
);
6687 * TitledElement is mixed into other classes to provide a `title` attribute.
6688 * Titles are rendered by the browser and are made visible when the user moves
6689 * the mouse over the element. Titles are not visible on touch devices.
6692 * // TitledElement provides a 'title' attribute to the
6693 * // ButtonWidget class
6694 * var button = new OO.ui.ButtonWidget( {
6695 * label: 'Button with Title',
6696 * title: 'I am a button'
6698 * $( 'body' ).append( button.$element );
6704 * @param {Object} [config] Configuration options
6705 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6706 * If this config is omitted, the title functionality is applied to $element, the
6707 * element created by the class.
6708 * @cfg {string|Function} [title] The title text or a function that returns text. If
6709 * this config is omitted, the value of the {@link #static-title static title} property is used.
6711 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
6712 // Configuration initialization
6713 config
= config
|| {};
6716 this.$titled
= null;
6720 this.setTitle( config
.title
|| this.constructor.static.title
);
6721 this.setTitledElement( config
.$titled
|| this.$element
);
6726 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
6728 /* Static Properties */
6731 * The title text, a function that returns text, or `null` for no title. The value of the static property
6732 * is overridden if the #title config option is used.
6736 * @property {string|Function|null}
6738 OO
.ui
.mixin
.TitledElement
.static.title
= null;
6743 * Set the titled element.
6745 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6746 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6748 * @param {jQuery} $titled Element that should use the 'titled' functionality
6750 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
6751 if ( this.$titled
) {
6752 this.$titled
.removeAttr( 'title' );
6755 this.$titled
= $titled
;
6757 this.$titled
.attr( 'title', this.title
);
6764 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6767 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
6768 title
= typeof title
=== 'function' ? OO
.ui
.resolveMsg( title
) : title
;
6769 title
= ( typeof title
=== 'string' && title
.length
) ? title
: null;
6771 if ( this.title
!== title
) {
6772 if ( this.$titled
) {
6773 if ( title
!== null ) {
6774 this.$titled
.attr( 'title', title
);
6776 this.$titled
.removeAttr( 'title' );
6788 * @return {string} Title string
6790 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
6795 * Element that can be automatically clipped to visible boundaries.
6797 * Whenever the element's natural height changes, you have to call
6798 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
6799 * clipping correctly.
6801 * The dimensions of #$clippableContainer will be compared to the boundaries of the
6802 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
6803 * then #$clippable will be given a fixed reduced height and/or width and will be made
6804 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
6805 * but you can build a static footer by setting #$clippableContainer to an element that contains
6806 * #$clippable and the footer.
6812 * @param {Object} [config] Configuration options
6813 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
6814 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
6815 * omit to use #$clippable
6817 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
6818 // Configuration initialization
6819 config
= config
|| {};
6822 this.$clippable
= null;
6823 this.$clippableContainer
= null;
6824 this.clipping
= false;
6825 this.clippedHorizontally
= false;
6826 this.clippedVertically
= false;
6827 this.$clippableScrollableContainer
= null;
6828 this.$clippableScroller
= null;
6829 this.$clippableWindow
= null;
6830 this.idealWidth
= null;
6831 this.idealHeight
= null;
6832 this.onClippableScrollHandler
= this.clip
.bind( this );
6833 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
6836 if ( config
.$clippableContainer
) {
6837 this.setClippableContainer( config
.$clippableContainer
);
6839 this.setClippableElement( config
.$clippable
|| this.$element
);
6845 * Set clippable element.
6847 * If an element is already set, it will be cleaned up before setting up the new element.
6849 * @param {jQuery} $clippable Element to make clippable
6851 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
6852 if ( this.$clippable
) {
6853 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
6854 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6855 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6858 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
6863 * Set clippable container.
6865 * This is the container that will be measured when deciding whether to clip. When clipping,
6866 * #$clippable will be resized in order to keep the clippable container fully visible.
6868 * If the clippable container is unset, #$clippable will be used.
6870 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
6872 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
6873 this.$clippableContainer
= $clippableContainer
;
6874 if ( this.$clippable
) {
6882 * Do not turn clipping on until after the element is attached to the DOM and visible.
6884 * @param {boolean} [clipping] Enable clipping, omit to toggle
6887 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
6888 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
6890 if ( this.clipping
!== clipping
) {
6891 this.clipping
= clipping
;
6893 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
6894 // If the clippable container is the root, we have to listen to scroll events and check
6895 // jQuery.scrollTop on the window because of browser inconsistencies
6896 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
6897 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
6898 this.$clippableScrollableContainer
;
6899 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
6900 this.$clippableWindow
= $( this.getElementWindow() )
6901 .on( 'resize', this.onClippableWindowResizeHandler
);
6902 // Initial clip after visible
6905 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6906 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6908 this.$clippableScrollableContainer
= null;
6909 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
6910 this.$clippableScroller
= null;
6911 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
6912 this.$clippableWindow
= null;
6920 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6922 * @return {boolean} Element will be clipped to the visible area
6924 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
6925 return this.clipping
;
6929 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6931 * @return {boolean} Part of the element is being clipped
6933 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
6934 return this.clippedHorizontally
|| this.clippedVertically
;
6938 * Check if the right of the element is being clipped by the nearest scrollable container.
6940 * @return {boolean} Part of the element is being clipped
6942 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
6943 return this.clippedHorizontally
;
6947 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6949 * @return {boolean} Part of the element is being clipped
6951 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
6952 return this.clippedVertically
;
6956 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6958 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6959 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6961 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
6962 this.idealWidth
= width
;
6963 this.idealHeight
= height
;
6965 if ( !this.clipping
) {
6966 // Update dimensions
6967 this.$clippable
.css( { width
: width
, height
: height
} );
6969 // While clipping, idealWidth and idealHeight are not considered
6973 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6974 * the element's natural height changes.
6976 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6977 * overlapped by, the visible area of the nearest scrollable container.
6981 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
6982 var $container
, extraHeight
, extraWidth
, ccOffset
,
6983 $scrollableContainer
, scOffset
, scHeight
, scWidth
,
6984 ccWidth
, scrollerIsWindow
, scrollTop
, scrollLeft
,
6985 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
6986 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
6987 buffer
= 7; // Chosen by fair dice roll
6989 if ( !this.clipping
) {
6990 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
6994 $container
= this.$clippableContainer
|| this.$clippable
;
6995 extraHeight
= $container
.outerHeight() - this.$clippable
.outerHeight();
6996 extraWidth
= $container
.outerWidth() - this.$clippable
.outerWidth();
6997 ccOffset
= $container
.offset();
6998 $scrollableContainer
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
6999 this.$clippableWindow
: this.$clippableScrollableContainer
;
7000 scOffset
= $scrollableContainer
.offset() || { top
: 0, left
: 0 };
7001 scHeight
= $scrollableContainer
.innerHeight() - buffer
;
7002 scWidth
= $scrollableContainer
.innerWidth() - buffer
;
7003 ccWidth
= $container
.outerWidth() + buffer
;
7004 scrollerIsWindow
= this.$clippableScroller
[ 0 ] === this.$clippableWindow
[ 0 ];
7005 scrollTop
= scrollerIsWindow
? this.$clippableScroller
.scrollTop() : 0;
7006 scrollLeft
= scrollerIsWindow
? this.$clippableScroller
.scrollLeft() : 0;
7007 desiredWidth
= ccOffset
.left
< 0 ?
7008 ccWidth
+ ccOffset
.left
:
7009 ( scOffset
.left
+ scrollLeft
+ scWidth
) - ccOffset
.left
;
7010 desiredHeight
= ( scOffset
.top
+ scrollTop
+ scHeight
) - ccOffset
.top
;
7011 allotedWidth
= desiredWidth
- extraWidth
;
7012 allotedHeight
= desiredHeight
- extraHeight
;
7013 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
7014 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
7015 clipWidth
= allotedWidth
< naturalWidth
;
7016 clipHeight
= allotedHeight
< naturalHeight
;
7019 this.$clippable
.css( { overflowX
: 'scroll', width
: Math
.max( 0, allotedWidth
) } );
7021 this.$clippable
.css( { width
: this.idealWidth
? this.idealWidth
- extraWidth
: '', overflowX
: '' } );
7024 this.$clippable
.css( { overflowY
: 'scroll', height
: Math
.max( 0, allotedHeight
) } );
7026 this.$clippable
.css( { height
: this.idealHeight
? this.idealHeight
- extraHeight
: '', overflowY
: '' } );
7029 // If we stopped clipping in at least one of the dimensions
7030 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
7031 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
7034 this.clippedHorizontally
= clipWidth
;
7035 this.clippedVertically
= clipHeight
;
7041 * Element that will stick under a specified container, even when it is inserted elsewhere in the
7042 * document (for example, in a OO.ui.Window's $overlay).
7044 * The elements's position is automatically calculated and maintained when window is resized or the
7045 * page is scrolled. If you reposition the container manually, you have to call #position to make
7046 * sure the element is still placed correctly.
7048 * As positioning is only possible when both the element and the container are attached to the DOM
7049 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
7050 * the #toggle method to display a floating popup, for example.
7056 * @param {Object} [config] Configuration options
7057 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
7058 * @cfg {jQuery} [$floatableContainer] Node to position below
7060 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
7061 // Configuration initialization
7062 config
= config
|| {};
7065 this.$floatable
= null;
7066 this.$floatableContainer
= null;
7067 this.$floatableWindow
= null;
7068 this.$floatableClosestScrollable
= null;
7069 this.onFloatableScrollHandler
= this.position
.bind( this );
7070 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
7073 this.setFloatableContainer( config
.$floatableContainer
);
7074 this.setFloatableElement( config
.$floatable
|| this.$element
);
7080 * Set floatable element.
7082 * If an element is already set, it will be cleaned up before setting up the new element.
7084 * @param {jQuery} $floatable Element to make floatable
7086 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
7087 if ( this.$floatable
) {
7088 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
7089 this.$floatable
.css( { left
: '', top
: '' } );
7092 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
7097 * Set floatable container.
7099 * The element will be always positioned under the specified container.
7101 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
7103 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
7104 this.$floatableContainer
= $floatableContainer
;
7105 if ( this.$floatable
) {
7111 * Toggle positioning.
7113 * Do not turn positioning on until after the element is attached to the DOM and visible.
7115 * @param {boolean} [positioning] Enable positioning, omit to toggle
7118 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
7119 var closestScrollableOfContainer
, closestScrollableOfFloatable
;
7121 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
7123 if ( this.positioning
!== positioning
) {
7124 this.positioning
= positioning
;
7126 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
7127 closestScrollableOfFloatable
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatable
[ 0 ] );
7128 if ( closestScrollableOfContainer
!== closestScrollableOfFloatable
) {
7129 // If the scrollable is the root, we have to listen to scroll events
7130 // on the window because of browser inconsistencies (or do we? someone should verify this)
7131 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
7132 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
7136 if ( positioning
) {
7137 this.$floatableWindow
= $( this.getElementWindow() );
7138 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
7140 if ( closestScrollableOfContainer
!== closestScrollableOfFloatable
) {
7141 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
7142 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
7145 // Initial position after visible
7148 if ( this.$floatableWindow
) {
7149 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
7150 this.$floatableWindow
= null;
7153 if ( this.$floatableClosestScrollable
) {
7154 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
7155 this.$floatableClosestScrollable
= null;
7158 this.$floatable
.css( { left
: '', top
: '' } );
7166 * Position the floatable below its container.
7168 * This should only be done when both of them are attached to the DOM and visible.
7172 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
7175 if ( !this.positioning
) {
7179 pos
= OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, this.$floatable
.offsetParent() );
7181 // Position under container
7182 pos
.top
+= this.$floatableContainer
.height();
7183 this.$floatable
.css( pos
);
7185 // We updated the position, so re-evaluate the clipping state.
7186 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
7187 // will not notice the need to update itself.)
7188 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
7189 // it not listen to the right events in the right places?
7198 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
7199 * Accesskeys allow an user to go to a specific element by using
7200 * a shortcut combination of a browser specific keys + the key
7204 * // AccessKeyedElement provides an 'accesskey' attribute to the
7205 * // ButtonWidget class
7206 * var button = new OO.ui.ButtonWidget( {
7207 * label: 'Button with Accesskey',
7210 * $( 'body' ).append( button.$element );
7216 * @param {Object} [config] Configuration options
7217 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
7218 * If this config is omitted, the accesskey functionality is applied to $element, the
7219 * element created by the class.
7220 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
7221 * this config is omitted, no accesskey will be added.
7223 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
7224 // Configuration initialization
7225 config
= config
|| {};
7228 this.$accessKeyed
= null;
7229 this.accessKey
= null;
7232 this.setAccessKey( config
.accessKey
|| null );
7233 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
7238 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
7240 /* Static Properties */
7243 * The access key, a function that returns a key, or `null` for no accesskey.
7247 * @property {string|Function|null}
7249 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
7254 * Set the accesskeyed element.
7256 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
7257 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
7259 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
7261 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
7262 if ( this.$accessKeyed
) {
7263 this.$accessKeyed
.removeAttr( 'accesskey' );
7266 this.$accessKeyed
= $accessKeyed
;
7267 if ( this.accessKey
) {
7268 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
7275 * @param {string|Function|null} accesskey Key, a function that returns a key, or `null` for no accesskey
7278 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
7279 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
7281 if ( this.accessKey
!== accessKey
) {
7282 if ( this.$accessKeyed
) {
7283 if ( accessKey
!== null ) {
7284 this.$accessKeyed
.attr( 'accesskey', accessKey
);
7286 this.$accessKeyed
.removeAttr( 'accesskey' );
7289 this.accessKey
= accessKey
;
7298 * @return {string} accessKey string
7300 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
7301 return this.accessKey
;
7305 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
7306 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
7307 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
7308 * which creates the tools on demand.
7310 * Every Tool subclass must implement two methods:
7312 * - {@link #onUpdateState}
7313 * - {@link #onSelect}
7315 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
7316 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
7317 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
7319 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
7320 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7324 * @extends OO.ui.Widget
7325 * @mixins OO.ui.mixin.IconElement
7326 * @mixins OO.ui.mixin.FlaggedElement
7327 * @mixins OO.ui.mixin.TabIndexedElement
7330 * @param {OO.ui.ToolGroup} toolGroup
7331 * @param {Object} [config] Configuration options
7332 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
7333 * the {@link #static-title static title} property is used.
7335 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
7336 * 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
7337 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
7339 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
7340 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
7341 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
7343 OO
.ui
.Tool
= function OoUiTool( toolGroup
, config
) {
7344 // Allow passing positional parameters inside the config object
7345 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
7347 toolGroup
= config
.toolGroup
;
7350 // Configuration initialization
7351 config
= config
|| {};
7353 // Parent constructor
7354 OO
.ui
.Tool
.parent
.call( this, config
);
7357 this.toolGroup
= toolGroup
;
7358 this.toolbar
= this.toolGroup
.getToolbar();
7359 this.active
= false;
7360 this.$title
= $( '<span>' );
7361 this.$accel
= $( '<span>' );
7362 this.$link
= $( '<a>' );
7365 // Mixin constructors
7366 OO
.ui
.mixin
.IconElement
.call( this, config
);
7367 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
7368 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$link
} ) );
7371 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
7374 this.$title
.addClass( 'oo-ui-tool-title' );
7376 .addClass( 'oo-ui-tool-accel' )
7378 // This may need to be changed if the key names are ever localized,
7379 // but for now they are essentially written in English
7384 .addClass( 'oo-ui-tool-link' )
7385 .append( this.$icon
, this.$title
, this.$accel
)
7386 .attr( 'role', 'button' );
7388 .data( 'oo-ui-tool', this )
7390 'oo-ui-tool ' + 'oo-ui-tool-name-' +
7391 this.constructor.static.name
.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
7393 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel
)
7394 .append( this.$link
);
7395 this.setTitle( config
.title
|| this.constructor.static.title
);
7400 OO
.inheritClass( OO
.ui
.Tool
, OO
.ui
.Widget
);
7401 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.IconElement
);
7402 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.FlaggedElement
);
7403 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.TabIndexedElement
);
7405 /* Static Properties */
7411 OO
.ui
.Tool
.static.tagName
= 'span';
7414 * Symbolic name of tool.
7416 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
7417 * also be used when adding tools to toolgroups.
7422 * @property {string}
7424 OO
.ui
.Tool
.static.name
= '';
7427 * Symbolic name of the group.
7429 * The group name is used to associate tools with each other so that they can be selected later by
7430 * a {@link OO.ui.ToolGroup toolgroup}.
7435 * @property {string}
7437 OO
.ui
.Tool
.static.group
= '';
7440 * 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.
7445 * @property {string|Function}
7447 OO
.ui
.Tool
.static.title
= '';
7450 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
7451 * Normally only the icon is displayed, or only the label if no icon is given.
7455 * @property {boolean}
7457 OO
.ui
.Tool
.static.displayBothIconAndLabel
= false;
7460 * Add tool to catch-all groups automatically.
7462 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
7463 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
7467 * @property {boolean}
7469 OO
.ui
.Tool
.static.autoAddToCatchall
= true;
7472 * Add tool to named groups automatically.
7474 * By default, tools that are configured with a static ‘group’ property are added
7475 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
7476 * toolgroups include tools by group name).
7479 * @property {boolean}
7482 OO
.ui
.Tool
.static.autoAddToGroup
= true;
7485 * Check if this tool is compatible with given data.
7487 * This is a stub that can be overridden to provide support for filtering tools based on an
7488 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
7489 * must also call this method so that the compatibility check can be performed.
7493 * @param {Mixed} data Data to check
7494 * @return {boolean} Tool can be used with data
7496 OO
.ui
.Tool
.static.isCompatibleWith = function () {
7503 * Handle the toolbar state being updated. This method is called when the
7504 * {@link OO.ui.Toolbar#event-updateState 'updateState' event} is emitted on the
7505 * {@link OO.ui.Toolbar Toolbar} that uses this tool, and should set the state of this tool
7506 * depending on application state (usually by calling #setDisabled to enable or disable the tool,
7507 * or #setActive to mark is as currently in-use or not).
7509 * This is an abstract method that must be overridden in a concrete subclass.
7515 OO
.ui
.Tool
.prototype.onUpdateState
= null;
7518 * Handle the tool being selected. This method is called when the user triggers this tool,
7519 * usually by clicking on its label/icon.
7521 * This is an abstract method that must be overridden in a concrete subclass.
7527 OO
.ui
.Tool
.prototype.onSelect
= null;
7530 * Check if the tool is active.
7532 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
7533 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
7535 * @return {boolean} Tool is active
7537 OO
.ui
.Tool
.prototype.isActive = function () {
7542 * Make the tool appear active or inactive.
7544 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
7545 * appear pressed or not.
7547 * @param {boolean} state Make tool appear active
7549 OO
.ui
.Tool
.prototype.setActive = function ( state
) {
7550 this.active
= !!state
;
7551 if ( this.active
) {
7552 this.$element
.addClass( 'oo-ui-tool-active' );
7554 this.$element
.removeClass( 'oo-ui-tool-active' );
7559 * Set the tool #title.
7561 * @param {string|Function} title Title text or a function that returns text
7564 OO
.ui
.Tool
.prototype.setTitle = function ( title
) {
7565 this.title
= OO
.ui
.resolveMsg( title
);
7571 * Get the tool #title.
7573 * @return {string} Title text
7575 OO
.ui
.Tool
.prototype.getTitle = function () {
7580 * Get the tool's symbolic name.
7582 * @return {string} Symbolic name of tool
7584 OO
.ui
.Tool
.prototype.getName = function () {
7585 return this.constructor.static.name
;
7591 OO
.ui
.Tool
.prototype.updateTitle = function () {
7592 var titleTooltips
= this.toolGroup
.constructor.static.titleTooltips
,
7593 accelTooltips
= this.toolGroup
.constructor.static.accelTooltips
,
7594 accel
= this.toolbar
.getToolAccelerator( this.constructor.static.name
),
7597 this.$title
.text( this.title
);
7598 this.$accel
.text( accel
);
7600 if ( titleTooltips
&& typeof this.title
=== 'string' && this.title
.length
) {
7601 tooltipParts
.push( this.title
);
7603 if ( accelTooltips
&& typeof accel
=== 'string' && accel
.length
) {
7604 tooltipParts
.push( accel
);
7606 if ( tooltipParts
.length
) {
7607 this.$link
.attr( 'title', tooltipParts
.join( ' ' ) );
7609 this.$link
.removeAttr( 'title' );
7616 * Destroying the tool removes all event handlers and the tool’s DOM elements.
7617 * Call this method whenever you are done using a tool.
7619 OO
.ui
.Tool
.prototype.destroy = function () {
7620 this.toolbar
.disconnect( this );
7621 this.$element
.remove();
7625 * Toolbars are complex interface components that permit users to easily access a variety
7626 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
7627 * part of the toolbar, but not configured as tools.
7629 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
7630 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
7631 * image’), and an icon.
7633 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
7634 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
7635 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
7636 * any order, but each can only appear once in the toolbar.
7638 * The toolbar can be synchronized with the state of the external "application", like a text
7639 * editor's editing area, marking tools as active/inactive (e.g. a 'bold' tool would be shown as
7640 * active when the text cursor was inside bolded text) or enabled/disabled (e.g. a table caption
7641 * tool would be disabled while the user is not editing a table). A state change is signalled by
7642 * emitting the {@link #event-updateState 'updateState' event}, which calls Tools'
7643 * {@link OO.ui.Tool#onUpdateState onUpdateState method}.
7645 * The following is an example of a basic toolbar.
7648 * // Example of a toolbar
7649 * // Create the toolbar
7650 * var toolFactory = new OO.ui.ToolFactory();
7651 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7652 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7654 * // We will be placing status text in this element when tools are used
7655 * var $area = $( '<p>' ).text( 'Toolbar example' );
7657 * // Define the tools that we're going to place in our toolbar
7659 * // Create a class inheriting from OO.ui.Tool
7660 * function SearchTool() {
7661 * SearchTool.parent.apply( this, arguments );
7663 * OO.inheritClass( SearchTool, OO.ui.Tool );
7664 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7665 * // of 'icon' and 'title' (displayed icon and text).
7666 * SearchTool.static.name = 'search';
7667 * SearchTool.static.icon = 'search';
7668 * SearchTool.static.title = 'Search...';
7669 * // Defines the action that will happen when this tool is selected (clicked).
7670 * SearchTool.prototype.onSelect = function () {
7671 * $area.text( 'Search tool clicked!' );
7672 * // Never display this tool as "active" (selected).
7673 * this.setActive( false );
7675 * SearchTool.prototype.onUpdateState = function () {};
7676 * // Make this tool available in our toolFactory and thus our toolbar
7677 * toolFactory.register( SearchTool );
7679 * // Register two more tools, nothing interesting here
7680 * function SettingsTool() {
7681 * SettingsTool.parent.apply( this, arguments );
7683 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7684 * SettingsTool.static.name = 'settings';
7685 * SettingsTool.static.icon = 'settings';
7686 * SettingsTool.static.title = 'Change settings';
7687 * SettingsTool.prototype.onSelect = function () {
7688 * $area.text( 'Settings tool clicked!' );
7689 * this.setActive( false );
7691 * SettingsTool.prototype.onUpdateState = function () {};
7692 * toolFactory.register( SettingsTool );
7694 * // Register two more tools, nothing interesting here
7695 * function StuffTool() {
7696 * StuffTool.parent.apply( this, arguments );
7698 * OO.inheritClass( StuffTool, OO.ui.Tool );
7699 * StuffTool.static.name = 'stuff';
7700 * StuffTool.static.icon = 'ellipsis';
7701 * StuffTool.static.title = 'More stuff';
7702 * StuffTool.prototype.onSelect = function () {
7703 * $area.text( 'More stuff tool clicked!' );
7704 * this.setActive( false );
7706 * StuffTool.prototype.onUpdateState = function () {};
7707 * toolFactory.register( StuffTool );
7709 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7710 * // little popup window (a PopupWidget).
7711 * function HelpTool( toolGroup, config ) {
7712 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7717 * this.popup.$body.append( '<p>I am helpful!</p>' );
7719 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7720 * HelpTool.static.name = 'help';
7721 * HelpTool.static.icon = 'help';
7722 * HelpTool.static.title = 'Help';
7723 * toolFactory.register( HelpTool );
7725 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7726 * // used once (but not all defined tools must be used).
7729 * // 'bar' tool groups display tools' icons only, side-by-side.
7731 * include: [ 'search', 'help' ]
7734 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7736 * indicator: 'down',
7738 * include: [ 'settings', 'stuff' ]
7740 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7741 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7742 * // since it's more complicated to use. (See the next example snippet on this page.)
7745 * // Create some UI around the toolbar and place it in the document
7746 * var frame = new OO.ui.PanelLayout( {
7750 * var contentFrame = new OO.ui.PanelLayout( {
7754 * frame.$element.append(
7756 * contentFrame.$element.append( $area )
7758 * $( 'body' ).append( frame.$element );
7760 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7762 * toolbar.initialize();
7763 * toolbar.emit( 'updateState' );
7765 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7766 * {@link #event-updateState 'updateState' event}.
7769 * // Create the toolbar
7770 * var toolFactory = new OO.ui.ToolFactory();
7771 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7772 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7774 * // We will be placing status text in this element when tools are used
7775 * var $area = $( '<p>' ).text( 'Toolbar example' );
7777 * // Define the tools that we're going to place in our toolbar
7779 * // Create a class inheriting from OO.ui.Tool
7780 * function SearchTool() {
7781 * SearchTool.parent.apply( this, arguments );
7783 * OO.inheritClass( SearchTool, OO.ui.Tool );
7784 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7785 * // of 'icon' and 'title' (displayed icon and text).
7786 * SearchTool.static.name = 'search';
7787 * SearchTool.static.icon = 'search';
7788 * SearchTool.static.title = 'Search...';
7789 * // Defines the action that will happen when this tool is selected (clicked).
7790 * SearchTool.prototype.onSelect = function () {
7791 * $area.text( 'Search tool clicked!' );
7792 * // Never display this tool as "active" (selected).
7793 * this.setActive( false );
7795 * SearchTool.prototype.onUpdateState = function () {};
7796 * // Make this tool available in our toolFactory and thus our toolbar
7797 * toolFactory.register( SearchTool );
7799 * // Register two more tools, nothing interesting here
7800 * function SettingsTool() {
7801 * SettingsTool.parent.apply( this, arguments );
7802 * this.reallyActive = false;
7804 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7805 * SettingsTool.static.name = 'settings';
7806 * SettingsTool.static.icon = 'settings';
7807 * SettingsTool.static.title = 'Change settings';
7808 * SettingsTool.prototype.onSelect = function () {
7809 * $area.text( 'Settings tool clicked!' );
7810 * // Toggle the active state on each click
7811 * this.reallyActive = !this.reallyActive;
7812 * this.setActive( this.reallyActive );
7813 * // To update the menu label
7814 * this.toolbar.emit( 'updateState' );
7816 * SettingsTool.prototype.onUpdateState = function () {};
7817 * toolFactory.register( SettingsTool );
7819 * // Register two more tools, nothing interesting here
7820 * function StuffTool() {
7821 * StuffTool.parent.apply( this, arguments );
7822 * this.reallyActive = false;
7824 * OO.inheritClass( StuffTool, OO.ui.Tool );
7825 * StuffTool.static.name = 'stuff';
7826 * StuffTool.static.icon = 'ellipsis';
7827 * StuffTool.static.title = 'More stuff';
7828 * StuffTool.prototype.onSelect = function () {
7829 * $area.text( 'More stuff tool clicked!' );
7830 * // Toggle the active state on each click
7831 * this.reallyActive = !this.reallyActive;
7832 * this.setActive( this.reallyActive );
7833 * // To update the menu label
7834 * this.toolbar.emit( 'updateState' );
7836 * StuffTool.prototype.onUpdateState = function () {};
7837 * toolFactory.register( StuffTool );
7839 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7840 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7841 * function HelpTool( toolGroup, config ) {
7842 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7847 * this.popup.$body.append( '<p>I am helpful!</p>' );
7849 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7850 * HelpTool.static.name = 'help';
7851 * HelpTool.static.icon = 'help';
7852 * HelpTool.static.title = 'Help';
7853 * toolFactory.register( HelpTool );
7855 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7856 * // used once (but not all defined tools must be used).
7859 * // 'bar' tool groups display tools' icons only, side-by-side.
7861 * include: [ 'search', 'help' ]
7864 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7865 * // Menu label indicates which items are selected.
7867 * indicator: 'down',
7868 * include: [ 'settings', 'stuff' ]
7872 * // Create some UI around the toolbar and place it in the document
7873 * var frame = new OO.ui.PanelLayout( {
7877 * var contentFrame = new OO.ui.PanelLayout( {
7881 * frame.$element.append(
7883 * contentFrame.$element.append( $area )
7885 * $( 'body' ).append( frame.$element );
7887 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7889 * toolbar.initialize();
7890 * toolbar.emit( 'updateState' );
7893 * @extends OO.ui.Element
7894 * @mixins OO.EventEmitter
7895 * @mixins OO.ui.mixin.GroupElement
7898 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7899 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7900 * @param {Object} [config] Configuration options
7901 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7902 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7904 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7906 OO
.ui
.Toolbar
= function OoUiToolbar( toolFactory
, toolGroupFactory
, config
) {
7907 // Allow passing positional parameters inside the config object
7908 if ( OO
.isPlainObject( toolFactory
) && config
=== undefined ) {
7909 config
= toolFactory
;
7910 toolFactory
= config
.toolFactory
;
7911 toolGroupFactory
= config
.toolGroupFactory
;
7914 // Configuration initialization
7915 config
= config
|| {};
7917 // Parent constructor
7918 OO
.ui
.Toolbar
.parent
.call( this, config
);
7920 // Mixin constructors
7921 OO
.EventEmitter
.call( this );
7922 OO
.ui
.mixin
.GroupElement
.call( this, config
);
7925 this.toolFactory
= toolFactory
;
7926 this.toolGroupFactory
= toolGroupFactory
;
7929 this.$bar
= $( '<div>' );
7930 this.$actions
= $( '<div>' );
7931 this.initialized
= false;
7932 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
7936 .add( this.$bar
).add( this.$group
).add( this.$actions
)
7937 .on( 'mousedown keydown', this.onPointerDown
.bind( this ) );
7940 this.$group
.addClass( 'oo-ui-toolbar-tools' );
7941 if ( config
.actions
) {
7942 this.$bar
.append( this.$actions
.addClass( 'oo-ui-toolbar-actions' ) );
7945 .addClass( 'oo-ui-toolbar-bar' )
7946 .append( this.$group
, '<div style="clear:both"></div>' );
7947 if ( config
.shadow
) {
7948 this.$bar
.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7950 this.$element
.addClass( 'oo-ui-toolbar' ).append( this.$bar
);
7955 OO
.inheritClass( OO
.ui
.Toolbar
, OO
.ui
.Element
);
7956 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.EventEmitter
);
7957 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.ui
.mixin
.GroupElement
);
7962 * @event updateState
7964 * An 'updateState' event must be emitted on the Toolbar (by calling `toolbar.emit( 'updateState' )`)
7965 * every time the state of the application using the toolbar changes, and an update to the state of
7966 * tools is required.
7968 * @param {Mixed...} data Application-defined parameters
7974 * Get the tool factory.
7976 * @return {OO.ui.ToolFactory} Tool factory
7978 OO
.ui
.Toolbar
.prototype.getToolFactory = function () {
7979 return this.toolFactory
;
7983 * Get the toolgroup factory.
7985 * @return {OO.Factory} Toolgroup factory
7987 OO
.ui
.Toolbar
.prototype.getToolGroupFactory = function () {
7988 return this.toolGroupFactory
;
7992 * Handles mouse down events.
7995 * @param {jQuery.Event} e Mouse down event
7997 OO
.ui
.Toolbar
.prototype.onPointerDown = function ( e
) {
7998 var $closestWidgetToEvent
= $( e
.target
).closest( '.oo-ui-widget' ),
7999 $closestWidgetToToolbar
= this.$element
.closest( '.oo-ui-widget' );
8000 if ( !$closestWidgetToEvent
.length
|| $closestWidgetToEvent
[ 0 ] === $closestWidgetToToolbar
[ 0 ] ) {
8006 * Handle window resize event.
8009 * @param {jQuery.Event} e Window resize event
8011 OO
.ui
.Toolbar
.prototype.onWindowResize = function () {
8012 this.$element
.toggleClass(
8013 'oo-ui-toolbar-narrow',
8014 this.$bar
.width() <= this.narrowThreshold
8019 * Sets up handles and preloads required information for the toolbar to work.
8020 * This must be called after it is attached to a visible document and before doing anything else.
8022 OO
.ui
.Toolbar
.prototype.initialize = function () {
8023 if ( !this.initialized
) {
8024 this.initialized
= true;
8025 this.narrowThreshold
= this.$group
.width() + this.$actions
.width();
8026 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
8027 this.onWindowResize();
8032 * Set up the toolbar.
8034 * The toolbar is set up with a list of toolgroup configurations that specify the type of
8035 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
8036 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
8037 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
8039 * @param {Object.<string,Array>} groups List of toolgroup configurations
8040 * @param {Array|string} [groups.include] Tools to include in the toolgroup
8041 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
8042 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
8043 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
8045 OO
.ui
.Toolbar
.prototype.setup = function ( groups
) {
8046 var i
, len
, type
, group
,
8048 defaultType
= 'bar';
8050 // Cleanup previous groups
8053 // Build out new groups
8054 for ( i
= 0, len
= groups
.length
; i
< len
; i
++ ) {
8055 group
= groups
[ i
];
8056 if ( group
.include
=== '*' ) {
8057 // Apply defaults to catch-all groups
8058 if ( group
.type
=== undefined ) {
8059 group
.type
= 'list';
8061 if ( group
.label
=== undefined ) {
8062 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
8065 // Check type has been registered
8066 type
= this.getToolGroupFactory().lookup( group
.type
) ? group
.type
: defaultType
;
8068 this.getToolGroupFactory().create( type
, this, group
)
8071 this.addItems( items
);
8075 * Remove all tools and toolgroups from the toolbar.
8077 OO
.ui
.Toolbar
.prototype.reset = function () {
8082 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
8083 this.items
[ i
].destroy();
8089 * Destroy the toolbar.
8091 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
8092 * this method whenever you are done using a toolbar.
8094 OO
.ui
.Toolbar
.prototype.destroy = function () {
8095 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
8097 this.$element
.remove();
8101 * Check if the tool is available.
8103 * Available tools are ones that have not yet been added to the toolbar.
8105 * @param {string} name Symbolic name of tool
8106 * @return {boolean} Tool is available
8108 OO
.ui
.Toolbar
.prototype.isToolAvailable = function ( name
) {
8109 return !this.tools
[ name
];
8113 * Prevent tool from being used again.
8115 * @param {OO.ui.Tool} tool Tool to reserve
8117 OO
.ui
.Toolbar
.prototype.reserveTool = function ( tool
) {
8118 this.tools
[ tool
.getName() ] = tool
;
8122 * Allow tool to be used again.
8124 * @param {OO.ui.Tool} tool Tool to release
8126 OO
.ui
.Toolbar
.prototype.releaseTool = function ( tool
) {
8127 delete this.tools
[ tool
.getName() ];
8131 * Get accelerator label for tool.
8133 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
8134 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
8135 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
8137 * @param {string} name Symbolic name of tool
8138 * @return {string|undefined} Tool accelerator label if available
8140 OO
.ui
.Toolbar
.prototype.getToolAccelerator = function () {
8145 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
8146 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
8147 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
8148 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
8150 * Toolgroups can contain individual tools, groups of tools, or all available tools, as specified
8151 * using the `include` config option. See OO.ui.ToolFactory#extract on documentation of the format.
8152 * The options `exclude`, `promote`, and `demote` support the same formats.
8154 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
8155 * please see the [OOjs UI documentation on MediaWiki][1].
8157 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
8161 * @extends OO.ui.Widget
8162 * @mixins OO.ui.mixin.GroupElement
8165 * @param {OO.ui.Toolbar} toolbar
8166 * @param {Object} [config] Configuration options
8167 * @cfg {Array|string} [include] List of tools to include in the toolgroup, see above.
8168 * @cfg {Array|string} [exclude] List of tools to exclude from the toolgroup, see above.
8169 * @cfg {Array|string} [promote] List of tools to promote to the beginning of the toolgroup, see above.
8170 * @cfg {Array|string} [demote] List of tools to demote to the end of the toolgroup, see above.
8171 * This setting is particularly useful when tools have been added to the toolgroup
8172 * en masse (e.g., via the catch-all selector).
8174 OO
.ui
.ToolGroup
= function OoUiToolGroup( toolbar
, config
) {
8175 // Allow passing positional parameters inside the config object
8176 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
8178 toolbar
= config
.toolbar
;
8181 // Configuration initialization
8182 config
= config
|| {};
8184 // Parent constructor
8185 OO
.ui
.ToolGroup
.parent
.call( this, config
);
8187 // Mixin constructors
8188 OO
.ui
.mixin
.GroupElement
.call( this, config
);
8191 this.toolbar
= toolbar
;
8193 this.pressed
= null;
8194 this.autoDisabled
= false;
8195 this.include
= config
.include
|| [];
8196 this.exclude
= config
.exclude
|| [];
8197 this.promote
= config
.promote
|| [];
8198 this.demote
= config
.demote
|| [];
8199 this.onCapturedMouseKeyUpHandler
= this.onCapturedMouseKeyUp
.bind( this );
8203 mousedown
: this.onMouseKeyDown
.bind( this ),
8204 mouseup
: this.onMouseKeyUp
.bind( this ),
8205 keydown
: this.onMouseKeyDown
.bind( this ),
8206 keyup
: this.onMouseKeyUp
.bind( this ),
8207 focus
: this.onMouseOverFocus
.bind( this ),
8208 blur
: this.onMouseOutBlur
.bind( this ),
8209 mouseover
: this.onMouseOverFocus
.bind( this ),
8210 mouseout
: this.onMouseOutBlur
.bind( this )
8212 this.toolbar
.getToolFactory().connect( this, { register
: 'onToolFactoryRegister' } );
8213 this.aggregate( { disable
: 'itemDisable' } );
8214 this.connect( this, { itemDisable
: 'updateDisabled' } );
8217 this.$group
.addClass( 'oo-ui-toolGroup-tools' );
8219 .addClass( 'oo-ui-toolGroup' )
8220 .append( this.$group
);
8226 OO
.inheritClass( OO
.ui
.ToolGroup
, OO
.ui
.Widget
);
8227 OO
.mixinClass( OO
.ui
.ToolGroup
, OO
.ui
.mixin
.GroupElement
);
8235 /* Static Properties */
8238 * Show labels in tooltips.
8242 * @property {boolean}
8244 OO
.ui
.ToolGroup
.static.titleTooltips
= false;
8247 * Show acceleration labels in tooltips.
8249 * Note: The OOjs UI library does not include an accelerator system, but does contain
8250 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
8251 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
8252 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
8256 * @property {boolean}
8258 OO
.ui
.ToolGroup
.static.accelTooltips
= false;
8261 * Automatically disable the toolgroup when all tools are disabled
8265 * @property {boolean}
8267 OO
.ui
.ToolGroup
.static.autoDisable
= true;
8274 OO
.ui
.ToolGroup
.prototype.isDisabled = function () {
8275 return this.autoDisabled
|| OO
.ui
.ToolGroup
.parent
.prototype.isDisabled
.apply( this, arguments
);
8281 OO
.ui
.ToolGroup
.prototype.updateDisabled = function () {
8282 var i
, item
, allDisabled
= true;
8284 if ( this.constructor.static.autoDisable
) {
8285 for ( i
= this.items
.length
- 1; i
>= 0; i
-- ) {
8286 item
= this.items
[ i
];
8287 if ( !item
.isDisabled() ) {
8288 allDisabled
= false;
8292 this.autoDisabled
= allDisabled
;
8294 OO
.ui
.ToolGroup
.parent
.prototype.updateDisabled
.apply( this, arguments
);
8298 * Handle mouse down and key down events.
8301 * @param {jQuery.Event} e Mouse down or key down event
8303 OO
.ui
.ToolGroup
.prototype.onMouseKeyDown = function ( e
) {
8305 !this.isDisabled() &&
8306 ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
|| e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
8308 this.pressed
= this.getTargetTool( e
);
8309 if ( this.pressed
) {
8310 this.pressed
.setActive( true );
8311 this.getElementDocument().addEventListener( 'mouseup', this.onCapturedMouseKeyUpHandler
, true );
8312 this.getElementDocument().addEventListener( 'keyup', this.onCapturedMouseKeyUpHandler
, true );
8319 * Handle captured mouse up and key up events.
8322 * @param {Event} e Mouse up or key up event
8324 OO
.ui
.ToolGroup
.prototype.onCapturedMouseKeyUp = function ( e
) {
8325 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseKeyUpHandler
, true );
8326 this.getElementDocument().removeEventListener( 'keyup', this.onCapturedMouseKeyUpHandler
, true );
8327 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
8328 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
8329 this.onMouseKeyUp( e
);
8333 * Handle mouse up and key up events.
8336 * @param {jQuery.Event} e Mouse up or key up event
8338 OO
.ui
.ToolGroup
.prototype.onMouseKeyUp = function ( e
) {
8339 var tool
= this.getTargetTool( e
);
8342 !this.isDisabled() && this.pressed
&& this.pressed
=== tool
&&
8343 ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
|| e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
8345 this.pressed
.onSelect();
8346 this.pressed
= null;
8350 this.pressed
= null;
8354 * Handle mouse over and focus events.
8357 * @param {jQuery.Event} e Mouse over or focus event
8359 OO
.ui
.ToolGroup
.prototype.onMouseOverFocus = function ( e
) {
8360 var tool
= this.getTargetTool( e
);
8362 if ( this.pressed
&& this.pressed
=== tool
) {
8363 this.pressed
.setActive( true );
8368 * Handle mouse out and blur events.
8371 * @param {jQuery.Event} e Mouse out or blur event
8373 OO
.ui
.ToolGroup
.prototype.onMouseOutBlur = function ( e
) {
8374 var tool
= this.getTargetTool( e
);
8376 if ( this.pressed
&& this.pressed
=== tool
) {
8377 this.pressed
.setActive( false );
8382 * Get the closest tool to a jQuery.Event.
8384 * Only tool links are considered, which prevents other elements in the tool such as popups from
8385 * triggering tool group interactions.
8388 * @param {jQuery.Event} e
8389 * @return {OO.ui.Tool|null} Tool, `null` if none was found
8391 OO
.ui
.ToolGroup
.prototype.getTargetTool = function ( e
) {
8393 $item
= $( e
.target
).closest( '.oo-ui-tool-link' );
8395 if ( $item
.length
) {
8396 tool
= $item
.parent().data( 'oo-ui-tool' );
8399 return tool
&& !tool
.isDisabled() ? tool
: null;
8403 * Handle tool registry register events.
8405 * If a tool is registered after the group is created, we must repopulate the list to account for:
8407 * - a tool being added that may be included
8408 * - a tool already included being overridden
8411 * @param {string} name Symbolic name of tool
8413 OO
.ui
.ToolGroup
.prototype.onToolFactoryRegister = function () {
8418 * Get the toolbar that contains the toolgroup.
8420 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
8422 OO
.ui
.ToolGroup
.prototype.getToolbar = function () {
8423 return this.toolbar
;
8427 * Add and remove tools based on configuration.
8429 OO
.ui
.ToolGroup
.prototype.populate = function () {
8430 var i
, len
, name
, tool
,
8431 toolFactory
= this.toolbar
.getToolFactory(),
8435 list
= this.toolbar
.getToolFactory().getTools(
8436 this.include
, this.exclude
, this.promote
, this.demote
8439 // Build a list of needed tools
8440 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
8444 toolFactory
.lookup( name
) &&
8445 // Tool is available or is already in this group
8446 ( this.toolbar
.isToolAvailable( name
) || this.tools
[ name
] )
8448 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
8449 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
8450 this.toolbar
.tools
[ name
] = true;
8451 tool
= this.tools
[ name
];
8453 // Auto-initialize tools on first use
8454 this.tools
[ name
] = tool
= toolFactory
.create( name
, this );
8457 this.toolbar
.reserveTool( tool
);
8459 names
[ name
] = true;
8462 // Remove tools that are no longer needed
8463 for ( name
in this.tools
) {
8464 if ( !names
[ name
] ) {
8465 this.tools
[ name
].destroy();
8466 this.toolbar
.releaseTool( this.tools
[ name
] );
8467 remove
.push( this.tools
[ name
] );
8468 delete this.tools
[ name
];
8471 if ( remove
.length
) {
8472 this.removeItems( remove
);
8474 // Update emptiness state
8476 this.$element
.removeClass( 'oo-ui-toolGroup-empty' );
8478 this.$element
.addClass( 'oo-ui-toolGroup-empty' );
8480 // Re-add tools (moving existing ones to new locations)
8481 this.addItems( add
);
8482 // Disabled state may depend on items
8483 this.updateDisabled();
8487 * Destroy toolgroup.
8489 OO
.ui
.ToolGroup
.prototype.destroy = function () {
8493 this.toolbar
.getToolFactory().disconnect( this );
8494 for ( name
in this.tools
) {
8495 this.toolbar
.releaseTool( this.tools
[ name
] );
8496 this.tools
[ name
].disconnect( this ).destroy();
8497 delete this.tools
[ name
];
8499 this.$element
.remove();
8503 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
8504 * consists of a header that contains the dialog title, a body with the message, and a footer that
8505 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
8506 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
8508 * There are two basic types of message dialogs, confirmation and alert:
8510 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
8511 * more details about the consequences.
8512 * - **alert**: the dialog title describes which event occurred and the message provides more information
8513 * about why the event occurred.
8515 * The MessageDialog class specifies two actions: ‘accept’, the primary
8516 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
8517 * passing along the selected action.
8519 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
8522 * // Example: Creating and opening a message dialog window.
8523 * var messageDialog = new OO.ui.MessageDialog();
8525 * // Create and append a window manager.
8526 * var windowManager = new OO.ui.WindowManager();
8527 * $( 'body' ).append( windowManager.$element );
8528 * windowManager.addWindows( [ messageDialog ] );
8529 * // Open the window.
8530 * windowManager.openWindow( messageDialog, {
8531 * title: 'Basic message dialog',
8532 * message: 'This is the message'
8535 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
8538 * @extends OO.ui.Dialog
8541 * @param {Object} [config] Configuration options
8543 OO
.ui
.MessageDialog
= function OoUiMessageDialog( config
) {
8544 // Parent constructor
8545 OO
.ui
.MessageDialog
.parent
.call( this, config
);
8548 this.verticalActionLayout
= null;
8551 this.$element
.addClass( 'oo-ui-messageDialog' );
8556 OO
.inheritClass( OO
.ui
.MessageDialog
, OO
.ui
.Dialog
);
8558 /* Static Properties */
8560 OO
.ui
.MessageDialog
.static.name
= 'message';
8562 OO
.ui
.MessageDialog
.static.size
= 'small';
8564 OO
.ui
.MessageDialog
.static.verbose
= false;
8569 * The title of a confirmation dialog describes what a progressive action will do. The
8570 * title of an alert dialog describes which event occurred.
8574 * @property {jQuery|string|Function|null}
8576 OO
.ui
.MessageDialog
.static.title
= null;
8579 * The message displayed in the dialog body.
8581 * A confirmation message describes the consequences of a progressive action. An alert
8582 * message describes why an event occurred.
8586 * @property {jQuery|string|Function|null}
8588 OO
.ui
.MessageDialog
.static.message
= null;
8590 // Note that OO.ui.alert() and OO.ui.confirm() rely on these.
8591 OO
.ui
.MessageDialog
.static.actions
= [
8592 { action
: 'accept', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-accept' ), flags
: 'primary' },
8593 { action
: 'reject', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-reject' ), flags
: 'safe' }
8601 OO
.ui
.MessageDialog
.prototype.setManager = function ( manager
) {
8602 OO
.ui
.MessageDialog
.parent
.prototype.setManager
.call( this, manager
);
8605 this.manager
.connect( this, {
8615 OO
.ui
.MessageDialog
.prototype.onActionResize = function ( action
) {
8617 return OO
.ui
.MessageDialog
.parent
.prototype.onActionResize
.call( this, action
);
8621 * Handle window resized events.
8625 OO
.ui
.MessageDialog
.prototype.onResize = function () {
8627 dialog
.fitActions();
8628 // Wait for CSS transition to finish and do it again :(
8629 setTimeout( function () {
8630 dialog
.fitActions();
8635 * Toggle action layout between vertical and horizontal.
8638 * @param {boolean} [value] Layout actions vertically, omit to toggle
8641 OO
.ui
.MessageDialog
.prototype.toggleVerticalActionLayout = function ( value
) {
8642 value
= value
=== undefined ? !this.verticalActionLayout
: !!value
;
8644 if ( value
!== this.verticalActionLayout
) {
8645 this.verticalActionLayout
= value
;
8647 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value
)
8648 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value
);
8657 OO
.ui
.MessageDialog
.prototype.getActionProcess = function ( action
) {
8659 return new OO
.ui
.Process( function () {
8660 this.close( { action
: action
} );
8663 return OO
.ui
.MessageDialog
.parent
.prototype.getActionProcess
.call( this, action
);
8669 * @param {Object} [data] Dialog opening data
8670 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8671 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8672 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8673 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8676 OO
.ui
.MessageDialog
.prototype.getSetupProcess = function ( data
) {
8680 return OO
.ui
.MessageDialog
.parent
.prototype.getSetupProcess
.call( this, data
)
8681 .next( function () {
8682 this.title
.setLabel(
8683 data
.title
!== undefined ? data
.title
: this.constructor.static.title
8685 this.message
.setLabel(
8686 data
.message
!== undefined ? data
.message
: this.constructor.static.message
8688 this.message
.$element
.toggleClass(
8689 'oo-ui-messageDialog-message-verbose',
8690 data
.verbose
!== undefined ? data
.verbose
: this.constructor.static.verbose
8698 OO
.ui
.MessageDialog
.prototype.getReadyProcess = function ( data
) {
8702 return OO
.ui
.MessageDialog
.parent
.prototype.getReadyProcess
.call( this, data
)
8703 .next( function () {
8704 // Focus the primary action button
8705 var actions
= this.actions
.get();
8706 actions
= actions
.filter( function ( action
) {
8707 return action
.getFlags().indexOf( 'primary' ) > -1;
8709 if ( actions
.length
> 0 ) {
8710 actions
[ 0 ].$button
.focus();
8718 OO
.ui
.MessageDialog
.prototype.getBodyHeight = function () {
8719 var bodyHeight
, oldOverflow
,
8720 $scrollable
= this.container
.$element
;
8722 oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
8723 $scrollable
[ 0 ].style
.overflow
= 'hidden';
8725 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
8727 bodyHeight
= this.text
.$element
.outerHeight( true );
8728 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
8736 OO
.ui
.MessageDialog
.prototype.setDimensions = function ( dim
) {
8737 var $scrollable
= this.container
.$element
;
8738 OO
.ui
.MessageDialog
.parent
.prototype.setDimensions
.call( this, dim
);
8740 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8741 // Need to do it after transition completes (250ms), add 50ms just in case.
8742 setTimeout( function () {
8743 var oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
8744 $scrollable
[ 0 ].style
.overflow
= 'hidden';
8746 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
8748 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
8757 OO
.ui
.MessageDialog
.prototype.initialize = function () {
8759 OO
.ui
.MessageDialog
.parent
.prototype.initialize
.call( this );
8762 this.$actions
= $( '<div>' );
8763 this.container
= new OO
.ui
.PanelLayout( {
8764 scrollable
: true, classes
: [ 'oo-ui-messageDialog-container' ]
8766 this.text
= new OO
.ui
.PanelLayout( {
8767 padded
: true, expanded
: false, classes
: [ 'oo-ui-messageDialog-text' ]
8769 this.message
= new OO
.ui
.LabelWidget( {
8770 classes
: [ 'oo-ui-messageDialog-message' ]
8774 this.title
.$element
.addClass( 'oo-ui-messageDialog-title' );
8775 this.$content
.addClass( 'oo-ui-messageDialog-content' );
8776 this.container
.$element
.append( this.text
.$element
);
8777 this.text
.$element
.append( this.title
.$element
, this.message
.$element
);
8778 this.$body
.append( this.container
.$element
);
8779 this.$actions
.addClass( 'oo-ui-messageDialog-actions' );
8780 this.$foot
.append( this.$actions
);
8786 OO
.ui
.MessageDialog
.prototype.attachActions = function () {
8787 var i
, len
, other
, special
, others
;
8790 OO
.ui
.MessageDialog
.parent
.prototype.attachActions
.call( this );
8792 special
= this.actions
.getSpecial();
8793 others
= this.actions
.getOthers();
8795 if ( special
.safe
) {
8796 this.$actions
.append( special
.safe
.$element
);
8797 special
.safe
.toggleFramed( false );
8799 if ( others
.length
) {
8800 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
8801 other
= others
[ i
];
8802 this.$actions
.append( other
.$element
);
8803 other
.toggleFramed( false );
8806 if ( special
.primary
) {
8807 this.$actions
.append( special
.primary
.$element
);
8808 special
.primary
.toggleFramed( false );
8811 if ( !this.isOpening() ) {
8812 // If the dialog is currently opening, this will be called automatically soon.
8813 // This also calls #fitActions.
8819 * Fit action actions into columns or rows.
8821 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8825 OO
.ui
.MessageDialog
.prototype.fitActions = function () {
8827 previous
= this.verticalActionLayout
,
8828 actions
= this.actions
.get();
8831 this.toggleVerticalActionLayout( false );
8832 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
8833 action
= actions
[ i
];
8834 if ( action
.$element
.innerWidth() < action
.$label
.outerWidth( true ) ) {
8835 this.toggleVerticalActionLayout( true );
8840 // Move the body out of the way of the foot
8841 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
8843 if ( this.verticalActionLayout
!== previous
) {
8844 // We changed the layout, window height might need to be updated.
8850 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8851 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8852 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8853 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8854 * required for each process.
8856 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8857 * processes with an animation. The header contains the dialog title as well as
8858 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8859 * a ‘primary’ action on the right (e.g., ‘Done’).
8861 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8862 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8865 * // Example: Creating and opening a process dialog window.
8866 * function MyProcessDialog( config ) {
8867 * MyProcessDialog.parent.call( this, config );
8869 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8871 * MyProcessDialog.static.title = 'Process dialog';
8872 * MyProcessDialog.static.actions = [
8873 * { action: 'save', label: 'Done', flags: 'primary' },
8874 * { label: 'Cancel', flags: 'safe' }
8877 * MyProcessDialog.prototype.initialize = function () {
8878 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8879 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8880 * 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>' );
8881 * this.$body.append( this.content.$element );
8883 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8884 * var dialog = this;
8886 * return new OO.ui.Process( function () {
8887 * dialog.close( { action: action } );
8890 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8893 * var windowManager = new OO.ui.WindowManager();
8894 * $( 'body' ).append( windowManager.$element );
8896 * var dialog = new MyProcessDialog();
8897 * windowManager.addWindows( [ dialog ] );
8898 * windowManager.openWindow( dialog );
8900 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8904 * @extends OO.ui.Dialog
8907 * @param {Object} [config] Configuration options
8909 OO
.ui
.ProcessDialog
= function OoUiProcessDialog( config
) {
8910 // Parent constructor
8911 OO
.ui
.ProcessDialog
.parent
.call( this, config
);
8914 this.fitOnOpen
= false;
8917 this.$element
.addClass( 'oo-ui-processDialog' );
8922 OO
.inheritClass( OO
.ui
.ProcessDialog
, OO
.ui
.Dialog
);
8927 * Handle dismiss button click events.
8933 OO
.ui
.ProcessDialog
.prototype.onDismissErrorButtonClick = function () {
8938 * Handle retry button click events.
8940 * Hides errors and then tries again.
8944 OO
.ui
.ProcessDialog
.prototype.onRetryButtonClick = function () {
8946 this.executeAction( this.currentAction
);
8952 OO
.ui
.ProcessDialog
.prototype.onActionResize = function ( action
) {
8953 if ( this.actions
.isSpecial( action
) ) {
8956 return OO
.ui
.ProcessDialog
.parent
.prototype.onActionResize
.call( this, action
);
8962 OO
.ui
.ProcessDialog
.prototype.initialize = function () {
8964 OO
.ui
.ProcessDialog
.parent
.prototype.initialize
.call( this );
8967 this.$navigation
= $( '<div>' );
8968 this.$location
= $( '<div>' );
8969 this.$safeActions
= $( '<div>' );
8970 this.$primaryActions
= $( '<div>' );
8971 this.$otherActions
= $( '<div>' );
8972 this.dismissButton
= new OO
.ui
.ButtonWidget( {
8973 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' )
8975 this.retryButton
= new OO
.ui
.ButtonWidget();
8976 this.$errors
= $( '<div>' );
8977 this.$errorsTitle
= $( '<div>' );
8980 this.dismissButton
.connect( this, { click
: 'onDismissErrorButtonClick' } );
8981 this.retryButton
.connect( this, { click
: 'onRetryButtonClick' } );
8984 this.title
.$element
.addClass( 'oo-ui-processDialog-title' );
8986 .append( this.title
.$element
)
8987 .addClass( 'oo-ui-processDialog-location' );
8988 this.$safeActions
.addClass( 'oo-ui-processDialog-actions-safe' );
8989 this.$primaryActions
.addClass( 'oo-ui-processDialog-actions-primary' );
8990 this.$otherActions
.addClass( 'oo-ui-processDialog-actions-other' );
8992 .addClass( 'oo-ui-processDialog-errors-title' )
8993 .text( OO
.ui
.msg( 'ooui-dialog-process-error' ) );
8995 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8996 .append( this.$errorsTitle
, this.dismissButton
.$element
, this.retryButton
.$element
);
8998 .addClass( 'oo-ui-processDialog-content' )
8999 .append( this.$errors
);
9001 .addClass( 'oo-ui-processDialog-navigation' )
9002 .append( this.$safeActions
, this.$location
, this.$primaryActions
);
9003 this.$head
.append( this.$navigation
);
9004 this.$foot
.append( this.$otherActions
);
9010 OO
.ui
.ProcessDialog
.prototype.getActionWidgets = function ( actions
) {
9011 var i
, len
, widgets
= [];
9012 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
9014 new OO
.ui
.ActionWidget( $.extend( { framed
: true }, actions
[ i
] ) )
9023 OO
.ui
.ProcessDialog
.prototype.attachActions = function () {
9024 var i
, len
, other
, special
, others
;
9027 OO
.ui
.ProcessDialog
.parent
.prototype.attachActions
.call( this );
9029 special
= this.actions
.getSpecial();
9030 others
= this.actions
.getOthers();
9031 if ( special
.primary
) {
9032 this.$primaryActions
.append( special
.primary
.$element
);
9034 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
9035 other
= others
[ i
];
9036 this.$otherActions
.append( other
.$element
);
9038 if ( special
.safe
) {
9039 this.$safeActions
.append( special
.safe
.$element
);
9043 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
9049 OO
.ui
.ProcessDialog
.prototype.executeAction = function ( action
) {
9051 return OO
.ui
.ProcessDialog
.parent
.prototype.executeAction
.call( this, action
)
9052 .fail( function ( errors
) {
9053 process
.showErrors( errors
|| [] );
9060 OO
.ui
.ProcessDialog
.prototype.setDimensions = function () {
9062 OO
.ui
.ProcessDialog
.parent
.prototype.setDimensions
.apply( this, arguments
);
9068 * Fit label between actions.
9073 OO
.ui
.ProcessDialog
.prototype.fitLabel = function () {
9074 var safeWidth
, primaryWidth
, biggerWidth
, labelWidth
, navigationWidth
, leftWidth
, rightWidth
,
9075 size
= this.getSizeProperties();
9077 if ( typeof size
.width
!== 'number' ) {
9078 if ( this.isOpened() ) {
9079 navigationWidth
= this.$head
.width() - 20;
9080 } else if ( this.isOpening() ) {
9081 if ( !this.fitOnOpen
) {
9082 // Size is relative and the dialog isn't open yet, so wait.
9083 this.manager
.opening
.done( this.fitLabel
.bind( this ) );
9084 this.fitOnOpen
= true;
9091 navigationWidth
= size
.width
- 20;
9094 safeWidth
= this.$safeActions
.is( ':visible' ) ? this.$safeActions
.width() : 0;
9095 primaryWidth
= this.$primaryActions
.is( ':visible' ) ? this.$primaryActions
.width() : 0;
9096 biggerWidth
= Math
.max( safeWidth
, primaryWidth
);
9098 labelWidth
= this.title
.$element
.width();
9100 if ( 2 * biggerWidth
+ labelWidth
< navigationWidth
) {
9101 // We have enough space to center the label
9102 leftWidth
= rightWidth
= biggerWidth
;
9104 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
9105 if ( this.getDir() === 'ltr' ) {
9106 leftWidth
= safeWidth
;
9107 rightWidth
= primaryWidth
;
9109 leftWidth
= primaryWidth
;
9110 rightWidth
= safeWidth
;
9114 this.$location
.css( { paddingLeft
: leftWidth
, paddingRight
: rightWidth
} );
9120 * Handle errors that occurred during accept or reject processes.
9123 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
9125 OO
.ui
.ProcessDialog
.prototype.showErrors = function ( errors
) {
9126 var i
, len
, $item
, actions
,
9132 if ( errors
instanceof OO
.ui
.Error
) {
9133 errors
= [ errors
];
9136 for ( i
= 0, len
= errors
.length
; i
< len
; i
++ ) {
9137 if ( !errors
[ i
].isRecoverable() ) {
9138 recoverable
= false;
9140 if ( errors
[ i
].isWarning() ) {
9143 $item
= $( '<div>' )
9144 .addClass( 'oo-ui-processDialog-error' )
9145 .append( errors
[ i
].getMessage() );
9146 items
.push( $item
[ 0 ] );
9148 this.$errorItems
= $( items
);
9149 if ( recoverable
) {
9150 abilities
[ this.currentAction
] = true;
9151 // Copy the flags from the first matching action
9152 actions
= this.actions
.get( { actions
: this.currentAction
} );
9153 if ( actions
.length
) {
9154 this.retryButton
.clearFlags().setFlags( actions
[ 0 ].getFlags() );
9157 abilities
[ this.currentAction
] = false;
9158 this.actions
.setAbilities( abilities
);
9161 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-continue' ) );
9163 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-retry' ) );
9165 this.retryButton
.toggle( recoverable
);
9166 this.$errorsTitle
.after( this.$errorItems
);
9167 this.$errors
.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
9175 OO
.ui
.ProcessDialog
.prototype.hideErrors = function () {
9176 this.$errors
.addClass( 'oo-ui-element-hidden' );
9177 if ( this.$errorItems
) {
9178 this.$errorItems
.remove();
9179 this.$errorItems
= null;
9186 OO
.ui
.ProcessDialog
.prototype.getTeardownProcess = function ( data
) {
9188 return OO
.ui
.ProcessDialog
.parent
.prototype.getTeardownProcess
.call( this, data
)
9189 .first( function () {
9190 // Make sure to hide errors
9192 this.fitOnOpen
= false;
9197 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
9198 * which is a widget that is specified by reference before any optional configuration settings.
9200 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
9202 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9203 * A left-alignment is used for forms with many fields.
9204 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9205 * A right-alignment is used for long but familiar forms which users tab through,
9206 * verifying the current field with a quick glance at the label.
9207 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9208 * that users fill out from top to bottom.
9209 * - **inline**: The label is placed after the field-widget and aligned to the left.
9210 * An inline-alignment is best used with checkboxes or radio buttons.
9212 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
9213 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
9215 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9217 * @extends OO.ui.Layout
9218 * @mixins OO.ui.mixin.LabelElement
9219 * @mixins OO.ui.mixin.TitledElement
9222 * @param {OO.ui.Widget} fieldWidget Field widget
9223 * @param {Object} [config] Configuration options
9224 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
9225 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
9226 * The array may contain strings or OO.ui.HtmlSnippet instances.
9227 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
9228 * The array may contain strings or OO.ui.HtmlSnippet instances.
9229 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
9230 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
9231 * For important messages, you are advised to use `notices`, as they are always shown.
9233 * @throws {Error} An error is thrown if no widget is specified
9235 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
9236 var hasInputWidget
, div
;
9238 // Allow passing positional parameters inside the config object
9239 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
9240 config
= fieldWidget
;
9241 fieldWidget
= config
.fieldWidget
;
9244 // Make sure we have required constructor arguments
9245 if ( fieldWidget
=== undefined ) {
9246 throw new Error( 'Widget not found' );
9249 hasInputWidget
= fieldWidget
.constructor.static.supportsSimpleLabel
;
9251 // Configuration initialization
9252 config
= $.extend( { align
: 'left' }, config
);
9254 // Parent constructor
9255 OO
.ui
.FieldLayout
.parent
.call( this, config
);
9257 // Mixin constructors
9258 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9259 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
9262 this.fieldWidget
= fieldWidget
;
9265 this.$field
= $( '<div>' );
9266 this.$messages
= $( '<ul>' );
9267 this.$body
= $( '<' + ( hasInputWidget
? 'label' : 'div' ) + '>' );
9269 if ( config
.help
) {
9270 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
9271 classes
: [ 'oo-ui-fieldLayout-help' ],
9277 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
9278 div
.html( config
.help
.toString() );
9280 div
.text( config
.help
);
9282 this.popupButtonWidget
.getPopup().$body
.append(
9283 div
.addClass( 'oo-ui-fieldLayout-help-content' )
9285 this.$help
= this.popupButtonWidget
.$element
;
9287 this.$help
= $( [] );
9291 if ( hasInputWidget
) {
9292 this.$label
.on( 'click', this.onLabelClick
.bind( this ) );
9294 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
9298 .addClass( 'oo-ui-fieldLayout' )
9299 .append( this.$help
, this.$body
);
9300 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
9301 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
9303 .addClass( 'oo-ui-fieldLayout-field' )
9304 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget
.isDisabled() )
9305 .append( this.fieldWidget
.$element
);
9307 this.setErrors( config
.errors
|| [] );
9308 this.setNotices( config
.notices
|| [] );
9309 this.setAlignment( config
.align
);
9314 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
9315 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
9316 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
9321 * Handle field disable events.
9324 * @param {boolean} value Field is disabled
9326 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
9327 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
9331 * Handle label mouse click events.
9334 * @param {jQuery.Event} e Mouse click event
9336 OO
.ui
.FieldLayout
.prototype.onLabelClick = function () {
9337 this.fieldWidget
.simulateLabelClick();
9342 * Get the widget contained by the field.
9344 * @return {OO.ui.Widget} Field widget
9346 OO
.ui
.FieldLayout
.prototype.getField = function () {
9347 return this.fieldWidget
;
9352 * @param {string} kind 'error' or 'notice'
9353 * @param {string|OO.ui.HtmlSnippet} text
9356 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
9357 var $listItem
, $icon
, message
;
9358 $listItem
= $( '<li>' );
9359 if ( kind
=== 'error' ) {
9360 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
9361 } else if ( kind
=== 'notice' ) {
9362 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
9366 message
= new OO
.ui
.LabelWidget( { label
: text
} );
9368 .append( $icon
, message
.$element
)
9369 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
9374 * Set the field alignment mode.
9377 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
9380 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
9381 if ( value
!== this.align
) {
9382 // Default to 'left'
9383 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
9387 if ( value
=== 'inline' ) {
9388 this.$body
.append( this.$field
, this.$label
);
9390 this.$body
.append( this.$label
, this.$field
);
9392 // Set classes. The following classes can be used here:
9393 // * oo-ui-fieldLayout-align-left
9394 // * oo-ui-fieldLayout-align-right
9395 // * oo-ui-fieldLayout-align-top
9396 // * oo-ui-fieldLayout-align-inline
9398 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
9400 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
9408 * Set the list of error messages.
9410 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
9411 * The array may contain strings or OO.ui.HtmlSnippet instances.
9414 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
9415 this.errors
= errors
.slice();
9416 this.updateMessages();
9421 * Set the list of notice messages.
9423 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
9424 * The array may contain strings or OO.ui.HtmlSnippet instances.
9427 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
9428 this.notices
= notices
.slice();
9429 this.updateMessages();
9434 * Update the rendering of error and notice messages.
9438 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
9440 this.$messages
.empty();
9442 if ( this.errors
.length
|| this.notices
.length
) {
9443 this.$body
.after( this.$messages
);
9445 this.$messages
.remove();
9449 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
9450 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
9452 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
9453 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
9458 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
9459 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
9460 * is required and is specified before any optional configuration settings.
9462 * Labels can be aligned in one of four ways:
9464 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9465 * A left-alignment is used for forms with many fields.
9466 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9467 * A right-alignment is used for long but familiar forms which users tab through,
9468 * verifying the current field with a quick glance at the label.
9469 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9470 * that users fill out from top to bottom.
9471 * - **inline**: The label is placed after the field-widget and aligned to the left.
9472 * An inline-alignment is best used with checkboxes or radio buttons.
9474 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
9475 * text is specified.
9478 * // Example of an ActionFieldLayout
9479 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
9480 * new OO.ui.TextInputWidget( {
9481 * placeholder: 'Field widget'
9483 * new OO.ui.ButtonWidget( {
9487 * label: 'An ActionFieldLayout. This label is aligned top',
9489 * help: 'This is help text'
9493 * $( 'body' ).append( actionFieldLayout.$element );
9496 * @extends OO.ui.FieldLayout
9499 * @param {OO.ui.Widget} fieldWidget Field widget
9500 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9502 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
9503 // Allow passing positional parameters inside the config object
9504 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
9505 config
= fieldWidget
;
9506 fieldWidget
= config
.fieldWidget
;
9507 buttonWidget
= config
.buttonWidget
;
9510 // Parent constructor
9511 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
9514 this.buttonWidget
= buttonWidget
;
9515 this.$button
= $( '<div>' );
9516 this.$input
= $( '<div>' );
9520 .addClass( 'oo-ui-actionFieldLayout' );
9522 .addClass( 'oo-ui-actionFieldLayout-button' )
9523 .append( this.buttonWidget
.$element
);
9525 .addClass( 'oo-ui-actionFieldLayout-input' )
9526 .append( this.fieldWidget
.$element
);
9528 .append( this.$input
, this.$button
);
9533 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
9536 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9537 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9538 * configured with a label as well. For more information and examples,
9539 * please see the [OOjs UI documentation on MediaWiki][1].
9542 * // Example of a fieldset layout
9543 * var input1 = new OO.ui.TextInputWidget( {
9544 * placeholder: 'A text input field'
9547 * var input2 = new OO.ui.TextInputWidget( {
9548 * placeholder: 'A text input field'
9551 * var fieldset = new OO.ui.FieldsetLayout( {
9552 * label: 'Example of a fieldset layout'
9555 * fieldset.addItems( [
9556 * new OO.ui.FieldLayout( input1, {
9557 * label: 'Field One'
9559 * new OO.ui.FieldLayout( input2, {
9560 * label: 'Field Two'
9563 * $( 'body' ).append( fieldset.$element );
9565 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9568 * @extends OO.ui.Layout
9569 * @mixins OO.ui.mixin.IconElement
9570 * @mixins OO.ui.mixin.LabelElement
9571 * @mixins OO.ui.mixin.GroupElement
9574 * @param {Object} [config] Configuration options
9575 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9577 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
9578 // Configuration initialization
9579 config
= config
|| {};
9581 // Parent constructor
9582 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
9584 // Mixin constructors
9585 OO
.ui
.mixin
.IconElement
.call( this, config
);
9586 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9587 OO
.ui
.mixin
.GroupElement
.call( this, config
);
9589 if ( config
.help
) {
9590 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
9591 classes
: [ 'oo-ui-fieldsetLayout-help' ],
9596 this.popupButtonWidget
.getPopup().$body
.append(
9598 .text( config
.help
)
9599 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9601 this.$help
= this.popupButtonWidget
.$element
;
9603 this.$help
= $( [] );
9608 .addClass( 'oo-ui-fieldsetLayout' )
9609 .prepend( this.$help
, this.$icon
, this.$label
, this.$group
);
9610 if ( Array
.isArray( config
.items
) ) {
9611 this.addItems( config
.items
);
9617 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
9618 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
9619 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
9620 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
9623 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9624 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9625 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9626 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9628 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9629 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9630 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9631 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9632 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9633 * often have simplified APIs to match the capabilities of HTML forms.
9634 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9636 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9637 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9640 * // Example of a form layout that wraps a fieldset layout
9641 * var input1 = new OO.ui.TextInputWidget( {
9642 * placeholder: 'Username'
9644 * var input2 = new OO.ui.TextInputWidget( {
9645 * placeholder: 'Password',
9648 * var submit = new OO.ui.ButtonInputWidget( {
9652 * var fieldset = new OO.ui.FieldsetLayout( {
9653 * label: 'A form layout'
9655 * fieldset.addItems( [
9656 * new OO.ui.FieldLayout( input1, {
9657 * label: 'Username',
9660 * new OO.ui.FieldLayout( input2, {
9661 * label: 'Password',
9664 * new OO.ui.FieldLayout( submit )
9666 * var form = new OO.ui.FormLayout( {
9667 * items: [ fieldset ],
9668 * action: '/api/formhandler',
9671 * $( 'body' ).append( form.$element );
9674 * @extends OO.ui.Layout
9675 * @mixins OO.ui.mixin.GroupElement
9678 * @param {Object} [config] Configuration options
9679 * @cfg {string} [method] HTML form `method` attribute
9680 * @cfg {string} [action] HTML form `action` attribute
9681 * @cfg {string} [enctype] HTML form `enctype` attribute
9682 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9684 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
9685 // Configuration initialization
9686 config
= config
|| {};
9688 // Parent constructor
9689 OO
.ui
.FormLayout
.parent
.call( this, config
);
9691 // Mixin constructors
9692 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
9695 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
9697 // Make sure the action is safe
9698 if ( config
.action
!== undefined && !OO
.ui
.isSafeUrl( config
.action
) ) {
9699 throw new Error( 'Potentially unsafe action provided: ' + config
.action
);
9704 .addClass( 'oo-ui-formLayout' )
9706 method
: config
.method
,
9707 action
: config
.action
,
9708 enctype
: config
.enctype
9710 if ( Array
.isArray( config
.items
) ) {
9711 this.addItems( config
.items
);
9717 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
9718 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
9723 * A 'submit' event is emitted when the form is submitted.
9728 /* Static Properties */
9730 OO
.ui
.FormLayout
.static.tagName
= 'form';
9735 * Handle form submit events.
9738 * @param {jQuery.Event} e Submit event
9741 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
9742 if ( this.emit( 'submit' ) ) {
9748 * 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)
9749 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9752 * var menuLayout = new OO.ui.MenuLayout( {
9755 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9756 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9757 * select = new OO.ui.SelectWidget( {
9759 * new OO.ui.OptionWidget( {
9763 * new OO.ui.OptionWidget( {
9767 * new OO.ui.OptionWidget( {
9771 * new OO.ui.OptionWidget( {
9776 * } ).on( 'select', function ( item ) {
9777 * menuLayout.setMenuPosition( item.getData() );
9780 * menuLayout.$menu.append(
9781 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9783 * menuLayout.$content.append(
9784 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9786 * $( 'body' ).append( menuLayout.$element );
9788 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9789 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9790 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9793 * .oo-ui-menuLayout-menu {
9797 * .oo-ui-menuLayout-content {
9805 * @extends OO.ui.Layout
9808 * @param {Object} [config] Configuration options
9809 * @cfg {boolean} [showMenu=true] Show menu
9810 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9812 OO
.ui
.MenuLayout
= function OoUiMenuLayout( config
) {
9813 // Configuration initialization
9814 config
= $.extend( {
9816 menuPosition
: 'before'
9819 // Parent constructor
9820 OO
.ui
.MenuLayout
.parent
.call( this, config
);
9825 * @property {jQuery}
9827 this.$menu
= $( '<div>' );
9831 * @property {jQuery}
9833 this.$content
= $( '<div>' );
9837 .addClass( 'oo-ui-menuLayout-menu' );
9838 this.$content
.addClass( 'oo-ui-menuLayout-content' );
9840 .addClass( 'oo-ui-menuLayout' )
9841 .append( this.$content
, this.$menu
);
9842 this.setMenuPosition( config
.menuPosition
);
9843 this.toggleMenu( config
.showMenu
);
9848 OO
.inheritClass( OO
.ui
.MenuLayout
, OO
.ui
.Layout
);
9855 * @param {boolean} showMenu Show menu, omit to toggle
9858 OO
.ui
.MenuLayout
.prototype.toggleMenu = function ( showMenu
) {
9859 showMenu
= showMenu
=== undefined ? !this.showMenu
: !!showMenu
;
9861 if ( this.showMenu
!== showMenu
) {
9862 this.showMenu
= showMenu
;
9864 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu
)
9865 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu
);
9872 * Check if menu is visible
9874 * @return {boolean} Menu is visible
9876 OO
.ui
.MenuLayout
.prototype.isMenuVisible = function () {
9877 return this.showMenu
;
9881 * Set menu position.
9883 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9884 * @throws {Error} If position value is not supported
9887 OO
.ui
.MenuLayout
.prototype.setMenuPosition = function ( position
) {
9888 this.$element
.removeClass( 'oo-ui-menuLayout-' + this.menuPosition
);
9889 this.menuPosition
= position
;
9890 this.$element
.addClass( 'oo-ui-menuLayout-' + position
);
9896 * Get menu position.
9898 * @return {string} Menu position
9900 OO
.ui
.MenuLayout
.prototype.getMenuPosition = function () {
9901 return this.menuPosition
;
9905 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9906 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9907 * through the pages and select which one to display. By default, only one page is
9908 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9909 * the booklet layout automatically focuses on the first focusable element, unless the
9910 * default setting is changed. Optionally, booklets can be configured to show
9911 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9914 * // Example of a BookletLayout that contains two PageLayouts.
9916 * function PageOneLayout( name, config ) {
9917 * PageOneLayout.parent.call( this, name, config );
9918 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9920 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9921 * PageOneLayout.prototype.setupOutlineItem = function () {
9922 * this.outlineItem.setLabel( 'Page One' );
9925 * function PageTwoLayout( name, config ) {
9926 * PageTwoLayout.parent.call( this, name, config );
9927 * this.$element.append( '<p>Second page</p>' );
9929 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9930 * PageTwoLayout.prototype.setupOutlineItem = function () {
9931 * this.outlineItem.setLabel( 'Page Two' );
9934 * var page1 = new PageOneLayout( 'one' ),
9935 * page2 = new PageTwoLayout( 'two' );
9937 * var booklet = new OO.ui.BookletLayout( {
9941 * booklet.addPages ( [ page1, page2 ] );
9942 * $( 'body' ).append( booklet.$element );
9945 * @extends OO.ui.MenuLayout
9948 * @param {Object} [config] Configuration options
9949 * @cfg {boolean} [continuous=false] Show all pages, one after another
9950 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9951 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9952 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9954 OO
.ui
.BookletLayout
= function OoUiBookletLayout( config
) {
9955 // Configuration initialization
9956 config
= config
|| {};
9958 // Parent constructor
9959 OO
.ui
.BookletLayout
.parent
.call( this, config
);
9962 this.currentPageName
= null;
9964 this.ignoreFocus
= false;
9965 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
9966 this.$content
.append( this.stackLayout
.$element
);
9967 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
9968 this.outlineVisible
= false;
9969 this.outlined
= !!config
.outlined
;
9970 if ( this.outlined
) {
9971 this.editable
= !!config
.editable
;
9972 this.outlineControlsWidget
= null;
9973 this.outlineSelectWidget
= new OO
.ui
.OutlineSelectWidget();
9974 this.outlinePanel
= new OO
.ui
.PanelLayout( { scrollable
: true } );
9975 this.$menu
.append( this.outlinePanel
.$element
);
9976 this.outlineVisible
= true;
9977 if ( this.editable
) {
9978 this.outlineControlsWidget
= new OO
.ui
.OutlineControlsWidget(
9979 this.outlineSelectWidget
9983 this.toggleMenu( this.outlined
);
9986 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
9987 if ( this.outlined
) {
9988 this.outlineSelectWidget
.connect( this, { select
: 'onOutlineSelectWidgetSelect' } );
9989 this.scrolling
= false;
9990 this.stackLayout
.connect( this, { visibleItemChange
: 'onStackLayoutVisibleItemChange' } );
9992 if ( this.autoFocus
) {
9993 // Event 'focus' does not bubble, but 'focusin' does
9994 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
9998 this.$element
.addClass( 'oo-ui-bookletLayout' );
9999 this.stackLayout
.$element
.addClass( 'oo-ui-bookletLayout-stackLayout' );
10000 if ( this.outlined
) {
10001 this.outlinePanel
.$element
10002 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
10003 .append( this.outlineSelectWidget
.$element
);
10004 if ( this.editable
) {
10005 this.outlinePanel
.$element
10006 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
10007 .append( this.outlineControlsWidget
.$element
);
10014 OO
.inheritClass( OO
.ui
.BookletLayout
, OO
.ui
.MenuLayout
);
10019 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
10021 * @param {OO.ui.PageLayout} page Current page
10025 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
10028 * @param {OO.ui.PageLayout[]} page Added pages
10029 * @param {number} index Index pages were added at
10033 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
10034 * {@link #removePages removed} from the booklet.
10037 * @param {OO.ui.PageLayout[]} pages Removed pages
10043 * Handle stack layout focus.
10046 * @param {jQuery.Event} e Focusin event
10048 OO
.ui
.BookletLayout
.prototype.onStackLayoutFocus = function ( e
) {
10051 // Find the page that an element was focused within
10052 $target
= $( e
.target
).closest( '.oo-ui-pageLayout' );
10053 for ( name
in this.pages
) {
10054 // Check for page match, exclude current page to find only page changes
10055 if ( this.pages
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentPageName
) {
10056 this.setPage( name
);
10063 * Handle visibleItemChange events from the stackLayout
10065 * The next visible page is set as the current page by selecting it
10068 * @param {OO.ui.PageLayout} page The next visible page in the layout
10070 OO
.ui
.BookletLayout
.prototype.onStackLayoutVisibleItemChange = function ( page
) {
10071 // Set a flag to so that the resulting call to #onStackLayoutSet doesn't
10072 // try and scroll the item into view again.
10073 this.scrolling
= true;
10074 this.outlineSelectWidget
.selectItemByData( page
.getName() );
10075 this.scrolling
= false;
10079 * Handle stack layout set events.
10082 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
10084 OO
.ui
.BookletLayout
.prototype.onStackLayoutSet = function ( page
) {
10086 if ( !this.scrolling
&& page
) {
10087 page
.scrollElementIntoView( { complete: function () {
10088 if ( layout
.autoFocus
) {
10096 * Focus the first input in the current page.
10098 * If no page is selected, the first selectable page will be selected.
10099 * If the focus is already in an element on the current page, nothing will happen.
10100 * @param {number} [itemIndex] A specific item to focus on
10102 OO
.ui
.BookletLayout
.prototype.focus = function ( itemIndex
) {
10104 items
= this.stackLayout
.getItems();
10106 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
10107 page
= items
[ itemIndex
];
10109 page
= this.stackLayout
.getCurrentItem();
10112 if ( !page
&& this.outlined
) {
10113 this.selectFirstSelectablePage();
10114 page
= this.stackLayout
.getCurrentItem();
10119 // Only change the focus if is not already in the current page
10120 if ( !OO
.ui
.contains( page
.$element
[ 0 ], this.getElementDocument().activeElement
, true ) ) {
10126 * Find the first focusable input in the booklet layout and focus
10129 OO
.ui
.BookletLayout
.prototype.focusFirstFocusable = function () {
10130 OO
.ui
.findFocusable( this.stackLayout
.$element
).focus();
10134 * Handle outline widget select events.
10137 * @param {OO.ui.OptionWidget|null} item Selected item
10139 OO
.ui
.BookletLayout
.prototype.onOutlineSelectWidgetSelect = function ( item
) {
10141 this.setPage( item
.getData() );
10146 * Check if booklet has an outline.
10148 * @return {boolean} Booklet has an outline
10150 OO
.ui
.BookletLayout
.prototype.isOutlined = function () {
10151 return this.outlined
;
10155 * Check if booklet has editing controls.
10157 * @return {boolean} Booklet is editable
10159 OO
.ui
.BookletLayout
.prototype.isEditable = function () {
10160 return this.editable
;
10164 * Check if booklet has a visible outline.
10166 * @return {boolean} Outline is visible
10168 OO
.ui
.BookletLayout
.prototype.isOutlineVisible = function () {
10169 return this.outlined
&& this.outlineVisible
;
10173 * Hide or show the outline.
10175 * @param {boolean} [show] Show outline, omit to invert current state
10178 OO
.ui
.BookletLayout
.prototype.toggleOutline = function ( show
) {
10179 if ( this.outlined
) {
10180 show
= show
=== undefined ? !this.outlineVisible
: !!show
;
10181 this.outlineVisible
= show
;
10182 this.toggleMenu( show
);
10189 * Get the page closest to the specified page.
10191 * @param {OO.ui.PageLayout} page Page to use as a reference point
10192 * @return {OO.ui.PageLayout|null} Page closest to the specified page
10194 OO
.ui
.BookletLayout
.prototype.getClosestPage = function ( page
) {
10195 var next
, prev
, level
,
10196 pages
= this.stackLayout
.getItems(),
10197 index
= pages
.indexOf( page
);
10199 if ( index
!== -1 ) {
10200 next
= pages
[ index
+ 1 ];
10201 prev
= pages
[ index
- 1 ];
10202 // Prefer adjacent pages at the same level
10203 if ( this.outlined
) {
10204 level
= this.outlineSelectWidget
.getItemFromData( page
.getName() ).getLevel();
10207 level
=== this.outlineSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
10213 level
=== this.outlineSelectWidget
.getItemFromData( next
.getName() ).getLevel()
10219 return prev
|| next
|| null;
10223 * Get the outline widget.
10225 * If the booklet is not outlined, the method will return `null`.
10227 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
10229 OO
.ui
.BookletLayout
.prototype.getOutline = function () {
10230 return this.outlineSelectWidget
;
10234 * Get the outline controls widget.
10236 * If the outline is not editable, the method will return `null`.
10238 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
10240 OO
.ui
.BookletLayout
.prototype.getOutlineControls = function () {
10241 return this.outlineControlsWidget
;
10245 * Get a page by its symbolic name.
10247 * @param {string} name Symbolic name of page
10248 * @return {OO.ui.PageLayout|undefined} Page, if found
10250 OO
.ui
.BookletLayout
.prototype.getPage = function ( name
) {
10251 return this.pages
[ name
];
10255 * Get the current page.
10257 * @return {OO.ui.PageLayout|undefined} Current page, if found
10259 OO
.ui
.BookletLayout
.prototype.getCurrentPage = function () {
10260 var name
= this.getCurrentPageName();
10261 return name
? this.getPage( name
) : undefined;
10265 * Get the symbolic name of the current page.
10267 * @return {string|null} Symbolic name of the current page
10269 OO
.ui
.BookletLayout
.prototype.getCurrentPageName = function () {
10270 return this.currentPageName
;
10274 * Add pages to the booklet layout
10276 * When pages are added with the same names as existing pages, the existing pages will be
10277 * automatically removed before the new pages are added.
10279 * @param {OO.ui.PageLayout[]} pages Pages to add
10280 * @param {number} index Index of the insertion point
10284 OO
.ui
.BookletLayout
.prototype.addPages = function ( pages
, index
) {
10285 var i
, len
, name
, page
, item
, currentIndex
,
10286 stackLayoutPages
= this.stackLayout
.getItems(),
10290 // Remove pages with same names
10291 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10293 name
= page
.getName();
10295 if ( Object
.prototype.hasOwnProperty
.call( this.pages
, name
) ) {
10296 // Correct the insertion index
10297 currentIndex
= stackLayoutPages
.indexOf( this.pages
[ name
] );
10298 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
10301 remove
.push( this.pages
[ name
] );
10304 if ( remove
.length
) {
10305 this.removePages( remove
);
10309 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10311 name
= page
.getName();
10312 this.pages
[ page
.getName() ] = page
;
10313 if ( this.outlined
) {
10314 item
= new OO
.ui
.OutlineOptionWidget( { data
: name
} );
10315 page
.setOutlineItem( item
);
10316 items
.push( item
);
10320 if ( this.outlined
&& items
.length
) {
10321 this.outlineSelectWidget
.addItems( items
, index
);
10322 this.selectFirstSelectablePage();
10324 this.stackLayout
.addItems( pages
, index
);
10325 this.emit( 'add', pages
, index
);
10331 * Remove the specified pages from the booklet layout.
10333 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
10335 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
10339 OO
.ui
.BookletLayout
.prototype.removePages = function ( pages
) {
10340 var i
, len
, name
, page
,
10343 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10345 name
= page
.getName();
10346 delete this.pages
[ name
];
10347 if ( this.outlined
) {
10348 items
.push( this.outlineSelectWidget
.getItemFromData( name
) );
10349 page
.setOutlineItem( null );
10352 if ( this.outlined
&& items
.length
) {
10353 this.outlineSelectWidget
.removeItems( items
);
10354 this.selectFirstSelectablePage();
10356 this.stackLayout
.removeItems( pages
);
10357 this.emit( 'remove', pages
);
10363 * Clear all pages from the booklet layout.
10365 * To remove only a subset of pages from the booklet, use the #removePages method.
10370 OO
.ui
.BookletLayout
.prototype.clearPages = function () {
10372 pages
= this.stackLayout
.getItems();
10375 this.currentPageName
= null;
10376 if ( this.outlined
) {
10377 this.outlineSelectWidget
.clearItems();
10378 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10379 pages
[ i
].setOutlineItem( null );
10382 this.stackLayout
.clearItems();
10384 this.emit( 'remove', pages
);
10390 * Set the current page by symbolic name.
10393 * @param {string} name Symbolic name of page
10395 OO
.ui
.BookletLayout
.prototype.setPage = function ( name
) {
10398 page
= this.pages
[ name
],
10399 previousPage
= this.currentPageName
&& this.pages
[ this.currentPageName
];
10401 if ( name
!== this.currentPageName
) {
10402 if ( this.outlined
) {
10403 selectedItem
= this.outlineSelectWidget
.getSelectedItem();
10404 if ( selectedItem
&& selectedItem
.getData() !== name
) {
10405 this.outlineSelectWidget
.selectItemByData( name
);
10409 if ( previousPage
) {
10410 previousPage
.setActive( false );
10411 // Blur anything focused if the next page doesn't have anything focusable.
10412 // This is not needed if the next page has something focusable (because once it is focused
10413 // this blur happens automatically). If the layout is non-continuous, this check is
10414 // meaningless because the next page is not visible yet and thus can't hold focus.
10417 this.stackLayout
.continuous
&&
10418 OO
.ui
.findFocusable( page
.$element
).length
!== 0
10420 $focused
= previousPage
.$element
.find( ':focus' );
10421 if ( $focused
.length
) {
10422 $focused
[ 0 ].blur();
10426 this.currentPageName
= name
;
10427 page
.setActive( true );
10428 this.stackLayout
.setItem( page
);
10429 if ( !this.stackLayout
.continuous
&& previousPage
) {
10430 // This should not be necessary, since any inputs on the previous page should have been
10431 // blurred when it was hidden, but browsers are not very consistent about this.
10432 $focused
= previousPage
.$element
.find( ':focus' );
10433 if ( $focused
.length
) {
10434 $focused
[ 0 ].blur();
10437 this.emit( 'set', page
);
10443 * Select the first selectable page.
10447 OO
.ui
.BookletLayout
.prototype.selectFirstSelectablePage = function () {
10448 if ( !this.outlineSelectWidget
.getSelectedItem() ) {
10449 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getFirstSelectableItem() );
10456 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
10457 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
10458 * select which one to display. By default, only one card is displayed at a time. When a user
10459 * navigates to a new card, the index layout automatically focuses on the first focusable element,
10460 * unless the default setting is changed.
10462 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
10465 * // Example of a IndexLayout that contains two CardLayouts.
10467 * function CardOneLayout( name, config ) {
10468 * CardOneLayout.parent.call( this, name, config );
10469 * this.$element.append( '<p>First card</p>' );
10471 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
10472 * CardOneLayout.prototype.setupTabItem = function () {
10473 * this.tabItem.setLabel( 'Card one' );
10476 * var card1 = new CardOneLayout( 'one' ),
10477 * card2 = new CardLayout( 'two', { label: 'Card two' } );
10479 * card2.$element.append( '<p>Second card</p>' );
10481 * var index = new OO.ui.IndexLayout();
10483 * index.addCards ( [ card1, card2 ] );
10484 * $( 'body' ).append( index.$element );
10487 * @extends OO.ui.MenuLayout
10490 * @param {Object} [config] Configuration options
10491 * @cfg {boolean} [continuous=false] Show all cards, one after another
10492 * @cfg {boolean} [expanded=true] Expand the content panel to fill the entire parent element.
10493 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
10495 OO
.ui
.IndexLayout
= function OoUiIndexLayout( config
) {
10496 // Configuration initialization
10497 config
= $.extend( {}, config
, { menuPosition
: 'top' } );
10499 // Parent constructor
10500 OO
.ui
.IndexLayout
.parent
.call( this, config
);
10503 this.currentCardName
= null;
10505 this.ignoreFocus
= false;
10506 this.stackLayout
= new OO
.ui
.StackLayout( {
10507 continuous
: !!config
.continuous
,
10508 expanded
: config
.expanded
10510 this.$content
.append( this.stackLayout
.$element
);
10511 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
10513 this.tabSelectWidget
= new OO
.ui
.TabSelectWidget();
10514 this.tabPanel
= new OO
.ui
.PanelLayout();
10515 this.$menu
.append( this.tabPanel
.$element
);
10517 this.toggleMenu( true );
10520 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
10521 this.tabSelectWidget
.connect( this, { select
: 'onTabSelectWidgetSelect' } );
10522 if ( this.autoFocus
) {
10523 // Event 'focus' does not bubble, but 'focusin' does
10524 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
10528 this.$element
.addClass( 'oo-ui-indexLayout' );
10529 this.stackLayout
.$element
.addClass( 'oo-ui-indexLayout-stackLayout' );
10530 this.tabPanel
.$element
10531 .addClass( 'oo-ui-indexLayout-tabPanel' )
10532 .append( this.tabSelectWidget
.$element
);
10537 OO
.inheritClass( OO
.ui
.IndexLayout
, OO
.ui
.MenuLayout
);
10542 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
10544 * @param {OO.ui.CardLayout} card Current card
10548 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
10551 * @param {OO.ui.CardLayout[]} card Added cards
10552 * @param {number} index Index cards were added at
10556 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
10557 * {@link #removeCards removed} from the index.
10560 * @param {OO.ui.CardLayout[]} cards Removed cards
10566 * Handle stack layout focus.
10569 * @param {jQuery.Event} e Focusin event
10571 OO
.ui
.IndexLayout
.prototype.onStackLayoutFocus = function ( e
) {
10574 // Find the card that an element was focused within
10575 $target
= $( e
.target
).closest( '.oo-ui-cardLayout' );
10576 for ( name
in this.cards
) {
10577 // Check for card match, exclude current card to find only card changes
10578 if ( this.cards
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentCardName
) {
10579 this.setCard( name
);
10586 * Handle stack layout set events.
10589 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
10591 OO
.ui
.IndexLayout
.prototype.onStackLayoutSet = function ( card
) {
10594 card
.scrollElementIntoView( { complete: function () {
10595 if ( layout
.autoFocus
) {
10603 * Focus the first input in the current card.
10605 * If no card is selected, the first selectable card will be selected.
10606 * If the focus is already in an element on the current card, nothing will happen.
10607 * @param {number} [itemIndex] A specific item to focus on
10609 OO
.ui
.IndexLayout
.prototype.focus = function ( itemIndex
) {
10611 items
= this.stackLayout
.getItems();
10613 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
10614 card
= items
[ itemIndex
];
10616 card
= this.stackLayout
.getCurrentItem();
10620 this.selectFirstSelectableCard();
10621 card
= this.stackLayout
.getCurrentItem();
10626 // Only change the focus if is not already in the current page
10627 if ( !OO
.ui
.contains( card
.$element
[ 0 ], this.getElementDocument().activeElement
, true ) ) {
10633 * Find the first focusable input in the index layout and focus
10636 OO
.ui
.IndexLayout
.prototype.focusFirstFocusable = function () {
10637 OO
.ui
.findFocusable( this.stackLayout
.$element
).focus();
10641 * Handle tab widget select events.
10644 * @param {OO.ui.OptionWidget|null} item Selected item
10646 OO
.ui
.IndexLayout
.prototype.onTabSelectWidgetSelect = function ( item
) {
10648 this.setCard( item
.getData() );
10653 * Get the card closest to the specified card.
10655 * @param {OO.ui.CardLayout} card Card to use as a reference point
10656 * @return {OO.ui.CardLayout|null} Card closest to the specified card
10658 OO
.ui
.IndexLayout
.prototype.getClosestCard = function ( card
) {
10659 var next
, prev
, level
,
10660 cards
= this.stackLayout
.getItems(),
10661 index
= cards
.indexOf( card
);
10663 if ( index
!== -1 ) {
10664 next
= cards
[ index
+ 1 ];
10665 prev
= cards
[ index
- 1 ];
10666 // Prefer adjacent cards at the same level
10667 level
= this.tabSelectWidget
.getItemFromData( card
.getName() ).getLevel();
10670 level
=== this.tabSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
10676 level
=== this.tabSelectWidget
.getItemFromData( next
.getName() ).getLevel()
10681 return prev
|| next
|| null;
10685 * Get the tabs widget.
10687 * @return {OO.ui.TabSelectWidget} Tabs widget
10689 OO
.ui
.IndexLayout
.prototype.getTabs = function () {
10690 return this.tabSelectWidget
;
10694 * Get a card by its symbolic name.
10696 * @param {string} name Symbolic name of card
10697 * @return {OO.ui.CardLayout|undefined} Card, if found
10699 OO
.ui
.IndexLayout
.prototype.getCard = function ( name
) {
10700 return this.cards
[ name
];
10704 * Get the current card.
10706 * @return {OO.ui.CardLayout|undefined} Current card, if found
10708 OO
.ui
.IndexLayout
.prototype.getCurrentCard = function () {
10709 var name
= this.getCurrentCardName();
10710 return name
? this.getCard( name
) : undefined;
10714 * Get the symbolic name of the current card.
10716 * @return {string|null} Symbolic name of the current card
10718 OO
.ui
.IndexLayout
.prototype.getCurrentCardName = function () {
10719 return this.currentCardName
;
10723 * Add cards to the index layout
10725 * When cards are added with the same names as existing cards, the existing cards will be
10726 * automatically removed before the new cards are added.
10728 * @param {OO.ui.CardLayout[]} cards Cards to add
10729 * @param {number} index Index of the insertion point
10733 OO
.ui
.IndexLayout
.prototype.addCards = function ( cards
, index
) {
10734 var i
, len
, name
, card
, item
, currentIndex
,
10735 stackLayoutCards
= this.stackLayout
.getItems(),
10739 // Remove cards with same names
10740 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10742 name
= card
.getName();
10744 if ( Object
.prototype.hasOwnProperty
.call( this.cards
, name
) ) {
10745 // Correct the insertion index
10746 currentIndex
= stackLayoutCards
.indexOf( this.cards
[ name
] );
10747 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
10750 remove
.push( this.cards
[ name
] );
10753 if ( remove
.length
) {
10754 this.removeCards( remove
);
10758 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10760 name
= card
.getName();
10761 this.cards
[ card
.getName() ] = card
;
10762 item
= new OO
.ui
.TabOptionWidget( { data
: name
} );
10763 card
.setTabItem( item
);
10764 items
.push( item
);
10767 if ( items
.length
) {
10768 this.tabSelectWidget
.addItems( items
, index
);
10769 this.selectFirstSelectableCard();
10771 this.stackLayout
.addItems( cards
, index
);
10772 this.emit( 'add', cards
, index
);
10778 * Remove the specified cards from the index layout.
10780 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10782 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10786 OO
.ui
.IndexLayout
.prototype.removeCards = function ( cards
) {
10787 var i
, len
, name
, card
,
10790 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10792 name
= card
.getName();
10793 delete this.cards
[ name
];
10794 items
.push( this.tabSelectWidget
.getItemFromData( name
) );
10795 card
.setTabItem( null );
10797 if ( items
.length
) {
10798 this.tabSelectWidget
.removeItems( items
);
10799 this.selectFirstSelectableCard();
10801 this.stackLayout
.removeItems( cards
);
10802 this.emit( 'remove', cards
);
10808 * Clear all cards from the index layout.
10810 * To remove only a subset of cards from the index, use the #removeCards method.
10815 OO
.ui
.IndexLayout
.prototype.clearCards = function () {
10817 cards
= this.stackLayout
.getItems();
10820 this.currentCardName
= null;
10821 this.tabSelectWidget
.clearItems();
10822 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10823 cards
[ i
].setTabItem( null );
10825 this.stackLayout
.clearItems();
10827 this.emit( 'remove', cards
);
10833 * Set the current card by symbolic name.
10836 * @param {string} name Symbolic name of card
10838 OO
.ui
.IndexLayout
.prototype.setCard = function ( name
) {
10841 card
= this.cards
[ name
],
10842 previousCard
= this.currentCardName
&& this.cards
[ this.currentCardName
];
10844 if ( name
!== this.currentCardName
) {
10845 selectedItem
= this.tabSelectWidget
.getSelectedItem();
10846 if ( selectedItem
&& selectedItem
.getData() !== name
) {
10847 this.tabSelectWidget
.selectItemByData( name
);
10850 if ( previousCard
) {
10851 previousCard
.setActive( false );
10852 // Blur anything focused if the next card doesn't have anything focusable.
10853 // This is not needed if the next card has something focusable (because once it is focused
10854 // this blur happens automatically). If the layout is non-continuous, this check is
10855 // meaningless because the next card is not visible yet and thus can't hold focus.
10858 this.stackLayout
.continuous
&&
10859 OO
.ui
.findFocusable( card
.$element
).length
!== 0
10861 $focused
= previousCard
.$element
.find( ':focus' );
10862 if ( $focused
.length
) {
10863 $focused
[ 0 ].blur();
10867 this.currentCardName
= name
;
10868 card
.setActive( true );
10869 this.stackLayout
.setItem( card
);
10870 if ( !this.stackLayout
.continuous
&& previousCard
) {
10871 // This should not be necessary, since any inputs on the previous card should have been
10872 // blurred when it was hidden, but browsers are not very consistent about this.
10873 $focused
= previousCard
.$element
.find( ':focus' );
10874 if ( $focused
.length
) {
10875 $focused
[ 0 ].blur();
10878 this.emit( 'set', card
);
10884 * Select the first selectable card.
10888 OO
.ui
.IndexLayout
.prototype.selectFirstSelectableCard = function () {
10889 if ( !this.tabSelectWidget
.getSelectedItem() ) {
10890 this.tabSelectWidget
.selectItem( this.tabSelectWidget
.getFirstSelectableItem() );
10897 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10898 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10901 * // Example of a panel layout
10902 * var panel = new OO.ui.PanelLayout( {
10906 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10908 * $( 'body' ).append( panel.$element );
10911 * @extends OO.ui.Layout
10914 * @param {Object} [config] Configuration options
10915 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10916 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10917 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10918 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10920 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
10921 // Configuration initialization
10922 config
= $.extend( {
10929 // Parent constructor
10930 OO
.ui
.PanelLayout
.parent
.call( this, config
);
10933 this.$element
.addClass( 'oo-ui-panelLayout' );
10934 if ( config
.scrollable
) {
10935 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
10937 if ( config
.padded
) {
10938 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
10940 if ( config
.expanded
) {
10941 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
10943 if ( config
.framed
) {
10944 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
10950 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
10955 * Focus the panel layout
10957 * The default implementation just focuses the first focusable element in the panel
10959 OO
.ui
.PanelLayout
.prototype.focus = function () {
10960 OO
.ui
.findFocusable( this.$element
).focus();
10964 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10965 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10966 * rather extended to include the required content and functionality.
10968 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10969 * item is customized (with a label) using the #setupTabItem method. See
10970 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10973 * @extends OO.ui.PanelLayout
10976 * @param {string} name Unique symbolic name of card
10977 * @param {Object} [config] Configuration options
10978 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] Label for card's tab
10980 OO
.ui
.CardLayout
= function OoUiCardLayout( name
, config
) {
10981 // Allow passing positional parameters inside the config object
10982 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
10984 name
= config
.name
;
10987 // Configuration initialization
10988 config
= $.extend( { scrollable
: true }, config
);
10990 // Parent constructor
10991 OO
.ui
.CardLayout
.parent
.call( this, config
);
10995 this.label
= config
.label
;
10996 this.tabItem
= null;
10997 this.active
= false;
11000 this.$element
.addClass( 'oo-ui-cardLayout' );
11005 OO
.inheritClass( OO
.ui
.CardLayout
, OO
.ui
.PanelLayout
);
11010 * An 'active' event is emitted when the card becomes active. Cards become active when they are
11011 * shown in a index layout that is configured to display only one card at a time.
11014 * @param {boolean} active Card is active
11020 * Get the symbolic name of the card.
11022 * @return {string} Symbolic name of card
11024 OO
.ui
.CardLayout
.prototype.getName = function () {
11029 * Check if card is active.
11031 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
11032 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
11034 * @return {boolean} Card is active
11036 OO
.ui
.CardLayout
.prototype.isActive = function () {
11037 return this.active
;
11043 * The tab item allows users to access the card from the index's tab
11044 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
11046 * @return {OO.ui.TabOptionWidget|null} Tab option widget
11048 OO
.ui
.CardLayout
.prototype.getTabItem = function () {
11049 return this.tabItem
;
11053 * Set or unset the tab item.
11055 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
11056 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
11057 * level), use #setupTabItem instead of this method.
11059 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
11062 OO
.ui
.CardLayout
.prototype.setTabItem = function ( tabItem
) {
11063 this.tabItem
= tabItem
|| null;
11065 this.setupTabItem();
11071 * Set up the tab item.
11073 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
11074 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
11075 * the #setTabItem method instead.
11077 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
11080 OO
.ui
.CardLayout
.prototype.setupTabItem = function () {
11081 if ( this.label
) {
11082 this.tabItem
.setLabel( this.label
);
11088 * Set the card to its 'active' state.
11090 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
11091 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
11092 * context, setting the active state on a card does nothing.
11094 * @param {boolean} value Card is active
11097 OO
.ui
.CardLayout
.prototype.setActive = function ( active
) {
11100 if ( active
!== this.active
) {
11101 this.active
= active
;
11102 this.$element
.toggleClass( 'oo-ui-cardLayout-active', this.active
);
11103 this.emit( 'active', this.active
);
11108 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
11109 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
11110 * rather extended to include the required content and functionality.
11112 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
11113 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
11114 * {@link OO.ui.BookletLayout BookletLayout} for an example.
11117 * @extends OO.ui.PanelLayout
11120 * @param {string} name Unique symbolic name of page
11121 * @param {Object} [config] Configuration options
11123 OO
.ui
.PageLayout
= function OoUiPageLayout( name
, config
) {
11124 // Allow passing positional parameters inside the config object
11125 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
11127 name
= config
.name
;
11130 // Configuration initialization
11131 config
= $.extend( { scrollable
: true }, config
);
11133 // Parent constructor
11134 OO
.ui
.PageLayout
.parent
.call( this, config
);
11138 this.outlineItem
= null;
11139 this.active
= false;
11142 this.$element
.addClass( 'oo-ui-pageLayout' );
11147 OO
.inheritClass( OO
.ui
.PageLayout
, OO
.ui
.PanelLayout
);
11152 * An 'active' event is emitted when the page becomes active. Pages become active when they are
11153 * shown in a booklet layout that is configured to display only one page at a time.
11156 * @param {boolean} active Page is active
11162 * Get the symbolic name of the page.
11164 * @return {string} Symbolic name of page
11166 OO
.ui
.PageLayout
.prototype.getName = function () {
11171 * Check if page is active.
11173 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
11174 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
11176 * @return {boolean} Page is active
11178 OO
.ui
.PageLayout
.prototype.isActive = function () {
11179 return this.active
;
11183 * Get outline item.
11185 * The outline item allows users to access the page from the booklet's outline
11186 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
11188 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
11190 OO
.ui
.PageLayout
.prototype.getOutlineItem = function () {
11191 return this.outlineItem
;
11195 * Set or unset the outline item.
11197 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
11198 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
11199 * level), use #setupOutlineItem instead of this method.
11201 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
11204 OO
.ui
.PageLayout
.prototype.setOutlineItem = function ( outlineItem
) {
11205 this.outlineItem
= outlineItem
|| null;
11206 if ( outlineItem
) {
11207 this.setupOutlineItem();
11213 * Set up the outline item.
11215 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
11216 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
11217 * the #setOutlineItem method instead.
11219 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
11222 OO
.ui
.PageLayout
.prototype.setupOutlineItem = function () {
11227 * Set the page to its 'active' state.
11229 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
11230 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
11231 * context, setting the active state on a page does nothing.
11233 * @param {boolean} value Page is active
11236 OO
.ui
.PageLayout
.prototype.setActive = function ( active
) {
11239 if ( active
!== this.active
) {
11240 this.active
= active
;
11241 this.$element
.toggleClass( 'oo-ui-pageLayout-active', active
);
11242 this.emit( 'active', this.active
);
11247 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
11248 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
11249 * by setting the #continuous option to 'true'.
11252 * // A stack layout with two panels, configured to be displayed continously
11253 * var myStack = new OO.ui.StackLayout( {
11255 * new OO.ui.PanelLayout( {
11256 * $content: $( '<p>Panel One</p>' ),
11260 * new OO.ui.PanelLayout( {
11261 * $content: $( '<p>Panel Two</p>' ),
11268 * $( 'body' ).append( myStack.$element );
11271 * @extends OO.ui.PanelLayout
11272 * @mixins OO.ui.mixin.GroupElement
11275 * @param {Object} [config] Configuration options
11276 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
11277 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
11279 OO
.ui
.StackLayout
= function OoUiStackLayout( config
) {
11280 // Configuration initialization
11281 config
= $.extend( { scrollable
: true }, config
);
11283 // Parent constructor
11284 OO
.ui
.StackLayout
.parent
.call( this, config
);
11286 // Mixin constructors
11287 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11290 this.currentItem
= null;
11291 this.continuous
= !!config
.continuous
;
11294 this.$element
.addClass( 'oo-ui-stackLayout' );
11295 if ( this.continuous
) {
11296 this.$element
.addClass( 'oo-ui-stackLayout-continuous' );
11297 this.$element
.on( 'scroll', OO
.ui
.debounce( this.onScroll
.bind( this ), 250 ) );
11299 if ( Array
.isArray( config
.items
) ) {
11300 this.addItems( config
.items
);
11306 OO
.inheritClass( OO
.ui
.StackLayout
, OO
.ui
.PanelLayout
);
11307 OO
.mixinClass( OO
.ui
.StackLayout
, OO
.ui
.mixin
.GroupElement
);
11312 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
11313 * {@link #clearItems cleared} or {@link #setItem displayed}.
11316 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
11320 * When used in continuous mode, this event is emitted when the user scrolls down
11321 * far enough such that currentItem is no longer visible.
11323 * @event visibleItemChange
11324 * @param {OO.ui.PanelLayout} panel The next visible item in the layout
11330 * Handle scroll events from the layout element
11332 * @param {jQuery.Event} e
11333 * @fires visibleItemChange
11335 OO
.ui
.StackLayout
.prototype.onScroll = function () {
11337 len
= this.items
.length
,
11338 currentIndex
= this.items
.indexOf( this.currentItem
),
11339 newIndex
= currentIndex
,
11340 containerRect
= this.$element
[ 0 ].getBoundingClientRect();
11342 if ( !containerRect
|| ( !containerRect
.top
&& !containerRect
.bottom
) ) {
11343 // Can't get bounding rect, possibly not attached.
11347 function getRect( item
) {
11348 return item
.$element
[ 0 ].getBoundingClientRect();
11351 function isVisible( item
) {
11352 var rect
= getRect( item
);
11353 return rect
.bottom
> containerRect
.top
&& rect
.top
< containerRect
.bottom
;
11356 currentRect
= getRect( this.currentItem
);
11358 if ( currentRect
.bottom
< containerRect
.top
) {
11359 // Scrolled down past current item
11360 while ( ++newIndex
< len
) {
11361 if ( isVisible( this.items
[ newIndex
] ) ) {
11365 } else if ( currentRect
.top
> containerRect
.bottom
) {
11366 // Scrolled up past current item
11367 while ( --newIndex
>= 0 ) {
11368 if ( isVisible( this.items
[ newIndex
] ) ) {
11374 if ( newIndex
!== currentIndex
) {
11375 this.emit( 'visibleItemChange', this.items
[ newIndex
] );
11380 * Get the current panel.
11382 * @return {OO.ui.Layout|null}
11384 OO
.ui
.StackLayout
.prototype.getCurrentItem = function () {
11385 return this.currentItem
;
11389 * Unset the current item.
11392 * @param {OO.ui.StackLayout} layout
11395 OO
.ui
.StackLayout
.prototype.unsetCurrentItem = function () {
11396 var prevItem
= this.currentItem
;
11397 if ( prevItem
=== null ) {
11401 this.currentItem
= null;
11402 this.emit( 'set', null );
11406 * Add panel layouts to the stack layout.
11408 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
11409 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
11412 * @param {OO.ui.Layout[]} items Panels to add
11413 * @param {number} [index] Index of the insertion point
11416 OO
.ui
.StackLayout
.prototype.addItems = function ( items
, index
) {
11417 // Update the visibility
11418 this.updateHiddenState( items
, this.currentItem
);
11421 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
, index
);
11423 if ( !this.currentItem
&& items
.length
) {
11424 this.setItem( items
[ 0 ] );
11431 * Remove the specified panels from the stack layout.
11433 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
11434 * you may wish to use the #clearItems method instead.
11436 * @param {OO.ui.Layout[]} items Panels to remove
11440 OO
.ui
.StackLayout
.prototype.removeItems = function ( items
) {
11442 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
11444 if ( items
.indexOf( this.currentItem
) !== -1 ) {
11445 if ( this.items
.length
) {
11446 this.setItem( this.items
[ 0 ] );
11448 this.unsetCurrentItem();
11456 * Clear all panels from the stack layout.
11458 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
11459 * a subset of panels, use the #removeItems method.
11464 OO
.ui
.StackLayout
.prototype.clearItems = function () {
11465 this.unsetCurrentItem();
11466 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
11472 * Show the specified panel.
11474 * If another panel is currently displayed, it will be hidden.
11476 * @param {OO.ui.Layout} item Panel to show
11480 OO
.ui
.StackLayout
.prototype.setItem = function ( item
) {
11481 if ( item
!== this.currentItem
) {
11482 this.updateHiddenState( this.items
, item
);
11484 if ( this.items
.indexOf( item
) !== -1 ) {
11485 this.currentItem
= item
;
11486 this.emit( 'set', item
);
11488 this.unsetCurrentItem();
11496 * Update the visibility of all items in case of non-continuous view.
11498 * Ensure all items are hidden except for the selected one.
11499 * This method does nothing when the stack is continuous.
11502 * @param {OO.ui.Layout[]} items Item list iterate over
11503 * @param {OO.ui.Layout} [selectedItem] Selected item to show
11505 OO
.ui
.StackLayout
.prototype.updateHiddenState = function ( items
, selectedItem
) {
11508 if ( !this.continuous
) {
11509 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
11510 if ( !selectedItem
|| selectedItem
!== items
[ i
] ) {
11511 items
[ i
].$element
.addClass( 'oo-ui-element-hidden' );
11514 if ( selectedItem
) {
11515 selectedItem
.$element
.removeClass( 'oo-ui-element-hidden' );
11521 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11522 * items), with small margins between them. Convenient when you need to put a number of block-level
11523 * widgets on a single line next to each other.
11525 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11528 * // HorizontalLayout with a text input and a label
11529 * var layout = new OO.ui.HorizontalLayout( {
11531 * new OO.ui.LabelWidget( { label: 'Label' } ),
11532 * new OO.ui.TextInputWidget( { value: 'Text' } )
11535 * $( 'body' ).append( layout.$element );
11538 * @extends OO.ui.Layout
11539 * @mixins OO.ui.mixin.GroupElement
11542 * @param {Object} [config] Configuration options
11543 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11545 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
11546 // Configuration initialization
11547 config
= config
|| {};
11549 // Parent constructor
11550 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
11552 // Mixin constructors
11553 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11556 this.$element
.addClass( 'oo-ui-horizontalLayout' );
11557 if ( Array
.isArray( config
.items
) ) {
11558 this.addItems( config
.items
);
11564 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
11565 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);
11568 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11569 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11570 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
11571 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
11574 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
11578 * // Example of a BarToolGroup with two tools
11579 * var toolFactory = new OO.ui.ToolFactory();
11580 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11581 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11583 * // We will be placing status text in this element when tools are used
11584 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
11586 * // Define the tools that we're going to place in our toolbar
11588 * // Create a class inheriting from OO.ui.Tool
11589 * function SearchTool() {
11590 * SearchTool.parent.apply( this, arguments );
11592 * OO.inheritClass( SearchTool, OO.ui.Tool );
11593 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
11594 * // of 'icon' and 'title' (displayed icon and text).
11595 * SearchTool.static.name = 'search';
11596 * SearchTool.static.icon = 'search';
11597 * SearchTool.static.title = 'Search...';
11598 * // Defines the action that will happen when this tool is selected (clicked).
11599 * SearchTool.prototype.onSelect = function () {
11600 * $area.text( 'Search tool clicked!' );
11601 * // Never display this tool as "active" (selected).
11602 * this.setActive( false );
11604 * SearchTool.prototype.onUpdateState = function () {};
11605 * // Make this tool available in our toolFactory and thus our toolbar
11606 * toolFactory.register( SearchTool );
11608 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
11609 * // little popup window (a PopupWidget).
11610 * function HelpTool( toolGroup, config ) {
11611 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11616 * this.popup.$body.append( '<p>I am helpful!</p>' );
11618 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11619 * HelpTool.static.name = 'help';
11620 * HelpTool.static.icon = 'help';
11621 * HelpTool.static.title = 'Help';
11622 * toolFactory.register( HelpTool );
11624 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11625 * // used once (but not all defined tools must be used).
11628 * // 'bar' tool groups display tools by icon only
11630 * include: [ 'search', 'help' ]
11634 * // Create some UI around the toolbar and place it in the document
11635 * var frame = new OO.ui.PanelLayout( {
11639 * var contentFrame = new OO.ui.PanelLayout( {
11643 * frame.$element.append(
11644 * toolbar.$element,
11645 * contentFrame.$element.append( $area )
11647 * $( 'body' ).append( frame.$element );
11649 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11651 * toolbar.initialize();
11653 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
11654 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11656 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11659 * @extends OO.ui.ToolGroup
11662 * @param {OO.ui.Toolbar} toolbar
11663 * @param {Object} [config] Configuration options
11665 OO
.ui
.BarToolGroup
= function OoUiBarToolGroup( toolbar
, config
) {
11666 // Allow passing positional parameters inside the config object
11667 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11669 toolbar
= config
.toolbar
;
11672 // Parent constructor
11673 OO
.ui
.BarToolGroup
.parent
.call( this, toolbar
, config
);
11676 this.$element
.addClass( 'oo-ui-barToolGroup' );
11681 OO
.inheritClass( OO
.ui
.BarToolGroup
, OO
.ui
.ToolGroup
);
11683 /* Static Properties */
11685 OO
.ui
.BarToolGroup
.static.titleTooltips
= true;
11687 OO
.ui
.BarToolGroup
.static.accelTooltips
= true;
11689 OO
.ui
.BarToolGroup
.static.name
= 'bar';
11692 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
11693 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
11694 * optional icon and label. This class can be used for other base classes that also use this functionality.
11698 * @extends OO.ui.ToolGroup
11699 * @mixins OO.ui.mixin.IconElement
11700 * @mixins OO.ui.mixin.IndicatorElement
11701 * @mixins OO.ui.mixin.LabelElement
11702 * @mixins OO.ui.mixin.TitledElement
11703 * @mixins OO.ui.mixin.ClippableElement
11704 * @mixins OO.ui.mixin.TabIndexedElement
11707 * @param {OO.ui.Toolbar} toolbar
11708 * @param {Object} [config] Configuration options
11709 * @cfg {string} [header] Text to display at the top of the popup
11711 OO
.ui
.PopupToolGroup
= function OoUiPopupToolGroup( toolbar
, config
) {
11712 // Allow passing positional parameters inside the config object
11713 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11715 toolbar
= config
.toolbar
;
11718 // Configuration initialization
11719 config
= config
|| {};
11721 // Parent constructor
11722 OO
.ui
.PopupToolGroup
.parent
.call( this, toolbar
, config
);
11725 this.active
= false;
11726 this.dragging
= false;
11727 this.onBlurHandler
= this.onBlur
.bind( this );
11728 this.$handle
= $( '<span>' );
11730 // Mixin constructors
11731 OO
.ui
.mixin
.IconElement
.call( this, config
);
11732 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
11733 OO
.ui
.mixin
.LabelElement
.call( this, config
);
11734 OO
.ui
.mixin
.TitledElement
.call( this, config
);
11735 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
11736 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
11740 keydown
: this.onHandleMouseKeyDown
.bind( this ),
11741 keyup
: this.onHandleMouseKeyUp
.bind( this ),
11742 mousedown
: this.onHandleMouseKeyDown
.bind( this ),
11743 mouseup
: this.onHandleMouseKeyUp
.bind( this )
11748 .addClass( 'oo-ui-popupToolGroup-handle' )
11749 .append( this.$icon
, this.$label
, this.$indicator
);
11750 // If the pop-up should have a header, add it to the top of the toolGroup.
11751 // Note: If this feature is useful for other widgets, we could abstract it into an
11752 // OO.ui.HeaderedElement mixin constructor.
11753 if ( config
.header
!== undefined ) {
11755 .prepend( $( '<span>' )
11756 .addClass( 'oo-ui-popupToolGroup-header' )
11757 .text( config
.header
)
11761 .addClass( 'oo-ui-popupToolGroup' )
11762 .prepend( this.$handle
);
11767 OO
.inheritClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ToolGroup
);
11768 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.IconElement
);
11769 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.IndicatorElement
);
11770 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.LabelElement
);
11771 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.TitledElement
);
11772 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.ClippableElement
);
11773 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.TabIndexedElement
);
11780 OO
.ui
.PopupToolGroup
.prototype.setDisabled = function () {
11782 OO
.ui
.PopupToolGroup
.parent
.prototype.setDisabled
.apply( this, arguments
);
11784 if ( this.isDisabled() && this.isElementAttached() ) {
11785 this.setActive( false );
11790 * Handle focus being lost.
11792 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11795 * @param {jQuery.Event} e Mouse up or key up event
11797 OO
.ui
.PopupToolGroup
.prototype.onBlur = function ( e
) {
11798 // Only deactivate when clicking outside the dropdown element
11799 if ( $( e
.target
).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element
[ 0 ] ) {
11800 this.setActive( false );
11807 OO
.ui
.PopupToolGroup
.prototype.onMouseKeyUp = function ( e
) {
11808 // Only close toolgroup when a tool was actually selected
11810 !this.isDisabled() && this.pressed
&& this.pressed
=== this.getTargetTool( e
) &&
11811 ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
|| e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11813 this.setActive( false );
11815 return OO
.ui
.PopupToolGroup
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11819 * Handle mouse up and key up events.
11822 * @param {jQuery.Event} e Mouse up or key up event
11824 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyUp = function ( e
) {
11826 !this.isDisabled() &&
11827 ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
|| e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11834 * Handle mouse down and key down events.
11837 * @param {jQuery.Event} e Mouse down or key down event
11839 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyDown = function ( e
) {
11841 !this.isDisabled() &&
11842 ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
|| e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11844 this.setActive( !this.active
);
11850 * Switch into 'active' mode.
11852 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11855 OO
.ui
.PopupToolGroup
.prototype.setActive = function ( value
) {
11856 var containerWidth
, containerLeft
;
11858 if ( this.active
!== value
) {
11859 this.active
= value
;
11861 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler
, true );
11862 this.getElementDocument().addEventListener( 'keyup', this.onBlurHandler
, true );
11864 this.$clippable
.css( 'left', '' );
11865 // Try anchoring the popup to the left first
11866 this.$element
.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11867 this.toggleClipping( true );
11868 if ( this.isClippedHorizontally() ) {
11869 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11870 this.toggleClipping( false );
11872 .removeClass( 'oo-ui-popupToolGroup-left' )
11873 .addClass( 'oo-ui-popupToolGroup-right' );
11874 this.toggleClipping( true );
11876 if ( this.isClippedHorizontally() ) {
11877 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11878 containerWidth
= this.$clippableScrollableContainer
.width();
11879 containerLeft
= this.$clippableScrollableContainer
.offset().left
;
11881 this.toggleClipping( false );
11882 this.$element
.removeClass( 'oo-ui-popupToolGroup-right' );
11884 this.$clippable
.css( {
11885 left
: -( this.$element
.offset().left
- containerLeft
),
11886 width
: containerWidth
11890 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler
, true );
11891 this.getElementDocument().removeEventListener( 'keyup', this.onBlurHandler
, true );
11892 this.$element
.removeClass(
11893 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11895 this.toggleClipping( false );
11901 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11902 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11903 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11904 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11905 * with a label, icon, indicator, header, and title.
11907 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11908 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11909 * users to collapse the list again.
11911 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11912 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11913 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11916 * // Example of a ListToolGroup
11917 * var toolFactory = new OO.ui.ToolFactory();
11918 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11919 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11921 * // Configure and register two tools
11922 * function SettingsTool() {
11923 * SettingsTool.parent.apply( this, arguments );
11925 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11926 * SettingsTool.static.name = 'settings';
11927 * SettingsTool.static.icon = 'settings';
11928 * SettingsTool.static.title = 'Change settings';
11929 * SettingsTool.prototype.onSelect = function () {
11930 * this.setActive( false );
11932 * SettingsTool.prototype.onUpdateState = function () {};
11933 * toolFactory.register( SettingsTool );
11934 * // Register two more tools, nothing interesting here
11935 * function StuffTool() {
11936 * StuffTool.parent.apply( this, arguments );
11938 * OO.inheritClass( StuffTool, OO.ui.Tool );
11939 * StuffTool.static.name = 'stuff';
11940 * StuffTool.static.icon = 'search';
11941 * StuffTool.static.title = 'Change the world';
11942 * StuffTool.prototype.onSelect = function () {
11943 * this.setActive( false );
11945 * StuffTool.prototype.onUpdateState = function () {};
11946 * toolFactory.register( StuffTool );
11949 * // Configurations for list toolgroup.
11951 * label: 'ListToolGroup',
11952 * indicator: 'down',
11953 * icon: 'ellipsis',
11954 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11955 * header: 'This is the header',
11956 * include: [ 'settings', 'stuff' ],
11957 * allowCollapse: ['stuff']
11961 * // Create some UI around the toolbar and place it in the document
11962 * var frame = new OO.ui.PanelLayout( {
11966 * frame.$element.append(
11969 * $( 'body' ).append( frame.$element );
11970 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11971 * toolbar.initialize();
11973 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11975 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11978 * @extends OO.ui.PopupToolGroup
11981 * @param {OO.ui.Toolbar} toolbar
11982 * @param {Object} [config] Configuration options
11983 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11984 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11985 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11986 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11987 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11988 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11989 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11990 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11991 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11992 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
11994 OO
.ui
.ListToolGroup
= function OoUiListToolGroup( toolbar
, config
) {
11995 // Allow passing positional parameters inside the config object
11996 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11998 toolbar
= config
.toolbar
;
12001 // Configuration initialization
12002 config
= config
|| {};
12004 // Properties (must be set before parent constructor, which calls #populate)
12005 this.allowCollapse
= config
.allowCollapse
;
12006 this.forceExpand
= config
.forceExpand
;
12007 this.expanded
= config
.expanded
!== undefined ? config
.expanded
: false;
12008 this.collapsibleTools
= [];
12010 // Parent constructor
12011 OO
.ui
.ListToolGroup
.parent
.call( this, toolbar
, config
);
12014 this.$element
.addClass( 'oo-ui-listToolGroup' );
12019 OO
.inheritClass( OO
.ui
.ListToolGroup
, OO
.ui
.PopupToolGroup
);
12021 /* Static Properties */
12023 OO
.ui
.ListToolGroup
.static.name
= 'list';
12030 OO
.ui
.ListToolGroup
.prototype.populate = function () {
12031 var i
, len
, allowCollapse
= [];
12033 OO
.ui
.ListToolGroup
.parent
.prototype.populate
.call( this );
12035 // Update the list of collapsible tools
12036 if ( this.allowCollapse
!== undefined ) {
12037 allowCollapse
= this.allowCollapse
;
12038 } else if ( this.forceExpand
!== undefined ) {
12039 allowCollapse
= OO
.simpleArrayDifference( Object
.keys( this.tools
), this.forceExpand
);
12042 this.collapsibleTools
= [];
12043 for ( i
= 0, len
= allowCollapse
.length
; i
< len
; i
++ ) {
12044 if ( this.tools
[ allowCollapse
[ i
] ] !== undefined ) {
12045 this.collapsibleTools
.push( this.tools
[ allowCollapse
[ i
] ] );
12049 // Keep at the end, even when tools are added
12050 this.$group
.append( this.getExpandCollapseTool().$element
);
12052 this.getExpandCollapseTool().toggle( this.collapsibleTools
.length
!== 0 );
12053 this.updateCollapsibleState();
12056 OO
.ui
.ListToolGroup
.prototype.getExpandCollapseTool = function () {
12057 var ExpandCollapseTool
;
12058 if ( this.expandCollapseTool
=== undefined ) {
12059 ExpandCollapseTool = function () {
12060 ExpandCollapseTool
.parent
.apply( this, arguments
);
12063 OO
.inheritClass( ExpandCollapseTool
, OO
.ui
.Tool
);
12065 ExpandCollapseTool
.prototype.onSelect = function () {
12066 this.toolGroup
.expanded
= !this.toolGroup
.expanded
;
12067 this.toolGroup
.updateCollapsibleState();
12068 this.setActive( false );
12070 ExpandCollapseTool
.prototype.onUpdateState = function () {
12071 // Do nothing. Tool interface requires an implementation of this function.
12074 ExpandCollapseTool
.static.name
= 'more-fewer';
12076 this.expandCollapseTool
= new ExpandCollapseTool( this );
12078 return this.expandCollapseTool
;
12084 OO
.ui
.ListToolGroup
.prototype.onMouseKeyUp = function ( e
) {
12085 // Do not close the popup when the user wants to show more/fewer tools
12087 $( e
.target
).closest( '.oo-ui-tool-name-more-fewer' ).length
&&
12088 ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
|| e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
12090 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
12091 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
12092 return OO
.ui
.ListToolGroup
.parent
.parent
.prototype.onMouseKeyUp
.call( this, e
);
12094 return OO
.ui
.ListToolGroup
.parent
.prototype.onMouseKeyUp
.call( this, e
);
12098 OO
.ui
.ListToolGroup
.prototype.updateCollapsibleState = function () {
12101 this.getExpandCollapseTool()
12102 .setIcon( this.expanded
? 'collapse' : 'expand' )
12103 .setTitle( OO
.ui
.msg( this.expanded
? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
12105 for ( i
= 0, len
= this.collapsibleTools
.length
; i
< len
; i
++ ) {
12106 this.collapsibleTools
[ i
].toggle( this.expanded
);
12111 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
12112 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
12113 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
12114 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
12115 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
12116 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
12118 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
12122 * // Example of a MenuToolGroup
12123 * var toolFactory = new OO.ui.ToolFactory();
12124 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
12125 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
12127 * // We will be placing status text in this element when tools are used
12128 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
12130 * // Define the tools that we're going to place in our toolbar
12132 * function SettingsTool() {
12133 * SettingsTool.parent.apply( this, arguments );
12134 * this.reallyActive = false;
12136 * OO.inheritClass( SettingsTool, OO.ui.Tool );
12137 * SettingsTool.static.name = 'settings';
12138 * SettingsTool.static.icon = 'settings';
12139 * SettingsTool.static.title = 'Change settings';
12140 * SettingsTool.prototype.onSelect = function () {
12141 * $area.text( 'Settings tool clicked!' );
12142 * // Toggle the active state on each click
12143 * this.reallyActive = !this.reallyActive;
12144 * this.setActive( this.reallyActive );
12145 * // To update the menu label
12146 * this.toolbar.emit( 'updateState' );
12148 * SettingsTool.prototype.onUpdateState = function () {};
12149 * toolFactory.register( SettingsTool );
12151 * function StuffTool() {
12152 * StuffTool.parent.apply( this, arguments );
12153 * this.reallyActive = false;
12155 * OO.inheritClass( StuffTool, OO.ui.Tool );
12156 * StuffTool.static.name = 'stuff';
12157 * StuffTool.static.icon = 'ellipsis';
12158 * StuffTool.static.title = 'More stuff';
12159 * StuffTool.prototype.onSelect = function () {
12160 * $area.text( 'More stuff tool clicked!' );
12161 * // Toggle the active state on each click
12162 * this.reallyActive = !this.reallyActive;
12163 * this.setActive( this.reallyActive );
12164 * // To update the menu label
12165 * this.toolbar.emit( 'updateState' );
12167 * StuffTool.prototype.onUpdateState = function () {};
12168 * toolFactory.register( StuffTool );
12170 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
12171 * // used once (but not all defined tools must be used).
12175 * header: 'This is the (optional) header',
12176 * title: 'This is the (optional) title',
12177 * indicator: 'down',
12178 * include: [ 'settings', 'stuff' ]
12182 * // Create some UI around the toolbar and place it in the document
12183 * var frame = new OO.ui.PanelLayout( {
12187 * var contentFrame = new OO.ui.PanelLayout( {
12191 * frame.$element.append(
12192 * toolbar.$element,
12193 * contentFrame.$element.append( $area )
12195 * $( 'body' ).append( frame.$element );
12197 * // Here is where the toolbar is actually built. This must be done after inserting it into the
12199 * toolbar.initialize();
12200 * toolbar.emit( 'updateState' );
12202 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
12203 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
12205 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
12208 * @extends OO.ui.PopupToolGroup
12211 * @param {OO.ui.Toolbar} toolbar
12212 * @param {Object} [config] Configuration options
12214 OO
.ui
.MenuToolGroup
= function OoUiMenuToolGroup( toolbar
, config
) {
12215 // Allow passing positional parameters inside the config object
12216 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
12218 toolbar
= config
.toolbar
;
12221 // Configuration initialization
12222 config
= config
|| {};
12224 // Parent constructor
12225 OO
.ui
.MenuToolGroup
.parent
.call( this, toolbar
, config
);
12228 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
12231 this.$element
.addClass( 'oo-ui-menuToolGroup' );
12236 OO
.inheritClass( OO
.ui
.MenuToolGroup
, OO
.ui
.PopupToolGroup
);
12238 /* Static Properties */
12240 OO
.ui
.MenuToolGroup
.static.name
= 'menu';
12245 * Handle the toolbar state being updated.
12247 * When the state changes, the title of each active item in the menu will be joined together and
12248 * used as a label for the group. The label will be empty if none of the items are active.
12252 OO
.ui
.MenuToolGroup
.prototype.onUpdateState = function () {
12256 for ( name
in this.tools
) {
12257 if ( this.tools
[ name
].isActive() ) {
12258 labelTexts
.push( this.tools
[ name
].getTitle() );
12262 this.setLabel( labelTexts
.join( ', ' ) || ' ' );
12266 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
12267 * 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
12268 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
12270 * // Example of a popup tool. When selected, a popup tool displays
12271 * // a popup window.
12272 * function HelpTool( toolGroup, config ) {
12273 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
12278 * this.popup.$body.append( '<p>I am helpful!</p>' );
12280 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
12281 * HelpTool.static.name = 'help';
12282 * HelpTool.static.icon = 'help';
12283 * HelpTool.static.title = 'Help';
12284 * toolFactory.register( HelpTool );
12286 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
12287 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
12289 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
12293 * @extends OO.ui.Tool
12294 * @mixins OO.ui.mixin.PopupElement
12297 * @param {OO.ui.ToolGroup} toolGroup
12298 * @param {Object} [config] Configuration options
12300 OO
.ui
.PopupTool
= function OoUiPopupTool( toolGroup
, config
) {
12301 // Allow passing positional parameters inside the config object
12302 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
12303 config
= toolGroup
;
12304 toolGroup
= config
.toolGroup
;
12307 // Parent constructor
12308 OO
.ui
.PopupTool
.parent
.call( this, toolGroup
, config
);
12310 // Mixin constructors
12311 OO
.ui
.mixin
.PopupElement
.call( this, config
);
12315 .addClass( 'oo-ui-popupTool' )
12316 .append( this.popup
.$element
);
12321 OO
.inheritClass( OO
.ui
.PopupTool
, OO
.ui
.Tool
);
12322 OO
.mixinClass( OO
.ui
.PopupTool
, OO
.ui
.mixin
.PopupElement
);
12327 * Handle the tool being selected.
12331 OO
.ui
.PopupTool
.prototype.onSelect = function () {
12332 if ( !this.isDisabled() ) {
12333 this.popup
.toggle();
12335 this.setActive( false );
12340 * Handle the toolbar state being updated.
12344 OO
.ui
.PopupTool
.prototype.onUpdateState = function () {
12345 this.setActive( false );
12349 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
12350 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
12351 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
12352 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
12353 * when the ToolGroupTool is selected.
12355 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
12357 * function SettingsTool() {
12358 * SettingsTool.parent.apply( this, arguments );
12360 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
12361 * SettingsTool.static.name = 'settings';
12362 * SettingsTool.static.title = 'Change settings';
12363 * SettingsTool.static.groupConfig = {
12364 * icon: 'settings',
12365 * label: 'ToolGroupTool',
12366 * include: [ 'setting1', 'setting2' ]
12368 * toolFactory.register( SettingsTool );
12370 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
12372 * Please note that this implementation is subject to change per [T74159] [2].
12374 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
12375 * [2]: https://phabricator.wikimedia.org/T74159
12379 * @extends OO.ui.Tool
12382 * @param {OO.ui.ToolGroup} toolGroup
12383 * @param {Object} [config] Configuration options
12385 OO
.ui
.ToolGroupTool
= function OoUiToolGroupTool( toolGroup
, config
) {
12386 // Allow passing positional parameters inside the config object
12387 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
12388 config
= toolGroup
;
12389 toolGroup
= config
.toolGroup
;
12392 // Parent constructor
12393 OO
.ui
.ToolGroupTool
.parent
.call( this, toolGroup
, config
);
12396 this.innerToolGroup
= this.createGroup( this.constructor.static.groupConfig
);
12399 this.innerToolGroup
.connect( this, { disable
: 'onToolGroupDisable' } );
12402 this.$link
.remove();
12404 .addClass( 'oo-ui-toolGroupTool' )
12405 .append( this.innerToolGroup
.$element
);
12410 OO
.inheritClass( OO
.ui
.ToolGroupTool
, OO
.ui
.Tool
);
12412 /* Static Properties */
12415 * Toolgroup configuration.
12417 * The toolgroup configuration consists of the tools to include, as well as an icon and label
12418 * to use for the bar item. Tools can be included by symbolic name, group, or with the
12419 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
12421 * @property {Object.<string,Array>}
12423 OO
.ui
.ToolGroupTool
.static.groupConfig
= {};
12428 * Handle the tool being selected.
12432 OO
.ui
.ToolGroupTool
.prototype.onSelect = function () {
12433 this.innerToolGroup
.setActive( !this.innerToolGroup
.active
);
12438 * Synchronize disabledness state of the tool with the inner toolgroup.
12441 * @param {boolean} disabled Element is disabled
12443 OO
.ui
.ToolGroupTool
.prototype.onToolGroupDisable = function ( disabled
) {
12444 this.setDisabled( disabled
);
12448 * Handle the toolbar state being updated.
12452 OO
.ui
.ToolGroupTool
.prototype.onUpdateState = function () {
12453 this.setActive( false );
12457 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
12459 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
12460 * more information.
12461 * @return {OO.ui.ListToolGroup}
12463 OO
.ui
.ToolGroupTool
.prototype.createGroup = function ( group
) {
12464 if ( group
.include
=== '*' ) {
12465 // Apply defaults to catch-all groups
12466 if ( group
.label
=== undefined ) {
12467 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
12471 return this.toolbar
.getToolGroupFactory().create( 'list', this.toolbar
, group
);
12475 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
12477 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
12482 * @extends OO.ui.mixin.GroupElement
12485 * @param {Object} [config] Configuration options
12487 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
12488 // Parent constructor
12489 OO
.ui
.mixin
.GroupWidget
.parent
.call( this, config
);
12494 OO
.inheritClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
12499 * Set the disabled state of the widget.
12501 * This will also update the disabled state of child widgets.
12503 * @param {boolean} disabled Disable widget
12506 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
12510 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
12511 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
12513 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
12514 if ( this.items
) {
12515 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
12516 this.items
[ i
].updateDisabled();
12524 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
12526 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
12527 * allows bidirectional communication.
12529 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
12537 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
12544 * Check if widget is disabled.
12546 * Checks parent if present, making disabled state inheritable.
12548 * @return {boolean} Widget is disabled
12550 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
12551 return this.disabled
||
12552 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
12556 * Set group element is in.
12558 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
12561 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
12563 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
12564 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
12566 // Initialize item disabled states
12567 this.updateDisabled();
12573 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
12574 * Controls include moving items up and down, removing items, and adding different kinds of items.
12576 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
12579 * @extends OO.ui.Widget
12580 * @mixins OO.ui.mixin.GroupElement
12581 * @mixins OO.ui.mixin.IconElement
12584 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
12585 * @param {Object} [config] Configuration options
12586 * @cfg {Object} [abilities] List of abilties
12587 * @cfg {boolean} [abilities.move=true] Allow moving movable items
12588 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
12590 OO
.ui
.OutlineControlsWidget
= function OoUiOutlineControlsWidget( outline
, config
) {
12591 // Allow passing positional parameters inside the config object
12592 if ( OO
.isPlainObject( outline
) && config
=== undefined ) {
12594 outline
= config
.outline
;
12597 // Configuration initialization
12598 config
= $.extend( { icon
: 'add' }, config
);
12600 // Parent constructor
12601 OO
.ui
.OutlineControlsWidget
.parent
.call( this, config
);
12603 // Mixin constructors
12604 OO
.ui
.mixin
.GroupElement
.call( this, config
);
12605 OO
.ui
.mixin
.IconElement
.call( this, config
);
12608 this.outline
= outline
;
12609 this.$movers
= $( '<div>' );
12610 this.upButton
= new OO
.ui
.ButtonWidget( {
12613 title
: OO
.ui
.msg( 'ooui-outline-control-move-up' )
12615 this.downButton
= new OO
.ui
.ButtonWidget( {
12618 title
: OO
.ui
.msg( 'ooui-outline-control-move-down' )
12620 this.removeButton
= new OO
.ui
.ButtonWidget( {
12623 title
: OO
.ui
.msg( 'ooui-outline-control-remove' )
12625 this.abilities
= { move: true, remove
: true };
12628 outline
.connect( this, {
12629 select
: 'onOutlineChange',
12630 add
: 'onOutlineChange',
12631 remove
: 'onOutlineChange'
12633 this.upButton
.connect( this, { click
: [ 'emit', 'move', -1 ] } );
12634 this.downButton
.connect( this, { click
: [ 'emit', 'move', 1 ] } );
12635 this.removeButton
.connect( this, { click
: [ 'emit', 'remove' ] } );
12638 this.$element
.addClass( 'oo-ui-outlineControlsWidget' );
12639 this.$group
.addClass( 'oo-ui-outlineControlsWidget-items' );
12641 .addClass( 'oo-ui-outlineControlsWidget-movers' )
12642 .append( this.removeButton
.$element
, this.upButton
.$element
, this.downButton
.$element
);
12643 this.$element
.append( this.$icon
, this.$group
, this.$movers
);
12644 this.setAbilities( config
.abilities
|| {} );
12649 OO
.inheritClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.Widget
);
12650 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.GroupElement
);
12651 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.IconElement
);
12657 * @param {number} places Number of places to move
12669 * @param {Object} abilities List of abilties
12670 * @param {boolean} [abilities.move] Allow moving movable items
12671 * @param {boolean} [abilities.remove] Allow removing removable items
12673 OO
.ui
.OutlineControlsWidget
.prototype.setAbilities = function ( abilities
) {
12676 for ( ability
in this.abilities
) {
12677 if ( abilities
[ ability
] !== undefined ) {
12678 this.abilities
[ ability
] = !!abilities
[ ability
];
12682 this.onOutlineChange();
12687 * Handle outline change events.
12689 OO
.ui
.OutlineControlsWidget
.prototype.onOutlineChange = function () {
12690 var i
, len
, firstMovable
, lastMovable
,
12691 items
= this.outline
.getItems(),
12692 selectedItem
= this.outline
.getSelectedItem(),
12693 movable
= this.abilities
.move && selectedItem
&& selectedItem
.isMovable(),
12694 removable
= this.abilities
.remove
&& selectedItem
&& selectedItem
.isRemovable();
12698 len
= items
.length
;
12699 while ( ++i
< len
) {
12700 if ( items
[ i
].isMovable() ) {
12701 firstMovable
= items
[ i
];
12707 if ( items
[ i
].isMovable() ) {
12708 lastMovable
= items
[ i
];
12713 this.upButton
.setDisabled( !movable
|| selectedItem
=== firstMovable
);
12714 this.downButton
.setDisabled( !movable
|| selectedItem
=== lastMovable
);
12715 this.removeButton
.setDisabled( !removable
);
12719 * ToggleWidget implements basic behavior of widgets with an on/off state.
12720 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
12724 * @extends OO.ui.Widget
12727 * @param {Object} [config] Configuration options
12728 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
12729 * By default, the toggle is in the 'off' state.
12731 OO
.ui
.ToggleWidget
= function OoUiToggleWidget( config
) {
12732 // Configuration initialization
12733 config
= config
|| {};
12735 // Parent constructor
12736 OO
.ui
.ToggleWidget
.parent
.call( this, config
);
12742 this.$element
.addClass( 'oo-ui-toggleWidget' );
12743 this.setValue( !!config
.value
);
12748 OO
.inheritClass( OO
.ui
.ToggleWidget
, OO
.ui
.Widget
);
12755 * A change event is emitted when the on/off state of the toggle changes.
12757 * @param {boolean} value Value representing the new state of the toggle
12763 * Get the value representing the toggle’s state.
12765 * @return {boolean} The on/off state of the toggle
12767 OO
.ui
.ToggleWidget
.prototype.getValue = function () {
12772 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
12774 * @param {boolean} value The state of the toggle
12778 OO
.ui
.ToggleWidget
.prototype.setValue = function ( value
) {
12780 if ( this.value
!== value
) {
12781 this.value
= value
;
12782 this.emit( 'change', value
);
12783 this.$element
.toggleClass( 'oo-ui-toggleWidget-on', value
);
12784 this.$element
.toggleClass( 'oo-ui-toggleWidget-off', !value
);
12785 this.$element
.attr( 'aria-checked', value
.toString() );
12791 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12792 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12793 * removed, and cleared from the group.
12796 * // Example: A ButtonGroupWidget with two buttons
12797 * var button1 = new OO.ui.PopupButtonWidget( {
12798 * label: 'Select a category',
12801 * $content: $( '<p>List of categories...</p>' ),
12806 * var button2 = new OO.ui.ButtonWidget( {
12807 * label: 'Add item'
12809 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12810 * items: [button1, button2]
12812 * $( 'body' ).append( buttonGroup.$element );
12815 * @extends OO.ui.Widget
12816 * @mixins OO.ui.mixin.GroupElement
12819 * @param {Object} [config] Configuration options
12820 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12822 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
12823 // Configuration initialization
12824 config
= config
|| {};
12826 // Parent constructor
12827 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
12829 // Mixin constructors
12830 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
12833 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
12834 if ( Array
.isArray( config
.items
) ) {
12835 this.addItems( config
.items
);
12841 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
12842 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
12845 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12846 * feels, and functionality can be customized via the class’s configuration options
12847 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12850 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12853 * // A button widget
12854 * var button = new OO.ui.ButtonWidget( {
12855 * label: 'Button with Icon',
12857 * iconTitle: 'Remove'
12859 * $( 'body' ).append( button.$element );
12861 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12864 * @extends OO.ui.Widget
12865 * @mixins OO.ui.mixin.ButtonElement
12866 * @mixins OO.ui.mixin.IconElement
12867 * @mixins OO.ui.mixin.IndicatorElement
12868 * @mixins OO.ui.mixin.LabelElement
12869 * @mixins OO.ui.mixin.TitledElement
12870 * @mixins OO.ui.mixin.FlaggedElement
12871 * @mixins OO.ui.mixin.TabIndexedElement
12872 * @mixins OO.ui.mixin.AccessKeyedElement
12875 * @param {Object} [config] Configuration options
12876 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12877 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12878 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12880 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
12881 // Configuration initialization
12882 config
= config
|| {};
12884 // Parent constructor
12885 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
12887 // Mixin constructors
12888 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
12889 OO
.ui
.mixin
.IconElement
.call( this, config
);
12890 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12891 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12892 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
12893 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
12894 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
12895 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
12899 this.target
= null;
12900 this.noFollow
= false;
12903 this.connect( this, { disable
: 'onDisable' } );
12906 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
12908 .addClass( 'oo-ui-buttonWidget' )
12909 .append( this.$button
);
12910 this.setHref( config
.href
);
12911 this.setTarget( config
.target
);
12912 this.setNoFollow( config
.noFollow
);
12917 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
12918 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
12919 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
12920 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
12921 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
12922 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
12923 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
12924 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
12925 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
12932 OO
.ui
.ButtonWidget
.prototype.onMouseDown = function ( e
) {
12933 if ( !this.isDisabled() ) {
12934 // Remove the tab-index while the button is down to prevent the button from stealing focus
12935 this.$button
.removeAttr( 'tabindex' );
12938 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown
.call( this, e
);
12944 OO
.ui
.ButtonWidget
.prototype.onMouseUp = function ( e
) {
12945 if ( !this.isDisabled() ) {
12946 // Restore the tab-index after the button is up to restore the button's accessibility
12947 this.$button
.attr( 'tabindex', this.tabIndex
);
12950 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp
.call( this, e
);
12954 * Get hyperlink location.
12956 * @return {string} Hyperlink location
12958 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
12963 * Get hyperlink target.
12965 * @return {string} Hyperlink target
12967 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
12968 return this.target
;
12972 * Get search engine traversal hint.
12974 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12976 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
12977 return this.noFollow
;
12981 * Set hyperlink location.
12983 * @param {string|null} href Hyperlink location, null to remove
12985 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
12986 href
= typeof href
=== 'string' ? href
: null;
12987 if ( href
!== null ) {
12988 if ( !OO
.ui
.isSafeUrl( href
) ) {
12989 throw new Error( 'Potentially unsafe href provided: ' + href
);
12994 if ( href
!== this.href
) {
13003 * Update the `href` attribute, in case of changes to href or
13009 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
13010 if ( this.href
!== null && !this.isDisabled() ) {
13011 this.$button
.attr( 'href', this.href
);
13013 this.$button
.removeAttr( 'href' );
13020 * Handle disable events.
13023 * @param {boolean} disabled Element is disabled
13025 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
13030 * Set hyperlink target.
13032 * @param {string|null} target Hyperlink target, null to remove
13034 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
13035 target
= typeof target
=== 'string' ? target
: null;
13037 if ( target
!== this.target
) {
13038 this.target
= target
;
13039 if ( target
!== null ) {
13040 this.$button
.attr( 'target', target
);
13042 this.$button
.removeAttr( 'target' );
13050 * Set search engine traversal hint.
13052 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
13054 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
13055 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
13057 if ( noFollow
!== this.noFollow
) {
13058 this.noFollow
= noFollow
;
13060 this.$button
.attr( 'rel', 'nofollow' );
13062 this.$button
.removeAttr( 'rel' );
13070 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
13071 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
13074 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
13075 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
13078 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
13081 * @extends OO.ui.ButtonWidget
13082 * @mixins OO.ui.mixin.PendingElement
13085 * @param {Object} [config] Configuration options
13086 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
13087 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
13088 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
13089 * for more information about setting modes.
13090 * @cfg {boolean} [framed=false] Render the action button with a frame
13092 OO
.ui
.ActionWidget
= function OoUiActionWidget( config
) {
13093 // Configuration initialization
13094 config
= $.extend( { framed
: false }, config
);
13096 // Parent constructor
13097 OO
.ui
.ActionWidget
.parent
.call( this, config
);
13099 // Mixin constructors
13100 OO
.ui
.mixin
.PendingElement
.call( this, config
);
13103 this.action
= config
.action
|| '';
13104 this.modes
= config
.modes
|| [];
13109 this.$element
.addClass( 'oo-ui-actionWidget' );
13114 OO
.inheritClass( OO
.ui
.ActionWidget
, OO
.ui
.ButtonWidget
);
13115 OO
.mixinClass( OO
.ui
.ActionWidget
, OO
.ui
.mixin
.PendingElement
);
13120 * A resize event is emitted when the size of the widget changes.
13128 * Check if the action is configured to be available in the specified `mode`.
13130 * @param {string} mode Name of mode
13131 * @return {boolean} The action is configured with the mode
13133 OO
.ui
.ActionWidget
.prototype.hasMode = function ( mode
) {
13134 return this.modes
.indexOf( mode
) !== -1;
13138 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
13142 OO
.ui
.ActionWidget
.prototype.getAction = function () {
13143 return this.action
;
13147 * Get the symbolic name of the mode or modes for which the action is configured to be available.
13149 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
13150 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
13153 * @return {string[]}
13155 OO
.ui
.ActionWidget
.prototype.getModes = function () {
13156 return this.modes
.slice();
13160 * Emit a resize event if the size has changed.
13165 OO
.ui
.ActionWidget
.prototype.propagateResize = function () {
13168 if ( this.isElementAttached() ) {
13169 width
= this.$element
.width();
13170 height
= this.$element
.height();
13172 if ( width
!== this.width
|| height
!== this.height
) {
13173 this.width
= width
;
13174 this.height
= height
;
13175 this.emit( 'resize' );
13185 OO
.ui
.ActionWidget
.prototype.setIcon = function () {
13187 OO
.ui
.mixin
.IconElement
.prototype.setIcon
.apply( this, arguments
);
13188 this.propagateResize();
13196 OO
.ui
.ActionWidget
.prototype.setLabel = function () {
13198 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.apply( this, arguments
);
13199 this.propagateResize();
13207 OO
.ui
.ActionWidget
.prototype.setFlags = function () {
13209 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags
.apply( this, arguments
);
13210 this.propagateResize();
13218 OO
.ui
.ActionWidget
.prototype.clearFlags = function () {
13220 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags
.apply( this, arguments
);
13221 this.propagateResize();
13227 * Toggle the visibility of the action button.
13229 * @param {boolean} [show] Show button, omit to toggle visibility
13232 OO
.ui
.ActionWidget
.prototype.toggle = function () {
13234 OO
.ui
.ActionWidget
.parent
.prototype.toggle
.apply( this, arguments
);
13235 this.propagateResize();
13241 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
13242 * which is used to display additional information or options.
13245 * // Example of a popup button.
13246 * var popupButton = new OO.ui.PopupButtonWidget( {
13247 * label: 'Popup button with options',
13250 * $content: $( '<p>Additional options here.</p>' ),
13252 * align: 'force-left'
13255 * // Append the button to the DOM.
13256 * $( 'body' ).append( popupButton.$element );
13259 * @extends OO.ui.ButtonWidget
13260 * @mixins OO.ui.mixin.PopupElement
13263 * @param {Object} [config] Configuration options
13265 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
13266 // Parent constructor
13267 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
13269 // Mixin constructors
13270 OO
.ui
.mixin
.PopupElement
.call( this, config
);
13273 this.connect( this, { click
: 'onAction' } );
13277 .addClass( 'oo-ui-popupButtonWidget' )
13278 .attr( 'aria-haspopup', 'true' )
13279 .append( this.popup
.$element
);
13284 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
13285 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
13290 * Handle the button action being triggered.
13294 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
13295 this.popup
.toggle();
13299 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
13300 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
13301 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
13302 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
13303 * and {@link OO.ui.mixin.LabelElement labels}. Please see
13304 * the [OOjs UI documentation][1] on MediaWiki for more information.
13307 * // Toggle buttons in the 'off' and 'on' state.
13308 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
13309 * label: 'Toggle Button off'
13311 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
13312 * label: 'Toggle Button on',
13315 * // Append the buttons to the DOM.
13316 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
13318 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
13321 * @extends OO.ui.ToggleWidget
13322 * @mixins OO.ui.mixin.ButtonElement
13323 * @mixins OO.ui.mixin.IconElement
13324 * @mixins OO.ui.mixin.IndicatorElement
13325 * @mixins OO.ui.mixin.LabelElement
13326 * @mixins OO.ui.mixin.TitledElement
13327 * @mixins OO.ui.mixin.FlaggedElement
13328 * @mixins OO.ui.mixin.TabIndexedElement
13331 * @param {Object} [config] Configuration options
13332 * @cfg {boolean} [value=false] The toggle button’s initial on/off
13333 * state. By default, the button is in the 'off' state.
13335 OO
.ui
.ToggleButtonWidget
= function OoUiToggleButtonWidget( config
) {
13336 // Configuration initialization
13337 config
= config
|| {};
13339 // Parent constructor
13340 OO
.ui
.ToggleButtonWidget
.parent
.call( this, config
);
13342 // Mixin constructors
13343 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
13344 OO
.ui
.mixin
.IconElement
.call( this, config
);
13345 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13346 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13347 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
13348 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
13349 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
13352 this.connect( this, { click
: 'onAction' } );
13355 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
13357 .addClass( 'oo-ui-toggleButtonWidget' )
13358 .append( this.$button
);
13363 OO
.inheritClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ToggleWidget
);
13364 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
13365 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IconElement
);
13366 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
13367 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.LabelElement
);
13368 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TitledElement
);
13369 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
13370 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13375 * Handle the button action being triggered.
13379 OO
.ui
.ToggleButtonWidget
.prototype.onAction = function () {
13380 this.setValue( !this.value
);
13386 OO
.ui
.ToggleButtonWidget
.prototype.setValue = function ( value
) {
13388 if ( value
!== this.value
) {
13389 // Might be called from parent constructor before ButtonElement constructor
13390 if ( this.$button
) {
13391 this.$button
.attr( 'aria-pressed', value
.toString() );
13393 this.setActive( value
);
13397 OO
.ui
.ToggleButtonWidget
.parent
.prototype.setValue
.call( this, value
);
13405 OO
.ui
.ToggleButtonWidget
.prototype.setButtonElement = function ( $button
) {
13406 if ( this.$button
) {
13407 this.$button
.removeAttr( 'aria-pressed' );
13409 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement
.call( this, $button
);
13410 this.$button
.attr( 'aria-pressed', this.value
.toString() );
13414 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxInputWidget combo box widget}
13415 * that allows for selecting multiple values.
13417 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
13420 * // Example: A CapsuleMultiSelectWidget.
13421 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
13422 * label: 'CapsuleMultiSelectWidget',
13423 * selected: [ 'Option 1', 'Option 3' ],
13426 * new OO.ui.MenuOptionWidget( {
13427 * data: 'Option 1',
13428 * label: 'Option One'
13430 * new OO.ui.MenuOptionWidget( {
13431 * data: 'Option 2',
13432 * label: 'Option Two'
13434 * new OO.ui.MenuOptionWidget( {
13435 * data: 'Option 3',
13436 * label: 'Option Three'
13438 * new OO.ui.MenuOptionWidget( {
13439 * data: 'Option 4',
13440 * label: 'Option Four'
13442 * new OO.ui.MenuOptionWidget( {
13443 * data: 'Option 5',
13444 * label: 'Option Five'
13449 * $( 'body' ).append( capsule.$element );
13451 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13454 * @extends OO.ui.Widget
13455 * @mixins OO.ui.mixin.TabIndexedElement
13456 * @mixins OO.ui.mixin.GroupElement
13459 * @param {Object} [config] Configuration options
13460 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
13461 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
13462 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
13463 * If specified, this popup will be shown instead of the menu (but the menu
13464 * will still be used for item labels and allowArbitrary=false). The widgets
13465 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
13466 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
13467 * This configuration is useful in cases where the expanded menu is larger than
13468 * its containing `<div>`. The specified overlay layer is usually on top of
13469 * the containing `<div>` and has a larger area. By default, the menu uses
13470 * relative positioning.
13472 OO
.ui
.CapsuleMultiSelectWidget
= function OoUiCapsuleMultiSelectWidget( config
) {
13475 // Configuration initialization
13476 config
= config
|| {};
13478 // Parent constructor
13479 OO
.ui
.CapsuleMultiSelectWidget
.parent
.call( this, config
);
13481 // Properties (must be set before mixin constructor calls)
13482 this.$input
= config
.popup
? null : $( '<input>' );
13483 this.$handle
= $( '<div>' );
13485 // Mixin constructors
13486 OO
.ui
.mixin
.GroupElement
.call( this, config
);
13487 if ( config
.popup
) {
13488 config
.popup
= $.extend( {}, config
.popup
, {
13492 OO
.ui
.mixin
.PopupElement
.call( this, config
);
13493 $tabFocus
= $( '<span>' );
13494 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: $tabFocus
} ) );
13498 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
13500 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13501 OO
.ui
.mixin
.IconElement
.call( this, config
);
13504 this.$content
= $( '<div>' );
13505 this.allowArbitrary
= !!config
.allowArbitrary
;
13506 this.$overlay
= config
.$overlay
|| this.$element
;
13507 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
13510 $input
: this.$input
,
13511 $container
: this.$element
,
13512 filterFromInput
: true,
13513 disabled
: this.isDisabled()
13519 if ( this.popup
) {
13521 focus
: this.onFocusForPopup
.bind( this )
13523 this.popup
.$element
.on( 'focusout', this.onPopupFocusOut
.bind( this ) );
13524 if ( this.popup
.$autoCloseIgnore
) {
13525 this.popup
.$autoCloseIgnore
.on( 'focusout', this.onPopupFocusOut
.bind( this ) );
13527 this.popup
.connect( this, {
13528 toggle: function ( visible
) {
13529 $tabFocus
.toggle( !visible
);
13534 focus
: this.onInputFocus
.bind( this ),
13535 blur
: this.onInputBlur
.bind( this ),
13536 'propertychange change click mouseup keydown keyup input cut paste select focus':
13537 OO
.ui
.debounce( this.updateInputSize
.bind( this ) ),
13538 keydown
: this.onKeyDown
.bind( this ),
13539 keypress
: this.onKeyPress
.bind( this )
13542 this.menu
.connect( this, {
13543 choose
: 'onMenuChoose',
13544 add
: 'onMenuItemsChange',
13545 remove
: 'onMenuItemsChange'
13548 mousedown
: this.onMouseDown
.bind( this )
13552 if ( this.$input
) {
13553 this.$input
.prop( 'disabled', this.isDisabled() );
13554 this.$input
.attr( {
13556 'aria-autocomplete': 'list'
13558 this.updateInputSize();
13560 if ( config
.data
) {
13561 this.setItemsFromData( config
.data
);
13563 this.$content
.addClass( 'oo-ui-capsuleMultiSelectWidget-content' )
13564 .append( this.$group
);
13565 this.$group
.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
13566 this.$handle
.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
13567 .append( this.$indicator
, this.$icon
, this.$content
);
13568 this.$element
.addClass( 'oo-ui-capsuleMultiSelectWidget' )
13569 .append( this.$handle
);
13570 if ( this.popup
) {
13571 this.$content
.append( $tabFocus
);
13572 this.$overlay
.append( this.popup
.$element
);
13574 this.$content
.append( this.$input
);
13575 this.$overlay
.append( this.menu
.$element
);
13577 this.onMenuItemsChange();
13582 OO
.inheritClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.Widget
);
13583 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.GroupElement
);
13584 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.PopupElement
);
13585 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13586 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.IndicatorElement
);
13587 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.IconElement
);
13594 * A change event is emitted when the set of selected items changes.
13596 * @param {Mixed[]} datas Data of the now-selected items
13602 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
13605 * @param {Mixed} data Custom data of any type.
13606 * @param {string} label The label text.
13607 * @return {OO.ui.CapsuleItemWidget}
13609 OO
.ui
.CapsuleMultiSelectWidget
.prototype.createItemWidget = function ( data
, label
) {
13610 return new OO
.ui
.CapsuleItemWidget( { data
: data
, label
: label
} );
13614 * Get the data of the items in the capsule
13615 * @return {Mixed[]}
13617 OO
.ui
.CapsuleMultiSelectWidget
.prototype.getItemsData = function () {
13618 return $.map( this.getItems(), function ( e
) { return e
.data
; } );
13622 * Set the items in the capsule by providing data
13624 * @param {Mixed[]} datas
13625 * @return {OO.ui.CapsuleMultiSelectWidget}
13627 OO
.ui
.CapsuleMultiSelectWidget
.prototype.setItemsFromData = function ( datas
) {
13630 items
= this.getItems();
13632 $.each( datas
, function ( i
, data
) {
13634 item
= menu
.getItemFromData( data
);
13637 label
= item
.label
;
13638 } else if ( widget
.allowArbitrary
) {
13639 label
= String( data
);
13645 for ( j
= 0; j
< items
.length
; j
++ ) {
13646 if ( items
[ j
].data
=== data
&& items
[ j
].label
=== label
) {
13648 items
.splice( j
, 1 );
13653 item
= widget
.createItemWidget( data
, label
);
13655 widget
.addItems( [ item
], i
);
13658 if ( items
.length
) {
13659 widget
.removeItems( items
);
13666 * Add items to the capsule by providing their data
13668 * @param {Mixed[]} datas
13669 * @return {OO.ui.CapsuleMultiSelectWidget}
13671 OO
.ui
.CapsuleMultiSelectWidget
.prototype.addItemsFromData = function ( datas
) {
13676 $.each( datas
, function ( i
, data
) {
13679 if ( !widget
.getItemFromData( data
) ) {
13680 item
= menu
.getItemFromData( data
);
13682 items
.push( widget
.createItemWidget( data
, item
.label
) );
13683 } else if ( widget
.allowArbitrary
) {
13684 items
.push( widget
.createItemWidget( data
, String( data
) ) );
13689 if ( items
.length
) {
13690 this.addItems( items
);
13697 * Remove items by data
13699 * @param {Mixed[]} datas
13700 * @return {OO.ui.CapsuleMultiSelectWidget}
13702 OO
.ui
.CapsuleMultiSelectWidget
.prototype.removeItemsFromData = function ( datas
) {
13706 $.each( datas
, function ( i
, data
) {
13707 var item
= widget
.getItemFromData( data
);
13709 items
.push( item
);
13713 if ( items
.length
) {
13714 this.removeItems( items
);
13723 OO
.ui
.CapsuleMultiSelectWidget
.prototype.addItems = function ( items
) {
13725 oldItems
= this.items
.slice();
13727 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
);
13729 if ( this.items
.length
!== oldItems
.length
) {
13733 for ( i
= 0, l
= oldItems
.length
; same
&& i
< l
; i
++ ) {
13734 same
= same
&& this.items
[ i
] === oldItems
[ i
];
13738 this.emit( 'change', this.getItemsData() );
13739 this.menu
.position();
13748 OO
.ui
.CapsuleMultiSelectWidget
.prototype.removeItems = function ( items
) {
13750 oldItems
= this.items
.slice();
13752 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
13754 if ( this.items
.length
!== oldItems
.length
) {
13758 for ( i
= 0, l
= oldItems
.length
; same
&& i
< l
; i
++ ) {
13759 same
= same
&& this.items
[ i
] === oldItems
[ i
];
13763 this.emit( 'change', this.getItemsData() );
13764 this.menu
.position();
13773 OO
.ui
.CapsuleMultiSelectWidget
.prototype.clearItems = function () {
13774 if ( this.items
.length
) {
13775 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
13776 this.emit( 'change', this.getItemsData() );
13777 this.menu
.position();
13783 * Get the capsule widget's menu.
13784 * @return {OO.ui.MenuSelectWidget} Menu widget
13786 OO
.ui
.CapsuleMultiSelectWidget
.prototype.getMenu = function () {
13791 * Handle focus events
13794 * @param {jQuery.Event} event
13796 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputFocus = function () {
13797 if ( !this.isDisabled() ) {
13798 this.menu
.toggle( true );
13803 * Handle blur events
13806 * @param {jQuery.Event} event
13808 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputBlur = function () {
13809 if ( this.allowArbitrary
&& this.$input
.val().trim() !== '' ) {
13810 this.addItemsFromData( [ this.$input
.val() ] );
13816 * Handle focus events
13819 * @param {jQuery.Event} event
13821 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onFocusForPopup = function () {
13822 if ( !this.isDisabled() ) {
13823 this.popup
.setSize( this.$handle
.width() );
13824 this.popup
.toggle( true );
13825 this.popup
.$element
.find( '*' )
13826 .filter( function () { return OO
.ui
.isFocusableElement( $( this ), true ); } )
13833 * Handles popup focus out events.
13836 * @param {Event} e Focus out event
13838 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onPopupFocusOut = function () {
13839 var widget
= this.popup
;
13841 setTimeout( function () {
13843 widget
.isVisible() &&
13844 !OO
.ui
.contains( widget
.$element
[ 0 ], document
.activeElement
, true ) &&
13845 ( !widget
.$autoCloseIgnore
|| !widget
.$autoCloseIgnore
.has( document
.activeElement
).length
)
13847 widget
.toggle( false );
13853 * Handle mouse down events.
13856 * @param {jQuery.Event} e Mouse down event
13858 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onMouseDown = function ( e
) {
13859 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
13863 this.updateInputSize();
13868 * Handle key press events.
13871 * @param {jQuery.Event} e Key press event
13873 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onKeyPress = function ( e
) {
13876 if ( !this.isDisabled() ) {
13877 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
13882 if ( !this.popup
) {
13883 this.menu
.toggle( true );
13884 if ( e
.which
=== OO
.ui
.Keys
.ENTER
) {
13885 item
= this.menu
.getItemFromLabel( this.$input
.val(), true );
13887 this.addItemsFromData( [ item
.data
] );
13889 } else if ( this.allowArbitrary
&& this.$input
.val().trim() !== '' ) {
13890 this.addItemsFromData( [ this.$input
.val() ] );
13896 // Make sure the input gets resized.
13897 setTimeout( this.updateInputSize
.bind( this ), 0 );
13903 * Handle key down events.
13906 * @param {jQuery.Event} e Key down event
13908 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onKeyDown = function ( e
) {
13909 if ( !this.isDisabled() ) {
13910 // 'keypress' event is not triggered for Backspace
13911 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.$input
.val() === '' ) {
13912 if ( this.items
.length
) {
13913 this.removeItems( this.items
.slice( -1 ) );
13921 * Update the dimensions of the text input field to encompass all available area.
13924 * @param {jQuery.Event} e Event of some sort
13926 OO
.ui
.CapsuleMultiSelectWidget
.prototype.updateInputSize = function () {
13927 var $lastItem
, direction
, contentWidth
, currentWidth
, bestWidth
;
13928 if ( !this.isDisabled() ) {
13929 this.$input
.css( 'width', '1em' );
13930 $lastItem
= this.$group
.children().last();
13931 direction
= OO
.ui
.Element
.static.getDir( this.$handle
);
13932 contentWidth
= this.$input
[ 0 ].scrollWidth
;
13933 currentWidth
= this.$input
.width();
13935 if ( contentWidth
< currentWidth
) {
13936 // All is fine, don't perform expensive calculations
13940 if ( !$lastItem
.length
) {
13941 bestWidth
= this.$content
.innerWidth();
13943 bestWidth
= direction
=== 'ltr' ?
13944 this.$content
.innerWidth() - $lastItem
.position().left
- $lastItem
.outerWidth() :
13945 $lastItem
.position().left
;
13947 // Some safety margin for sanity, because I *really* don't feel like finding out where the few
13948 // pixels this is off by are coming from.
13950 if ( contentWidth
> bestWidth
) {
13951 // This will result in the input getting shifted to the next line
13952 bestWidth
= this.$content
.innerWidth() - 10;
13954 this.$input
.width( Math
.floor( bestWidth
) );
13956 this.menu
.position();
13961 * Handle menu choose events.
13964 * @param {OO.ui.OptionWidget} item Chosen item
13966 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onMenuChoose = function ( item
) {
13967 if ( item
&& item
.isVisible() ) {
13968 this.addItemsFromData( [ item
.getData() ] );
13974 * Handle menu item change events.
13978 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onMenuItemsChange = function () {
13979 this.setItemsFromData( this.getItemsData() );
13980 this.$element
.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu
.isEmpty() );
13984 * Clear the input field
13987 OO
.ui
.CapsuleMultiSelectWidget
.prototype.clearInput = function () {
13988 if ( this.$input
) {
13989 this.$input
.val( '' );
13990 this.updateInputSize();
13992 if ( this.popup
) {
13993 this.popup
.toggle( false );
13995 this.menu
.toggle( false );
13996 this.menu
.selectItem();
13997 this.menu
.highlightItem();
14003 OO
.ui
.CapsuleMultiSelectWidget
.prototype.setDisabled = function ( disabled
) {
14007 OO
.ui
.CapsuleMultiSelectWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
14009 if ( this.$input
) {
14010 this.$input
.prop( 'disabled', this.isDisabled() );
14013 this.menu
.setDisabled( this.isDisabled() );
14015 if ( this.popup
) {
14016 this.popup
.setDisabled( this.isDisabled() );
14019 if ( this.items
) {
14020 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14021 this.items
[ i
].updateDisabled();
14031 * @return {OO.ui.CapsuleMultiSelectWidget}
14033 OO
.ui
.CapsuleMultiSelectWidget
.prototype.focus = function () {
14034 if ( !this.isDisabled() ) {
14035 if ( this.popup
) {
14036 this.popup
.setSize( this.$handle
.width() );
14037 this.popup
.toggle( true );
14038 this.popup
.$element
.find( '*' )
14039 .filter( function () { return OO
.ui
.isFocusableElement( $( this ), true ); } )
14043 this.updateInputSize();
14044 this.menu
.toggle( true );
14045 this.$input
.focus();
14052 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
14053 * CapsuleMultiSelectWidget} to display the selected items.
14056 * @extends OO.ui.Widget
14057 * @mixins OO.ui.mixin.ItemWidget
14058 * @mixins OO.ui.mixin.IndicatorElement
14059 * @mixins OO.ui.mixin.LabelElement
14060 * @mixins OO.ui.mixin.FlaggedElement
14061 * @mixins OO.ui.mixin.TabIndexedElement
14064 * @param {Object} [config] Configuration options
14066 OO
.ui
.CapsuleItemWidget
= function OoUiCapsuleItemWidget( config
) {
14067 // Configuration initialization
14068 config
= config
|| {};
14070 // Parent constructor
14071 OO
.ui
.CapsuleItemWidget
.parent
.call( this, config
);
14073 // Properties (must be set before mixin constructor calls)
14074 this.$indicator
= $( '<span>' );
14076 // Mixin constructors
14077 OO
.ui
.mixin
.ItemWidget
.call( this );
14078 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$indicator
, indicator
: 'clear' } ) );
14079 OO
.ui
.mixin
.LabelElement
.call( this, config
);
14080 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
14081 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
14084 this.$indicator
.on( {
14085 keydown
: this.onCloseKeyDown
.bind( this ),
14086 click
: this.onCloseClick
.bind( this )
14091 .addClass( 'oo-ui-capsuleItemWidget' )
14092 .append( this.$indicator
, this.$label
);
14097 OO
.inheritClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.Widget
);
14098 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.ItemWidget
);
14099 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.IndicatorElement
);
14100 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.LabelElement
);
14101 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.FlaggedElement
);
14102 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.TabIndexedElement
);
14107 * Handle close icon clicks
14108 * @param {jQuery.Event} event
14110 OO
.ui
.CapsuleItemWidget
.prototype.onCloseClick = function () {
14111 var element
= this.getElementGroup();
14113 if ( !this.isDisabled() && element
&& $.isFunction( element
.removeItems
) ) {
14114 element
.removeItems( [ this ] );
14120 * Handle close keyboard events
14121 * @param {jQuery.Event} event Key down event
14123 OO
.ui
.CapsuleItemWidget
.prototype.onCloseKeyDown = function ( e
) {
14124 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems
) ) {
14125 switch ( e
.which
) {
14126 case OO
.ui
.Keys
.ENTER
:
14127 case OO
.ui
.Keys
.BACKSPACE
:
14128 case OO
.ui
.Keys
.SPACE
:
14129 this.getElementGroup().removeItems( [ this ] );
14136 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
14137 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
14138 * users can interact with it.
14140 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
14141 * OO.ui.DropdownInputWidget instead.
14144 * // Example: A DropdownWidget with a menu that contains three options
14145 * var dropDown = new OO.ui.DropdownWidget( {
14146 * label: 'Dropdown menu: Select a menu option',
14149 * new OO.ui.MenuOptionWidget( {
14153 * new OO.ui.MenuOptionWidget( {
14157 * new OO.ui.MenuOptionWidget( {
14165 * $( 'body' ).append( dropDown.$element );
14167 * dropDown.getMenu().selectItemByData( 'b' );
14169 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
14171 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
14173 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
14176 * @extends OO.ui.Widget
14177 * @mixins OO.ui.mixin.IconElement
14178 * @mixins OO.ui.mixin.IndicatorElement
14179 * @mixins OO.ui.mixin.LabelElement
14180 * @mixins OO.ui.mixin.TitledElement
14181 * @mixins OO.ui.mixin.TabIndexedElement
14184 * @param {Object} [config] Configuration options
14185 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
14186 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
14187 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
14188 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
14190 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
14191 // Configuration initialization
14192 config
= $.extend( { indicator
: 'down' }, config
);
14194 // Parent constructor
14195 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
14197 // Properties (must be set before TabIndexedElement constructor call)
14198 this.$handle
= this.$( '<span>' );
14199 this.$overlay
= config
.$overlay
|| this.$element
;
14201 // Mixin constructors
14202 OO
.ui
.mixin
.IconElement
.call( this, config
);
14203 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
14204 OO
.ui
.mixin
.LabelElement
.call( this, config
);
14205 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
14206 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
14209 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend( {
14211 $container
: this.$element
14212 }, config
.menu
) );
14216 click
: this.onClick
.bind( this ),
14217 keypress
: this.onKeyPress
.bind( this )
14219 this.menu
.connect( this, { select
: 'onMenuSelect' } );
14223 .addClass( 'oo-ui-dropdownWidget-handle' )
14224 .append( this.$icon
, this.$label
, this.$indicator
);
14226 .addClass( 'oo-ui-dropdownWidget' )
14227 .append( this.$handle
);
14228 this.$overlay
.append( this.menu
.$element
);
14233 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
14234 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
14235 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
14236 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
14237 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
14238 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
14245 * @return {OO.ui.MenuSelectWidget} Menu of widget
14247 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
14252 * Handles menu select events.
14255 * @param {OO.ui.MenuOptionWidget} item Selected menu item
14257 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
14261 this.setLabel( null );
14265 selectedLabel
= item
.getLabel();
14267 // If the label is a DOM element, clone it, because setLabel will append() it
14268 if ( selectedLabel
instanceof jQuery
) {
14269 selectedLabel
= selectedLabel
.clone();
14272 this.setLabel( selectedLabel
);
14276 * Handle mouse click events.
14279 * @param {jQuery.Event} e Mouse click event
14281 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
14282 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
14283 this.menu
.toggle();
14289 * Handle key press events.
14292 * @param {jQuery.Event} e Key press event
14294 OO
.ui
.DropdownWidget
.prototype.onKeyPress = function ( e
) {
14295 if ( !this.isDisabled() &&
14296 ( ( e
.which
=== OO
.ui
.Keys
.SPACE
&& !this.menu
.isVisible() ) || e
.which
=== OO
.ui
.Keys
.ENTER
)
14298 this.menu
.toggle();
14304 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
14305 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
14306 * OO.ui.mixin.IndicatorElement indicators}.
14307 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14310 * // Example of a file select widget
14311 * var selectFile = new OO.ui.SelectFileWidget();
14312 * $( 'body' ).append( selectFile.$element );
14314 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
14317 * @extends OO.ui.Widget
14318 * @mixins OO.ui.mixin.IconElement
14319 * @mixins OO.ui.mixin.IndicatorElement
14320 * @mixins OO.ui.mixin.PendingElement
14321 * @mixins OO.ui.mixin.LabelElement
14324 * @param {Object} [config] Configuration options
14325 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
14326 * @cfg {string} [placeholder] Text to display when no file is selected.
14327 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
14328 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
14329 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
14330 * @cfg {boolean} [dragDropUI=false] Deprecated alias for showDropTarget
14332 OO
.ui
.SelectFileWidget
= function OoUiSelectFileWidget( config
) {
14335 // TODO: Remove in next release
14336 if ( config
&& config
.dragDropUI
) {
14337 config
.showDropTarget
= true;
14340 // Configuration initialization
14341 config
= $.extend( {
14343 placeholder
: OO
.ui
.msg( 'ooui-selectfile-placeholder' ),
14344 notsupported
: OO
.ui
.msg( 'ooui-selectfile-not-supported' ),
14346 showDropTarget
: false
14349 // Parent constructor
14350 OO
.ui
.SelectFileWidget
.parent
.call( this, config
);
14352 // Mixin constructors
14353 OO
.ui
.mixin
.IconElement
.call( this, config
);
14354 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
14355 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$info
} ) );
14356 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { autoFitLabel
: true } ) );
14359 this.$info
= $( '<span>' );
14362 this.showDropTarget
= config
.showDropTarget
;
14363 this.isSupported
= this.constructor.static.isSupported();
14364 this.currentFile
= null;
14365 if ( Array
.isArray( config
.accept
) ) {
14366 this.accept
= config
.accept
;
14368 this.accept
= null;
14370 this.placeholder
= config
.placeholder
;
14371 this.notsupported
= config
.notsupported
;
14372 this.onFileSelectedHandler
= this.onFileSelected
.bind( this );
14374 this.selectButton
= new OO
.ui
.ButtonWidget( {
14375 classes
: [ 'oo-ui-selectFileWidget-selectButton' ],
14376 label
: OO
.ui
.msg( 'ooui-selectfile-button-select' ),
14377 disabled
: this.disabled
|| !this.isSupported
14380 this.clearButton
= new OO
.ui
.ButtonWidget( {
14381 classes
: [ 'oo-ui-selectFileWidget-clearButton' ],
14384 disabled
: this.disabled
14388 this.selectButton
.$button
.on( {
14389 keypress
: this.onKeyPress
.bind( this )
14391 this.clearButton
.connect( this, {
14392 click
: 'onClearClick'
14394 if ( config
.droppable
) {
14395 dragHandler
= this.onDragEnterOrOver
.bind( this );
14396 this.$element
.on( {
14397 dragenter
: dragHandler
,
14398 dragover
: dragHandler
,
14399 dragleave
: this.onDragLeave
.bind( this ),
14400 drop
: this.onDrop
.bind( this )
14407 this.$label
.addClass( 'oo-ui-selectFileWidget-label' );
14409 .addClass( 'oo-ui-selectFileWidget-info' )
14410 .append( this.$icon
, this.$label
, this.clearButton
.$element
, this.$indicator
);
14412 .addClass( 'oo-ui-selectFileWidget' )
14413 .append( this.$info
, this.selectButton
.$element
);
14414 if ( config
.droppable
&& config
.showDropTarget
) {
14415 this.$dropTarget
= $( '<div>' )
14416 .addClass( 'oo-ui-selectFileWidget-dropTarget' )
14417 .text( OO
.ui
.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
14419 click
: this.onDropTargetClick
.bind( this )
14421 this.$element
.prepend( this.$dropTarget
);
14427 OO
.inheritClass( OO
.ui
.SelectFileWidget
, OO
.ui
.Widget
);
14428 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IconElement
);
14429 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IndicatorElement
);
14430 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.PendingElement
);
14431 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.LabelElement
);
14433 /* Static Properties */
14436 * Check if this widget is supported
14439 * @return {boolean}
14441 OO
.ui
.SelectFileWidget
.static.isSupported = function () {
14443 if ( OO
.ui
.SelectFileWidget
.static.isSupportedCache
=== null ) {
14444 $input
= $( '<input type="file">' );
14445 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= $input
[ 0 ].files
!== undefined;
14447 return OO
.ui
.SelectFileWidget
.static.isSupportedCache
;
14450 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= null;
14457 * A change event is emitted when the on/off state of the toggle changes.
14459 * @param {File|null} value New value
14465 * Get the current value of the field
14467 * @return {File|null}
14469 OO
.ui
.SelectFileWidget
.prototype.getValue = function () {
14470 return this.currentFile
;
14474 * Set the current value of the field
14476 * @param {File|null} file File to select
14478 OO
.ui
.SelectFileWidget
.prototype.setValue = function ( file
) {
14479 if ( this.currentFile
!== file
) {
14480 this.currentFile
= file
;
14482 this.emit( 'change', this.currentFile
);
14487 * Focus the widget.
14489 * Focusses the select file button.
14493 OO
.ui
.SelectFileWidget
.prototype.focus = function () {
14494 this.selectButton
.$button
[ 0 ].focus();
14499 * Update the user interface when a file is selected or unselected
14503 OO
.ui
.SelectFileWidget
.prototype.updateUI = function () {
14505 if ( !this.isSupported
) {
14506 this.$element
.addClass( 'oo-ui-selectFileWidget-notsupported' );
14507 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
14508 this.setLabel( this.notsupported
);
14510 this.$element
.addClass( 'oo-ui-selectFileWidget-supported' );
14511 if ( this.currentFile
) {
14512 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
14514 if ( this.currentFile
.type
!== '' ) {
14515 $label
= $label
.add( $( '<span>' ).addClass( 'oo-ui-selectFileWidget-fileType' ).text( this.currentFile
.type
) );
14517 $label
= $label
.add( $( '<span>' ).text( this.currentFile
.name
) );
14518 this.setLabel( $label
);
14520 this.$element
.addClass( 'oo-ui-selectFileWidget-empty' );
14521 this.setLabel( this.placeholder
);
14527 * Add the input to the widget
14531 OO
.ui
.SelectFileWidget
.prototype.addInput = function () {
14532 if ( this.$input
) {
14533 this.$input
.remove();
14536 if ( !this.isSupported
) {
14537 this.$input
= null;
14541 this.$input
= $( '<input type="file">' );
14542 this.$input
.on( 'change', this.onFileSelectedHandler
);
14543 this.$input
.attr( {
14546 if ( this.accept
) {
14547 this.$input
.attr( 'accept', this.accept
.join( ', ' ) );
14549 this.selectButton
.$button
.append( this.$input
);
14553 * Determine if we should accept this file
14556 * @param {string} File MIME type
14557 * @return {boolean}
14559 OO
.ui
.SelectFileWidget
.prototype.isAllowedType = function ( mimeType
) {
14562 if ( !this.accept
|| !mimeType
) {
14566 for ( i
= 0; i
< this.accept
.length
; i
++ ) {
14567 mimeTest
= this.accept
[ i
];
14568 if ( mimeTest
=== mimeType
) {
14570 } else if ( mimeTest
.substr( -2 ) === '/*' ) {
14571 mimeTest
= mimeTest
.substr( 0, mimeTest
.length
- 1 );
14572 if ( mimeType
.substr( 0, mimeTest
.length
) === mimeTest
) {
14582 * Handle file selection from the input
14585 * @param {jQuery.Event} e
14587 OO
.ui
.SelectFileWidget
.prototype.onFileSelected = function ( e
) {
14588 var file
= OO
.getProp( e
.target
, 'files', 0 ) || null;
14590 if ( file
&& !this.isAllowedType( file
.type
) ) {
14594 this.setValue( file
);
14599 * Handle clear button click events.
14603 OO
.ui
.SelectFileWidget
.prototype.onClearClick = function () {
14604 this.setValue( null );
14609 * Handle key press events.
14612 * @param {jQuery.Event} e Key press event
14614 OO
.ui
.SelectFileWidget
.prototype.onKeyPress = function ( e
) {
14615 if ( this.isSupported
&& !this.isDisabled() && this.$input
&&
14616 ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
14618 this.$input
.click();
14624 * Handle drop target click events.
14627 * @param {jQuery.Event} e Key press event
14629 OO
.ui
.SelectFileWidget
.prototype.onDropTargetClick = function () {
14630 if ( this.isSupported
&& !this.isDisabled() && this.$input
) {
14631 this.$input
.click();
14637 * Handle drag enter and over events
14640 * @param {jQuery.Event} e Drag event
14642 OO
.ui
.SelectFileWidget
.prototype.onDragEnterOrOver = function ( e
) {
14644 droppableFile
= false,
14645 dt
= e
.originalEvent
.dataTransfer
;
14647 e
.preventDefault();
14648 e
.stopPropagation();
14650 if ( this.isDisabled() || !this.isSupported
) {
14651 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14652 dt
.dropEffect
= 'none';
14656 // DataTransferItem and File both have a type property, but in Chrome files
14657 // have no information at this point.
14658 itemOrFile
= OO
.getProp( dt
, 'items', 0 ) || OO
.getProp( dt
, 'files', 0 );
14659 if ( itemOrFile
) {
14660 if ( this.isAllowedType( itemOrFile
.type
) ) {
14661 droppableFile
= true;
14663 // dt.types is Array-like, but not an Array
14664 } else if ( Array
.prototype.indexOf
.call( OO
.getProp( dt
, 'types' ) || [], 'Files' ) !== -1 ) {
14665 // File information is not available at this point for security so just assume
14666 // it is acceptable for now.
14667 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
14668 droppableFile
= true;
14671 this.$element
.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile
);
14672 if ( !droppableFile
) {
14673 dt
.dropEffect
= 'none';
14680 * Handle drag leave events
14683 * @param {jQuery.Event} e Drag event
14685 OO
.ui
.SelectFileWidget
.prototype.onDragLeave = function () {
14686 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14690 * Handle drop events
14693 * @param {jQuery.Event} e Drop event
14695 OO
.ui
.SelectFileWidget
.prototype.onDrop = function ( e
) {
14697 dt
= e
.originalEvent
.dataTransfer
;
14699 e
.preventDefault();
14700 e
.stopPropagation();
14701 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14703 if ( this.isDisabled() || !this.isSupported
) {
14707 file
= OO
.getProp( dt
, 'files', 0 );
14708 if ( file
&& !this.isAllowedType( file
.type
) ) {
14712 this.setValue( file
);
14721 OO
.ui
.SelectFileWidget
.prototype.setDisabled = function ( disabled
) {
14722 OO
.ui
.SelectFileWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
14723 if ( this.selectButton
) {
14724 this.selectButton
.setDisabled( disabled
);
14726 if ( this.clearButton
) {
14727 this.clearButton
.setDisabled( disabled
);
14733 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
14734 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
14735 * for a list of icons included in the library.
14738 * // An icon widget with a label
14739 * var myIcon = new OO.ui.IconWidget( {
14741 * iconTitle: 'Help'
14743 * // Create a label.
14744 * var iconLabel = new OO.ui.LabelWidget( {
14747 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
14749 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
14752 * @extends OO.ui.Widget
14753 * @mixins OO.ui.mixin.IconElement
14754 * @mixins OO.ui.mixin.TitledElement
14755 * @mixins OO.ui.mixin.FlaggedElement
14758 * @param {Object} [config] Configuration options
14760 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
14761 // Configuration initialization
14762 config
= config
|| {};
14764 // Parent constructor
14765 OO
.ui
.IconWidget
.parent
.call( this, config
);
14767 // Mixin constructors
14768 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
14769 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
14770 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
14773 this.$element
.addClass( 'oo-ui-iconWidget' );
14778 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
14779 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
14780 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
14781 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
14783 /* Static Properties */
14785 OO
.ui
.IconWidget
.static.tagName
= 'span';
14788 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
14789 * attention to the status of an item or to clarify the function of a control. For a list of
14790 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
14793 * // Example of an indicator widget
14794 * var indicator1 = new OO.ui.IndicatorWidget( {
14795 * indicator: 'alert'
14798 * // Create a fieldset layout to add a label
14799 * var fieldset = new OO.ui.FieldsetLayout();
14800 * fieldset.addItems( [
14801 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
14803 * $( 'body' ).append( fieldset.$element );
14805 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
14808 * @extends OO.ui.Widget
14809 * @mixins OO.ui.mixin.IndicatorElement
14810 * @mixins OO.ui.mixin.TitledElement
14813 * @param {Object} [config] Configuration options
14815 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
14816 // Configuration initialization
14817 config
= config
|| {};
14819 // Parent constructor
14820 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
14822 // Mixin constructors
14823 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
14824 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
14827 this.$element
.addClass( 'oo-ui-indicatorWidget' );
14832 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
14833 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
14834 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
14836 /* Static Properties */
14838 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
14841 * InputWidget is the base class for all input widgets, which
14842 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
14843 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
14844 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14846 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14850 * @extends OO.ui.Widget
14851 * @mixins OO.ui.mixin.FlaggedElement
14852 * @mixins OO.ui.mixin.TabIndexedElement
14853 * @mixins OO.ui.mixin.TitledElement
14854 * @mixins OO.ui.mixin.AccessKeyedElement
14857 * @param {Object} [config] Configuration options
14858 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
14859 * @cfg {string} [value=''] The value of the input.
14860 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
14861 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
14862 * before it is accepted.
14864 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
14865 // Configuration initialization
14866 config
= config
|| {};
14868 // Parent constructor
14869 OO
.ui
.InputWidget
.parent
.call( this, config
);
14872 this.$input
= this.getInputElement( config
);
14874 this.inputFilter
= config
.inputFilter
;
14876 // Mixin constructors
14877 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
14878 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
14879 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
14880 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
14883 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
14887 .addClass( 'oo-ui-inputWidget-input' )
14888 .attr( 'name', config
.name
)
14889 .prop( 'disabled', this.isDisabled() );
14891 .addClass( 'oo-ui-inputWidget' )
14892 .append( this.$input
);
14893 this.setValue( config
.value
);
14894 this.setAccessKey( config
.accessKey
);
14895 if ( config
.dir
) {
14896 this.setDir( config
.dir
);
14902 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
14903 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
14904 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
14905 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
14906 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
14908 /* Static Properties */
14910 OO
.ui
.InputWidget
.static.supportsSimpleLabel
= true;
14912 /* Static Methods */
14917 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
14918 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
14919 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
14920 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
14927 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
14928 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
14929 state
.value
= config
.$input
.val();
14930 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14931 state
.focus
= config
.$input
.is( ':focus' );
14940 * A change event is emitted when the value of the input changes.
14942 * @param {string} value
14948 * Get input element.
14950 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14951 * different circumstances. The element must have a `value` property (like form elements).
14954 * @param {Object} config Configuration options
14955 * @return {jQuery} Input element
14957 OO
.ui
.InputWidget
.prototype.getInputElement = function ( config
) {
14958 // See #reusePreInfuseDOM about config.$input
14959 return config
.$input
|| $( '<input>' );
14963 * Handle potentially value-changing events.
14966 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14968 OO
.ui
.InputWidget
.prototype.onEdit = function () {
14970 if ( !this.isDisabled() ) {
14971 // Allow the stack to clear so the value will be updated
14972 setTimeout( function () {
14973 widget
.setValue( widget
.$input
.val() );
14979 * Get the value of the input.
14981 * @return {string} Input value
14983 OO
.ui
.InputWidget
.prototype.getValue = function () {
14984 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14985 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14986 var value
= this.$input
.val();
14987 if ( this.value
!== value
) {
14988 this.setValue( value
);
14994 * Set the directionality of the input, either RTL (right-to-left) or LTR (left-to-right).
14996 * @deprecated since v0.13.1, use #setDir directly
14997 * @param {boolean} isRTL Directionality is right-to-left
15000 OO
.ui
.InputWidget
.prototype.setRTL = function ( isRTL
) {
15001 this.setDir( isRTL
? 'rtl' : 'ltr' );
15006 * Set the directionality of the input.
15008 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
15011 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
15012 this.$input
.prop( 'dir', dir
);
15017 * Set the value of the input.
15019 * @param {string} value New value
15023 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
15024 value
= this.cleanUpValue( value
);
15025 // Update the DOM if it has changed. Note that with cleanUpValue, it
15026 // is possible for the DOM value to change without this.value changing.
15027 if ( this.$input
.val() !== value
) {
15028 this.$input
.val( value
);
15030 if ( this.value
!== value
) {
15031 this.value
= value
;
15032 this.emit( 'change', this.value
);
15038 * Set the input's access key.
15039 * FIXME: This is the same code as in OO.ui.mixin.ButtonElement, maybe find a better place for it?
15041 * @param {string} accessKey Input's access key, use empty string to remove
15044 OO
.ui
.InputWidget
.prototype.setAccessKey = function ( accessKey
) {
15045 accessKey
= typeof accessKey
=== 'string' && accessKey
.length
? accessKey
: null;
15047 if ( this.accessKey
!== accessKey
) {
15048 if ( this.$input
) {
15049 if ( accessKey
!== null ) {
15050 this.$input
.attr( 'accesskey', accessKey
);
15052 this.$input
.removeAttr( 'accesskey' );
15055 this.accessKey
= accessKey
;
15062 * Clean up incoming value.
15064 * Ensures value is a string, and converts undefined and null to empty string.
15067 * @param {string} value Original value
15068 * @return {string} Cleaned up value
15070 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
15071 if ( value
=== undefined || value
=== null ) {
15073 } else if ( this.inputFilter
) {
15074 return this.inputFilter( String( value
) );
15076 return String( value
);
15081 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
15082 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
15085 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
15086 if ( !this.isDisabled() ) {
15087 if ( this.$input
.is( ':checkbox, :radio' ) ) {
15088 this.$input
.click();
15090 if ( this.$input
.is( ':input' ) ) {
15091 this.$input
[ 0 ].focus();
15099 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
15100 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
15101 if ( this.$input
) {
15102 this.$input
.prop( 'disabled', this.isDisabled() );
15112 OO
.ui
.InputWidget
.prototype.focus = function () {
15113 this.$input
[ 0 ].focus();
15122 OO
.ui
.InputWidget
.prototype.blur = function () {
15123 this.$input
[ 0 ].blur();
15130 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
15131 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
15132 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
15133 this.setValue( state
.value
);
15135 if ( state
.focus
) {
15141 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
15142 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
15143 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
15144 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
15145 * [OOjs UI documentation on MediaWiki] [1] for more information.
15148 * // A ButtonInputWidget rendered as an HTML button, the default.
15149 * var button = new OO.ui.ButtonInputWidget( {
15150 * label: 'Input button',
15154 * $( 'body' ).append( button.$element );
15156 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
15159 * @extends OO.ui.InputWidget
15160 * @mixins OO.ui.mixin.ButtonElement
15161 * @mixins OO.ui.mixin.IconElement
15162 * @mixins OO.ui.mixin.IndicatorElement
15163 * @mixins OO.ui.mixin.LabelElement
15164 * @mixins OO.ui.mixin.TitledElement
15167 * @param {Object} [config] Configuration options
15168 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
15169 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
15170 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
15171 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
15172 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
15174 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
15175 // Configuration initialization
15176 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
15178 // Properties (must be set before parent constructor, which calls #setValue)
15179 this.useInputTag
= config
.useInputTag
;
15181 // Parent constructor
15182 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
15184 // Mixin constructors
15185 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
15186 OO
.ui
.mixin
.IconElement
.call( this, config
);
15187 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
15188 OO
.ui
.mixin
.LabelElement
.call( this, config
);
15189 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
15192 if ( !config
.useInputTag
) {
15193 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
15195 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
15200 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
15201 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
15202 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
15203 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
15204 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
15205 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
15207 /* Static Properties */
15210 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
15211 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
15213 OO
.ui
.ButtonInputWidget
.static.supportsSimpleLabel
= false;
15221 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
15223 // See InputWidget#reusePreInfuseDOM about config.$input
15224 if ( config
.$input
) {
15225 return config
.$input
.empty();
15227 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
15228 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
15234 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
15236 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
15237 * text, or `null` for no label
15240 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
15241 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
15243 if ( this.useInputTag
) {
15244 if ( typeof label
=== 'function' ) {
15245 label
= OO
.ui
.resolveMsg( label
);
15247 if ( label
instanceof jQuery
) {
15248 label
= label
.text();
15253 this.$input
.val( label
);
15260 * Set the value of the input.
15262 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
15263 * they do not support {@link #value values}.
15265 * @param {string} value New value
15268 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
15269 if ( !this.useInputTag
) {
15270 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
15276 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
15277 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
15278 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
15279 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
15281 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15284 * // An example of selected, unselected, and disabled checkbox inputs
15285 * var checkbox1=new OO.ui.CheckboxInputWidget( {
15289 * var checkbox2=new OO.ui.CheckboxInputWidget( {
15292 * var checkbox3=new OO.ui.CheckboxInputWidget( {
15296 * // Create a fieldset layout with fields for each checkbox.
15297 * var fieldset = new OO.ui.FieldsetLayout( {
15298 * label: 'Checkboxes'
15300 * fieldset.addItems( [
15301 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
15302 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
15303 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
15305 * $( 'body' ).append( fieldset.$element );
15307 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15310 * @extends OO.ui.InputWidget
15313 * @param {Object} [config] Configuration options
15314 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
15316 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
15317 // Configuration initialization
15318 config
= config
|| {};
15320 // Parent constructor
15321 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
15325 .addClass( 'oo-ui-checkboxInputWidget' )
15326 // Required for pretty styling in MediaWiki theme
15327 .append( $( '<span>' ) );
15328 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
15333 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
15335 /* Static Methods */
15340 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
15341 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
15342 state
.checked
= config
.$input
.prop( 'checked' );
15352 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
15353 return $( '<input type="checkbox" />' );
15359 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
15361 if ( !this.isDisabled() ) {
15362 // Allow the stack to clear so the value will be updated
15363 setTimeout( function () {
15364 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
15370 * Set selection state of this checkbox.
15372 * @param {boolean} state `true` for selected
15375 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
15377 if ( this.selected
!== state
) {
15378 this.selected
= state
;
15379 this.$input
.prop( 'checked', this.selected
);
15380 this.emit( 'change', this.selected
);
15386 * Check if this checkbox is selected.
15388 * @return {boolean} Checkbox is selected
15390 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
15391 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
15392 // it, and we won't know unless they're kind enough to trigger a 'change' event.
15393 var selected
= this.$input
.prop( 'checked' );
15394 if ( this.selected
!== selected
) {
15395 this.setSelected( selected
);
15397 return this.selected
;
15403 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
15404 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
15405 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
15406 this.setSelected( state
.checked
);
15411 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
15412 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15413 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15414 * more information about input widgets.
15416 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
15417 * are no options. If no `value` configuration option is provided, the first option is selected.
15418 * If you need a state representing no value (no option being selected), use a DropdownWidget.
15420 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
15423 * // Example: A DropdownInputWidget with three options
15424 * var dropdownInput = new OO.ui.DropdownInputWidget( {
15426 * { data: 'a', label: 'First' },
15427 * { data: 'b', label: 'Second'},
15428 * { data: 'c', label: 'Third' }
15431 * $( 'body' ).append( dropdownInput.$element );
15433 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15436 * @extends OO.ui.InputWidget
15437 * @mixins OO.ui.mixin.TitledElement
15440 * @param {Object} [config] Configuration options
15441 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15442 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
15444 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
15445 // Configuration initialization
15446 config
= config
|| {};
15448 // Properties (must be done before parent constructor which calls #setDisabled)
15449 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
15451 // Parent constructor
15452 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
15454 // Mixin constructors
15455 OO
.ui
.mixin
.TitledElement
.call( this, config
);
15458 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
15461 this.setOptions( config
.options
|| [] );
15463 .addClass( 'oo-ui-dropdownInputWidget' )
15464 .append( this.dropdownWidget
.$element
);
15469 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
15470 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
15478 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function ( config
) {
15479 // See InputWidget#reusePreInfuseDOM about config.$input
15480 if ( config
.$input
) {
15481 return config
.$input
.addClass( 'oo-ui-element-hidden' );
15483 return $( '<input type="hidden">' );
15487 * Handles menu select events.
15490 * @param {OO.ui.MenuOptionWidget} item Selected menu item
15492 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
15493 this.setValue( item
.getData() );
15499 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
15500 value
= this.cleanUpValue( value
);
15501 this.dropdownWidget
.getMenu().selectItemByData( value
);
15502 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
15509 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
15510 this.dropdownWidget
.setDisabled( state
);
15511 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
15516 * Set the options available for this input.
15518 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15521 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
15523 value
= this.getValue(),
15526 // Rebuild the dropdown menu
15527 this.dropdownWidget
.getMenu()
15529 .addItems( options
.map( function ( opt
) {
15530 var optValue
= widget
.cleanUpValue( opt
.data
);
15531 return new OO
.ui
.MenuOptionWidget( {
15533 label
: opt
.label
!== undefined ? opt
.label
: optValue
15537 // Restore the previous value, or reset to something sensible
15538 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
15539 // Previous value is still available, ensure consistency with the dropdown
15540 this.setValue( value
);
15542 // No longer valid, reset
15543 if ( options
.length
) {
15544 this.setValue( options
[ 0 ].data
);
15554 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
15555 this.dropdownWidget
.getMenu().toggle( true );
15562 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
15563 this.dropdownWidget
.getMenu().toggle( false );
15568 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
15569 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
15570 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
15571 * please see the [OOjs UI documentation on MediaWiki][1].
15573 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15576 * // An example of selected, unselected, and disabled radio inputs
15577 * var radio1 = new OO.ui.RadioInputWidget( {
15581 * var radio2 = new OO.ui.RadioInputWidget( {
15584 * var radio3 = new OO.ui.RadioInputWidget( {
15588 * // Create a fieldset layout with fields for each radio button.
15589 * var fieldset = new OO.ui.FieldsetLayout( {
15590 * label: 'Radio inputs'
15592 * fieldset.addItems( [
15593 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
15594 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
15595 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
15597 * $( 'body' ).append( fieldset.$element );
15599 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15602 * @extends OO.ui.InputWidget
15605 * @param {Object} [config] Configuration options
15606 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
15608 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
15609 // Configuration initialization
15610 config
= config
|| {};
15612 // Parent constructor
15613 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
15617 .addClass( 'oo-ui-radioInputWidget' )
15618 // Required for pretty styling in MediaWiki theme
15619 .append( $( '<span>' ) );
15620 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
15625 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
15627 /* Static Methods */
15632 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
15633 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
15634 state
.checked
= config
.$input
.prop( 'checked' );
15644 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
15645 return $( '<input type="radio" />' );
15651 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
15652 // RadioInputWidget doesn't track its state.
15656 * Set selection state of this radio button.
15658 * @param {boolean} state `true` for selected
15661 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
15662 // RadioInputWidget doesn't track its state.
15663 this.$input
.prop( 'checked', state
);
15668 * Check if this radio button is selected.
15670 * @return {boolean} Radio is selected
15672 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
15673 return this.$input
.prop( 'checked' );
15679 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
15680 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
15681 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
15682 this.setSelected( state
.checked
);
15687 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
15688 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15689 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15690 * more information about input widgets.
15692 * This and OO.ui.DropdownInputWidget support the same configuration options.
15695 * // Example: A RadioSelectInputWidget with three options
15696 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
15698 * { data: 'a', label: 'First' },
15699 * { data: 'b', label: 'Second'},
15700 * { data: 'c', label: 'Third' }
15703 * $( 'body' ).append( radioSelectInput.$element );
15705 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15708 * @extends OO.ui.InputWidget
15711 * @param {Object} [config] Configuration options
15712 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15714 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
15715 // Configuration initialization
15716 config
= config
|| {};
15718 // Properties (must be done before parent constructor which calls #setDisabled)
15719 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
15721 // Parent constructor
15722 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
15725 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
15728 this.setOptions( config
.options
|| [] );
15730 .addClass( 'oo-ui-radioSelectInputWidget' )
15731 .append( this.radioSelectWidget
.$element
);
15736 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
15738 /* Static Properties */
15740 OO
.ui
.RadioSelectInputWidget
.static.supportsSimpleLabel
= false;
15742 /* Static Methods */
15747 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
15748 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
15749 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
15759 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
15760 return $( '<input type="hidden">' );
15764 * Handles menu select events.
15767 * @param {OO.ui.RadioOptionWidget} item Selected menu item
15769 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
15770 this.setValue( item
.getData() );
15776 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
15777 value
= this.cleanUpValue( value
);
15778 this.radioSelectWidget
.selectItemByData( value
);
15779 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
15786 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
15787 this.radioSelectWidget
.setDisabled( state
);
15788 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
15793 * Set the options available for this input.
15795 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15798 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
15800 value
= this.getValue(),
15803 // Rebuild the radioSelect menu
15804 this.radioSelectWidget
15806 .addItems( options
.map( function ( opt
) {
15807 var optValue
= widget
.cleanUpValue( opt
.data
);
15808 return new OO
.ui
.RadioOptionWidget( {
15810 label
: opt
.label
!== undefined ? opt
.label
: optValue
15814 // Restore the previous value, or reset to something sensible
15815 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
15816 // Previous value is still available, ensure consistency with the radioSelect
15817 this.setValue( value
);
15819 // No longer valid, reset
15820 if ( options
.length
) {
15821 this.setValue( options
[ 0 ].data
);
15829 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
15830 * size of the field as well as its presentation. In addition, these widgets can be configured
15831 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
15832 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
15833 * which modifies incoming values rather than validating them.
15834 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
15836 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15839 * // Example of a text input widget
15840 * var textInput = new OO.ui.TextInputWidget( {
15841 * value: 'Text input'
15843 * $( 'body' ).append( textInput.$element );
15845 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15848 * @extends OO.ui.InputWidget
15849 * @mixins OO.ui.mixin.IconElement
15850 * @mixins OO.ui.mixin.IndicatorElement
15851 * @mixins OO.ui.mixin.PendingElement
15852 * @mixins OO.ui.mixin.LabelElement
15855 * @param {Object} [config] Configuration options
15856 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
15857 * 'email' or 'url'. Ignored if `multiline` is true.
15859 * Some values of `type` result in additional behaviors:
15861 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
15862 * empties the text field
15863 * @cfg {string} [placeholder] Placeholder text
15864 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
15865 * instruct the browser to focus this widget.
15866 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
15867 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
15868 * @cfg {boolean} [multiline=false] Allow multiple lines of text
15869 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
15870 * specifies minimum number of rows to display.
15871 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
15872 * Use the #maxRows config to specify a maximum number of displayed rows.
15873 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
15874 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
15875 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
15876 * the value or placeholder text: `'before'` or `'after'`
15877 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
15878 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
15879 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
15880 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
15881 * (the value must contain only numbers); when RegExp, a regular expression that must match the
15882 * value for it to be considered valid; when Function, a function receiving the value as parameter
15883 * that must return true, or promise resolving to true, for it to be considered valid.
15885 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
15886 // Configuration initialization
15887 config
= $.extend( {
15889 labelPosition
: 'after'
15891 if ( config
.type
=== 'search' ) {
15892 if ( config
.icon
=== undefined ) {
15893 config
.icon
= 'search';
15895 // indicator: 'clear' is set dynamically later, depending on value
15897 if ( config
.required
) {
15898 if ( config
.indicator
=== undefined ) {
15899 config
.indicator
= 'required';
15903 // Parent constructor
15904 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
15906 // Mixin constructors
15907 OO
.ui
.mixin
.IconElement
.call( this, config
);
15908 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
15909 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
15910 OO
.ui
.mixin
.LabelElement
.call( this, config
);
15913 this.type
= this.getSaneType( config
);
15914 this.readOnly
= false;
15915 this.multiline
= !!config
.multiline
;
15916 this.autosize
= !!config
.autosize
;
15917 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
15918 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
15919 this.validate
= null;
15920 this.styleHeight
= null;
15921 this.scrollWidth
= null;
15923 // Clone for resizing
15924 if ( this.autosize
) {
15925 this.$clone
= this.$input
15927 .insertAfter( this.$input
)
15928 .attr( 'aria-hidden', 'true' )
15929 .addClass( 'oo-ui-element-hidden' );
15932 this.setValidation( config
.validate
);
15933 this.setLabelPosition( config
.labelPosition
);
15937 keypress
: this.onKeyPress
.bind( this ),
15938 blur
: this.onBlur
.bind( this )
15941 focus
: this.onElementAttach
.bind( this )
15943 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
15944 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
15945 this.on( 'labelChange', this.updatePosition
.bind( this ) );
15946 this.connect( this, {
15947 change
: 'onChange',
15948 disable
: 'onDisable'
15953 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
15954 .append( this.$icon
, this.$indicator
);
15955 this.setReadOnly( !!config
.readOnly
);
15956 this.updateSearchIndicator();
15957 if ( config
.placeholder
) {
15958 this.$input
.attr( 'placeholder', config
.placeholder
);
15960 if ( config
.maxLength
!== undefined ) {
15961 this.$input
.attr( 'maxlength', config
.maxLength
);
15963 if ( config
.autofocus
) {
15964 this.$input
.attr( 'autofocus', 'autofocus' );
15966 if ( config
.required
) {
15967 this.$input
.attr( 'required', 'required' );
15968 this.$input
.attr( 'aria-required', 'true' );
15970 if ( config
.autocomplete
=== false ) {
15971 this.$input
.attr( 'autocomplete', 'off' );
15972 // Turning off autocompletion also disables "form caching" when the user navigates to a
15973 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
15975 beforeunload: function () {
15976 this.$input
.removeAttr( 'autocomplete' );
15978 pageshow: function () {
15979 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
15980 // whole page... it shouldn't hurt, though.
15981 this.$input
.attr( 'autocomplete', 'off' );
15985 if ( this.multiline
&& config
.rows
) {
15986 this.$input
.attr( 'rows', config
.rows
);
15988 if ( this.label
|| config
.autosize
) {
15989 this.installParentChangeDetector();
15995 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
15996 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
15997 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
15998 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
15999 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
16001 /* Static Properties */
16003 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
16008 /* Static Methods */
16013 OO
.ui
.TextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
16014 var state
= OO
.ui
.TextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
16015 if ( config
.multiline
) {
16016 state
.scrollTop
= config
.$input
.scrollTop();
16024 * An `enter` event is emitted when the user presses 'enter' inside the text box.
16026 * Not emitted if the input is multiline.
16032 * A `resize` event is emitted when autosize is set and the widget resizes
16040 * Handle icon mouse down events.
16043 * @param {jQuery.Event} e Mouse down event
16046 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
16047 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
16048 this.$input
[ 0 ].focus();
16054 * Handle indicator mouse down events.
16057 * @param {jQuery.Event} e Mouse down event
16060 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
16061 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
16062 if ( this.type
=== 'search' ) {
16063 // Clear the text field
16064 this.setValue( '' );
16066 this.$input
[ 0 ].focus();
16072 * Handle key press events.
16075 * @param {jQuery.Event} e Key press event
16076 * @fires enter If enter key is pressed and input is not multiline
16078 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
16079 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
16080 this.emit( 'enter', e
);
16085 * Handle blur events.
16088 * @param {jQuery.Event} e Blur event
16090 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
16091 this.setValidityFlag();
16095 * Handle element attach events.
16098 * @param {jQuery.Event} e Element attach event
16100 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
16101 // Any previously calculated size is now probably invalid if we reattached elsewhere
16102 this.valCache
= null;
16104 this.positionLabel();
16108 * Handle change events.
16110 * @param {string} value
16113 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
16114 this.updateSearchIndicator();
16115 this.setValidityFlag();
16120 * Handle disable events.
16122 * @param {boolean} disabled Element is disabled
16125 OO
.ui
.TextInputWidget
.prototype.onDisable = function () {
16126 this.updateSearchIndicator();
16130 * Check if the input is {@link #readOnly read-only}.
16132 * @return {boolean}
16134 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
16135 return this.readOnly
;
16139 * Set the {@link #readOnly read-only} state of the input.
16141 * @param {boolean} state Make input read-only
16144 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
16145 this.readOnly
= !!state
;
16146 this.$input
.prop( 'readOnly', this.readOnly
);
16147 this.updateSearchIndicator();
16152 * Support function for making #onElementAttach work across browsers.
16154 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
16155 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
16157 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
16158 * first time that the element gets attached to the documented.
16160 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
16161 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
16162 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
16165 if ( MutationObserver
) {
16166 // The new way. If only it wasn't so ugly.
16168 if ( this.$element
.closest( 'html' ).length
) {
16169 // Widget is attached already, do nothing. This breaks the functionality of this function when
16170 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
16171 // would require observation of the whole document, which would hurt performance of other,
16172 // more important code.
16176 // Find topmost node in the tree
16177 topmostNode
= this.$element
[ 0 ];
16178 while ( topmostNode
.parentNode
) {
16179 topmostNode
= topmostNode
.parentNode
;
16182 // We have no way to detect the $element being attached somewhere without observing the entire
16183 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
16184 // parent node of $element, and instead detect when $element is removed from it (and thus
16185 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
16186 // doesn't get attached, we end up back here and create the parent.
16188 mutationObserver
= new MutationObserver( function ( mutations
) {
16189 var i
, j
, removedNodes
;
16190 for ( i
= 0; i
< mutations
.length
; i
++ ) {
16191 removedNodes
= mutations
[ i
].removedNodes
;
16192 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
16193 if ( removedNodes
[ j
] === topmostNode
) {
16194 setTimeout( onRemove
, 0 );
16201 onRemove = function () {
16202 // If the node was attached somewhere else, report it
16203 if ( widget
.$element
.closest( 'html' ).length
) {
16204 widget
.onElementAttach();
16206 mutationObserver
.disconnect();
16207 widget
.installParentChangeDetector();
16210 // Create a fake parent and observe it
16211 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
16212 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
16214 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
16215 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
16216 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
16221 * Automatically adjust the size of the text input.
16223 * This only affects #multiline inputs that are {@link #autosize autosized}.
16228 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
16229 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
16230 idealHeight
, newHeight
, scrollWidth
, property
;
16232 if ( this.multiline
&& this.$input
.val() !== this.valCache
) {
16233 if ( this.autosize
) {
16235 .val( this.$input
.val() )
16236 .attr( 'rows', this.minRows
)
16237 // Set inline height property to 0 to measure scroll height
16238 .css( 'height', 0 );
16240 this.$clone
.removeClass( 'oo-ui-element-hidden' );
16242 this.valCache
= this.$input
.val();
16244 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
16246 // Remove inline height property to measure natural heights
16247 this.$clone
.css( 'height', '' );
16248 innerHeight
= this.$clone
.innerHeight();
16249 outerHeight
= this.$clone
.outerHeight();
16251 // Measure max rows height
16253 .attr( 'rows', this.maxRows
)
16254 .css( 'height', 'auto' )
16256 maxInnerHeight
= this.$clone
.innerHeight();
16258 // Difference between reported innerHeight and scrollHeight with no scrollbars present
16259 // Equals 1 on Blink-based browsers and 0 everywhere else
16260 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
16261 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
16263 this.$clone
.addClass( 'oo-ui-element-hidden' );
16265 // Only apply inline height when expansion beyond natural height is needed
16266 // Use the difference between the inner and outer height as a buffer
16267 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
16268 if ( newHeight
!== this.styleHeight
) {
16269 this.$input
.css( 'height', newHeight
);
16270 this.styleHeight
= newHeight
;
16271 this.emit( 'resize' );
16274 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
16275 if ( scrollWidth
!== this.scrollWidth
) {
16276 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
16278 this.$label
.css( { right
: '', left
: '' } );
16279 this.$indicator
.css( { right
: '', left
: '' } );
16281 if ( scrollWidth
) {
16282 this.$indicator
.css( property
, scrollWidth
);
16283 if ( this.labelPosition
=== 'after' ) {
16284 this.$label
.css( property
, scrollWidth
);
16288 this.scrollWidth
= scrollWidth
;
16289 this.positionLabel();
16299 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
16300 return config
.multiline
?
16301 $( '<textarea>' ) :
16302 $( '<input type="' + this.getSaneType( config
) + '" />' );
16306 * Get sanitized value for 'type' for given config.
16308 * @param {Object} config Configuration options
16309 * @return {string|null}
16312 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
16313 var type
= [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config
.type
) !== -1 ?
16316 return config
.multiline
? 'multiline' : type
;
16320 * Check if the input supports multiple lines.
16322 * @return {boolean}
16324 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
16325 return !!this.multiline
;
16329 * Check if the input automatically adjusts its size.
16331 * @return {boolean}
16333 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
16334 return !!this.autosize
;
16338 * Focus the input and select a specified range within the text.
16340 * @param {number} from Select from offset
16341 * @param {number} [to] Select to offset, defaults to from
16344 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
16345 var isBackwards
, start
, end
,
16346 input
= this.$input
[ 0 ];
16350 isBackwards
= to
< from;
16351 start
= isBackwards
? to
: from;
16352 end
= isBackwards
? from : to
;
16356 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
16361 * Get an object describing the current selection range in a directional manner
16363 * @return {Object} Object containing 'from' and 'to' offsets
16365 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
16366 var input
= this.$input
[ 0 ],
16367 start
= input
.selectionStart
,
16368 end
= input
.selectionEnd
,
16369 isBackwards
= input
.selectionDirection
=== 'backward';
16372 from: isBackwards
? end
: start
,
16373 to
: isBackwards
? start
: end
16378 * Get the length of the text input value.
16380 * This could differ from the length of #getValue if the
16381 * value gets filtered
16383 * @return {number} Input length
16385 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
16386 return this.$input
[ 0 ].value
.length
;
16390 * Focus the input and select the entire text.
16394 OO
.ui
.TextInputWidget
.prototype.select = function () {
16395 return this.selectRange( 0, this.getInputLength() );
16399 * Focus the input and move the cursor to the start.
16403 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
16404 return this.selectRange( 0 );
16408 * Focus the input and move the cursor to the end.
16412 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
16413 return this.selectRange( this.getInputLength() );
16417 * Insert new content into the input.
16419 * @param {string} content Content to be inserted
16422 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
16424 range
= this.getRange(),
16425 value
= this.getValue();
16427 start
= Math
.min( range
.from, range
.to
);
16428 end
= Math
.max( range
.from, range
.to
);
16430 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
16431 this.selectRange( start
+ content
.length
);
16436 * Insert new content either side of a selection.
16438 * @param {string} pre Content to be inserted before the selection
16439 * @param {string} post Content to be inserted after the selection
16442 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
16444 range
= this.getRange(),
16445 offset
= pre
.length
;
16447 start
= Math
.min( range
.from, range
.to
);
16448 end
= Math
.max( range
.from, range
.to
);
16450 this.selectRange( start
).insertContent( pre
);
16451 this.selectRange( offset
+ end
).insertContent( post
);
16453 this.selectRange( offset
+ start
, offset
+ end
);
16458 * Set the validation pattern.
16460 * The validation pattern is either a regular expression, a function, or the symbolic name of a
16461 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
16462 * value must contain only numbers).
16464 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
16465 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
16467 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
16468 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
16469 this.validate
= validate
;
16471 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
16476 * Sets the 'invalid' flag appropriately.
16478 * @param {boolean} [isValid] Optionally override validation result
16480 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
16482 setFlag = function ( valid
) {
16484 widget
.$input
.attr( 'aria-invalid', 'true' );
16486 widget
.$input
.removeAttr( 'aria-invalid' );
16488 widget
.setFlags( { invalid
: !valid
} );
16491 if ( isValid
!== undefined ) {
16492 setFlag( isValid
);
16494 this.getValidity().then( function () {
16503 * Check if a value is valid.
16505 * This method returns a promise that resolves with a boolean `true` if the current value is
16506 * considered valid according to the supplied {@link #validate validation pattern}.
16509 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
16511 OO
.ui
.TextInputWidget
.prototype.isValid = function () {
16514 if ( this.validate
instanceof Function
) {
16515 result
= this.validate( this.getValue() );
16516 if ( $.isFunction( result
.promise
) ) {
16517 return result
.promise();
16519 return $.Deferred().resolve( !!result
).promise();
16522 return $.Deferred().resolve( !!this.getValue().match( this.validate
) ).promise();
16527 * Get the validity of current value.
16529 * This method returns a promise that resolves if the value is valid and rejects if
16530 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
16532 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
16534 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
16535 var result
, promise
;
16537 function rejectOrResolve( valid
) {
16539 return $.Deferred().resolve().promise();
16541 return $.Deferred().reject().promise();
16545 if ( this.validate
instanceof Function
) {
16546 result
= this.validate( this.getValue() );
16548 if ( $.isFunction( result
.promise
) ) {
16549 promise
= $.Deferred();
16551 result
.then( function ( valid
) {
16561 return promise
.promise();
16563 return rejectOrResolve( result
);
16566 return rejectOrResolve( this.getValue().match( this.validate
) );
16571 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
16573 * @param {string} labelPosition Label position, 'before' or 'after'
16576 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
16577 this.labelPosition
= labelPosition
;
16578 this.updatePosition();
16583 * Update the position of the inline label.
16585 * This method is called by #setLabelPosition, and can also be called on its own if
16586 * something causes the label to be mispositioned.
16590 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
16591 var after
= this.labelPosition
=== 'after';
16594 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
16595 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
16597 this.valCache
= null;
16598 this.scrollWidth
= null;
16600 this.positionLabel();
16606 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
16607 * already empty or when it's not editable.
16609 OO
.ui
.TextInputWidget
.prototype.updateSearchIndicator = function () {
16610 if ( this.type
=== 'search' ) {
16611 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
16612 this.setIndicator( null );
16614 this.setIndicator( 'clear' );
16620 * Position the label by setting the correct padding on the input.
16625 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
16626 var after
, rtl
, property
;
16627 // Clear old values
16629 // Clear old values if present
16631 'padding-right': '',
16635 if ( this.label
) {
16636 this.$element
.append( this.$label
);
16638 this.$label
.detach();
16642 after
= this.labelPosition
=== 'after';
16643 rtl
= this.$element
.css( 'direction' ) === 'rtl';
16644 property
= after
=== rtl
? 'padding-left' : 'padding-right';
16646 this.$input
.css( property
, this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 ) );
16654 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
16655 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
16656 if ( state
.scrollTop
!== undefined ) {
16657 this.$input
.scrollTop( state
.scrollTop
);
16662 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
16663 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
16664 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
16666 * - by typing a value in the text input field. If the value exactly matches the value of a menu
16667 * option, that option will appear to be selected.
16668 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
16671 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
16673 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
16676 * // Example: A ComboBoxInputWidget.
16677 * var comboBox = new OO.ui.ComboBoxInputWidget( {
16678 * label: 'ComboBoxInputWidget',
16679 * value: 'Option 1',
16682 * new OO.ui.MenuOptionWidget( {
16683 * data: 'Option 1',
16684 * label: 'Option One'
16686 * new OO.ui.MenuOptionWidget( {
16687 * data: 'Option 2',
16688 * label: 'Option Two'
16690 * new OO.ui.MenuOptionWidget( {
16691 * data: 'Option 3',
16692 * label: 'Option Three'
16694 * new OO.ui.MenuOptionWidget( {
16695 * data: 'Option 4',
16696 * label: 'Option Four'
16698 * new OO.ui.MenuOptionWidget( {
16699 * data: 'Option 5',
16700 * label: 'Option Five'
16705 * $( 'body' ).append( comboBox.$element );
16707 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16710 * @extends OO.ui.TextInputWidget
16713 * @param {Object} [config] Configuration options
16714 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
16715 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
16716 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
16717 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
16718 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
16720 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
16721 // Configuration initialization
16722 config
= $.extend( {
16725 // For backwards-compatibility with ComboBoxWidget config
16726 $.extend( config
, config
.input
);
16728 // Parent constructor
16729 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
16732 this.$overlay
= config
.$overlay
|| this.$element
;
16733 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
16737 $container
: this.$element
,
16738 disabled
: this.isDisabled()
16742 // For backwards-compatibility with ComboBoxWidget
16746 this.$indicator
.on( {
16747 click
: this.onIndicatorClick
.bind( this ),
16748 keypress
: this.onIndicatorKeyPress
.bind( this )
16750 this.connect( this, {
16751 change
: 'onInputChange',
16752 enter
: 'onInputEnter'
16754 this.menu
.connect( this, {
16755 choose
: 'onMenuChoose',
16756 add
: 'onMenuItemsChange',
16757 remove
: 'onMenuItemsChange'
16761 this.$input
.attr( {
16763 'aria-autocomplete': 'list'
16765 // Do not override options set via config.menu.items
16766 if ( config
.options
!== undefined ) {
16767 this.setOptions( config
.options
);
16769 // Extra class for backwards-compatibility with ComboBoxWidget
16770 this.$element
.addClass( 'oo-ui-comboBoxInputWidget oo-ui-comboBoxWidget' );
16771 this.$overlay
.append( this.menu
.$element
);
16772 this.onMenuItemsChange();
16777 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
16782 * Get the combobox's menu.
16783 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
16785 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
16790 * Get the combobox's text input widget.
16791 * @return {OO.ui.TextInputWidget} Text input widget
16793 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
16798 * Handle input change events.
16801 * @param {string} value New value
16803 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
16804 var match
= this.menu
.getItemFromData( value
);
16806 this.menu
.selectItem( match
);
16807 if ( this.menu
.getHighlightedItem() ) {
16808 this.menu
.highlightItem( match
);
16811 if ( !this.isDisabled() ) {
16812 this.menu
.toggle( true );
16817 * Handle mouse click events.
16820 * @param {jQuery.Event} e Mouse click event
16822 OO
.ui
.ComboBoxInputWidget
.prototype.onIndicatorClick = function ( e
) {
16823 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
16824 this.menu
.toggle();
16825 this.$input
[ 0 ].focus();
16831 * Handle key press events.
16834 * @param {jQuery.Event} e Key press event
16836 OO
.ui
.ComboBoxInputWidget
.prototype.onIndicatorKeyPress = function ( e
) {
16837 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
16838 this.menu
.toggle();
16839 this.$input
[ 0 ].focus();
16845 * Handle input enter events.
16849 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
16850 if ( !this.isDisabled() ) {
16851 this.menu
.toggle( false );
16856 * Handle menu choose events.
16859 * @param {OO.ui.OptionWidget} item Chosen item
16861 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
16862 this.setValue( item
.getData() );
16866 * Handle menu item change events.
16870 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
16871 var match
= this.menu
.getItemFromData( this.getValue() );
16872 this.menu
.selectItem( match
);
16873 if ( this.menu
.getHighlightedItem() ) {
16874 this.menu
.highlightItem( match
);
16876 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
16882 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function ( disabled
) {
16884 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
16887 this.menu
.setDisabled( this.isDisabled() );
16894 * Set the options available for this input.
16896 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
16899 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
16902 .addItems( options
.map( function ( opt
) {
16903 return new OO
.ui
.MenuOptionWidget( {
16905 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
16914 * @deprecated Use OO.ui.ComboBoxInputWidget instead.
16916 OO
.ui
.ComboBoxWidget
= OO
.ui
.ComboBoxInputWidget
;
16919 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
16920 * be configured with a `label` option that is set to a string, a label node, or a function:
16922 * - String: a plaintext string
16923 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
16924 * label that includes a link or special styling, such as a gray color or additional graphical elements.
16925 * - Function: a function that will produce a string in the future. Functions are used
16926 * in cases where the value of the label is not currently defined.
16928 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
16929 * will come into focus when the label is clicked.
16932 * // Examples of LabelWidgets
16933 * var label1 = new OO.ui.LabelWidget( {
16934 * label: 'plaintext label'
16936 * var label2 = new OO.ui.LabelWidget( {
16937 * label: $( '<a href="default.html">jQuery label</a>' )
16939 * // Create a fieldset layout with fields for each example
16940 * var fieldset = new OO.ui.FieldsetLayout();
16941 * fieldset.addItems( [
16942 * new OO.ui.FieldLayout( label1 ),
16943 * new OO.ui.FieldLayout( label2 )
16945 * $( 'body' ).append( fieldset.$element );
16948 * @extends OO.ui.Widget
16949 * @mixins OO.ui.mixin.LabelElement
16952 * @param {Object} [config] Configuration options
16953 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
16954 * Clicking the label will focus the specified input field.
16956 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
16957 // Configuration initialization
16958 config
= config
|| {};
16960 // Parent constructor
16961 OO
.ui
.LabelWidget
.parent
.call( this, config
);
16963 // Mixin constructors
16964 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
16965 OO
.ui
.mixin
.TitledElement
.call( this, config
);
16968 this.input
= config
.input
;
16971 if ( this.input
instanceof OO
.ui
.InputWidget
) {
16972 this.$element
.on( 'click', this.onClick
.bind( this ) );
16976 this.$element
.addClass( 'oo-ui-labelWidget' );
16981 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
16982 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
16983 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
16985 /* Static Properties */
16987 OO
.ui
.LabelWidget
.static.tagName
= 'span';
16992 * Handles label mouse click events.
16995 * @param {jQuery.Event} e Mouse click event
16997 OO
.ui
.LabelWidget
.prototype.onClick = function () {
16998 this.input
.simulateLabelClick();
17003 * OptionWidgets are special elements that can be selected and configured with data. The
17004 * data is often unique for each option, but it does not have to be. OptionWidgets are used
17005 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
17006 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
17008 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17011 * @extends OO.ui.Widget
17012 * @mixins OO.ui.mixin.LabelElement
17013 * @mixins OO.ui.mixin.FlaggedElement
17016 * @param {Object} [config] Configuration options
17018 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
17019 // Configuration initialization
17020 config
= config
|| {};
17022 // Parent constructor
17023 OO
.ui
.OptionWidget
.parent
.call( this, config
);
17025 // Mixin constructors
17026 OO
.ui
.mixin
.ItemWidget
.call( this );
17027 OO
.ui
.mixin
.LabelElement
.call( this, config
);
17028 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
17031 this.selected
= false;
17032 this.highlighted
= false;
17033 this.pressed
= false;
17037 .data( 'oo-ui-optionWidget', this )
17038 .attr( 'role', 'option' )
17039 .attr( 'aria-selected', 'false' )
17040 .addClass( 'oo-ui-optionWidget' )
17041 .append( this.$label
);
17046 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
17047 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
17048 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
17049 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
17051 /* Static Properties */
17053 OO
.ui
.OptionWidget
.static.selectable
= true;
17055 OO
.ui
.OptionWidget
.static.highlightable
= true;
17057 OO
.ui
.OptionWidget
.static.pressable
= true;
17059 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
17064 * Check if the option can be selected.
17066 * @return {boolean} Item is selectable
17068 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
17069 return this.constructor.static.selectable
&& !this.isDisabled() && this.isVisible();
17073 * Check if the option can be highlighted. A highlight indicates that the option
17074 * may be selected when a user presses enter or clicks. Disabled items cannot
17077 * @return {boolean} Item is highlightable
17079 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
17080 return this.constructor.static.highlightable
&& !this.isDisabled() && this.isVisible();
17084 * Check if the option can be pressed. The pressed state occurs when a user mouses
17085 * down on an item, but has not yet let go of the mouse.
17087 * @return {boolean} Item is pressable
17089 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
17090 return this.constructor.static.pressable
&& !this.isDisabled() && this.isVisible();
17094 * Check if the option is selected.
17096 * @return {boolean} Item is selected
17098 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
17099 return this.selected
;
17103 * Check if the option is highlighted. A highlight indicates that the
17104 * item may be selected when a user presses enter or clicks.
17106 * @return {boolean} Item is highlighted
17108 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
17109 return this.highlighted
;
17113 * Check if the option is pressed. The pressed state occurs when a user mouses
17114 * down on an item, but has not yet let go of the mouse. The item may appear
17115 * selected, but it will not be selected until the user releases the mouse.
17117 * @return {boolean} Item is pressed
17119 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
17120 return this.pressed
;
17124 * Set the option’s selected state. In general, all modifications to the selection
17125 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
17126 * method instead of this method.
17128 * @param {boolean} [state=false] Select option
17131 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
17132 if ( this.constructor.static.selectable
) {
17133 this.selected
= !!state
;
17135 .toggleClass( 'oo-ui-optionWidget-selected', state
)
17136 .attr( 'aria-selected', state
.toString() );
17137 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
17138 this.scrollElementIntoView();
17140 this.updateThemeClasses();
17146 * Set the option’s highlighted state. In general, all programmatic
17147 * modifications to the highlight should be handled by the
17148 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
17149 * method instead of this method.
17151 * @param {boolean} [state=false] Highlight option
17154 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
17155 if ( this.constructor.static.highlightable
) {
17156 this.highlighted
= !!state
;
17157 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
17158 this.updateThemeClasses();
17164 * Set the option’s pressed state. In general, all
17165 * programmatic modifications to the pressed state should be handled by the
17166 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
17167 * method instead of this method.
17169 * @param {boolean} [state=false] Press option
17172 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
17173 if ( this.constructor.static.pressable
) {
17174 this.pressed
= !!state
;
17175 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
17176 this.updateThemeClasses();
17182 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
17183 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
17184 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
17185 * options. For more information about options and selects, please see the
17186 * [OOjs UI documentation on MediaWiki][1].
17189 * // Decorated options in a select widget
17190 * var select = new OO.ui.SelectWidget( {
17192 * new OO.ui.DecoratedOptionWidget( {
17194 * label: 'Option with icon',
17197 * new OO.ui.DecoratedOptionWidget( {
17199 * label: 'Option with indicator',
17200 * indicator: 'next'
17204 * $( 'body' ).append( select.$element );
17206 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17209 * @extends OO.ui.OptionWidget
17210 * @mixins OO.ui.mixin.IconElement
17211 * @mixins OO.ui.mixin.IndicatorElement
17214 * @param {Object} [config] Configuration options
17216 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
17217 // Parent constructor
17218 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
17220 // Mixin constructors
17221 OO
.ui
.mixin
.IconElement
.call( this, config
);
17222 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
17226 .addClass( 'oo-ui-decoratedOptionWidget' )
17227 .prepend( this.$icon
)
17228 .append( this.$indicator
);
17233 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
17234 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
17235 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
17238 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
17239 * can be selected and configured with data. The class is
17240 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
17241 * [OOjs UI documentation on MediaWiki] [1] for more information.
17243 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
17246 * @extends OO.ui.DecoratedOptionWidget
17247 * @mixins OO.ui.mixin.ButtonElement
17248 * @mixins OO.ui.mixin.TabIndexedElement
17249 * @mixins OO.ui.mixin.TitledElement
17252 * @param {Object} [config] Configuration options
17254 OO
.ui
.ButtonOptionWidget
= function OoUiButtonOptionWidget( config
) {
17255 // Configuration initialization
17256 config
= config
|| {};
17258 // Parent constructor
17259 OO
.ui
.ButtonOptionWidget
.parent
.call( this, config
);
17261 // Mixin constructors
17262 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
17263 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
17264 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, {
17265 $tabIndexed
: this.$button
,
17270 this.$element
.addClass( 'oo-ui-buttonOptionWidget' );
17271 this.$button
.append( this.$element
.contents() );
17272 this.$element
.append( this.$button
);
17277 OO
.inheritClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
17278 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.ButtonElement
);
17279 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.TitledElement
);
17280 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.TabIndexedElement
);
17282 /* Static Properties */
17284 // Allow button mouse down events to pass through so they can be handled by the parent select widget
17285 OO
.ui
.ButtonOptionWidget
.static.cancelButtonMouseDownEvents
= false;
17287 OO
.ui
.ButtonOptionWidget
.static.highlightable
= false;
17294 OO
.ui
.ButtonOptionWidget
.prototype.setSelected = function ( state
) {
17295 OO
.ui
.ButtonOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
17297 if ( this.constructor.static.selectable
) {
17298 this.setActive( state
);
17305 * RadioOptionWidget is an option widget that looks like a radio button.
17306 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
17307 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
17309 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
17312 * @extends OO.ui.OptionWidget
17315 * @param {Object} [config] Configuration options
17317 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
17318 // Configuration initialization
17319 config
= config
|| {};
17321 // Properties (must be done before parent constructor which calls #setDisabled)
17322 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
17324 // Parent constructor
17325 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
17328 this.radio
.$input
.on( 'focus', this.onInputFocus
.bind( this ) );
17331 // Remove implicit role, we're handling it ourselves
17332 this.radio
.$input
.attr( 'role', 'presentation' );
17334 .addClass( 'oo-ui-radioOptionWidget' )
17335 .attr( 'role', 'radio' )
17336 .attr( 'aria-checked', 'false' )
17337 .removeAttr( 'aria-selected' )
17338 .prepend( this.radio
.$element
);
17343 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
17345 /* Static Properties */
17347 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
17349 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
17351 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
17353 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
17358 * @param {jQuery.Event} e Focus event
17361 OO
.ui
.RadioOptionWidget
.prototype.onInputFocus = function () {
17362 this.radio
.$input
.blur();
17363 this.$element
.parent().focus();
17369 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
17370 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
17372 this.radio
.setSelected( state
);
17374 .attr( 'aria-checked', state
.toString() )
17375 .removeAttr( 'aria-selected' );
17383 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
17384 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
17386 this.radio
.setDisabled( this.isDisabled() );
17392 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
17393 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
17394 * the [OOjs UI documentation on MediaWiki] [1] for more information.
17396 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
17399 * @extends OO.ui.DecoratedOptionWidget
17402 * @param {Object} [config] Configuration options
17404 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
17405 // Configuration initialization
17406 config
= $.extend( { icon
: 'check' }, config
);
17408 // Parent constructor
17409 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
17413 .attr( 'role', 'menuitem' )
17414 .addClass( 'oo-ui-menuOptionWidget' );
17419 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
17421 /* Static Properties */
17423 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
17426 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
17427 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
17430 * var myDropdown = new OO.ui.DropdownWidget( {
17433 * new OO.ui.MenuSectionOptionWidget( {
17436 * new OO.ui.MenuOptionWidget( {
17438 * label: 'Welsh Corgi'
17440 * new OO.ui.MenuOptionWidget( {
17442 * label: 'Standard Poodle'
17444 * new OO.ui.MenuSectionOptionWidget( {
17447 * new OO.ui.MenuOptionWidget( {
17454 * $( 'body' ).append( myDropdown.$element );
17457 * @extends OO.ui.DecoratedOptionWidget
17460 * @param {Object} [config] Configuration options
17462 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
17463 // Parent constructor
17464 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
17467 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
17472 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
17474 /* Static Properties */
17476 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
17478 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
17481 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
17483 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
17484 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
17488 * @extends OO.ui.DecoratedOptionWidget
17491 * @param {Object} [config] Configuration options
17492 * @cfg {number} [level] Indentation level
17493 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
17495 OO
.ui
.OutlineOptionWidget
= function OoUiOutlineOptionWidget( config
) {
17496 // Configuration initialization
17497 config
= config
|| {};
17499 // Parent constructor
17500 OO
.ui
.OutlineOptionWidget
.parent
.call( this, config
);
17504 this.movable
= !!config
.movable
;
17505 this.removable
= !!config
.removable
;
17508 this.$element
.addClass( 'oo-ui-outlineOptionWidget' );
17509 this.setLevel( config
.level
);
17514 OO
.inheritClass( OO
.ui
.OutlineOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
17516 /* Static Properties */
17518 OO
.ui
.OutlineOptionWidget
.static.highlightable
= false;
17520 OO
.ui
.OutlineOptionWidget
.static.scrollIntoViewOnSelect
= true;
17522 OO
.ui
.OutlineOptionWidget
.static.levelClass
= 'oo-ui-outlineOptionWidget-level-';
17524 OO
.ui
.OutlineOptionWidget
.static.levels
= 3;
17529 * Check if item is movable.
17531 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17533 * @return {boolean} Item is movable
17535 OO
.ui
.OutlineOptionWidget
.prototype.isMovable = function () {
17536 return this.movable
;
17540 * Check if item is removable.
17542 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17544 * @return {boolean} Item is removable
17546 OO
.ui
.OutlineOptionWidget
.prototype.isRemovable = function () {
17547 return this.removable
;
17551 * Get indentation level.
17553 * @return {number} Indentation level
17555 OO
.ui
.OutlineOptionWidget
.prototype.getLevel = function () {
17562 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17564 * @param {boolean} movable Item is movable
17567 OO
.ui
.OutlineOptionWidget
.prototype.setMovable = function ( movable
) {
17568 this.movable
= !!movable
;
17569 this.updateThemeClasses();
17574 * Set removability.
17576 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17578 * @param {boolean} removable Item is removable
17581 OO
.ui
.OutlineOptionWidget
.prototype.setRemovable = function ( removable
) {
17582 this.removable
= !!removable
;
17583 this.updateThemeClasses();
17588 * Set indentation level.
17590 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
17593 OO
.ui
.OutlineOptionWidget
.prototype.setLevel = function ( level
) {
17594 var levels
= this.constructor.static.levels
,
17595 levelClass
= this.constructor.static.levelClass
,
17598 this.level
= level
? Math
.max( 0, Math
.min( levels
- 1, level
) ) : 0;
17600 if ( this.level
=== i
) {
17601 this.$element
.addClass( levelClass
+ i
);
17603 this.$element
.removeClass( levelClass
+ i
);
17606 this.updateThemeClasses();
17612 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
17614 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
17615 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
17619 * @extends OO.ui.OptionWidget
17622 * @param {Object} [config] Configuration options
17624 OO
.ui
.TabOptionWidget
= function OoUiTabOptionWidget( config
) {
17625 // Configuration initialization
17626 config
= config
|| {};
17628 // Parent constructor
17629 OO
.ui
.TabOptionWidget
.parent
.call( this, config
);
17632 this.$element
.addClass( 'oo-ui-tabOptionWidget' );
17637 OO
.inheritClass( OO
.ui
.TabOptionWidget
, OO
.ui
.OptionWidget
);
17639 /* Static Properties */
17641 OO
.ui
.TabOptionWidget
.static.highlightable
= false;
17644 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
17645 * By default, each popup has an anchor that points toward its origin.
17646 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
17649 * // A popup widget.
17650 * var popup = new OO.ui.PopupWidget( {
17651 * $content: $( '<p>Hi there!</p>' ),
17656 * $( 'body' ).append( popup.$element );
17657 * // To display the popup, toggle the visibility to 'true'.
17658 * popup.toggle( true );
17660 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
17663 * @extends OO.ui.Widget
17664 * @mixins OO.ui.mixin.LabelElement
17665 * @mixins OO.ui.mixin.ClippableElement
17668 * @param {Object} [config] Configuration options
17669 * @cfg {number} [width=320] Width of popup in pixels
17670 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
17671 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
17672 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
17673 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
17674 * popup is leaning towards the right of the screen.
17675 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
17676 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
17677 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
17678 * sentence in the given language.
17679 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
17680 * See the [OOjs UI docs on MediaWiki][3] for an example.
17681 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
17682 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
17683 * @cfg {jQuery} [$content] Content to append to the popup's body
17684 * @cfg {jQuery} [$footer] Content to append to the popup's footer
17685 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
17686 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
17687 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
17689 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
17690 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
17692 * @cfg {boolean} [padded] Add padding to the popup's body
17694 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
17695 // Configuration initialization
17696 config
= config
|| {};
17698 // Parent constructor
17699 OO
.ui
.PopupWidget
.parent
.call( this, config
);
17701 // Properties (must be set before ClippableElement constructor call)
17702 this.$body
= $( '<div>' );
17703 this.$popup
= $( '<div>' );
17705 // Mixin constructors
17706 OO
.ui
.mixin
.LabelElement
.call( this, config
);
17707 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
17708 $clippable
: this.$body
,
17709 $clippableContainer
: this.$popup
17713 this.$head
= $( '<div>' );
17714 this.$footer
= $( '<div>' );
17715 this.$anchor
= $( '<div>' );
17716 // If undefined, will be computed lazily in updateDimensions()
17717 this.$container
= config
.$container
;
17718 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
17719 this.autoClose
= !!config
.autoClose
;
17720 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
17721 this.transitionTimeout
= null;
17722 this.anchor
= null;
17723 this.width
= config
.width
!== undefined ? config
.width
: 320;
17724 this.height
= config
.height
!== undefined ? config
.height
: null;
17725 this.setAlignment( config
.align
);
17726 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
17727 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
17728 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
17731 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
17734 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
17735 this.$body
.addClass( 'oo-ui-popupWidget-body' );
17736 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
17738 .addClass( 'oo-ui-popupWidget-head' )
17739 .append( this.$label
, this.closeButton
.$element
);
17740 this.$footer
.addClass( 'oo-ui-popupWidget-footer' );
17741 if ( !config
.head
) {
17742 this.$head
.addClass( 'oo-ui-element-hidden' );
17744 if ( !config
.$footer
) {
17745 this.$footer
.addClass( 'oo-ui-element-hidden' );
17748 .addClass( 'oo-ui-popupWidget-popup' )
17749 .append( this.$head
, this.$body
, this.$footer
);
17751 .addClass( 'oo-ui-popupWidget' )
17752 .append( this.$popup
, this.$anchor
);
17753 // Move content, which was added to #$element by OO.ui.Widget, to the body
17754 if ( config
.$content
instanceof jQuery
) {
17755 this.$body
.append( config
.$content
);
17757 if ( config
.$footer
instanceof jQuery
) {
17758 this.$footer
.append( config
.$footer
);
17760 if ( config
.padded
) {
17761 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
17764 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
17765 // that reference properties not initialized at that time of parent class construction
17766 // TODO: Find a better way to handle post-constructor setup
17767 this.visible
= false;
17768 this.$element
.addClass( 'oo-ui-element-hidden' );
17773 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
17774 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
17775 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
17780 * Handles mouse down events.
17783 * @param {MouseEvent} e Mouse down event
17785 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
17787 this.isVisible() &&
17788 !$.contains( this.$element
[ 0 ], e
.target
) &&
17789 ( !this.$autoCloseIgnore
|| !this.$autoCloseIgnore
.has( e
.target
).length
)
17791 this.toggle( false );
17796 * Bind mouse down listener.
17800 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
17801 // Capture clicks outside popup
17802 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler
, true );
17806 * Handles close button click events.
17810 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
17811 if ( this.isVisible() ) {
17812 this.toggle( false );
17817 * Unbind mouse down listener.
17821 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
17822 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler
, true );
17826 * Handles key down events.
17829 * @param {KeyboardEvent} e Key down event
17831 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
17833 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
17836 this.toggle( false );
17837 e
.preventDefault();
17838 e
.stopPropagation();
17843 * Bind key down listener.
17847 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
17848 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
17852 * Unbind key down listener.
17856 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
17857 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
17861 * Show, hide, or toggle the visibility of the anchor.
17863 * @param {boolean} [show] Show anchor, omit to toggle
17865 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
17866 show
= show
=== undefined ? !this.anchored
: !!show
;
17868 if ( this.anchored
!== show
) {
17870 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
17872 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
17874 this.anchored
= show
;
17879 * Check if the anchor is visible.
17881 * @return {boolean} Anchor is visible
17883 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
17884 return this.anchor
;
17890 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
17892 show
= show
=== undefined ? !this.isVisible() : !!show
;
17894 change
= show
!== this.isVisible();
17897 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
17901 if ( this.autoClose
) {
17902 this.bindMouseDownListener();
17903 this.bindKeyDownListener();
17905 this.updateDimensions();
17906 this.toggleClipping( true );
17908 this.toggleClipping( false );
17909 if ( this.autoClose
) {
17910 this.unbindMouseDownListener();
17911 this.unbindKeyDownListener();
17920 * Set the size of the popup.
17922 * Changing the size may also change the popup's position depending on the alignment.
17924 * @param {number} width Width in pixels
17925 * @param {number} height Height in pixels
17926 * @param {boolean} [transition=false] Use a smooth transition
17929 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
17930 this.width
= width
;
17931 this.height
= height
!== undefined ? height
: null;
17932 if ( this.isVisible() ) {
17933 this.updateDimensions( transition
);
17938 * Update the size and position.
17940 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
17941 * be called automatically.
17943 * @param {boolean} [transition=false] Use a smooth transition
17946 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
17947 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
17948 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
17949 align
= this.align
,
17952 if ( !this.$container
) {
17953 // Lazy-initialize $container if not specified in constructor
17954 this.$container
= $( this.getClosestScrollableElementContainer() );
17957 // Set height and width before measuring things, since it might cause our measurements
17958 // to change (e.g. due to scrollbars appearing or disappearing)
17961 height
: this.height
!== null ? this.height
: 'auto'
17964 // If we are in RTL, we need to flip the alignment, unless it is center
17965 if ( align
=== 'forwards' || align
=== 'backwards' ) {
17966 if ( this.$container
.css( 'direction' ) === 'rtl' ) {
17967 align
= ( { forwards
: 'force-left', backwards
: 'force-right' } )[ this.align
];
17969 align
= ( { forwards
: 'force-right', backwards
: 'force-left' } )[ this.align
];
17974 // Compute initial popupOffset based on alignment
17975 popupOffset
= this.width
* ( { 'force-left': -1, center
: -0.5, 'force-right': 0 } )[ align
];
17977 // Figure out if this will cause the popup to go beyond the edge of the container
17978 originOffset
= this.$element
.offset().left
;
17979 containerLeft
= this.$container
.offset().left
;
17980 containerWidth
= this.$container
.innerWidth();
17981 containerRight
= containerLeft
+ containerWidth
;
17982 popupLeft
= popupOffset
- this.containerPadding
;
17983 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
17984 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
17985 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
17987 // Adjust offset to make the popup not go beyond the edge, if needed
17988 if ( overlapRight
< 0 ) {
17989 popupOffset
+= overlapRight
;
17990 } else if ( overlapLeft
< 0 ) {
17991 popupOffset
-= overlapLeft
;
17994 // Adjust offset to avoid anchor being rendered too close to the edge
17995 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
17996 // TODO: Find a measurement that works for CSS anchors and image anchors
17997 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
17998 if ( popupOffset
+ this.width
< anchorWidth
) {
17999 popupOffset
= anchorWidth
- this.width
;
18000 } else if ( -popupOffset
< anchorWidth
) {
18001 popupOffset
= -anchorWidth
;
18004 // Prevent transition from being interrupted
18005 clearTimeout( this.transitionTimeout
);
18006 if ( transition
) {
18007 // Enable transition
18008 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
18011 // Position body relative to anchor
18012 this.$popup
.css( 'margin-left', popupOffset
);
18014 if ( transition
) {
18015 // Prevent transitioning after transition is complete
18016 this.transitionTimeout
= setTimeout( function () {
18017 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
18020 // Prevent transitioning immediately
18021 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
18024 // Reevaluate clipping state since we've relocated and resized the popup
18031 * Set popup alignment
18032 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
18033 * `backwards` or `forwards`.
18035 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
18036 // Validate alignment and transform deprecated values
18037 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
18038 this.align
= { left
: 'force-right', right
: 'force-left' }[ align
] || align
;
18040 this.align
= 'center';
18045 * Get popup alignment
18046 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
18047 * `backwards` or `forwards`.
18049 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
18054 * Progress bars visually display the status of an operation, such as a download,
18055 * and can be either determinate or indeterminate:
18057 * - **determinate** process bars show the percent of an operation that is complete.
18059 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
18060 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
18061 * not use percentages.
18063 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
18066 * // Examples of determinate and indeterminate progress bars.
18067 * var progressBar1 = new OO.ui.ProgressBarWidget( {
18070 * var progressBar2 = new OO.ui.ProgressBarWidget();
18072 * // Create a FieldsetLayout to layout progress bars
18073 * var fieldset = new OO.ui.FieldsetLayout;
18074 * fieldset.addItems( [
18075 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
18076 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
18078 * $( 'body' ).append( fieldset.$element );
18081 * @extends OO.ui.Widget
18084 * @param {Object} [config] Configuration options
18085 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
18086 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
18087 * By default, the progress bar is indeterminate.
18089 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
18090 // Configuration initialization
18091 config
= config
|| {};
18093 // Parent constructor
18094 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
18097 this.$bar
= $( '<div>' );
18098 this.progress
= null;
18101 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
18102 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
18105 role
: 'progressbar',
18106 'aria-valuemin': 0,
18107 'aria-valuemax': 100
18109 .addClass( 'oo-ui-progressBarWidget' )
18110 .append( this.$bar
);
18115 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
18117 /* Static Properties */
18119 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
18124 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
18126 * @return {number|boolean} Progress percent
18128 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
18129 return this.progress
;
18133 * Set the percent of the process completed or `false` for an indeterminate process.
18135 * @param {number|boolean} progress Progress percent or `false` for indeterminate
18137 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
18138 this.progress
= progress
;
18140 if ( progress
!== false ) {
18141 this.$bar
.css( 'width', this.progress
+ '%' );
18142 this.$element
.attr( 'aria-valuenow', this.progress
);
18144 this.$bar
.css( 'width', '' );
18145 this.$element
.removeAttr( 'aria-valuenow' );
18147 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress
);
18151 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
18152 * and a menu of search results, which is displayed beneath the query
18153 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
18154 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
18155 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
18157 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
18158 * the [OOjs UI demos][1] for an example.
18160 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
18163 * @extends OO.ui.Widget
18166 * @param {Object} [config] Configuration options
18167 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
18168 * @cfg {string} [value] Initial query value
18170 OO
.ui
.SearchWidget
= function OoUiSearchWidget( config
) {
18171 // Configuration initialization
18172 config
= config
|| {};
18174 // Parent constructor
18175 OO
.ui
.SearchWidget
.parent
.call( this, config
);
18178 this.query
= new OO
.ui
.TextInputWidget( {
18180 placeholder
: config
.placeholder
,
18181 value
: config
.value
18183 this.results
= new OO
.ui
.SelectWidget();
18184 this.$query
= $( '<div>' );
18185 this.$results
= $( '<div>' );
18188 this.query
.connect( this, {
18189 change
: 'onQueryChange',
18190 enter
: 'onQueryEnter'
18192 this.query
.$input
.on( 'keydown', this.onQueryKeydown
.bind( this ) );
18196 .addClass( 'oo-ui-searchWidget-query' )
18197 .append( this.query
.$element
);
18199 .addClass( 'oo-ui-searchWidget-results' )
18200 .append( this.results
.$element
);
18202 .addClass( 'oo-ui-searchWidget' )
18203 .append( this.$results
, this.$query
);
18208 OO
.inheritClass( OO
.ui
.SearchWidget
, OO
.ui
.Widget
);
18213 * Handle query key down events.
18216 * @param {jQuery.Event} e Key down event
18218 OO
.ui
.SearchWidget
.prototype.onQueryKeydown = function ( e
) {
18219 var highlightedItem
, nextItem
,
18220 dir
= e
.which
=== OO
.ui
.Keys
.DOWN
? 1 : ( e
.which
=== OO
.ui
.Keys
.UP
? -1 : 0 );
18223 highlightedItem
= this.results
.getHighlightedItem();
18224 if ( !highlightedItem
) {
18225 highlightedItem
= this.results
.getSelectedItem();
18227 nextItem
= this.results
.getRelativeSelectableItem( highlightedItem
, dir
);
18228 this.results
.highlightItem( nextItem
);
18229 nextItem
.scrollElementIntoView();
18234 * Handle select widget select events.
18236 * Clears existing results. Subclasses should repopulate items according to new query.
18239 * @param {string} value New value
18241 OO
.ui
.SearchWidget
.prototype.onQueryChange = function () {
18243 this.results
.clearItems();
18247 * Handle select widget enter key events.
18249 * Chooses highlighted item.
18252 * @param {string} value New value
18254 OO
.ui
.SearchWidget
.prototype.onQueryEnter = function () {
18255 var highlightedItem
= this.results
.getHighlightedItem();
18256 if ( highlightedItem
) {
18257 this.results
.chooseItem( highlightedItem
);
18262 * Get the query input.
18264 * @return {OO.ui.TextInputWidget} Query input
18266 OO
.ui
.SearchWidget
.prototype.getQuery = function () {
18271 * Get the search results menu.
18273 * @return {OO.ui.SelectWidget} Menu of search results
18275 OO
.ui
.SearchWidget
.prototype.getResults = function () {
18276 return this.results
;
18280 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
18281 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
18282 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
18285 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
18286 * information, please see the [OOjs UI documentation on MediaWiki][1].
18289 * // Example of a select widget with three options
18290 * var select = new OO.ui.SelectWidget( {
18292 * new OO.ui.OptionWidget( {
18294 * label: 'Option One',
18296 * new OO.ui.OptionWidget( {
18298 * label: 'Option Two',
18300 * new OO.ui.OptionWidget( {
18302 * label: 'Option Three',
18306 * $( 'body' ).append( select.$element );
18308 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18312 * @extends OO.ui.Widget
18313 * @mixins OO.ui.mixin.GroupWidget
18316 * @param {Object} [config] Configuration options
18317 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
18318 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
18319 * the [OOjs UI documentation on MediaWiki] [2] for examples.
18320 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18322 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
18323 // Configuration initialization
18324 config
= config
|| {};
18326 // Parent constructor
18327 OO
.ui
.SelectWidget
.parent
.call( this, config
);
18329 // Mixin constructors
18330 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
18333 this.pressed
= false;
18334 this.selecting
= null;
18335 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
18336 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
18337 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
18338 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
18339 this.keyPressBuffer
= '';
18340 this.keyPressBufferTimer
= null;
18343 this.connect( this, {
18346 this.$element
.on( {
18347 mousedown
: this.onMouseDown
.bind( this ),
18348 mouseover
: this.onMouseOver
.bind( this ),
18349 mouseleave
: this.onMouseLeave
.bind( this )
18354 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
18355 .attr( 'role', 'listbox' );
18356 if ( Array
.isArray( config
.items
) ) {
18357 this.addItems( config
.items
);
18363 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
18365 // Need to mixin base class as well
18366 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupElement
);
18367 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
18370 OO
.ui
.SelectWidget
.static.passAllFilter = function () {
18379 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
18381 * @param {OO.ui.OptionWidget|null} item Highlighted item
18387 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
18388 * pressed state of an option.
18390 * @param {OO.ui.OptionWidget|null} item Pressed item
18396 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
18398 * @param {OO.ui.OptionWidget|null} item Selected item
18403 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
18404 * @param {OO.ui.OptionWidget} item Chosen item
18410 * An `add` event is emitted when options are added to the select with the #addItems method.
18412 * @param {OO.ui.OptionWidget[]} items Added items
18413 * @param {number} index Index of insertion point
18419 * A `remove` event is emitted when options are removed from the select with the #clearItems
18420 * or #removeItems methods.
18422 * @param {OO.ui.OptionWidget[]} items Removed items
18428 * Handle mouse down events.
18431 * @param {jQuery.Event} e Mouse down event
18433 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
18436 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
18437 this.togglePressed( true );
18438 item
= this.getTargetItem( e
);
18439 if ( item
&& item
.isSelectable() ) {
18440 this.pressItem( item
);
18441 this.selecting
= item
;
18442 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
18443 this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler
, true );
18450 * Handle mouse up events.
18453 * @param {jQuery.Event} e Mouse up event
18455 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
18458 this.togglePressed( false );
18459 if ( !this.selecting
) {
18460 item
= this.getTargetItem( e
);
18461 if ( item
&& item
.isSelectable() ) {
18462 this.selecting
= item
;
18465 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
&& this.selecting
) {
18466 this.pressItem( null );
18467 this.chooseItem( this.selecting
);
18468 this.selecting
= null;
18471 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
18472 this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler
, true );
18478 * Handle mouse move events.
18481 * @param {jQuery.Event} e Mouse move event
18483 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
18486 if ( !this.isDisabled() && this.pressed
) {
18487 item
= this.getTargetItem( e
);
18488 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
18489 this.pressItem( item
);
18490 this.selecting
= item
;
18497 * Handle mouse over events.
18500 * @param {jQuery.Event} e Mouse over event
18502 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
18505 if ( !this.isDisabled() ) {
18506 item
= this.getTargetItem( e
);
18507 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
18513 * Handle mouse leave events.
18516 * @param {jQuery.Event} e Mouse over event
18518 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
18519 if ( !this.isDisabled() ) {
18520 this.highlightItem( null );
18526 * Handle key down events.
18529 * @param {jQuery.Event} e Key down event
18531 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
18534 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
18536 if ( !this.isDisabled() && this.isVisible() ) {
18537 switch ( e
.keyCode
) {
18538 case OO
.ui
.Keys
.ENTER
:
18539 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
18540 // Was only highlighted, now let's select it. No-op if already selected.
18541 this.chooseItem( currentItem
);
18545 case OO
.ui
.Keys
.UP
:
18546 case OO
.ui
.Keys
.LEFT
:
18547 this.clearKeyPressBuffer();
18548 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
18551 case OO
.ui
.Keys
.DOWN
:
18552 case OO
.ui
.Keys
.RIGHT
:
18553 this.clearKeyPressBuffer();
18554 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
18557 case OO
.ui
.Keys
.ESCAPE
:
18558 case OO
.ui
.Keys
.TAB
:
18559 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
18560 currentItem
.setHighlighted( false );
18562 this.unbindKeyDownListener();
18563 this.unbindKeyPressListener();
18564 // Don't prevent tabbing away / defocusing
18570 if ( nextItem
.constructor.static.highlightable
) {
18571 this.highlightItem( nextItem
);
18573 this.chooseItem( nextItem
);
18575 nextItem
.scrollElementIntoView();
18579 // Can't just return false, because e is not always a jQuery event
18580 e
.preventDefault();
18581 e
.stopPropagation();
18587 * Bind key down listener.
18591 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
18592 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler
, true );
18596 * Unbind key down listener.
18600 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
18601 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler
, true );
18605 * Clear the key-press buffer
18609 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
18610 if ( this.keyPressBufferTimer
) {
18611 clearTimeout( this.keyPressBufferTimer
);
18612 this.keyPressBufferTimer
= null;
18614 this.keyPressBuffer
= '';
18618 * Handle key press events.
18621 * @param {jQuery.Event} e Key press event
18623 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
18624 var c
, filter
, item
;
18626 if ( !e
.charCode
) {
18627 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
18628 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
18633 if ( String
.fromCodePoint
) {
18634 c
= String
.fromCodePoint( e
.charCode
);
18636 c
= String
.fromCharCode( e
.charCode
);
18639 if ( this.keyPressBufferTimer
) {
18640 clearTimeout( this.keyPressBufferTimer
);
18642 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
18644 item
= this.getHighlightedItem() || this.getSelectedItem();
18646 if ( this.keyPressBuffer
=== c
) {
18647 // Common (if weird) special case: typing "xxxx" will cycle through all
18648 // the items beginning with "x".
18650 item
= this.getRelativeSelectableItem( item
, 1 );
18653 this.keyPressBuffer
+= c
;
18656 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
18657 if ( !item
|| !filter( item
) ) {
18658 item
= this.getRelativeSelectableItem( item
, 1, filter
);
18661 if ( item
.constructor.static.highlightable
) {
18662 this.highlightItem( item
);
18664 this.chooseItem( item
);
18666 item
.scrollElementIntoView();
18673 * Get a matcher for the specific string
18676 * @param {string} s String to match against items
18677 * @param {boolean} [exact=false] Only accept exact matches
18678 * @return {Function} function ( OO.ui.OptionItem ) => boolean
18680 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
18683 if ( s
.normalize
) {
18686 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
18687 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
18691 re
= new RegExp( re
, 'i' );
18692 return function ( item
) {
18693 var l
= item
.getLabel();
18694 if ( typeof l
!== 'string' ) {
18695 l
= item
.$label
.text();
18697 if ( l
.normalize
) {
18700 return re
.test( l
);
18705 * Bind key press listener.
18709 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
18710 this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler
, true );
18714 * Unbind key down listener.
18716 * If you override this, be sure to call this.clearKeyPressBuffer() from your
18721 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
18722 this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler
, true );
18723 this.clearKeyPressBuffer();
18727 * Visibility change handler
18730 * @param {boolean} visible
18732 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
18734 this.clearKeyPressBuffer();
18739 * Get the closest item to a jQuery.Event.
18742 * @param {jQuery.Event} e
18743 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
18745 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
18746 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
18750 * Get selected item.
18752 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
18754 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
18757 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18758 if ( this.items
[ i
].isSelected() ) {
18759 return this.items
[ i
];
18766 * Get highlighted item.
18768 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
18770 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
18773 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18774 if ( this.items
[ i
].isHighlighted() ) {
18775 return this.items
[ i
];
18782 * Toggle pressed state.
18784 * Press is a state that occurs when a user mouses down on an item, but
18785 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
18786 * until the user releases the mouse.
18788 * @param {boolean} pressed An option is being pressed
18790 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
18791 if ( pressed
=== undefined ) {
18792 pressed
= !this.pressed
;
18794 if ( pressed
!== this.pressed
) {
18796 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
18797 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
18798 this.pressed
= pressed
;
18803 * Highlight an option. If the `item` param is omitted, no options will be highlighted
18804 * and any existing highlight will be removed. The highlight is mutually exclusive.
18806 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
18810 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
18811 var i
, len
, highlighted
,
18814 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18815 highlighted
= this.items
[ i
] === item
;
18816 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
18817 this.items
[ i
].setHighlighted( highlighted
);
18822 this.emit( 'highlight', item
);
18829 * Fetch an item by its label.
18831 * @param {string} label Label of the item to select.
18832 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18833 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
18835 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
18836 var i
, item
, found
,
18837 len
= this.items
.length
,
18838 filter
= this.getItemMatcher( label
, true );
18840 for ( i
= 0; i
< len
; i
++ ) {
18841 item
= this.items
[ i
];
18842 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18849 filter
= this.getItemMatcher( label
, false );
18850 for ( i
= 0; i
< len
; i
++ ) {
18851 item
= this.items
[ i
];
18852 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18868 * Programmatically select an option by its label. If the item does not exist,
18869 * all options will be deselected.
18871 * @param {string} [label] Label of the item to select.
18872 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18876 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
18877 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
18878 if ( label
=== undefined || !itemFromLabel
) {
18879 return this.selectItem();
18881 return this.selectItem( itemFromLabel
);
18885 * Programmatically select an option by its data. If the `data` parameter is omitted,
18886 * or if the item does not exist, all options will be deselected.
18888 * @param {Object|string} [data] Value of the item to select, omit to deselect all
18892 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
18893 var itemFromData
= this.getItemFromData( data
);
18894 if ( data
=== undefined || !itemFromData
) {
18895 return this.selectItem();
18897 return this.selectItem( itemFromData
);
18901 * Programmatically select an option by its reference. If the `item` parameter is omitted,
18902 * all options will be deselected.
18904 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
18908 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
18909 var i
, len
, selected
,
18912 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18913 selected
= this.items
[ i
] === item
;
18914 if ( this.items
[ i
].isSelected() !== selected
) {
18915 this.items
[ i
].setSelected( selected
);
18920 this.emit( 'select', item
);
18929 * Press is a state that occurs when a user mouses down on an item, but has not
18930 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
18931 * releases the mouse.
18933 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
18937 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
18938 var i
, len
, pressed
,
18941 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18942 pressed
= this.items
[ i
] === item
;
18943 if ( this.items
[ i
].isPressed() !== pressed
) {
18944 this.items
[ i
].setPressed( pressed
);
18949 this.emit( 'press', item
);
18958 * Note that ‘choose’ should never be modified programmatically. A user can choose
18959 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
18960 * use the #selectItem method.
18962 * This method is identical to #selectItem, but may vary in subclasses that take additional action
18963 * when users choose an item with the keyboard or mouse.
18965 * @param {OO.ui.OptionWidget} item Item to choose
18969 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
18971 this.selectItem( item
);
18972 this.emit( 'choose', item
);
18979 * Get an option by its position relative to the specified item (or to the start of the option array,
18980 * if item is `null`). The direction in which to search through the option array is specified with a
18981 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
18982 * `null` if there are no options in the array.
18984 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
18985 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
18986 * @param {Function} filter Only consider items for which this function returns
18987 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
18988 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
18990 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
18991 var currentIndex
, nextIndex
, i
,
18992 increase
= direction
> 0 ? 1 : -1,
18993 len
= this.items
.length
;
18995 if ( !$.isFunction( filter
) ) {
18996 filter
= OO
.ui
.SelectWidget
.static.passAllFilter
;
18999 if ( item
instanceof OO
.ui
.OptionWidget
) {
19000 currentIndex
= this.items
.indexOf( item
);
19001 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
19003 // If no item is selected and moving forward, start at the beginning.
19004 // If moving backward, start at the end.
19005 nextIndex
= direction
> 0 ? 0 : len
- 1;
19008 for ( i
= 0; i
< len
; i
++ ) {
19009 item
= this.items
[ nextIndex
];
19010 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
19013 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
19019 * Get the next selectable item or `null` if there are no selectable items.
19020 * Disabled options and menu-section markers and breaks are not selectable.
19022 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
19024 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
19027 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
19028 item
= this.items
[ i
];
19029 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
19038 * Add an array of options to the select. Optionally, an index number can be used to
19039 * specify an insertion point.
19041 * @param {OO.ui.OptionWidget[]} items Items to add
19042 * @param {number} [index] Index to insert items after
19046 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
19048 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
19050 // Always provide an index, even if it was omitted
19051 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
19057 * Remove the specified array of options from the select. Options will be detached
19058 * from the DOM, not removed, so they can be reused later. To remove all options from
19059 * the select, you may wish to use the #clearItems method instead.
19061 * @param {OO.ui.OptionWidget[]} items Items to remove
19065 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
19068 // Deselect items being removed
19069 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
19071 if ( item
.isSelected() ) {
19072 this.selectItem( null );
19077 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
19079 this.emit( 'remove', items
);
19085 * Clear all options from the select. Options will be detached from the DOM, not removed,
19086 * so that they can be reused later. To remove a subset of options from the select, use
19087 * the #removeItems method.
19092 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
19093 var items
= this.items
.slice();
19096 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
19099 this.selectItem( null );
19101 this.emit( 'remove', items
);
19107 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
19108 * button options and is used together with
19109 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
19110 * highlighting, choosing, and selecting mutually exclusive options. Please see
19111 * the [OOjs UI documentation on MediaWiki] [1] for more information.
19114 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
19115 * var option1 = new OO.ui.ButtonOptionWidget( {
19117 * label: 'Option 1',
19118 * title: 'Button option 1'
19121 * var option2 = new OO.ui.ButtonOptionWidget( {
19123 * label: 'Option 2',
19124 * title: 'Button option 2'
19127 * var option3 = new OO.ui.ButtonOptionWidget( {
19129 * label: 'Option 3',
19130 * title: 'Button option 3'
19133 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
19134 * items: [ option1, option2, option3 ]
19136 * $( 'body' ).append( buttonSelect.$element );
19138 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
19141 * @extends OO.ui.SelectWidget
19142 * @mixins OO.ui.mixin.TabIndexedElement
19145 * @param {Object} [config] Configuration options
19147 OO
.ui
.ButtonSelectWidget
= function OoUiButtonSelectWidget( config
) {
19148 // Parent constructor
19149 OO
.ui
.ButtonSelectWidget
.parent
.call( this, config
);
19151 // Mixin constructors
19152 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19155 this.$element
.on( {
19156 focus
: this.bindKeyDownListener
.bind( this ),
19157 blur
: this.unbindKeyDownListener
.bind( this )
19161 this.$element
.addClass( 'oo-ui-buttonSelectWidget' );
19166 OO
.inheritClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.SelectWidget
);
19167 OO
.mixinClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19170 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
19171 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
19172 * an interface for adding, removing and selecting options.
19173 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
19175 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
19176 * OO.ui.RadioSelectInputWidget instead.
19179 * // A RadioSelectWidget with RadioOptions.
19180 * var option1 = new OO.ui.RadioOptionWidget( {
19182 * label: 'Selected radio option'
19185 * var option2 = new OO.ui.RadioOptionWidget( {
19187 * label: 'Unselected radio option'
19190 * var radioSelect=new OO.ui.RadioSelectWidget( {
19191 * items: [ option1, option2 ]
19194 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
19195 * radioSelect.selectItem( option1 );
19197 * $( 'body' ).append( radioSelect.$element );
19199 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
19203 * @extends OO.ui.SelectWidget
19204 * @mixins OO.ui.mixin.TabIndexedElement
19207 * @param {Object} [config] Configuration options
19209 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
19210 // Parent constructor
19211 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
19213 // Mixin constructors
19214 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19217 this.$element
.on( {
19218 focus
: this.bindKeyDownListener
.bind( this ),
19219 blur
: this.unbindKeyDownListener
.bind( this )
19224 .addClass( 'oo-ui-radioSelectWidget' )
19225 .attr( 'role', 'radiogroup' );
19230 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
19231 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19234 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
19235 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
19236 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
19237 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
19238 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
19239 * and customized to be opened, closed, and displayed as needed.
19241 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
19242 * mouse outside the menu.
19244 * Menus also have support for keyboard interaction:
19246 * - Enter/Return key: choose and select a menu option
19247 * - Up-arrow key: highlight the previous menu option
19248 * - Down-arrow key: highlight the next menu option
19249 * - Esc key: hide the menu
19251 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
19252 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
19255 * @extends OO.ui.SelectWidget
19256 * @mixins OO.ui.mixin.ClippableElement
19259 * @param {Object} [config] Configuration options
19260 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
19261 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
19262 * and {@link OO.ui.mixin.LookupElement LookupElement}
19263 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
19264 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
19265 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
19266 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
19267 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
19268 * that button, unless the button (or its parent widget) is passed in here.
19269 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
19270 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
19272 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
19273 // Configuration initialization
19274 config
= config
|| {};
19276 // Parent constructor
19277 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
19279 // Mixin constructors
19280 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
19283 this.newItems
= null;
19284 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
19285 this.filterFromInput
= !!config
.filterFromInput
;
19286 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
19287 this.$widget
= config
.widget
? config
.widget
.$element
: null;
19288 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
19289 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
19293 .addClass( 'oo-ui-menuSelectWidget' )
19294 .attr( 'role', 'menu' );
19296 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
19297 // that reference properties not initialized at that time of parent class construction
19298 // TODO: Find a better way to handle post-constructor setup
19299 this.visible
= false;
19300 this.$element
.addClass( 'oo-ui-element-hidden' );
19305 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
19306 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
19311 * Handles document mouse down events.
19314 * @param {jQuery.Event} e Key down event
19316 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
19318 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
19319 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
19321 this.toggle( false );
19328 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
19329 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
19331 if ( !this.isDisabled() && this.isVisible() ) {
19332 switch ( e
.keyCode
) {
19333 case OO
.ui
.Keys
.LEFT
:
19334 case OO
.ui
.Keys
.RIGHT
:
19335 // Do nothing if a text field is associated, arrow keys will be handled natively
19336 if ( !this.$input
) {
19337 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
19340 case OO
.ui
.Keys
.ESCAPE
:
19341 case OO
.ui
.Keys
.TAB
:
19342 if ( currentItem
) {
19343 currentItem
.setHighlighted( false );
19345 this.toggle( false );
19346 // Don't prevent tabbing away, prevent defocusing
19347 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
19348 e
.preventDefault();
19349 e
.stopPropagation();
19353 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
19360 * Update menu item visibility after input changes.
19363 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
19365 len
= this.items
.length
,
19366 showAll
= !this.isVisible(),
19367 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
19369 for ( i
= 0; i
< len
; i
++ ) {
19370 item
= this.items
[ i
];
19371 if ( item
instanceof OO
.ui
.OptionWidget
) {
19372 item
.toggle( showAll
|| filter( item
) );
19376 // Reevaluate clipping
19383 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
19384 if ( this.$input
) {
19385 this.$input
.on( 'keydown', this.onKeyDownHandler
);
19387 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
19394 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
19395 if ( this.$input
) {
19396 this.$input
.off( 'keydown', this.onKeyDownHandler
);
19398 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
19405 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
19406 if ( this.$input
) {
19407 if ( this.filterFromInput
) {
19408 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
19411 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
19418 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
19419 if ( this.$input
) {
19420 if ( this.filterFromInput
) {
19421 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
19422 this.updateItemVisibility();
19425 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
19432 * When a user chooses an item, the menu is closed.
19434 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
19435 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
19436 * @param {OO.ui.OptionWidget} item Item to choose
19439 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
19440 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
19441 this.toggle( false );
19448 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
19452 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
19455 if ( !this.newItems
) {
19456 this.newItems
= [];
19459 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
19461 if ( this.isVisible() ) {
19462 // Defer fitting label until item has been attached
19465 this.newItems
.push( item
);
19469 // Reevaluate clipping
19478 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
19480 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
19482 // Reevaluate clipping
19491 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
19493 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
19495 // Reevaluate clipping
19504 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
19505 var i
, len
, change
;
19507 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
19508 change
= visible
!== this.isVisible();
19511 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
19515 this.bindKeyDownListener();
19516 this.bindKeyPressListener();
19518 if ( this.newItems
&& this.newItems
.length
) {
19519 for ( i
= 0, len
= this.newItems
.length
; i
< len
; i
++ ) {
19520 this.newItems
[ i
].fitLabel();
19522 this.newItems
= null;
19524 this.toggleClipping( true );
19527 if ( this.autoHide
) {
19528 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
19531 this.unbindKeyDownListener();
19532 this.unbindKeyPressListener();
19533 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
19534 this.toggleClipping( false );
19542 * FloatingMenuSelectWidget is a menu that will stick under a specified
19543 * container, even when it is inserted elsewhere in the document (for example,
19544 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
19545 * menu from being clipped too aggresively.
19547 * The menu's position is automatically calculated and maintained when the menu
19548 * is toggled or the window is resized.
19550 * See OO.ui.ComboBoxInputWidget for an example of a widget that uses this class.
19553 * @extends OO.ui.MenuSelectWidget
19554 * @mixins OO.ui.mixin.FloatableElement
19557 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
19558 * Deprecated, omit this parameter and specify `$container` instead.
19559 * @param {Object} [config] Configuration options
19560 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
19562 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
19563 // Allow 'inputWidget' parameter and config for backwards compatibility
19564 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
19565 config
= inputWidget
;
19566 inputWidget
= config
.inputWidget
;
19569 // Configuration initialization
19570 config
= config
|| {};
19572 // Parent constructor
19573 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, config
);
19575 // Properties (must be set before mixin constructors)
19576 this.inputWidget
= inputWidget
; // For backwards compatibility
19577 this.$container
= config
.$container
|| this.inputWidget
.$element
;
19579 // Mixins constructors
19580 OO
.ui
.mixin
.FloatableElement
.call( this, $.extend( {}, config
, { $floatableContainer
: this.$container
} ) );
19583 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
19584 // For backwards compatibility
19585 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
19590 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
19591 OO
.mixinClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
19593 // For backwards compatibility
19594 OO
.ui
.TextInputMenuSelectWidget
= OO
.ui
.FloatingMenuSelectWidget
;
19601 OO
.ui
.FloatingMenuSelectWidget
.prototype.toggle = function ( visible
) {
19603 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
19604 change
= visible
!== this.isVisible();
19606 if ( change
&& visible
) {
19607 // Make sure the width is set before the parent method runs.
19608 this.setIdealSize( this.$container
.width() );
19612 // This will call this.clip(), which is nonsensical since we're not positioned yet...
19613 OO
.ui
.FloatingMenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
19616 this.togglePositioning( this.isVisible() );
19623 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
19624 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
19626 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
19629 * @extends OO.ui.SelectWidget
19630 * @mixins OO.ui.mixin.TabIndexedElement
19633 * @param {Object} [config] Configuration options
19635 OO
.ui
.OutlineSelectWidget
= function OoUiOutlineSelectWidget( config
) {
19636 // Parent constructor
19637 OO
.ui
.OutlineSelectWidget
.parent
.call( this, config
);
19639 // Mixin constructors
19640 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19643 this.$element
.on( {
19644 focus
: this.bindKeyDownListener
.bind( this ),
19645 blur
: this.unbindKeyDownListener
.bind( this )
19649 this.$element
.addClass( 'oo-ui-outlineSelectWidget' );
19654 OO
.inheritClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.SelectWidget
);
19655 OO
.mixinClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19658 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
19660 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
19663 * @extends OO.ui.SelectWidget
19664 * @mixins OO.ui.mixin.TabIndexedElement
19667 * @param {Object} [config] Configuration options
19669 OO
.ui
.TabSelectWidget
= function OoUiTabSelectWidget( config
) {
19670 // Parent constructor
19671 OO
.ui
.TabSelectWidget
.parent
.call( this, config
);
19673 // Mixin constructors
19674 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19677 this.$element
.on( {
19678 focus
: this.bindKeyDownListener
.bind( this ),
19679 blur
: this.unbindKeyDownListener
.bind( this )
19683 this.$element
.addClass( 'oo-ui-tabSelectWidget' );
19688 OO
.inheritClass( OO
.ui
.TabSelectWidget
, OO
.ui
.SelectWidget
);
19689 OO
.mixinClass( OO
.ui
.TabSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19692 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
19693 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
19694 * (to adjust the value in increments) to allow the user to enter a number.
19697 * // Example: A NumberInputWidget.
19698 * var numberInput = new OO.ui.NumberInputWidget( {
19699 * label: 'NumberInputWidget',
19700 * input: { value: 5, min: 1, max: 10 }
19702 * $( 'body' ).append( numberInput.$element );
19705 * @extends OO.ui.Widget
19708 * @param {Object} [config] Configuration options
19709 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
19710 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
19711 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
19712 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
19713 * @cfg {number} [min=-Infinity] Minimum allowed value
19714 * @cfg {number} [max=Infinity] Maximum allowed value
19715 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
19716 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
19718 OO
.ui
.NumberInputWidget
= function OoUiNumberInputWidget( config
) {
19719 // Configuration initialization
19720 config
= $.extend( {
19728 // Parent constructor
19729 OO
.ui
.NumberInputWidget
.parent
.call( this, config
);
19732 this.input
= new OO
.ui
.TextInputWidget( $.extend(
19734 disabled
: this.isDisabled()
19738 this.minusButton
= new OO
.ui
.ButtonWidget( $.extend(
19740 disabled
: this.isDisabled(),
19743 config
.minusButton
,
19745 classes
: [ 'oo-ui-numberInputWidget-minusButton' ],
19749 this.plusButton
= new OO
.ui
.ButtonWidget( $.extend(
19751 disabled
: this.isDisabled(),
19756 classes
: [ 'oo-ui-numberInputWidget-plusButton' ],
19762 this.input
.connect( this, {
19763 change
: this.emit
.bind( this, 'change' ),
19764 enter
: this.emit
.bind( this, 'enter' )
19766 this.input
.$input
.on( {
19767 keydown
: this.onKeyDown
.bind( this ),
19768 'wheel mousewheel DOMMouseScroll': this.onWheel
.bind( this )
19770 this.plusButton
.connect( this, {
19771 click
: [ 'onButtonClick', +1 ]
19773 this.minusButton
.connect( this, {
19774 click
: [ 'onButtonClick', -1 ]
19778 this.setIsInteger( !!config
.isInteger
);
19779 this.setRange( config
.min
, config
.max
);
19780 this.setStep( config
.step
, config
.pageStep
);
19782 this.$field
= $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
19784 this.minusButton
.$element
,
19785 this.input
.$element
,
19786 this.plusButton
.$element
19788 this.$element
.addClass( 'oo-ui-numberInputWidget' ).append( this.$field
);
19789 this.input
.setValidation( this.validateNumber
.bind( this ) );
19794 OO
.inheritClass( OO
.ui
.NumberInputWidget
, OO
.ui
.Widget
);
19799 * A `change` event is emitted when the value of the input changes.
19805 * An `enter` event is emitted when the user presses 'enter' inside the text box.
19813 * Set whether only integers are allowed
19814 * @param {boolean} flag
19816 OO
.ui
.NumberInputWidget
.prototype.setIsInteger = function ( flag
) {
19817 this.isInteger
= !!flag
;
19818 this.input
.setValidityFlag();
19822 * Get whether only integers are allowed
19823 * @return {boolean} Flag value
19825 OO
.ui
.NumberInputWidget
.prototype.getIsInteger = function () {
19826 return this.isInteger
;
19830 * Set the range of allowed values
19831 * @param {number} min Minimum allowed value
19832 * @param {number} max Maximum allowed value
19834 OO
.ui
.NumberInputWidget
.prototype.setRange = function ( min
, max
) {
19836 throw new Error( 'Minimum (' + min
+ ') must not be greater than maximum (' + max
+ ')' );
19840 this.input
.setValidityFlag();
19844 * Get the current range
19845 * @return {number[]} Minimum and maximum values
19847 OO
.ui
.NumberInputWidget
.prototype.getRange = function () {
19848 return [ this.min
, this.max
];
19852 * Set the stepping deltas
19853 * @param {number} step Normal step
19854 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
19856 OO
.ui
.NumberInputWidget
.prototype.setStep = function ( step
, pageStep
) {
19858 throw new Error( 'Step value must be positive' );
19860 if ( pageStep
=== null ) {
19861 pageStep
= step
* 10;
19862 } else if ( pageStep
<= 0 ) {
19863 throw new Error( 'Page step value must be positive' );
19866 this.pageStep
= pageStep
;
19870 * Get the current stepping values
19871 * @return {number[]} Step and page step
19873 OO
.ui
.NumberInputWidget
.prototype.getStep = function () {
19874 return [ this.step
, this.pageStep
];
19878 * Get the current value of the widget
19881 OO
.ui
.NumberInputWidget
.prototype.getValue = function () {
19882 return this.input
.getValue();
19886 * Get the current value of the widget as a number
19887 * @return {number} May be NaN, or an invalid number
19889 OO
.ui
.NumberInputWidget
.prototype.getNumericValue = function () {
19890 return +this.input
.getValue();
19894 * Set the value of the widget
19895 * @param {string} value Invalid values are allowed
19897 OO
.ui
.NumberInputWidget
.prototype.setValue = function ( value
) {
19898 this.input
.setValue( value
);
19902 * Adjust the value of the widget
19903 * @param {number} delta Adjustment amount
19905 OO
.ui
.NumberInputWidget
.prototype.adjustValue = function ( delta
) {
19906 var n
, v
= this.getNumericValue();
19909 if ( isNaN( delta
) || !isFinite( delta
) ) {
19910 throw new Error( 'Delta must be a finite number' );
19913 if ( isNaN( v
) ) {
19917 n
= Math
.max( Math
.min( n
, this.max
), this.min
);
19918 if ( this.isInteger
) {
19919 n
= Math
.round( n
);
19924 this.setValue( n
);
19931 * @param {string} value Field value
19932 * @return {boolean}
19934 OO
.ui
.NumberInputWidget
.prototype.validateNumber = function ( value
) {
19936 if ( isNaN( n
) || !isFinite( n
) ) {
19940 /*jshint bitwise: false */
19941 if ( this.isInteger
&& ( n
| 0 ) !== n
) {
19944 /*jshint bitwise: true */
19946 if ( n
< this.min
|| n
> this.max
) {
19954 * Handle mouse click events.
19957 * @param {number} dir +1 or -1
19959 OO
.ui
.NumberInputWidget
.prototype.onButtonClick = function ( dir
) {
19960 this.adjustValue( dir
* this.step
);
19964 * Handle mouse wheel events.
19967 * @param {jQuery.Event} event
19969 OO
.ui
.NumberInputWidget
.prototype.onWheel = function ( event
) {
19972 // Standard 'wheel' event
19973 if ( event
.originalEvent
.deltaMode
!== undefined ) {
19974 this.sawWheelEvent
= true;
19976 if ( event
.originalEvent
.deltaY
) {
19977 delta
= -event
.originalEvent
.deltaY
;
19978 } else if ( event
.originalEvent
.deltaX
) {
19979 delta
= event
.originalEvent
.deltaX
;
19982 // Non-standard events
19983 if ( !this.sawWheelEvent
) {
19984 if ( event
.originalEvent
.wheelDeltaX
) {
19985 delta
= -event
.originalEvent
.wheelDeltaX
;
19986 } else if ( event
.originalEvent
.wheelDeltaY
) {
19987 delta
= event
.originalEvent
.wheelDeltaY
;
19988 } else if ( event
.originalEvent
.wheelDelta
) {
19989 delta
= event
.originalEvent
.wheelDelta
;
19990 } else if ( event
.originalEvent
.detail
) {
19991 delta
= -event
.originalEvent
.detail
;
19996 delta
= delta
< 0 ? -1 : 1;
19997 this.adjustValue( delta
* this.step
);
20004 * Handle key down events.
20007 * @param {jQuery.Event} e Key down event
20009 OO
.ui
.NumberInputWidget
.prototype.onKeyDown = function ( e
) {
20010 if ( !this.isDisabled() ) {
20011 switch ( e
.which
) {
20012 case OO
.ui
.Keys
.UP
:
20013 this.adjustValue( this.step
);
20015 case OO
.ui
.Keys
.DOWN
:
20016 this.adjustValue( -this.step
);
20018 case OO
.ui
.Keys
.PAGEUP
:
20019 this.adjustValue( this.pageStep
);
20021 case OO
.ui
.Keys
.PAGEDOWN
:
20022 this.adjustValue( -this.pageStep
);
20031 OO
.ui
.NumberInputWidget
.prototype.setDisabled = function ( disabled
) {
20033 OO
.ui
.NumberInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
20035 if ( this.input
) {
20036 this.input
.setDisabled( this.isDisabled() );
20038 if ( this.minusButton
) {
20039 this.minusButton
.setDisabled( this.isDisabled() );
20041 if ( this.plusButton
) {
20042 this.plusButton
.setDisabled( this.isDisabled() );
20049 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
20050 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
20051 * visually by a slider in the leftmost position.
20054 * // Toggle switches in the 'off' and 'on' position.
20055 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
20056 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
20060 * // Create a FieldsetLayout to layout and label switches
20061 * var fieldset = new OO.ui.FieldsetLayout( {
20062 * label: 'Toggle switches'
20064 * fieldset.addItems( [
20065 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
20066 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
20068 * $( 'body' ).append( fieldset.$element );
20071 * @extends OO.ui.ToggleWidget
20072 * @mixins OO.ui.mixin.TabIndexedElement
20075 * @param {Object} [config] Configuration options
20076 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
20077 * By default, the toggle switch is in the 'off' position.
20079 OO
.ui
.ToggleSwitchWidget
= function OoUiToggleSwitchWidget( config
) {
20080 // Parent constructor
20081 OO
.ui
.ToggleSwitchWidget
.parent
.call( this, config
);
20083 // Mixin constructors
20084 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
20087 this.dragging
= false;
20088 this.dragStart
= null;
20089 this.sliding
= false;
20090 this.$glow
= $( '<span>' );
20091 this.$grip
= $( '<span>' );
20094 this.$element
.on( {
20095 click
: this.onClick
.bind( this ),
20096 keypress
: this.onKeyPress
.bind( this )
20100 this.$glow
.addClass( 'oo-ui-toggleSwitchWidget-glow' );
20101 this.$grip
.addClass( 'oo-ui-toggleSwitchWidget-grip' );
20103 .addClass( 'oo-ui-toggleSwitchWidget' )
20104 .attr( 'role', 'checkbox' )
20105 .append( this.$glow
, this.$grip
);
20110 OO
.inheritClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.ToggleWidget
);
20111 OO
.mixinClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.mixin
.TabIndexedElement
);
20116 * Handle mouse click events.
20119 * @param {jQuery.Event} e Mouse click event
20121 OO
.ui
.ToggleSwitchWidget
.prototype.onClick = function ( e
) {
20122 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
20123 this.setValue( !this.value
);
20129 * Handle key press events.
20132 * @param {jQuery.Event} e Key press event
20134 OO
.ui
.ToggleSwitchWidget
.prototype.onKeyPress = function ( e
) {
20135 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
20136 this.setValue( !this.value
);